From 0a34cdec1ab41f9a62ed3a99b395dd920f34cedc Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 22 Nov 2026 10:02:19 +0800 Subject: [PATCH 01/64] perf(linux): record a Vulkan image's commands only when they are stale Every changed frame reset the command pool and re-recorded the whole scene for every swapchain image, so a caret blink, which changes one rectangle's instance data, recorded thousands of vkCmd calls three times. The renderer now keeps a generation of what the commands draw: the compositing batches, the label textures, the scene buffer and the extent. A frame that changes one of those advances it; each image keeps the generation it was recorded at and is recorded again, alone, when it is acquired with stale commands. A frame that only writes instance data records nothing. The command pool resets buffers individually, and the offscreen target records before its readback. Stage 1 of ADR 0091. Checked on the Linux test machine (lavapipe): the recording, offscreen and window-recovery tests pass. Viva-only. --- internal/platform/linux/api_linux_test.go | 15 +-- internal/platform/linux/input_linux_test.go | 37 +++++++- internal/platform/linux/offscreen_linux.go | 3 + internal/platform/linux/vulkan_linux.go | 93 ++++++++++++++----- .../linux/vulkan_recovery_linux_test.go | 5 + internal/platform/linux/vulkan_text_linux.go | 5 + 6 files changed, 125 insertions(+), 33 deletions(-) diff --git a/internal/platform/linux/api_linux_test.go b/internal/platform/linux/api_linux_test.go index e0ae3b230..d89055b80 100644 --- a/internal/platform/linux/api_linux_test.go +++ b/internal/platform/linux/api_linux_test.go @@ -959,22 +959,25 @@ func TestResizeRecordsStagedCommandsAtAnAlreadyMatchingExtent(t *testing.T) { recordings++ return vkSuccess } - // Recovery may already have rebuilt the surface to the requested extent, - // but retrying a staged upload still resets its drawing commands. + // A staged scene makes the commands stale; a resize to the extent the + // surface already has rebuilds nothing, and the stale commands are recorded + // once, when their image is submitted. if changed, err := renderer.stage(platform.Frame{TextLabels: []platform.TextLabel{}}); !changed || err != nil { t.Fatalf("stage: changed=%v err=%v", changed, err) } if err := renderer.resize(100, 100); err != nil { t.Fatal(err) } - if recordings != 1 || recreations != 0 { + if recordings != 0 || recreations != 0 { t.Fatalf("matching extent recorded %d times and rebuilt %d times", recordings, recreations) } - if err := renderer.resize(100, 100); err != nil { - t.Fatal(err) + for range 2 { + if err := renderer.ensureRecorded(0); err != nil { + t.Fatal(err) + } } if recordings != 1 { - t.Fatalf("unchanged resize recorded commands again: %d", recordings) + t.Fatalf("submitting the stale image recorded it %d times, want once", recordings) } } diff --git a/internal/platform/linux/input_linux_test.go b/internal/platform/linux/input_linux_test.go index 00fbdbde2..bf3fcf902 100644 --- a/internal/platform/linux/input_linux_test.go +++ b/internal/platform/linux/input_linux_test.go @@ -214,7 +214,10 @@ func TestEventRouterSkipsUnknownKeysAndPropagatesErrors(t *testing.T) { } } -func TestRendererApplyReRecordsOnlyChangedFrames(t *testing.T) { +// A frame stages its scene and leaves the commands to the next submit: an image is +// recorded once for a scene, a frame that only changes instance data (a caret +// blinking) records nothing, and one that changes the batches records again. +func TestRendererRecordsAnImageOnlyWhenItsCommandsAreStale(t *testing.T) { waits, resets, begins, ends := 0, 0, 0, 0 storage := make([]byte, 64*vkInstanceBytes) renderer := vulkanRenderer{ @@ -260,13 +263,41 @@ func TestRendererApplyReRecordsOnlyChangedFrames(t *testing.T) { if waits != 0 || resets != 0 { t.Fatalf("empty apply waited=%d reset=%d", waits, resets) } + renderer.recordExtent = vkExtent2D{Width: 100, Height: 80} rectangles := []render.Rectangle{{Bounds: scene.Rect{Width: 10, Height: 10}, Color: scene.Color{Alpha: 1}}} changed, err := renderer.apply(platform.Frame{Update: render.Update{Rebuild: true, Count: 1}, Rectangles: rectangles}) if err != nil || !changed { t.Fatalf("changed apply changed=%v err=%v", changed, err) } - if waits != 1 || resets != 1 || begins != 2 || ends != 2 { - t.Fatalf("command lifecycle waits=%d resets=%d begins=%d ends=%d", waits, resets, begins, ends) + if waits != 1 || resets != 0 || begins != 0 { + t.Fatalf("staging waits=%d resets=%d begins=%d, want the fence and no recording", waits, resets, begins) + } + submit := func() { + t.Helper() + if err := renderer.ensureRecorded(0); err != nil { + t.Fatal(err) + } + } + submit() + submit() + if begins != 1 || ends != 1 { + t.Fatalf("one scene recorded image 0 begins=%d ends=%d, want once", begins, ends) + } + rectangles[0].Color.Alpha = 0.5 // a caret fading: new instance data, same batches + if _, err := renderer.apply(platform.Frame{Update: render.Update{First: 0, Count: 1}, Rectangles: rectangles}); err != nil { + t.Fatal(err) + } + submit() + if begins != 1 { + t.Fatalf("a frame that changed instance data recorded again: begins=%d", begins) + } + rectangles = append(rectangles, render.Rectangle{Bounds: scene.Rect{Width: 5, Height: 5}, Color: scene.Color{Alpha: 1}, Layer: 3}) + if _, err := renderer.apply(platform.Frame{Update: render.Update{First: 1, Count: 1}, Rectangles: rectangles}); err != nil { + t.Fatal(err) + } + submit() + if begins != 2 { + t.Fatalf("a frame that changed the batches did not record again: begins=%d", begins) } rectangles[0].Bounds.Width = 99 if renderer.rectangles[0].Bounds.Width != 10 { diff --git a/internal/platform/linux/offscreen_linux.go b/internal/platform/linux/offscreen_linux.go index 2895eb9b5..5860d349e 100644 --- a/internal/platform/linux/offscreen_linux.go +++ b/internal/platform/linux/offscreen_linux.go @@ -212,6 +212,9 @@ func (renderer *vulkanRenderer) readImage() (*image.RGBA, error) { if err := vkCheck(renderer.api.waitForFences(renderer.device, 1, &renderer.fence, 1, math.MaxUint64), "wait before readback"); err != nil { return nil, err } + if err := renderer.ensureRecorded(0); err != nil { + return nil, err + } begin := vkCommandBufferBeginInfo{SType: vkStructureCommandBeginInfo, Flags: vkCommandOneTimeSubmit} if err := vkCheck(renderer.api.beginCommandBuffer(target.readbackCommand, &begin), "begin readback command"); err != nil { return nil, err diff --git a/internal/platform/linux/vulkan_linux.go b/internal/platform/linux/vulkan_linux.go index 998efaa83..f30075107 100644 --- a/internal/platform/linux/vulkan_linux.go +++ b/internal/platform/linux/vulkan_linux.go @@ -7,6 +7,7 @@ import ( "math" "os" "path/filepath" + "slices" "sync" "unsafe" @@ -404,9 +405,17 @@ type vulkanRenderer struct { uploadCommand uintptr imageAvailable, renderFinished, fence uintptr views, framebuffers, commands []uintptr - // commandsStaged means a scene update reset the command pool and left - // recording to resize. Device recovery may already have changed its extent. - commandsStaged bool + // commandGeneration counts changes to what the commands draw: the batches, + // the label textures, the buffers they bind, the extent. recorded holds, for + // each target image, the generation its commands were recorded at; an image + // is recorded again only when it is about to be submitted with stale ones, + // so a frame that only changed instance data (a caret blink, a colour fading) + // records nothing. recordExtent is the extent commands are recorded at. + commandGeneration uint64 + recorded []uint64 + recordExtent vkExtent2D + recordings int + lastBatches []compositingBatch queueFamily, width, height, format uint32 surfaceFormat vkSurfaceFormat hasSurfaceFormat bool @@ -951,7 +960,9 @@ func (renderer *vulkanRenderer) createCommands(images uint32) error { renderer.commands = nil renderer.uploadCommand = 0 } - poolInfo := vkCommandPoolCreateInfo{SType: vkStructureCommandPoolCreateInfo, Family: renderer.queueFamily} + // Command buffers are recorded one at a time, when an image is submitted with + // stale commands: beginning one resets it. + poolInfo := vkCommandPoolCreateInfo{SType: vkStructureCommandPoolCreateInfo, Flags: vkCommandPoolResetCommandBuffer, Family: renderer.queueFamily} if err := vkCheck(renderer.api.createCommandPool(renderer.device, &poolInfo, nil, &renderer.commandPool), "create command pool"); err != nil { return err } @@ -987,7 +998,41 @@ func (renderer *vulkanRenderer) createScenePipelines(extent vkExtent2D) error { return renderer.recordCommands(extent) } +// recordCommands makes every target image's commands stale and records them at +// extent now: what a new swapchain, a new frame or a rebuilt device needs before +// its first submit. A changed scene only invalidateCommands. func (renderer *vulkanRenderer) recordCommands(extent vkExtent2D) error { + renderer.recordExtent = extent + renderer.invalidateCommands() + for index := range renderer.commands { + if err := renderer.ensureRecorded(uint32(index)); err != nil { + return err + } + } + return nil +} + +// invalidateCommands marks every image's commands stale. +func (renderer *vulkanRenderer) invalidateCommands() { renderer.commandGeneration++ } + +// ensureRecorded records the commands of target image index when they are stale. +func (renderer *vulkanRenderer) ensureRecorded(index uint32) error { + if len(renderer.recorded) != len(renderer.commands) { + renderer.recorded = make([]uint64, len(renderer.commands)) + renderer.commandGeneration++ // a fresh slice holds zeros: none is current + } + if renderer.recorded[index] == renderer.commandGeneration { + return nil + } + if err := renderer.recordImage(index, renderer.recordExtent); err != nil { + return err + } + renderer.recorded[index] = renderer.commandGeneration + return nil +} + +// recordImage records the commands that draw the scene into target image index. +func (renderer *vulkanRenderer) recordImage(index uint32, extent vkExtent2D) error { scratch := &renderer.scratch scratch.clear = vkClearValue{Color: [4]float32{float32(renderer.color.Red), float32(renderer.color.Green), float32(renderer.color.Blue), float32(renderer.color.Alpha)}} // A window frame leaves the margin transparent and draws the scene inside it. @@ -999,7 +1044,8 @@ func (renderer *vulkanRenderer) recordCommands(extent vkExtent2D) error { renderer.frame.upload(renderer, extent.Width, extent.Height) } scratch.contentX, scratch.contentY = contentX, contentY - for index, command := range renderer.commands { + { + command := renderer.commands[index] scratch.begin = vkCommandBufferBeginInfo{SType: vkStructureCommandBeginInfo} if err := vkCheck(renderer.api.beginCommandBuffer(command, &scratch.begin), "begin clear command"); err != nil { return err @@ -1030,7 +1076,7 @@ func (renderer *vulkanRenderer) recordCommands(extent vkExtent2D) error { } } scratch.contentX, scratch.contentY = 0, 0 - renderer.commandsStaged = false + renderer.recordings++ return nil } @@ -1190,6 +1236,9 @@ func (renderer *vulkanRenderer) presentOnce() (bool, error) { if image >= uint32(len(renderer.commands)) { return false, fmt.Errorf("linux: Vulkan acquired invalid image %d", image) } + if err := renderer.ensureRecorded(image); err != nil { + return false, err + } if err := vkCheck(renderer.api.resetFences(renderer.device, 1, &renderer.fence), "reset frame fence"); err != nil { return false, err } @@ -1245,15 +1294,10 @@ func (renderer *vulkanRenderer) stage(frame platform.Frame) (bool, error) { } } +// applyFrame stages frame; the commands it makes stale are recorded when their +// image is next submitted. func (renderer *vulkanRenderer) applyFrame(frame platform.Frame) (bool, error) { - changed, err := renderer.stageFrame(frame) - if err != nil || !changed { - return changed, err - } - if err := renderer.recordCommands(vkExtent2D{Width: renderer.width, Height: renderer.height}); err != nil { - return false, err - } - return true, nil + return renderer.stageFrame(frame) } func (renderer *vulkanRenderer) stageFrame(frame platform.Frame) (bool, error) { @@ -1284,10 +1328,7 @@ func (renderer *vulkanRenderer) stageFrame(frame platform.Frame) (bool, error) { if err := vkCheck(renderer.api.waitForFences(renderer.device, 1, &renderer.fence, 1, math.MaxUint64), "wait before scene update"); err != nil { return false, err } - if err := vkCheck(renderer.api.resetCommandPool(renderer.device, renderer.commandPool, 0), "reset scene commands"); err != nil { - return false, err - } - renderer.commandsStaged = true + buffer, textures := renderer.scene.buffer, renderer.text.generation if !frame.Update.Empty() { if frame.Update.Rebuild { renderer.rectangles = append(renderer.rectangles[:0], frame.Rectangles...) @@ -1322,6 +1363,14 @@ func (renderer *vulkanRenderer) stageFrame(frame platform.Frame) (bool, error) { if err := renderer.text.upload(renderer, renderer.pixelScale(), renderer.textViewport(renderer.width, renderer.height)); err != nil { return false, err } + // The commands draw the batches and bind the scene buffer and the label + // textures: only a change to one of those makes them stale. New instance + // data in the same buffer is drawn by the commands already recorded. + if frame.TextLabels != nil || buffer != renderer.scene.buffer || textures != renderer.text.generation || + !slices.Equal(renderer.lastBatches, renderer.compositingBatches) { + renderer.lastBatches = append(renderer.lastBatches[:0], renderer.compositingBatches...) + renderer.invalidateCommands() + } return true, nil } @@ -1397,11 +1446,7 @@ func (renderer *vulkanRenderer) resizeOnce(width, height uint32) error { return nil } if width == renderer.width && height == renderer.height { - // Recovery during stage can rebuild the swapchain at this extent before - // retrying the scene upload. That retry still needs recorded commands. - if renderer.commandsStaged { - return renderer.recordCommands(vkExtent2D{Width: width, Height: height}) - } + // Stale commands are recorded when their image is next submitted. return nil } renderer.width, renderer.height = width, height @@ -1600,7 +1645,7 @@ func (renderer *vulkanRenderer) releaseDevice() { renderer.hasSurfaceFormat = false renderer.hasPresentMode = false renderer.hasPendingCapabilities = false - renderer.commandsStaged = false + renderer.recorded = nil } func (renderer *vulkanRenderer) selectPresentMode() uint32 { diff --git a/internal/platform/linux/vulkan_recovery_linux_test.go b/internal/platform/linux/vulkan_recovery_linux_test.go index f9e3efb0d..8940b503b 100644 --- a/internal/platform/linux/vulkan_recovery_linux_test.go +++ b/internal/platform/linux/vulkan_recovery_linux_test.go @@ -138,6 +138,11 @@ func TestResizeRecordsCommandsAfterStageRecovery(t *testing.T) { clear(recorded) return reset(device, pool, flags) } + begin := renderer.api.beginCommandBuffer + renderer.api.beginCommandBuffer = func(command uintptr, info *vkCommandBufferBeginInfo) int32 { + delete(recorded, command) // beginning a buffer resets it + return begin(command, info) + } end := renderer.api.endCommandBuffer renderer.api.endCommandBuffer = func(command uintptr) int32 { status := end(command) diff --git a/internal/platform/linux/vulkan_text_linux.go b/internal/platform/linux/vulkan_text_linux.go index 1a48da957..b8cc88fa0 100644 --- a/internal/platform/linux/vulkan_text_linux.go +++ b/internal/platform/linux/vulkan_text_linux.go @@ -38,6 +38,7 @@ const ( vkSamplerMipmapLinear = 1 vkSamplerAddressClampEdge = 2 vkCommandOneTimeSubmit = 1 + vkCommandPoolResetCommandBuffer = 2 vkMaximumTextLabels = 2048 ) @@ -194,6 +195,9 @@ type vulkanText struct { used []bool candidates map[vulkanTextureKey]int reordered []vulkanLabelTexture + // generation counts the uploads that replaced label textures: commands that + // bind the old ones are stale once it moves. + generation uint64 } type vulkanTextureKey struct { @@ -685,6 +689,7 @@ func (textState *vulkanText) upload(renderer *vulkanRenderer, scale float32, vie if !dirty { return nil } + textState.generation++ begin := vkCommandBufferBeginInfo{SType: vkStructureCommandBeginInfo, Flags: vkCommandOneTimeSubmit} if err := vkCheck(renderer.api.beginCommandBuffer(renderer.uploadCommand, &begin), "begin text upload"); err != nil { return err From a813f1e38bc245ae18c3de1c0b632a7602872a3a Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 22 Nov 2026 10:20:42 +0800 Subject: [PATCH 02/64] fix(linux): give every window and renderer its own copy of the shared tables Loading the xcb and Vulkan function tables once handed every caller the same table, so a window or renderer whose functions were wrapped (as the recovery and resize tests wrap them) changed every other one in the process. The libraries are still opened and bound once; each caller now gets a copy of the bound table, a few hundred bytes per window. Follows ADR 0093 step 1 (9ad1e9d7). Viva-only. --- internal/platform/linux/shared_api_linux_test.go | 16 +++++++++++----- internal/platform/linux/xcb_linux.go | 14 ++++++++++---- 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/internal/platform/linux/shared_api_linux_test.go b/internal/platform/linux/shared_api_linux_test.go index 0158713ca..9ee56bb19 100644 --- a/internal/platform/linux/shared_api_linux_test.go +++ b/internal/platform/linux/shared_api_linux_test.go @@ -2,18 +2,24 @@ package linux import "testing" -// The libxcb and libvulkan function tables are the process's: every window, the -// clipboard and the desktop settings share the one loaded first, and a machine -// without the library is found once. +// The libxcb and libvulkan libraries are opened once per process, and a machine +// without one is found once; every caller gets its own copy of the bound table, +// so wrapping one window's functions leaves another's alone. func TestFunctionTablesAreLoadedOnce(t *testing.T) { x1, xErr1 := loadXCB() x2, xErr2 := loadXCB() - if x1 != x2 || xErr1 != xErr2 { + if xErr1 != xErr2 || (xErr1 == nil && (x1.library != x2.library || x1 == x2)) { t.Fatalf("loadXCB gave %p, %v then %p, %v", x1, xErr1, x2, xErr2) } v1, vErr1 := loadVulkan() v2, vErr2 := loadVulkan() - if v1 != v2 || vErr1 != vErr2 { + if vErr1 != vErr2 || (vErr1 == nil && (v1.library != v2.library || v1 == v2)) { t.Fatalf("loadVulkan gave %p, %v then %p, %v", v1, vErr1, v2, vErr2) } + if xErr1 == nil { + x1.connect = nil + if x2.connect == nil { + t.Fatal("changing one copy of the table changed another") + } + } } diff --git a/internal/platform/linux/xcb_linux.go b/internal/platform/linux/xcb_linux.go index 029fd560a..ccfd38973 100644 --- a/internal/platform/linux/xcb_linux.go +++ b/internal/platform/linux/xcb_linux.go @@ -351,12 +351,18 @@ type xcbAPI struct { free func(unsafe.Pointer) } -// loadXCB is the process's libxcb and libc function table: loaded the first -// time a window, the clipboard or a desktop setting needs it and kept for the -// life of the process, as the Pango services are. A failure is kept too. +// loadXCB gives a copy of the process's libxcb and libc function table: the +// libraries are opened and bound the first time a window, the clipboard or a +// desktop setting needs them and kept for the life of the process, as the Pango +// services are; a failure is kept too. Each caller owns its copy, so one window's +// table can be wrapped (as tests do) without reaching another's. func loadXCB() (*xcbAPI, error) { xcbOnce.Do(func() { xcbShared, xcbErr = openXCB() }) - return xcbShared, xcbErr + if xcbErr != nil { + return nil, xcbErr + } + api := *xcbShared + return &api, nil } var ( From aaa3a7ac197ecc12ca1cb5ee51bb379e7c0b5e41 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 22 Nov 2026 10:20:42 +0800 Subject: [PATCH 03/64] perf(linux): stage label uploads through kept buffers, without idling the GPU Each changed label made and freed its own staging buffer and memory, and every upload ended with vkDeviceWaitIdle, stalling the whole GPU once per batch of changed rows. Uploads now copy into staging chunks the renderer keeps, persistently mapped; a page that outgrows a chunk takes another, and the next upload merges them into one. An upload fence replaces the device wait: the next upload, or the next frame that replaces label images, waits for it, and the frame drawn after an upload reads its images through the barriers recorded with the copies. Loading the Vulkan table also gives each renderer its own copy of it. ADR 0091 stage 3, staging and synchronization; image sub-allocation is next. Checked on the Linux test machine (lavapipe): the new staging test, the offscreen text tests and window recovery pass. Viva-only. --- internal/platform/linux/vulkan_linux.go | 15 +- .../platform/linux/vulkan_staging_linux.go | 171 ++++++++++++++++++ .../linux/vulkan_staging_linux_test.go | 69 +++++++ internal/platform/linux/vulkan_text_linux.go | 99 +++------- 4 files changed, 276 insertions(+), 78 deletions(-) create mode 100644 internal/platform/linux/vulkan_staging_linux.go create mode 100644 internal/platform/linux/vulkan_staging_linux_test.go diff --git a/internal/platform/linux/vulkan_linux.go b/internal/platform/linux/vulkan_linux.go index f30075107..3c0019ad4 100644 --- a/internal/platform/linux/vulkan_linux.go +++ b/internal/platform/linux/vulkan_linux.go @@ -568,11 +568,16 @@ func vulkanDriverManifestsExist(paths []string) bool { return false } -// loadVulkan is the process's libvulkan function table, loaded once and kept -// for the life of the process; a machine without a driver is found once. +// loadVulkan gives a copy of the process's libvulkan function table, loaded and +// bound once and kept for the life of the process; a machine without a driver is +// found once. Each renderer owns its copy, as each window owns its xcb table. func loadVulkan() (*vulkanAPI, error) { vulkanOnce.Do(func() { vulkanShared, vulkanErr = openVulkan() }) - return vulkanShared, vulkanErr + if vulkanErr != nil { + return nil, vulkanErr + } + api := *vulkanShared + return &api, nil } var ( @@ -1328,6 +1333,10 @@ func (renderer *vulkanRenderer) stageFrame(frame platform.Frame) (bool, error) { if err := vkCheck(renderer.api.waitForFences(renderer.device, 1, &renderer.fence, 1, math.MaxUint64), "wait before scene update"); err != nil { return false, err } + // The last text upload may still be copying into images this frame replaces. + if err := renderer.text.staging.settle(renderer); err != nil { + return false, err + } buffer, textures := renderer.scene.buffer, renderer.text.generation if !frame.Update.Empty() { if frame.Update.Rebuild { diff --git a/internal/platform/linux/vulkan_staging_linux.go b/internal/platform/linux/vulkan_staging_linux.go new file mode 100644 index 000000000..d90247322 --- /dev/null +++ b/internal/platform/linux/vulkan_staging_linux.go @@ -0,0 +1,171 @@ +//go:build linux + +package linux + +import ( + "fmt" + "math" + "runtime" + "unsafe" +) + +// stagingChunk is one host-visible buffer the label pixels are copied through, +// mapped for as long as it lives. +type stagingChunk struct { + buffer, memory uintptr + mapped unsafe.Pointer + size, used uint64 +} + +// textStaging is where an upload's label pixels wait for the copy into their +// images: chunks kept between uploads, so a steady page allocates no staging +// memory, and an upload fence instead of waiting for the whole device to idle. +// An upload that outgrows its chunk takes another; the next upload, once the +// fence says the copies are done, merges them into one of their total size. +type textStaging struct { + chunks []stagingChunk + fence uintptr + pending bool // an upload was submitted and its fence not yet waited for +} + +// stagingChunkMinimum is the smallest chunk: a few hundred terminal rows. +const stagingChunkMinimum = 1 << 20 + +// settle waits for the last upload's copies, after which its chunks and the +// images it wrote may be reused or destroyed. +func (staging *textStaging) settle(renderer *vulkanRenderer) error { + if !staging.pending { + return nil + } + if err := vkCheck(renderer.api.waitForFences(renderer.device, 1, &staging.fence, 1, math.MaxUint64), "wait for text upload"); err != nil { + return err + } + staging.pending = false + return nil +} + +// begin readies the chunks for an upload: the last one has settled, and the +// chunks it needed are one. +func (staging *textStaging) begin(renderer *vulkanRenderer) error { + if err := staging.settle(renderer); err != nil { + return err + } + if staging.fence == 0 { + info := vkFenceCreateInfo{SType: vkStructureFenceCreateInfo} + if err := vkCheck(renderer.api.createFence(renderer.device, &info, nil, &staging.fence), "create text upload fence"); err != nil { + return err + } + } + if len(staging.chunks) > 1 { + var total uint64 + for index := range staging.chunks { + total += staging.chunks[index].size + } + staging.closeChunks(renderer) + if err := staging.grow(renderer, total); err != nil { + return err + } + } + for index := range staging.chunks { + staging.chunks[index].used = 0 + } + return nil +} + +// stage copies pixels into a chunk and returns the buffer and offset the copy +// into the image reads them from. +func (staging *textStaging) stage(renderer *vulkanRenderer, pixels []byte) (buffer uintptr, offset uint64, err error) { + need := uint64(len(pixels)) + last := len(staging.chunks) - 1 + if last < 0 || staging.chunks[last].size-staging.chunks[last].used < need { + size := uint64(stagingChunkMinimum) + if last >= 0 { + size = max(size, staging.chunks[last].size*2) + } + if err := staging.grow(renderer, max(size, need)); err != nil { + return 0, 0, err + } + last = len(staging.chunks) - 1 + } + chunk := &staging.chunks[last] + offset = chunk.used + copy(unsafe.Slice((*byte)(unsafe.Add(chunk.mapped, offset)), len(pixels)), pixels) + runtime.KeepAlive(pixels) + // A copy reads its texels from an offset that is a multiple of the texel's + // size; 16 suits every format and the optimal copy alignment of common drivers. + chunk.used = (offset + need + 15) &^ 15 + return chunk.buffer, offset, nil +} + +// submit hands the upload command to the queue with the fence. +func (staging *textStaging) submit(renderer *vulkanRenderer, command uintptr) error { + if err := vkCheck(renderer.api.resetFences(renderer.device, 1, &staging.fence), "reset text upload fence"); err != nil { + return err + } + submit := vkSubmitInfo{SType: vkStructureSubmitInfo, CommandCount: 1, Commands: &command} + if err := vkCheck(renderer.api.queueSubmit(renderer.queue, 1, &submit, staging.fence), "submit text upload"); err != nil { + return err + } + staging.pending = true + return nil +} + +func (staging *textStaging) grow(renderer *vulkanRenderer, size uint64) (err error) { + var chunk stagingChunk + defer func() { + if err != nil { + if chunk.memory != 0 { + renderer.api.freeMemory(renderer.device, chunk.memory, nil) + } + if chunk.buffer != 0 { + renderer.api.destroyBuffer(renderer.device, chunk.buffer, nil) + } + } + }() + info := vkBufferCreateInfo{SType: vkStructureBufferCreateInfo, Size: size, Usage: vkBufferUsageTransferSource, SharingMode: vkSharingExclusive} + if err := vkCheck(renderer.api.createBuffer(renderer.device, &info, nil, &chunk.buffer), "create text staging buffer"); err != nil { + return err + } + var requirements vkMemoryRequirements + renderer.api.getBufferMemoryRequirements(renderer.device, chunk.buffer, &requirements) + memoryType, ok := renderer.memoryType(requirements.MemoryTypeBits, vkMemoryHostVisible|vkMemoryHostCoherent) + if !ok { + return fmt.Errorf("Vulkan device has no coherent staging memory") + } + allocation := vkMemoryAllocateInfo{SType: vkStructureMemoryAllocateInfo, AllocationSize: requirements.Size, MemoryTypeIndex: memoryType} + if err := vkCheck(renderer.api.allocateMemory(renderer.device, &allocation, nil, &chunk.memory), "allocate text staging memory"); err != nil { + return err + } + if err := vkCheck(renderer.api.bindBufferMemory(renderer.device, chunk.buffer, chunk.memory, 0), "bind text staging memory"); err != nil { + return err + } + if err := vkCheck(renderer.api.mapMemory(renderer.device, chunk.memory, 0, size, 0, &chunk.mapped), "map text staging memory"); err != nil { + return err + } + chunk.size = size + staging.chunks = append(staging.chunks, chunk) + return nil +} + +func (staging *textStaging) closeChunks(renderer *vulkanRenderer) { + for index := range staging.chunks { + chunk := &staging.chunks[index] + renderer.api.unmapMemory(renderer.device, chunk.memory) + renderer.api.destroyBuffer(renderer.device, chunk.buffer, nil) + renderer.api.freeMemory(renderer.device, chunk.memory, nil) + } + staging.chunks = staging.chunks[:0] +} + +// close destroys the chunks and the fence; the device has finished with them. +func (staging *textStaging) close(renderer *vulkanRenderer) { + if renderer == nil || renderer.api == nil || renderer.device == 0 { + *staging = textStaging{} + return + } + staging.closeChunks(renderer) + if staging.fence != 0 { + renderer.api.destroyFence(renderer.device, staging.fence, nil) + } + *staging = textStaging{} +} diff --git a/internal/platform/linux/vulkan_staging_linux_test.go b/internal/platform/linux/vulkan_staging_linux_test.go new file mode 100644 index 000000000..a890f6415 --- /dev/null +++ b/internal/platform/linux/vulkan_staging_linux_test.go @@ -0,0 +1,69 @@ +package linux + +import ( + "fmt" + "testing" + + "github.com/vivaui/viva/internal/platform" +) + +// Labels uploaded frame after frame go through the staging chunks the renderer +// keeps: no upload waits for the whole device, a page larger than a chunk takes +// more and the next upload merges them back into one, and what is drawn is the +// text of the latest frame. +func TestTextUploadsReuseStagingWithoutIdlingTheDevice(t *testing.T) { + offscreen := newTestOffscreen(t, 400, 300) + renderer := offscreen.renderer + idles := 0 + idle := renderer.api.deviceWaitIdle + renderer.api.deviceWaitIdle = func(device uintptr) int32 { + idles++ + return idle(device) + } + page := func(round, rows int) []platform.TextLabel { + labels := make([]platform.TextLabel, rows) + for index := range labels { + labels[index] = platform.TextLabel{ + Value: fmt.Sprintf("round %d row %d of a long line of text", round, index), + X: 4, Y: float32(index%12) * 24, Width: 390, Height: 22, FontSize: 15, + Color: platform.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1}, + } + } + return labels + } + if err := offscreen.Set(nil, page(0, 4)); err != nil { + t.Skipf("text is not available here: %v", err) + } + // Enough rows that one upload outgrows the first chunk. + big := page(1, 600) + if err := offscreen.Set(nil, big); err != nil { + t.Fatal(err) + } + if len(renderer.text.staging.chunks) < 2 { + t.Skipf("the page fit one chunk (%d); the test needs a larger one", len(renderer.text.staging.chunks)) + } + if err := offscreen.Set(nil, page(2, 12)); err != nil { + t.Fatal(err) + } + if len(renderer.text.staging.chunks) != 1 { + t.Fatalf("the next upload kept %d chunks, want them merged into one", len(renderer.text.staging.chunks)) + } + if idles != 0 { + t.Fatalf("uploads waited for the device to idle %d times", idles) + } + pixels, err := offscreen.Image() + if err != nil { + t.Fatal(err) + } + painted := 0 + for y := 0; y < 24; y++ { + for x := 0; x < 400; x++ { + if isPainted(pixels, x, y) { + painted++ + } + } + } + if painted < 30 { + t.Fatal("the latest frame's first row drew no glyphs") + } +} diff --git a/internal/platform/linux/vulkan_text_linux.go b/internal/platform/linux/vulkan_text_linux.go index b8cc88fa0..e21a9349e 100644 --- a/internal/platform/linux/vulkan_text_linux.go +++ b/internal/platform/linux/vulkan_text_linux.go @@ -4,7 +4,6 @@ import ( "fmt" "hash/maphash" "math" - "runtime" "unsafe" "github.com/vivaui/viva/gfx" @@ -198,6 +197,7 @@ type vulkanText struct { // generation counts the uploads that replaced label textures: commands that // bind the old ones are stale once it moves. generation uint64 + staging textStaging } type vulkanTextureKey struct { @@ -250,8 +250,6 @@ func textureKey(label platform.TextLabel) vulkanTextureKey { return key } -type vulkanStagingBuffer struct{ buffer, memory uintptr } - func registerVulkanText(api *vulkanAPI, library uintptr) { puregoRegister(&api.createImage, library, "vkCreateImage") puregoRegister(&api.destroyImage, library, "vkDestroyImage") @@ -690,17 +688,15 @@ func (textState *vulkanText) upload(renderer *vulkanRenderer, scale float32, vie return nil } textState.generation++ + // The last upload's copies are done before its chunks, its command buffer + // and the images below are reused or replaced. + if err := textState.staging.begin(renderer); err != nil { + return err + } begin := vkCommandBufferBeginInfo{SType: vkStructureCommandBeginInfo, Flags: vkCommandOneTimeSubmit} if err := vkCheck(renderer.api.beginCommandBuffer(renderer.uploadCommand, &begin), "begin text upload"); err != nil { return err } - staging := make([]vulkanStagingBuffer, 0, len(textState.labels)) - closeStaging := func() { - for index := range staging { - staging[index].close(renderer) - } - } - defer closeStaging() for index := range textState.labels { label := &textState.labels[index] if !label.needsUpload(scale, viewport) { @@ -742,11 +738,9 @@ func (textState *vulkanText) upload(renderer *vulkanRenderer, scale float32, vie } spans = textState.services.spans } - stage, err := label.createImage(renderer, textState, renderer.uploadCommand, pixels, uint32(width), uint32(height)) - if err != nil { + if err := label.createImage(renderer, textState, renderer.uploadCommand, pixels, uint32(width), uint32(height)); err != nil { return fmt.Errorf("linux: upload label %d: %w", index, err) } - staging = append(staging, stage) label.scale, label.lcd = scale, lcd label.width, label.height, label.skip, label.wide = width, height, skip, wide label.spans = append(label.spans[:0], spans...) // after createImage, which clears the label @@ -754,12 +748,9 @@ func (textState *vulkanText) upload(renderer *vulkanRenderer, scale float32, vie if err := vkCheck(renderer.api.endCommandBuffer(renderer.uploadCommand), "end text upload"); err != nil { return err } - command := renderer.uploadCommand - submit := vkSubmitInfo{SType: vkStructureSubmitInfo, CommandCount: 1, Commands: &command} - if err := vkCheck(renderer.api.queueSubmit(renderer.queue, 1, &submit, 0), "submit text upload"); err != nil { - return err - } - return vkCheck(renderer.api.deviceWaitIdle(renderer.device), "wait for text upload") + // The frame drawn after this reads the images through the barriers recorded + // with the copies: nothing waits for the device here. + return textState.staging.submit(renderer, renderer.uploadCommand) } // Reserve up to sixteen cells on a grid row, so a pixel-by-pixel window resize @@ -798,16 +789,15 @@ func tightBitmap(source []byte, width, height, stride int) []byte { return pixels } -func (label *vulkanLabelTexture) createImage(renderer *vulkanRenderer, textState *vulkanText, command uintptr, pixels []byte, width, height uint32) (vulkanStagingBuffer, error) { +func (label *vulkanLabelTexture) createImage(renderer *vulkanRenderer, textState *vulkanText, command uintptr, pixels []byte, width, height uint32) error { label.closeImage(renderer) - stage, err := createTextStaging(renderer, pixels) + buffer, offset, err := textState.staging.stage(renderer, pixels) if err != nil { - return vulkanStagingBuffer{}, err + return err } failed := true defer func() { if failed { - stage.close(renderer) label.closeImage(renderer) } }() @@ -818,20 +808,20 @@ func (label *vulkanLabelTexture) createImage(renderer *vulkanRenderer, textState Usage: vkImageUsageTransferDestination | vkImageUsageSampled, SharingMode: vkSharingExclusive, } if err := vkCheck(renderer.api.createImage(renderer.device, &imageInfo, nil, &label.image), "create text image"); err != nil { - return vulkanStagingBuffer{}, err + return err } var requirements vkMemoryRequirements renderer.api.getImageMemoryRequirements(renderer.device, label.image, &requirements) memoryType, ok := renderer.memoryType(requirements.MemoryTypeBits, vkMemoryDeviceLocal) if !ok { - return vulkanStagingBuffer{}, fmt.Errorf("Vulkan device has no device-local image memory") + return fmt.Errorf("Vulkan device has no device-local image memory") } allocation := vkMemoryAllocateInfo{SType: vkStructureMemoryAllocateInfo, AllocationSize: requirements.Size, MemoryTypeIndex: memoryType} if err := vkCheck(renderer.api.allocateMemory(renderer.device, &allocation, nil, &label.memory), "allocate text image memory"); err != nil { - return vulkanStagingBuffer{}, err + return err } if err := vkCheck(renderer.api.bindImageMemory(renderer.device, label.image, label.memory, 0), "bind text image memory"); err != nil { - return vulkanStagingBuffer{}, err + return err } barrier := vkImageMemoryBarrier{ SType: vkStructureImageMemoryBarrier, OldLayout: vkImageLayoutUndefined, NewLayout: vkImageLayoutTransferDestination, @@ -839,8 +829,8 @@ func (label *vulkanLabelTexture) createImage(renderer *vulkanRenderer, textState Range: vkSubresourceRange{Aspect: vkImageAspectColor, LevelCount: 1, LayerCount: 1}, DestinationAccess: vkAccessTransferWrite, } renderer.api.cmdPipelineBarrier(command, vkPipelineStageTop, vkPipelineStageTransfer, 0, 0, nil, 0, nil, 1, &barrier) - region := vkBufferImageCopy{ImageSubresource: vkImageSubresourceLayers{Aspect: vkImageAspectColor, LayerCount: 1}, ImageExtent: vkExtent3D{Width: width, Height: height, Depth: 1}} - renderer.api.cmdCopyBufferToImage(command, stage.buffer, label.image, vkImageLayoutTransferDestination, 1, ®ion) + region := vkBufferImageCopy{BufferOffset: offset, ImageSubresource: vkImageSubresourceLayers{Aspect: vkImageAspectColor, LayerCount: 1}, ImageExtent: vkExtent3D{Width: width, Height: height, Depth: 1}} + renderer.api.cmdCopyBufferToImage(command, buffer, label.image, vkImageLayoutTransferDestination, 1, ®ion) barrier.SourceAccess = vkAccessTransferWrite barrier.DestinationAccess = vkAccessShaderRead barrier.OldLayout = vkImageLayoutTransferDestination @@ -848,62 +838,19 @@ func (label *vulkanLabelTexture) createImage(renderer *vulkanRenderer, textState renderer.api.cmdPipelineBarrier(command, vkPipelineStageTransfer, vkPipelineStageFragment, 0, 0, nil, 0, nil, 1, &barrier) viewInfo := vkImageViewCreateInfo{SType: vkStructureImageViewCreateInfo, Image: label.image, ViewType: vkImageViewType2D, Format: vkFormatBGRA8, Range: vkSubresourceRange{Aspect: vkImageAspectColor, LevelCount: 1, LayerCount: 1}} if err := vkCheck(renderer.api.createImageView(renderer.device, &viewInfo, nil, &label.view), "create text image view"); err != nil { - return vulkanStagingBuffer{}, err + return err } if label.set == 0 { allocate := vkDescriptorSetAllocateInfo{SType: vkStructureDescriptorSetAllocateInfo, Pool: textState.descriptorPool, SetCount: 1, SetLayouts: &textState.descriptorLayout} if err := vkCheck(renderer.api.allocateDescriptorSets(renderer.device, &allocate, &label.set), "allocate text descriptor"); err != nil { - return vulkanStagingBuffer{}, err + return err } } imageDescriptor := vkDescriptorImageInfo{Sampler: textState.sampler, ImageView: label.view, ImageLayout: vkImageLayoutShaderReadOnly} write := vkWriteDescriptorSet{SType: vkStructureWriteDescriptorSet, DestinationSet: label.set, DescriptorCount: 1, DescriptorType: vkDescriptorCombinedImageSampler, ImageInfo: &imageDescriptor} renderer.api.updateDescriptorSets(renderer.device, 1, &write, 0, nil) failed = false - return stage, nil -} - -func createTextStaging(renderer *vulkanRenderer, pixels []byte) (vulkanStagingBuffer, error) { - var stage vulkanStagingBuffer - info := vkBufferCreateInfo{SType: vkStructureBufferCreateInfo, Size: uint64(len(pixels)), Usage: vkBufferUsageTransferSource, SharingMode: vkSharingExclusive} - if err := vkCheck(renderer.api.createBuffer(renderer.device, &info, nil, &stage.buffer), "create text staging buffer"); err != nil { - return stage, err - } - var requirements vkMemoryRequirements - renderer.api.getBufferMemoryRequirements(renderer.device, stage.buffer, &requirements) - memoryType, ok := renderer.memoryType(requirements.MemoryTypeBits, vkMemoryHostVisible|vkMemoryHostCoherent) - if !ok { - stage.close(renderer) - return stage, fmt.Errorf("Vulkan device has no coherent staging memory") - } - allocation := vkMemoryAllocateInfo{SType: vkStructureMemoryAllocateInfo, AllocationSize: requirements.Size, MemoryTypeIndex: memoryType} - if err := vkCheck(renderer.api.allocateMemory(renderer.device, &allocation, nil, &stage.memory), "allocate text staging memory"); err != nil { - stage.close(renderer) - return stage, err - } - if err := vkCheck(renderer.api.bindBufferMemory(renderer.device, stage.buffer, stage.memory, 0), "bind text staging memory"); err != nil { - stage.close(renderer) - return stage, err - } - var mapped unsafe.Pointer - if err := vkCheck(renderer.api.mapMemory(renderer.device, stage.memory, 0, uint64(len(pixels)), 0, &mapped), "map text staging memory"); err != nil { - stage.close(renderer) - return stage, err - } - copy(unsafe.Slice((*byte)(mapped), len(pixels)), pixels) - runtime.KeepAlive(pixels) - renderer.api.unmapMemory(renderer.device, stage.memory) - return stage, nil -} - -func (stage *vulkanStagingBuffer) close(renderer *vulkanRenderer) { - if stage.buffer != 0 { - renderer.api.destroyBuffer(renderer.device, stage.buffer, nil) - } - if stage.memory != 0 { - renderer.api.freeMemory(renderer.device, stage.memory, nil) - } - stage.buffer, stage.memory = 0, 0 + return nil } func (textState *vulkanText) record(renderer *vulkanRenderer, command uintptr, extent vkExtent2D, index int) { @@ -1058,6 +1005,7 @@ func (textState *vulkanText) destroyPipeline(renderer *vulkanRenderer) { func (textState *vulkanText) close(renderer *vulkanRenderer) { textState.destroyPipeline(renderer) + textState.staging.close(renderer) for index := range textState.labels { textState.labels[index].closeImage(renderer) } @@ -1085,6 +1033,7 @@ func (textState *vulkanText) close(renderer *vulkanRenderer) { // the next time the textures are made. func (textState *vulkanText) release(renderer *vulkanRenderer) { textState.destroyPipeline(renderer) + textState.staging.close(renderer) for index := range textState.labels { textState.labels[index].closeImage(renderer) // The sets went with the pool below. From 4d7ef0782da5a22e220be055c211bb36d2bea914 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 22 Nov 2026 10:22:48 +0800 Subject: [PATCH 04/64] perf(linux): sub-allocate label image memory from blocks Every uploaded label image made its own vkAllocateMemory, a kernel call against a driver limit of a few thousand allocations, and freed it when the row changed. Label images now take aligned spans of 16 MiB blocks per memory type; a freed span joins its neighbours, a block left empty is freed unless it is the last, and an image larger than a quarter block keeps memory of its own. Replacing twelve rows after a large page makes no image allocation. ADR 0091 stage 3, image memory. Checked on the Linux test machine (lavapipe): the pool, staging and offscreen text tests pass. Viva-only. --- .../platform/linux/vulkan_imagepool_linux.go | 140 ++++++++++++++++++ .../linux/vulkan_staging_linux_test.go | 33 +++++ internal/platform/linux/vulkan_text_linux.go | 23 ++- 3 files changed, 191 insertions(+), 5 deletions(-) create mode 100644 internal/platform/linux/vulkan_imagepool_linux.go diff --git a/internal/platform/linux/vulkan_imagepool_linux.go b/internal/platform/linux/vulkan_imagepool_linux.go new file mode 100644 index 000000000..9dd065f42 --- /dev/null +++ b/internal/platform/linux/vulkan_imagepool_linux.go @@ -0,0 +1,140 @@ +//go:build linux + +package linux + +import "slices" + +// imagePool hands out device memory for label images from large blocks, so a +// page whose rows change does not make a driver allocation per row: drivers +// allow a few thousand allocations, and each is a call into the kernel. An image +// too large for a block gets memory of its own, as before. +type imagePool struct{ blocks []*imageBlock } + +// imageBlock is one device allocation, carved into image memory. +type imageBlock struct { + memory uintptr + memoryType uint32 + size uint64 + free []memorySpan // ordered by offset, never touching +} + +type memorySpan struct{ offset, size uint64 } + +// imageSlice is where a label's image memory is: a span of a block, or, with no +// block, memory of its own. +type imageSlice struct { + block *imageBlock + offset, size uint64 +} + +// imageBlockSize is a block's size: a few hundred terminal rows at 2x. +const imageBlockSize = 16 << 20 + +// allocate finds memory of memoryType for an image of requirements, and returns +// the memory and offset to bind it at. +func (pool *imagePool) allocate(renderer *vulkanRenderer, memoryType uint32, requirements vkMemoryRequirements) (uintptr, imageSlice, error) { + alignment := max(requirements.Alignment, 1) + if requirements.Size > imageBlockSize/4 { + memory, err := allocateDeviceMemory(renderer, memoryType, requirements.Size, "allocate text image memory") + return memory, imageSlice{}, err + } + for _, block := range pool.blocks { + if block.memoryType != memoryType { + continue + } + if offset, ok := block.carve(requirements.Size, alignment); ok { + return block.memory, imageSlice{block: block, offset: offset, size: requirements.Size}, nil + } + } + memory, err := allocateDeviceMemory(renderer, memoryType, imageBlockSize, "allocate text image block") + if err != nil { + return 0, imageSlice{}, err + } + block := &imageBlock{memory: memory, memoryType: memoryType, size: imageBlockSize, free: []memorySpan{{0, imageBlockSize}}} + pool.blocks = append(pool.blocks, block) + offset, _ := block.carve(requirements.Size, alignment) + return memory, imageSlice{block: block, offset: offset, size: requirements.Size}, nil +} + +// carve takes size bytes at an offset aligned to alignment from the first free +// span that holds them. +func (block *imageBlock) carve(size, alignment uint64) (uint64, bool) { + for index, span := range block.free { + start := (span.offset + alignment - 1) / alignment * alignment + end := span.offset + span.size + if start+size > end { + continue + } + // What is left before and after the image stays free. + var parts [2]memorySpan + count := 0 + if start > span.offset { + parts[count] = memorySpan{span.offset, start - span.offset} + count++ + } + if start+size < end { + parts[count] = memorySpan{start + size, end - start - size} + count++ + } + block.free = slices.Replace(block.free, index, index+1, parts[:count]...) + return start, true + } + return 0, false +} + +// release gives a label's memory back: to its block, or to the driver when it +// had memory of its own. A block that is left empty is freed unless it is the +// pool's last one, which a page that changes keeps using. +func (pool *imagePool) release(renderer *vulkanRenderer, memory uintptr, slice imageSlice) { + block := slice.block + if block == nil { + if memory != 0 { + renderer.api.freeMemory(renderer.device, memory, nil) + } + return + } + block.give(slice.offset, slice.size) + if len(block.free) == 1 && block.free[0].size == block.size && len(pool.blocks) > 1 { + renderer.api.freeMemory(renderer.device, block.memory, nil) + pool.blocks = slices.DeleteFunc(pool.blocks, func(candidate *imageBlock) bool { return candidate == block }) + } +} + +// give returns [offset, offset+size) to the free spans, joining its neighbours. +func (block *imageBlock) give(offset, size uint64) { + index, _ := slices.BinarySearchFunc(block.free, offset, func(span memorySpan, offset uint64) int { + switch { + case span.offset < offset: + return -1 + case span.offset > offset: + return 1 + } + return 0 + }) + block.free = slices.Insert(block.free, index, memorySpan{offset, size}) + if index+1 < len(block.free) && block.free[index].offset+block.free[index].size == block.free[index+1].offset { + block.free[index].size += block.free[index+1].size + block.free = slices.Delete(block.free, index+1, index+2) + } + if index > 0 && block.free[index-1].offset+block.free[index-1].size == block.free[index].offset { + block.free[index-1].size += block.free[index].size + block.free = slices.Delete(block.free, index, index+1) + } +} + +// close frees every block; the images in them are destroyed already. +func (pool *imagePool) close(renderer *vulkanRenderer) { + if renderer != nil && renderer.api != nil && renderer.device != 0 { + for _, block := range pool.blocks { + renderer.api.freeMemory(renderer.device, block.memory, nil) + } + } + pool.blocks = nil +} + +func allocateDeviceMemory(renderer *vulkanRenderer, memoryType uint32, size uint64, action string) (uintptr, error) { + var memory uintptr + allocation := vkMemoryAllocateInfo{SType: vkStructureMemoryAllocateInfo, AllocationSize: size, MemoryTypeIndex: memoryType} + err := vkCheck(renderer.api.allocateMemory(renderer.device, &allocation, nil, &memory), action) + return memory, err +} diff --git a/internal/platform/linux/vulkan_staging_linux_test.go b/internal/platform/linux/vulkan_staging_linux_test.go index a890f6415..10db13679 100644 --- a/internal/platform/linux/vulkan_staging_linux_test.go +++ b/internal/platform/linux/vulkan_staging_linux_test.go @@ -3,6 +3,7 @@ package linux import ( "fmt" "testing" + "unsafe" "github.com/vivaui/viva/internal/platform" ) @@ -42,9 +43,20 @@ func TestTextUploadsReuseStagingWithoutIdlingTheDevice(t *testing.T) { if len(renderer.text.staging.chunks) < 2 { t.Skipf("the page fit one chunk (%d); the test needs a larger one", len(renderer.text.staging.chunks)) } + allocations := 0 + allocate := renderer.api.allocateMemory + renderer.api.allocateMemory = func(device uintptr, info *vkMemoryAllocateInfo, callbacks unsafe.Pointer, memory *uintptr) int32 { + allocations++ + return allocate(device, info, callbacks, memory) + } if err := offscreen.Set(nil, page(2, 12)); err != nil { t.Fatal(err) } + // Twelve new images and the merged staging chunk: the images come out of the + // blocks the big page made, only the chunk is a driver allocation. + if allocations > 1 { + t.Fatalf("replacing twelve labels made %d driver allocations, want the images from the pool", allocations) + } if len(renderer.text.staging.chunks) != 1 { t.Fatalf("the next upload kept %d chunks, want them merged into one", len(renderer.text.staging.chunks)) } @@ -67,3 +79,24 @@ func TestTextUploadsReuseStagingWithoutIdlingTheDevice(t *testing.T) { t.Fatal("the latest frame's first row drew no glyphs") } } + +// Freed image memory goes back to its block and joins its free neighbours, so a +// block whose images are all gone is one free span again. +func TestImageBlockGivesBackAndJoinsSpans(t *testing.T) { + block := &imageBlock{size: 1024, free: []memorySpan{{0, 1024}}} + a, _ := block.carve(100, 64) + b, _ := block.carve(100, 64) + c, ok := block.carve(100, 256) + if !ok || a != 0 || b != 128 || c != 256 { + t.Fatalf("carved at %d, %d, %d (ok %v), want aligned offsets 0, 128, 256", a, b, c, ok) + } + block.give(b, 100) + block.give(a, 100) + block.give(c, 100) + if len(block.free) != 1 || block.free[0] != (memorySpan{0, 1024}) { + t.Fatalf("free spans after giving everything back = %v", block.free) + } + if _, ok := block.carve(2048, 1); ok { + t.Fatal("carved more than the block holds") + } +} diff --git a/internal/platform/linux/vulkan_text_linux.go b/internal/platform/linux/vulkan_text_linux.go index e21a9349e..36cffe70d 100644 --- a/internal/platform/linux/vulkan_text_linux.go +++ b/internal/platform/linux/vulkan_text_linux.go @@ -161,7 +161,10 @@ type vulkanLabelTexture struct { label platform.TextLabel runs []gfx.TextRun image, memory, view, set uintptr - scale float32 + // slice is where memory came from: a span of the pool's block, or its own. + slice imageSlice + pool *imagePool + scale float32 // width and height are the texture's size in device pixels. width, height int // skip is the device column of the label the texture starts at: a line wider than a @@ -198,6 +201,7 @@ type vulkanText struct { // bind the old ones are stale once it moves. generation uint64 staging textStaging + images imagePool } type vulkanTextureKey struct { @@ -816,11 +820,12 @@ func (label *vulkanLabelTexture) createImage(renderer *vulkanRenderer, textState if !ok { return fmt.Errorf("Vulkan device has no device-local image memory") } - allocation := vkMemoryAllocateInfo{SType: vkStructureMemoryAllocateInfo, AllocationSize: requirements.Size, MemoryTypeIndex: memoryType} - if err := vkCheck(renderer.api.allocateMemory(renderer.device, &allocation, nil, &label.memory), "allocate text image memory"); err != nil { + memory, slice, err := textState.images.allocate(renderer, memoryType, requirements) + if err != nil { return err } - if err := vkCheck(renderer.api.bindImageMemory(renderer.device, label.image, label.memory, 0), "bind text image memory"); err != nil { + label.memory, label.slice, label.pool = memory, slice, &textState.images + if err := vkCheck(renderer.api.bindImageMemory(renderer.device, label.image, label.memory, slice.offset), "bind text image memory"); err != nil { return err } barrier := vkImageMemoryBarrier{ @@ -975,6 +980,7 @@ func (label *vulkanLabelTexture) closeImage(renderer *vulkanRenderer) { if renderer == nil || renderer.api == nil || renderer.device == 0 { label.image, label.memory, label.view, label.scale, label.lcd = 0, 0, 0, 0, false label.width, label.height, label.spans = 0, 0, label.spans[:0] + label.slice, label.pool = imageSlice{}, nil return } if label.view != 0 { @@ -983,10 +989,13 @@ func (label *vulkanLabelTexture) closeImage(renderer *vulkanRenderer) { if label.image != 0 { renderer.api.destroyImage(renderer.device, label.image, nil) } - if label.memory != 0 { + if label.pool != nil { + label.pool.release(renderer, label.memory, label.slice) + } else if label.memory != 0 { renderer.api.freeMemory(renderer.device, label.memory, nil) } label.image, label.memory, label.view, label.scale, label.lcd = 0, 0, 0, 0, false + label.slice, label.pool = imageSlice{}, nil label.width, label.height, label.spans = 0, 0, label.spans[:0] } @@ -1009,6 +1018,8 @@ func (textState *vulkanText) close(renderer *vulkanRenderer) { for index := range textState.labels { textState.labels[index].closeImage(renderer) } + textState.images.close(renderer) + if renderer != nil && renderer.api != nil && renderer.device != 0 { if textState.descriptorPool != 0 { renderer.api.destroyDescriptorPool(renderer.device, textState.descriptorPool, nil) @@ -1039,6 +1050,8 @@ func (textState *vulkanText) release(renderer *vulkanRenderer) { // The sets went with the pool below. textState.labels[index].set = 0 } + textState.images.close(renderer) + if renderer.api != nil && renderer.device != 0 { if textState.descriptorPool != 0 { renderer.api.destroyDescriptorPool(renderer.device, textState.descriptorPool, nil) From 1b627a4b89128373c50b22007d46e14523d40752 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 22 Nov 2026 10:29:19 +0800 Subject: [PATCH 05/64] perf(linux): read selections over one kept connection Every clipboard or primary read opened an X connection, made a 1x1 input window, interned its atoms with a round trip each and tore it all down afterwards; Motty's remote desktop does that on every pointer press. Reads now share one process connection and window, made by the first read and kept: a mutex lets one read wait for its replies at a time, replies left over from a read that gave up are dropped before the next, a connection the server dropped is made again, and the connection keeps the atoms it resolved. Font settings are read once already, and a global shortcut keeps its own connection for its key events. ADR 0093 step 2. Checked on the Linux test machine with xclip: the primary, INCR both ways, clipboard manager and new shared-connection tests pass. Viva-only. --- .../linux/selection_live_linux_test.go | 22 ++++++ internal/platform/linux/system_linux.go | 70 ++++++++++++++----- internal/platform/linux/xcb_linux.go | 10 +++ 3 files changed, 83 insertions(+), 19 deletions(-) diff --git a/internal/platform/linux/selection_live_linux_test.go b/internal/platform/linux/selection_live_linux_test.go index f76cd90ad..7c3a7e8ce 100644 --- a/internal/platform/linux/selection_live_linux_test.go +++ b/internal/platform/linux/selection_live_linux_test.go @@ -323,3 +323,25 @@ func TestAClosingWindowLeavesItsClipboardWithAManagerThatFollowsTheProtocol(t *t t.Fatalf("after the window closed the clipboard holds %q", got) } } + +// Reads of the clipboard share one X connection and its window, made by the +// first read and kept, so a paste costs no connection of its own. +func TestClipboardReadsShareOneConnection(t *testing.T) { + if os.Getenv("VIVA_LINUX_XCB_SMOKE") != "1" || os.Getenv("DISPLAY") == "" { + t.Skip("set VIVA_LINUX_XCB_SMOKE=1 with an X11 display") + } + if _, err := readClipboardX11(); err != nil { + t.Fatal(err) + } + selections.mu.Lock() + first, window := selections.connection, selections.requestor + selections.mu.Unlock() + if _, err := readClipboardX11(); err != nil { + t.Fatal(err) + } + selections.mu.Lock() + defer selections.mu.Unlock() + if first == 0 || selections.connection != first || selections.requestor != window { + t.Fatalf("the second read used connection %#x window %d, the first %#x window %d", selections.connection, selections.requestor, first, window) + } +} diff --git a/internal/platform/linux/system_linux.go b/internal/platform/linux/system_linux.go index 3fd26f15e..7000efb9e 100644 --- a/internal/platform/linux/system_linux.go +++ b/internal/platform/linux/system_linux.go @@ -8,6 +8,7 @@ import ( "path/filepath" "runtime" "strings" + "sync" "time" "unicode/utf8" "unsafe" @@ -70,7 +71,7 @@ func readSelectionTextX11(name string) (string, error) { if err != nil { return "", err } - defer closeClipboardRequest(api, connection, requestor) + defer closeClipboardRequest() if owner == xcbAtomNone { return "", nil } @@ -114,7 +115,7 @@ func clipboardOffersImage() (bool, error) { if err != nil { return false, err } - defer closeClipboardRequest(api, connection, requestor) + defer closeClipboardRequest() if owner == xcbAtomNone { return false, nil } @@ -172,7 +173,7 @@ func ClipboardImagePNG() ([]byte, error) { if err != nil { return nil, err } - defer closeClipboardRequest(api, connection, requestor) + defer closeClipboardRequest() if owner == xcbAtomNone { return nil, platform.ErrNoClipboardImage } @@ -223,7 +224,7 @@ func ClipboardFiles() ([]string, error) { if err != nil { return nil, err } - defer closeClipboardRequest(api, connection, requestor) + defer closeClipboardRequest() if owner == xcbAtomNone { return nil, platform.ErrNoClipboardFiles } @@ -317,37 +318,68 @@ func ownedClipboardFiles() ([]string, bool) { return append([]string(nil), win.clipboardFiles...), true } -// openClipboardRequest connects to the X server with a 1x1 input window to -// receive a selection reply, and finds the CLIPBOARD owner. +// selections is the process's connection for reading selections: one X +// connection and one 1x1 input window that every clipboard and primary read +// shares, made by the first read and kept, instead of a connection, a window +// and a round trip per atom for each paste. A read holds mu from +// openSelectionRequest to closeClipboardRequest, so two reads take turns: the +// replies a read waits for arrive on this connection and only it may take +// them. A connection the X server dropped is made again by the next read. +var selections struct { + mu sync.Mutex + api *xcbAPI + connection uintptr + requestor uint32 +} + +// openClipboardRequest finds the CLIPBOARD owner on the selection connection, +// whose 1x1 input window receives the reply. func openClipboardRequest() (api *xcbAPI, connection uintptr, requestor, clipboard, owner uint32, err error) { return openSelectionRequest("CLIPBOARD") } // openSelectionRequest is openClipboardRequest for any selection, by name. func openSelectionRequest(name string) (api *xcbAPI, connection uintptr, requestor, selection, owner uint32, err error) { - var screen *xcbScreen - api, connection, screen, err = openSystemConnection() - if err != nil { - return nil, 0, 0, 0, 0, err + selections.mu.Lock() + if selections.connection != 0 && selections.api.connectionHasError(selections.connection) != 0 { + selections.api.disconnect(selections.connection) + selections.connection = 0 + } + if selections.connection == 0 { + var screen *xcbScreen + api, connection, screen, err = openSystemConnection() + if err != nil { + selections.mu.Unlock() + return nil, 0, 0, 0, 0, err + } + api.atoms = make(map[string]uint32, 16) + requestor = api.generateID(connection) + // PropertyNotify events pace an INCR transfer: the owner writes each chunk + // when the previous one is deleted. + eventMask := uint32(xcbEventPropertyChange) + api.createWindow(connection, xcbCopyFromParent, requestor, screen.Root, 0, 0, 1, 1, 0, xcbWindowClassInput, screen.RootVisual, xcbCWEventMask, &eventMask) + selections.api, selections.connection, selections.requestor = api, connection, requestor + } + api, connection, requestor = selections.api, selections.connection, selections.requestor + // A reply that came after the read that asked for it gave up is not this + // read's answer. + for event := api.pollForEvent(connection); event != nil; event = api.pollForEvent(connection) { + api.free(event) } - requestor = api.generateID(connection) - // PropertyNotify events pace an INCR transfer: the owner writes each chunk when - // the previous one is deleted. - eventMask := uint32(xcbEventPropertyChange) - api.createWindow(connection, xcbCopyFromParent, requestor, screen.Root, 0, 0, 1, 1, 0, xcbWindowClassInput, screen.RootVisual, xcbCWEventMask, &eventMask) if selection, err = api.atom(connection, name); err == nil { owner, err = selectionOwner(api, connection, selection) } if err != nil { - closeClipboardRequest(api, connection, requestor) + closeClipboardRequest() return nil, 0, 0, 0, 0, err } return api, connection, requestor, selection, owner, nil } -func closeClipboardRequest(api *xcbAPI, connection uintptr, requestor uint32) { - api.destroyWindow(connection, requestor) - api.disconnect(connection) +// closeClipboardRequest ends a read: the selection connection is free for the +// next one, and kept. +func closeClipboardRequest() { + selections.mu.Unlock() } // readSelectionBytes asks the selection owner to convert to target and returns diff --git a/internal/platform/linux/xcb_linux.go b/internal/platform/linux/xcb_linux.go index ccfd38973..c6bdf30fc 100644 --- a/internal/platform/linux/xcb_linux.go +++ b/internal/platform/linux/xcb_linux.go @@ -290,6 +290,10 @@ type pollFD struct { type xcbAPI struct { library uintptr libc uintptr + // atoms, when set, keeps the atoms atom resolved: an atom names the same + // thing for as long as the X server runs, so a connection that resolves the + // same names again and again (the selection client) asks once. + atoms map[string]uint32 connect func(*byte, *int32) uintptr disconnect func(uintptr) @@ -444,6 +448,9 @@ func openXCB() (*xcbAPI, error) { } func (api *xcbAPI) atom(connection uintptr, name string) (uint32, error) { + if atom, ok := api.atoms[name]; ok { + return atom, nil + } value := append([]byte(name), 0) cookie := api.internAtom(connection, 0, uint16(len(value)-1), &value[0]) var nativeError unsafe.Pointer @@ -459,5 +466,8 @@ func (api *xcbAPI) atom(connection uintptr, name string) (uint32, error) { return 0, fmt.Errorf("linux: resolve X atom %q", name) } defer api.free(unsafe.Pointer(reply)) + if api.atoms != nil { + api.atoms[name] = reply.Atom + } return reply.Atom, nil } From b108bb194edc2ab831cd3e069ae152be61007613 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 22 Nov 2026 10:34:54 +0800 Subject: [PATCH 06/64] refactor(text): reach the editor's runes through a store The Editor read and wrote its []rune directly in some 150 places: length, indexing, slicing, grapheme boundaries and the tail shuffle of every edit. They go through runeStore now (Len, At, Slice, View, Next, Prev, Replace, String), still backed by a []rune, so the text can change how it is held without touching the editing code. No behavior changes. Step 1 of ADR 0092 (editor text storage). Viva-only. --- text/code.go | 64 ++++++++++++++++----------------- text/composition.go | 34 +++++++++--------- text/edit_journal.go | 10 +++--- text/editing.go | 38 ++++++++++---------- text/editor.go | 78 ++++++++++++++++------------------------- text/lf_labels.go | 2 +- text/line_journal.go | 8 ++--- text/multi_replace.go | 26 +++++++------- text/multiselection.go | 14 ++++---- text/offsets.go | 28 +++++++-------- text/store.go | 44 +++++++++++++++++++++++ text/text_cache_test.go | 2 +- text/transaction.go | 2 +- text/visual.go | 12 +++---- 14 files changed, 195 insertions(+), 167 deletions(-) create mode 100644 text/store.go diff --git a/text/code.go b/text/code.go index 3e973df99..82ce86c31 100644 --- a/text/code.go +++ b/text/code.go @@ -57,7 +57,7 @@ func isIndentRune(r rune) bool { return r == ' ' || r == '\t' } // lineStartAt is the index of the first rune of the line that contains index. func (editor *Editor) lineStartAt(index int) int { - for index > 0 && editor.runes[index-1] != '\n' { + for index > 0 && editor.runes.At(index-1) != '\n' { index-- } return index @@ -66,7 +66,7 @@ func (editor *Editor) lineStartAt(index int) int { // lineEndAt is the index of the newline that ends the line containing index, or // the length of the text. func (editor *Editor) lineEndAt(index int) int { - for index < len(editor.runes) && editor.runes[index] != '\n' { + for index < editor.runes.Len() && editor.runes.At(index) != '\n' { index++ } return index @@ -75,7 +75,7 @@ func (editor *Editor) lineEndAt(index int) int { // indentEnd is the index of the first rune of [start, end) that is not a space // or a tab: where the text of the line begins. func (editor *Editor) indentEnd(start, end int) int { - for start < end && isIndentRune(editor.runes[start]) { + for start < end && isIndentRune(editor.runes.At(start)) { start++ } return start @@ -94,7 +94,7 @@ func cellsOf(r rune, column, tabWidth int) int { func (editor *Editor) column(index, tabWidth int) int { column := 0 for at := editor.lineStartAt(index); at < index; at++ { - column += cellsOf(editor.runes[at], column, tabWidth) + column += cellsOf(editor.runes.At(at), column, tabWidth) } return column } @@ -107,8 +107,8 @@ func (editor *Editor) editBlock(target Range, replacement []rune, anchor, caret before := editor.selectionState() change := editor.replace(target, string(replacement), false) editor.clearSecondary() - editor.anchor = clamp(anchor, 0, len(editor.runes)) - editor.caret = clamp(caret, 0, len(editor.runes)) + editor.anchor = clamp(anchor, 0, editor.runes.Len()) + editor.caret = clamp(caret, 0, editor.runes.Len()) editor.composing = false editor.releaseCompositionHistory() editor.record(change, before, editor.selectionState(), editSeparate) @@ -122,7 +122,7 @@ func (editor *Editor) selectedLines() (first, last int) { selection := editor.Selection() first = editor.lineStartAt(selection.Start) end := selection.End - if end > selection.Start && editor.runes[end-1] == '\n' { + if end > selection.Start && editor.runes.At(end-1) == '\n' { end-- } return first, editor.lineEndAt(end) @@ -148,7 +148,7 @@ func (editor *Editor) transformLines(first, last int, transform func(line []rune ) for position := first; ; { end := editor.lineEndAt(position) - out, change := transform(editor.runes[position:end]) + out, change := transform(editor.runes.Slice(position, end)) oldStarts = append(oldStarts, position) newStarts = append(newStarts, first+len(block)) changes = append(changes, change) @@ -196,19 +196,19 @@ func (editor *Editor) InsertNewlineCode(options CodeOptions) { selection := editor.Selection() start := editor.lineStartAt(selection.Start) indentEnd := min(editor.indentEnd(start, selection.Start), selection.Start) - indent := append([]rune(nil), editor.runes[start:indentEnd]...) + indent := append([]rune(nil), editor.runes.Slice(start, indentEnd)...) blank := indentEnd == selection.Start // nothing but indentation before the caret extra := false for at := selection.Start; at > start; at-- { - if r := editor.runes[at-1]; !isIndentRune(r) { + if r := editor.runes.At(at - 1); !isIndentRune(r) { extra = containsRune(options.IndentAfter, r) break } } hasCloser := false - if extra && selection.End < len(editor.runes) { + if extra && selection.End < editor.runes.Len() { if previous, ok := editor.previousCodeRune(selection.Start, start); ok { - hasCloser = isBracket(previous) && closerOf(previous) == editor.runes[selection.End] + hasCloser = isBracket(previous) && closerOf(previous) == editor.runes.At(selection.End) } } text := append([]rune{'\n'}, indent...) @@ -231,7 +231,7 @@ func (editor *Editor) InsertNewlineCode(options CodeOptions) { // lineStart that is not a space or a tab. func (editor *Editor) previousCodeRune(index, lineStart int) (rune, bool) { for at := index; at > lineStart; at-- { - if r := editor.runes[at-1]; !isIndentRune(r) { + if r := editor.runes.At(at - 1); !isIndentRune(r) { return r, true } } @@ -247,7 +247,7 @@ func (editor *Editor) InsertTabCode(options CodeOptions) { return } selection := editor.Selection() - if selection.Start != selection.End && containsRuneIn(editor.runes[selection.Start:selection.End], '\n') { + if selection.Start != selection.End && containsRuneIn(editor.runes.Slice(selection.Start, selection.End), '\n') { editor.indentLines(options) return } @@ -330,7 +330,7 @@ func (editor *Editor) ToggleLineComment(options CodeOptions) { if depth := text - position; shallowest < 0 || depth < shallowest { shallowest = depth } - if !hasRunePrefix(editor.runes[text:end], prefix) { + if !hasRunePrefix(editor.runes.Slice(text, end), prefix) { allCommented = false } } @@ -401,11 +401,11 @@ func (editor *Editor) DuplicateLines(up bool) { } first, last := editor.selectedLines() if up { - block := append(append([]rune(nil), editor.runes[first:last]...), '\n') + block := append(append([]rune(nil), editor.runes.Slice(first, last)...), '\n') editor.editBlock(Range{Start: first, End: first}, block, editor.anchor, editor.caret) return } - block := append([]rune{'\n'}, editor.runes[first:last]...) + block := append([]rune{'\n'}, editor.runes.Slice(first, last)...) shift := len(block) editor.editBlock(Range{Start: last, End: last}, block, editor.anchor+shift, editor.caret+shift) } @@ -418,23 +418,23 @@ func (editor *Editor) MoveLines(up bool) { return } first, last := editor.selectedLines() - block := editor.runes[first:last] + block := editor.runes.Slice(first, last) if up { if first == 0 { return } previousStart := editor.lineStartAt(first - 1) - previous := editor.runes[previousStart : first-1] + previous := editor.runes.Slice(previousStart, first-1) moved := append(append(append([]rune(nil), block...), '\n'), previous...) shift := -(len(previous) + 1) editor.editBlock(Range{Start: previousStart, End: last}, moved, editor.anchor+shift, editor.caret+shift) return } - if last >= len(editor.runes) { + if last >= editor.runes.Len() { return } nextEnd := editor.lineEndAt(last + 1) - next := editor.runes[last+1 : nextEnd] + next := editor.runes.Slice(last+1, nextEnd) moved := append(append(append([]rune(nil), next...), '\n'), block...) shift := len(next) + 1 editor.editBlock(Range{Start: first, End: nextEnd}, moved, editor.anchor+shift, editor.caret+shift) @@ -449,7 +449,7 @@ func (editor *Editor) DeleteLines() { first, last := editor.selectedLines() start, end, caret := first, last, first switch { - case last < len(editor.runes): + case last < editor.runes.Len(): end++ // the line's own newline goes with it case first > 0: start-- // the last line has none: the one before it does @@ -479,10 +479,10 @@ func (editor *Editor) TypeCode(value string, options CodeOptions) { case opens && selection.Start != selection.End: wrapped := make([]rune, 0, selection.End-selection.Start+2) wrapped = append(wrapped, typed) - wrapped = append(wrapped, editor.runes[selection.Start:selection.End]...) + wrapped = append(wrapped, editor.runes.Slice(selection.Start, selection.End)...) wrapped = append(wrapped, closer) editor.editBlock(selection, wrapped, selection.Start+1, selection.End+1) - case selection.Start == selection.End && isCloserOrQuote(typed) && editor.caret < len(editor.runes) && editor.runes[editor.caret] == typed: + case selection.Start == selection.End && isCloserOrQuote(typed) && editor.caret < editor.runes.Len() && editor.runes.At(editor.caret) == typed: editor.MoveTo(editor.caret+1, false) case opens && selection.Start == selection.End && editor.mayPair(typed, editor.caret): editor.editBlock(selection, []rune{typed, closer}, selection.Start+1, selection.Start+1) @@ -493,14 +493,14 @@ func (editor *Editor) TypeCode(value string, options CodeOptions) { // mayPair reports whether an opener typed at index should insert its closer. func (editor *Editor) mayPair(typed rune, index int) bool { - if index < len(editor.runes) { - next := editor.runes[index] + if index < editor.runes.Len() { + next := editor.runes.At(index) if !isIndentRune(next) && next != '\n' && !containsRune(";:.,=}])> ", next) { return false } } if isQuoteRune(typed) && index > 0 { - previous := editor.runes[index-1] + previous := editor.runes.At(index - 1) if previous == typed || previous == '\\' || isWordRune(previous) { return false } @@ -521,9 +521,9 @@ func (editor *Editor) DeleteBackwardCode(options CodeOptions) { return } caret := selection.Start - previous := editor.runes[caret-1] - if options.AutoClose && caret < len(editor.runes) { - if closer, ok := pairCloser(previous); ok && editor.runes[caret] == closer { + previous := editor.runes.At(caret - 1) + if options.AutoClose && caret < editor.runes.Len() { + if closer, ok := pairCloser(previous); ok && editor.runes.At(caret) == closer { before := editor.selectionState() change := editor.replace(Range{Start: caret - 1, End: caret + 1}, "", false) editor.collapse(caret - 1) @@ -533,7 +533,7 @@ func (editor *Editor) DeleteBackwardCode(options CodeOptions) { } if options.AutoIndent && !options.HardTabs && previous == ' ' { start := editor.lineStartAt(caret) - if onlySpaces(editor.runes[start:caret]) { + if onlySpaces(editor.runes.Slice(start, caret)) { width := options.tabWidth() remove := (caret - start) % width if remove == 0 { @@ -686,7 +686,7 @@ func (editor *Editor) Backspace() { // them. It ends an active composition, which the replaced text may include. func (editor *Editor) ReplaceRange(target Range, value string) { editor.sealTentativeHistory() - target = normalizeRange(target, len(editor.runes)) + target = normalizeRange(target, editor.runes.Len()) before := editor.selectionState() change := editor.replace(target, value, false) editor.clearSecondary() // one range replaced, one caret left diff --git a/text/composition.go b/text/composition.go index d1e032692..a0b9fe487 100644 --- a/text/composition.go +++ b/text/composition.go @@ -365,7 +365,7 @@ func (editor *Editor) planCompositionEvent(state *compositionState, event Compos case CompositionEmptyCommit: needBase = !state.active } - base := editor.runes + base := editor.runes.View() if needBase { var baseOK bool base, baseOK = editor.compositionPlanBase(state) @@ -536,7 +536,7 @@ func (editor *Editor) compositionPlanScalars(plan *compositionPlan, base []rune, // current text directly. func (editor *Editor) compositionPlanBase(state *compositionState) ([]rune, bool) { if !state.active { - return editor.runes, true + return editor.runes.View(), true } return editor.compositionRollbackRunes(state) } @@ -548,12 +548,12 @@ func (editor *Editor) compositionPlanBase(state *compositionState) ([]rune, bool // document once per unit. The returned slice is owned by the caller. func (editor *Editor) compositionRollbackRunes(state *compositionState) ([]rune, bool) { if state == nil || !state.active { - return editor.runes, true + return editor.runes.View(), true } if state.unitStart < 0 || state.unitStart > len(editor.history) { return nil, false } - final := editor.runes + final := editor.runes.View() capacity := len(final) for index := state.unitStart; index < len(editor.history); index++ { edit := &editor.history[index] @@ -627,7 +627,7 @@ func (editor *Editor) compositionRollbackSteps(state *compositionState) int { } func (editor *Editor) compositionReplacementRange(event CompositionEvent) Range { - return editor.compositionReplacementRangeFor(editor.runes, event) + return editor.compositionReplacementRangeFor(editor.runes.View(), event) } func (editor *Editor) compositionReplacementRangeFor(base []rune, event CompositionEvent) Range { @@ -637,7 +637,7 @@ func (editor *Editor) compositionReplacementRangeFor(base []rune, event Composit if event.HasReplacement { return normalizeRange(event.Replacement, len(base)) } - if len(base) == len(editor.runes) { + if len(base) == editor.runes.Len() { return editor.Selection() } return Range{Start: editor.caret, End: editor.caret} @@ -693,7 +693,7 @@ func (editor *Editor) applyCompositionResult(state *compositionState, event Comp explicit = editor.compositionUTF16Range(event.ReplacementUTF16) hasExplicit = true case event.HasReplacement: - explicit = normalizeRange(event.Replacement, len(editor.runes)) + explicit = normalizeRange(event.Replacement, editor.runes.Len()) hasExplicit = true } if !wasActive && len(text) == 0 && (!hasExplicit || explicit.Start == explicit.End) { @@ -812,7 +812,7 @@ func (editor *Editor) rollbackComposition(state *compositionState, pending *hist state.completed = false state.completedStart = -1 state.eventStart = -1 - editor.collapse(clamp(state.start, 0, len(editor.runes))) + editor.collapse(clamp(state.start, 0, editor.runes.Len())) editor.BreakUndoGroup() if pending != nil { pending.retainedTo = pending.current @@ -840,7 +840,7 @@ func (editor *Editor) truncateCompositionUnits(from int) { } func (editor *Editor) compositionDeleteOrdinary(target Range) bool { - target = normalizeRange(target, len(editor.runes)) + target = normalizeRange(target, editor.runes.Len()) if target.Start == target.End { return false } @@ -890,7 +890,7 @@ func (editor *Editor) compositionInsertScalarsWithBreak(start int, text []rune, if breakBefore { editor.BreakUndoGroup() } - start = clamp(start, 0, len(editor.runes)) + start = clamp(start, 0, editor.runes.Len()) editor.collapse(start) for index := range text { before := editor.selectionState() @@ -912,7 +912,7 @@ func (editor *Editor) compositionInsertEventScalars(start int, text []rune, brea if !editor.overwrite { return editor.compositionInsertScalarsWithBreak(start, text, breakFirst) } - start = clamp(start, 0, len(editor.runes)) + start = clamp(start, 0, editor.runes.Len()) editor.collapse(start) for _, value := range text { start = editor.compositionOverwriteScalar(start, value) @@ -925,9 +925,9 @@ func (editor *Editor) compositionInsertEventScalars(start int, text []rune, brea // a line terminator, then insert the scalar. It uses one ordinary change/unit, // so it neither deletes a grapheme cluster nor the whole replacement width. func (editor *Editor) compositionOverwriteScalar(start int, value rune) int { - start = clamp(start, 0, len(editor.runes)) + start = clamp(start, 0, editor.runes.Len()) target := Range{Start: start, End: start} - if start < len(editor.runes) && !compositionLineEnd(editor.runes[start]) { + if start < editor.runes.Len() && !compositionLineEnd(editor.runes.At(start)) { target.End = start + 1 } before := editor.selectionState() @@ -944,7 +944,7 @@ func (editor *Editor) compositionOverwriteScalar(start int, value rune) int { // selection deletion shares one ordinary unit with the first scalar, while the // producer still receives the exact ordered delete and per-scalar inserts. func (editor *Editor) compositionReplaceAndInsert(target Range, text []rune) { - target = normalizeRange(target, len(editor.runes)) + target = normalizeRange(target, editor.runes.Len()) if target.Start == target.End || len(text) == 0 { editor.compositionInsertEventScalars(target.Start, text, false) return @@ -967,7 +967,7 @@ func (editor *Editor) compositionReplaceAndInsert(target Range, text []rune) { // the pinned source start-from-zero/relative-length conversion; out-of-range or // split-surrogate boundaries fall to the document end as the E1 contract binds. func (editor *Editor) compositionUTF16Range(raw UTF16Range) Range { - return editor.compositionUTF16RangeFor(editor.runes, raw) + return editor.compositionUTF16RangeFor(editor.runes.View(), raw) } func (editor *Editor) compositionUTF16RangeFor(text []rune, raw UTF16Range) Range { @@ -992,7 +992,7 @@ func (editor *Editor) compositionUTF16RangeFor(text []rune, raw UTF16Range) Rang // an already resolved rune start. It never adds the raw start and length, so a // huge positive length simply falls to the document end instead of overflowing. func (editor *Editor) compositionUTF16Relative(start, units int) (int, bool) { - return editor.compositionUTF16RelativeIn(editor.runes, start, units) + return editor.compositionUTF16RelativeIn(editor.runes.View(), start, units) } func (editor *Editor) compositionUTF16RelativeIn(text []rune, start, units int) (int, bool) { @@ -1020,7 +1020,7 @@ func (editor *Editor) compositionUTF16RelativeIn(text []rune, start, units int) } func (editor *Editor) compositionUTF16Start(units, total int) (int, bool) { - return editor.compositionUTF16StartIn(editor.runes, units, total) + return editor.compositionUTF16StartIn(editor.runes.View(), units, total) } func (editor *Editor) compositionUTF16StartIn(text []rune, units, total int) (int, bool) { diff --git a/text/edit_journal.go b/text/edit_journal.go index 988dded9f..1868494a2 100644 --- a/text/edit_journal.go +++ b/text/edit_journal.go @@ -69,23 +69,23 @@ func (editor *Editor) prepareEdit(start, end int, replacement []rune) Edit { at, offset := editor.offsets.index, editor.offsets.offset if start < at && start <= at-start { at, offset = 0, 0 - } else if start >= at && editor.textValid && len(editor.runes)-start < start-at { - at, offset = len(editor.runes), len(editor.text) + } else if start >= at && editor.textValid && editor.runes.Len()-start < start-at { + at, offset = editor.runes.Len(), len(editor.text) } for at < start { - offset += runeBytes(editor.runes[at]) + offset += runeBytes(editor.runes.At(at)) at++ } for at > start { at-- - offset -= runeBytes(editor.runes[at]) + offset -= runeBytes(editor.runes.At(at)) } editor.offsets = offsetMemo{index: start, offset: offset} if !editor.journal.tracking { return Edit{} } edit := Edit{Start: offset} - for _, character := range editor.runes[start:end] { + for _, character := range editor.runes.Slice(start, end) { edit.Removed += runeBytes(character) } for _, character := range replacement { diff --git a/text/editing.go b/text/editing.go index 5795804c4..87c7ebd3e 100644 --- a/text/editing.go +++ b/text/editing.go @@ -59,24 +59,24 @@ func wordClass(r rune) int { func (editor *Editor) wordBoundary(forward bool) int { at := editor.caret if forward { - if at < len(editor.runes) { - kind := wordClass(editor.runes[at]) - for at < len(editor.runes) && wordClass(editor.runes[at]) == kind { - at = nextBoundary(editor.runes, at) + if at < editor.runes.Len() { + kind := wordClass(editor.runes.At(at)) + for at < editor.runes.Len() && wordClass(editor.runes.At(at)) == kind { + at = editor.runes.Next(at) } } - for at < len(editor.runes) && wordClass(editor.runes[at]) == 0 { - at = nextBoundary(editor.runes, at) + for at < editor.runes.Len() && wordClass(editor.runes.At(at)) == 0 { + at = editor.runes.Next(at) } } else { - for at > 0 && wordClass(editor.runes[previousBoundary(editor.runes, at)]) == 0 { - at = previousBoundary(editor.runes, at) + for at > 0 && wordClass(editor.runes.At(editor.runes.Prev(at))) == 0 { + at = editor.runes.Prev(at) } if at > 0 { - kind := wordClass(editor.runes[previousBoundary(editor.runes, at)]) + kind := wordClass(editor.runes.At(editor.runes.Prev(at))) for at > 0 { - previous := previousBoundary(editor.runes, at) - if wordClass(editor.runes[previous]) != kind { + previous := editor.runes.Prev(at) + if wordClass(editor.runes.At(previous)) != kind { break } at = previous @@ -183,7 +183,7 @@ func (editor *Editor) DeleteWord(forward bool) { } func (editor *Editor) insideCRLF(at int) bool { - return at > 0 && at < len(editor.runes) && editor.runes[at-1] == '\r' && editor.runes[at] == '\n' + return at > 0 && at < editor.runes.Len() && editor.runes.At(at-1) == '\r' && editor.runes.At(at) == '\n' } // lineBoundary finds the logical line's start or the first rune of its LF or @@ -191,14 +191,14 @@ func (editor *Editor) insideCRLF(at int) bool { func (editor *Editor) lineBoundary(end bool) int { at := editor.caret if end { - for at < len(editor.runes) && editor.runes[at] != '\n' { + for at < editor.runes.Len() && editor.runes.At(at) != '\n' { at++ } - if at > 0 && at < len(editor.runes) && editor.runes[at-1] == '\r' { + if at > 0 && at < editor.runes.Len() && editor.runes.At(at-1) == '\r' { at-- } } else { - for at > 0 && editor.runes[at-1] != '\n' { + for at > 0 && editor.runes.At(at-1) != '\n' { at-- } } @@ -234,7 +234,7 @@ func (editor *Editor) DeleteToLineBoundary(end bool) { // A caret between CR and LF is at the start of that ending for line // purposes. Normalizing it first keeps the boundary and the deletion on // one position, so the pair is never split. - editor.collapse(previousBoundary(editor.runes, editor.caret)) + editor.collapse(editor.runes.Prev(editor.caret)) } boundary := editor.lineBoundary(end) target := ordered(Range{Start: editor.caret, End: boundary}) @@ -242,11 +242,11 @@ func (editor *Editor) DeleteToLineBoundary(end bool) { if target.Start == target.End { // A caret already on the boundary removes the grapheme beyond it, which // joins the line, as DeleteForward and DeleteBackward do. - if end && editor.caret < len(editor.runes) { - target = Range{Start: editor.caret, End: nextBoundary(editor.runes, editor.caret)} + if end && editor.caret < editor.runes.Len() { + target = Range{Start: editor.caret, End: editor.runes.Next(editor.caret)} kind = editDeleteForward } else if !end && editor.caret > 0 { - target = Range{Start: previousBoundary(editor.runes, editor.caret), End: editor.caret} + target = Range{Start: editor.runes.Prev(editor.caret), End: editor.caret} kind = editDeleteBackward } } diff --git a/text/editor.go b/text/editor.go index 3ce5e195c..9d9d0f4aa 100644 --- a/text/editor.go +++ b/text/editor.go @@ -68,7 +68,7 @@ type textChange struct { // thread, where native input and painting run. Read a string snapshot there // before starting background work; the returned string remains valid after edits. type Editor struct { - runes []rune + runes runeStore anchor int caret int // secondary is the multi-selection's other selections, normalized: ordered @@ -139,7 +139,7 @@ type Editor struct { func NewEditor(initial string) *Editor { runes := []rune(initial) end := len(runes) - return &Editor{runes: runes, anchor: end, caret: end} + return &Editor{runes: runeStore{runes: runes}, anchor: end, caret: end} } // String returns the current UTF-8 text. The conversion is cached until the @@ -169,10 +169,10 @@ func (editor *Editor) CommittedString() string { } } if !editor.compositionBaseValid { - committed := make([]rune, 0, len(editor.runes)-editor.composition.End+editor.composition.Start+len(editor.compositionOriginal)) - committed = append(committed, editor.runes[:editor.composition.Start]...) + committed := make([]rune, 0, editor.runes.Len()-editor.composition.End+editor.composition.Start+len(editor.compositionOriginal)) + committed = append(committed, editor.runes.Slice(0, editor.composition.Start)...) committed = append(committed, editor.compositionOriginal...) - committed = append(committed, editor.runes[editor.composition.End:]...) + committed = append(committed, editor.runes.Slice(editor.composition.End, editor.runes.Len())...) editor.compositionBase = string(committed) editor.compositionBaseValid = true } @@ -210,7 +210,7 @@ func (editor *Editor) SetOverwrite(overwrite bool) { // RuneCount returns the number of Unicode code points. func (editor *Editor) RuneCount() int { - return len(editor.runes) + return editor.runes.Len() } // Selection returns the normalized selection range. @@ -229,8 +229,8 @@ func (editor *Editor) Caret() int { // Start, as Caret reports, and Selection still returns it in order. func (editor *Editor) SetSelection(selection Range) { editor.sealTentativeHistory() - anchor := clamp(selection.Start, 0, len(editor.runes)) - caret := clamp(selection.End, 0, len(editor.runes)) + anchor := clamp(selection.Start, 0, editor.runes.Len()) + caret := clamp(selection.End, 0, editor.runes.Len()) if editor.anchor != anchor || editor.caret != caret || editor.composing { editor.BreakUndoGroup() } @@ -249,7 +249,7 @@ func (editor *Editor) SetSelection(selection Range) { func (editor *Editor) MoveTo(index int, extend bool) { editor.sealTentativeHistory() editor.BreakUndoGroup() - index = clamp(index, 0, len(editor.runes)) + index = clamp(index, 0, editor.runes.Len()) if extend { editor.caret = index } else { @@ -394,8 +394,8 @@ func (editor *Editor) CancelComposition() bool { if labels != nil { labels.ops.cancel(labels) } - editor.anchor = clamp(editor.compositionAnchor, 0, len(editor.runes)) - editor.caret = clamp(editor.compositionCaret, 0, len(editor.runes)) + editor.anchor = clamp(editor.compositionAnchor, 0, editor.runes.Len()) + editor.caret = clamp(editor.compositionCaret, 0, editor.runes.Len()) editor.composing = false editor.legacyComposition = false editor.composition = Range{} @@ -437,7 +437,7 @@ func (editor *Editor) DeleteBackward() bool { if caret == 0 { return false } - start := previousBoundary(editor.runes, caret) + start := editor.runes.Prev(caret) before := editor.selectionState() change := editor.replace(Range{Start: start, End: caret}, "", false) editor.collapse(start) @@ -458,10 +458,10 @@ func (editor *Editor) DeleteForward() bool { editor.composing = false // see DeleteBackward editor.releaseCompositionHistory() caret := editor.caret - if caret == len(editor.runes) { + if caret == editor.runes.Len() { return false } - end := nextBoundary(editor.runes, caret) + end := editor.runes.Next(caret) before := editor.selectionState() change := editor.replace(Range{Start: caret, End: end}, "", false) editor.record(change, before, editor.selectionState(), editDeleteForward) @@ -523,9 +523,9 @@ func (editor *Editor) MoveRight(extend bool) bool { // RuneIndexToUTF16 converts a rune index to a native UTF-16 code-unit index. func (editor *Editor) RuneIndexToUTF16(index int) int { - index = clamp(index, 0, len(editor.runes)) + index = clamp(index, 0, editor.runes.Len()) units := 0 - for _, value := range editor.runes[:index] { + for _, value := range editor.runes.Slice(0, index) { if value > 0xffff { units += 2 } else { @@ -542,7 +542,7 @@ func (editor *Editor) UTF16ToRuneIndex(units int) int { return 0 } consumed := 0 - for index, value := range editor.runes { + for index, value := range editor.runes.View() { width := 1 if value > 0xffff { width = 2 @@ -555,7 +555,7 @@ func (editor *Editor) UTF16ToRuneIndex(units int) int { return index + 1 } } - return len(editor.runes) + return editor.runes.Len() } func (editor *Editor) deleteSelectionOrComposition() bool { @@ -593,7 +593,7 @@ func (editor *Editor) replace(target Range, value string, overwrite bool) textCh // Explicit composition passes one borrowed scalar at a time; ordinary callers // still pass the same newly allocated rune slice through replace. func (editor *Editor) replaceRunes(target Range, replacement []rune, overwrite bool) textChange { - target = normalizeRange(target, len(editor.runes)) + target = normalizeRange(target, editor.runes.Len()) if editor.accept != nil { kept := replacement[:0] for _, r := range replacement { @@ -604,22 +604,22 @@ func (editor *Editor) replaceRunes(target Range, replacement []rune, overwrite b replacement = kept } if overwrite && len(replacement) > 0 { - if editor.maxRunes > 0 && len(editor.runes) >= editor.maxRunes && target.Start >= len(editor.runes) { - target.Start = len(editor.runes) - 1 // a full field: the last rune is replaced + if editor.maxRunes > 0 && editor.runes.Len() >= editor.maxRunes && target.Start >= editor.runes.Len() { + target.Start = editor.runes.Len() - 1 // a full field: the last rune is replaced } - target.End = min(target.Start+len(replacement), len(editor.runes)) + target.End = min(target.Start+len(replacement), editor.runes.Len()) } editor.lastReplaceStart = target.Start removed := target.End - target.Start if editor.maxRunes > 0 { - room := max(editor.maxRunes-(len(editor.runes)-removed), 0) + room := max(editor.maxRunes-(editor.runes.Len()-removed), 0) if len(replacement) > room { replacement = replacement[:room] } } change := textChange{ start: target.Start, - removed: append([]rune(nil), editor.runes[target.Start:target.End]...), + removed: append([]rune(nil), editor.runes.Slice(target.Start, target.End)...), inserted: replacement, } edit := editor.prepareEdit(target.Start, target.End, replacement) @@ -636,15 +636,7 @@ func (editor *Editor) replaceRunes(target Range, replacement []rune, overwrite b } editor.spliceText(target.Start, target.End, replacement) editor.offsets.trim(target.Start) - delta := len(replacement) - removed - if delta > 0 { - editor.runes = append(editor.runes, make([]rune, delta)...) - copy(editor.runes[target.End+delta:], editor.runes[target.End:len(editor.runes)-delta]) - } else if delta < 0 { - copy(editor.runes[target.Start+len(replacement):], editor.runes[target.End:]) - editor.runes = editor.runes[:len(editor.runes)+delta] - } - copy(editor.runes[target.Start:], replacement) + editor.runes.Replace(target.Start, target.End, replacement) editor.recordEdit(edit) if lines != nil { editor.recordLineContext(edit, context) @@ -797,8 +789,8 @@ func (editor *Editor) selectionState() editorSelection { } func (editor *Editor) restoreSelection(selection editorSelection) { - editor.anchor = clamp(selection.anchor, 0, len(editor.runes)) - editor.caret = clamp(selection.caret, 0, len(editor.runes)) + editor.anchor = clamp(selection.anchor, 0, editor.runes.Len()) + editor.caret = clamp(selection.caret, 0, editor.runes.Len()) editor.clearSecondary() editor.composing = false editor.releaseCompositionHistory() @@ -1002,8 +994,8 @@ func (editor *Editor) trimHistory() { } func (editor *Editor) replaceExact(start, removed int, replacement []rune) { - start = clamp(start, 0, len(editor.runes)) - end := clamp(start+removed, start, len(editor.runes)) + start = clamp(start, 0, editor.runes.Len()) + end := clamp(start+removed, start, editor.runes.Len()) edit := editor.prepareEdit(start, end, replacement) var lines *lineJournal var context lineContext @@ -1014,18 +1006,10 @@ func (editor *Editor) replaceExact(start, removed int, replacement []rune) { } } if lines != nil && lines.labels != nil { - lines.labels.ops.replace(lines.labels, context.line, editor.runes[start:end], replacement) + lines.labels.ops.replace(lines.labels, context.line, editor.runes.Slice(start, end), replacement) } editor.spliceText(start, end, replacement) - delta := len(replacement) - (end - start) - if delta > 0 { - editor.runes = append(editor.runes, make([]rune, delta)...) - copy(editor.runes[end+delta:], editor.runes[end:len(editor.runes)-delta]) - } else if delta < 0 { - copy(editor.runes[start+len(replacement):], editor.runes[end:]) - editor.runes = editor.runes[:len(editor.runes)+delta] - } - copy(editor.runes[start:], replacement) + editor.runes.Replace(start, end, replacement) editor.lastReplaceStart = start editor.offsets.trim(start) editor.recordEdit(edit) diff --git a/text/lf_labels.go b/text/lf_labels.go index 490a0950f..3a3222376 100644 --- a/text/lf_labels.go +++ b/text/lf_labels.go @@ -72,7 +72,7 @@ func (editor *Editor) TrackLFLabels(labels []byte, defaultLabel byte, mapper LFL if editor == nil || editor.composing || editor.CanUndo() || editor.CanRedo() || editor.lfLabelState() != nil || editor.journal != nil && editor.journal.private { return false } - if countLabelLF(editor.runes) != len(labels) { + if countLabelLF(editor.runes.View()) != len(labels) { return false } editor.TrackLineEdits() diff --git a/text/line_journal.go b/text/line_journal.go index bbb9b425a..67dc59407 100644 --- a/text/line_journal.go +++ b/text/line_journal.go @@ -119,23 +119,23 @@ func (editor *Editor) prepareLineContext(start, end int, replacement []rune) lin } lines := editor.journal.lines position, line := lines.position, lines.line - if position > len(editor.runes) || start < position && start <= position-start { + if position > editor.runes.Len() || start < position && start <= position-start { position, line = 0, 0 } for position < start { - if editor.runes[position] == '\n' { + if editor.runes.At(position) == '\n' { line++ } position++ } for position > start { position-- - if editor.runes[position] == '\n' { + if editor.runes.At(position) == '\n' { line-- } } lines.position, lines.line = start, line - return makeLineContext(line, start == 0 || editor.runes[start-1] == '\n', editor.runes[start:end], replacement) + return makeLineContext(line, start == 0 || editor.runes.At(start-1) == '\n', editor.runes.Slice(start, end), replacement) } func makeLineContext(line int, atLineStart bool, removed, inserted []rune) lineContext { diff --git a/text/multi_replace.go b/text/multi_replace.go index 05739afe6..3606e010e 100644 --- a/text/multi_replace.go +++ b/text/multi_replace.go @@ -50,9 +50,9 @@ func (editor *Editor) ValidateReplaceRanges(edits []Replacement, options Replace return fmt.Errorf("cannot replace ranges in a restricted editor") } previousStart, previousEnd := -1, -1 - resultingRunes := len(editor.runes) + resultingRunes := editor.runes.Len() for index, edit := range edits { - if edit.Range.Start < 0 || edit.Range.End < edit.Range.Start || edit.Range.End > len(editor.runes) || + if edit.Range.Start < 0 || edit.Range.End < edit.Range.Start || edit.Range.End > editor.runes.Len() || index > 0 && (edit.Range.Start <= previousStart || edit.Range.Start < previousEnd) { return fmt.Errorf("invalid or overlapping replacement at index %d", index) } @@ -96,19 +96,19 @@ func (editor *Editor) ReplaceRangesWith(edits []Replacement, options ReplaceRang var labelSpans []lfLabelSpan for _, edit := range edits { for runePosition < edit.Range.Start { - if contexts != nil && editor.runes[runePosition] == '\n' { + if contexts != nil && editor.runes.At(runePosition) == '\n' { linePosition++ } - bytePosition += runeBytes(editor.runes[runePosition]) + bytePosition += runeBytes(editor.runes.At(runePosition)) runePosition++ } primitive := Edit{Start: bytePosition} sourceLine := linePosition for runePosition < edit.Range.End { - if contexts != nil && editor.runes[runePosition] == '\n' { + if contexts != nil && editor.runes.At(runePosition) == '\n' { linePosition++ } - width := runeBytes(editor.runes[runePosition]) + width := runeBytes(editor.runes.At(runePosition)) primitive.Removed += width bytePosition += width runePosition++ @@ -117,13 +117,13 @@ func (editor *Editor) ReplaceRangesWith(edits []Replacement, options ReplaceRang for _, character := range inserted { primitive.Inserted += runeBytes(character) } - replacement = append(replacement, editor.runes[position:edit.Range.Start]...) + replacement = append(replacement, editor.runes.Slice(position, edit.Range.Start)...) if primitive.Removed != 0 || primitive.Inserted != 0 { primitives = append(primitives, primitive) if contexts != nil { - atLineStart := edit.Range.Start == 0 || editor.runes[edit.Range.Start-1] == '\n' + atLineStart := edit.Range.Start == 0 || editor.runes.At(edit.Range.Start-1) == '\n' if options.Forward { - atLineStart = start == 0 || editor.runes[start-1] == '\n' + atLineStart = start == 0 || editor.runes.At(start-1) == '\n' if len(replacement) > 0 { atLineStart = replacement[len(replacement)-1] == '\n' } @@ -132,18 +132,18 @@ func (editor *Editor) ReplaceRangesWith(edits []Replacement, options ReplaceRang if options.Forward { line += lineShift } - context := makeLineContext(line, atLineStart, editor.runes[edit.Range.Start:edit.Range.End], inserted) + context := makeLineContext(line, atLineStart, editor.runes.Slice(edit.Range.Start, edit.Range.End), inserted) contexts = append(contexts, context) lineShift += context.inserted - context.removed if labels != nil && (context.removed != 0 || context.inserted != 0) { - labelSpans = append(labelSpans, lfLabelSpan{line: line, removed: editor.runes[edit.Range.Start:edit.Range.End], inserted: inserted}) + labelSpans = append(labelSpans, lfLabelSpan{line: line, removed: editor.runes.Slice(edit.Range.Start, edit.Range.End), inserted: inserted}) } } } replacement = append(replacement, inserted...) position = edit.Range.End } - changed := !slices.Equal(replacement, editor.runes[start:end]) + changed := !slices.Equal(replacement, editor.runes.Slice(start, end)) if !options.Forward { slices.Reverse(labelSpans) } @@ -175,7 +175,7 @@ func (editor *Editor) ReplaceRangesWith(edits []Replacement, options ReplaceRang } func (editor *Editor) commitBatch(target Range, replacement string, primitives []Edit, contexts []lineContext, after *Range, labelPlan *lfLabelPlan) { - target = normalizeRange(target, len(editor.runes)) + target = normalizeRange(target, editor.runes.Len()) // Empty targets do not become primitives. Retain only the accepted backing // in producer mode, including the line contexts keyed by that same slice. if editor.historyState() != nil { diff --git a/text/multiselection.go b/text/multiselection.go index 191f02120..dc75caec2 100644 --- a/text/multiselection.go +++ b/text/multiselection.go @@ -104,8 +104,8 @@ func (editor *Editor) AddSelection(selection Range) bool { } states := editor.selectionStates() states = append(states, editorSelection{ - anchor: clamp(selection.Start, 0, len(editor.runes)), - caret: clamp(selection.End, 0, len(editor.runes)), + anchor: clamp(selection.Start, 0, editor.runes.Len()), + caret: clamp(selection.End, 0, editor.runes.Len()), }) merged, main := normalizeSelections(states, len(states)-1) previous, _ := normalizeSelections(editor.selectionStates(), 0) @@ -146,8 +146,8 @@ func (editor *Editor) SetSelections(selections []Range, main int) bool { states := make([]editorSelection, len(selections)) for index, selection := range selections { states[index] = editorSelection{ - anchor: clamp(selection.Start, 0, len(editor.runes)), - caret: clamp(selection.End, 0, len(editor.runes)), + anchor: clamp(selection.Start, 0, editor.runes.Len()), + caret: clamp(selection.End, 0, editor.runes.Len()), } } merged, mergedMain := normalizeSelections(states, main) @@ -353,17 +353,17 @@ func (editor *Editor) multiDelete(forward bool) bool { start, end := selection.from(), selection.to() if start == end { if forward { - limit := len(editor.runes) + limit := editor.runes.Len() if index+1 < len(ordered) { limit = ordered[index+1].from() } - end = min(nextBoundary(editor.runes, end), limit) + end = min(editor.runes.Next(end), limit) } else { limit := 0 if index > 0 { limit = ordered[index-1].to() } - start = max(previousBoundary(editor.runes, start), limit) + start = max(editor.runes.Prev(start), limit) } } edits[index] = multiEdit{start: start, end: end} diff --git a/text/offsets.go b/text/offsets.go index ba20f8a5b..ff8cb3bdc 100644 --- a/text/offsets.go +++ b/text/offsets.go @@ -23,18 +23,18 @@ func (memo *offsetMemo) trim(start int) { // text from every rune encodes the whole document; and an input method's many // small edits between two reads cost one rebuild, not one copy each. func (editor *Editor) spliceText(start, end int, replacement []rune) { - tail := len(editor.runes) - end + tail := editor.runes.Len() - end switch { case editor.textValid: editor.keepPrefix, editor.keepSuffix = start, tail - editor.keepSuffixBytes = len(editor.text) - editor.byteAt(start) - runesBytes(editor.runes[start:end]) + editor.keepSuffixBytes = len(editor.text) - editor.byteAt(start) - runesBytes(editor.runes.Slice(start, end)) editor.textValid, editor.textBase = false, true case editor.textBase: editor.keepPrefix = min(editor.keepPrefix, start) if tail < editor.keepSuffix { // The edit reaches into the kept tail: what it covers of it is no // longer the cached text's. - editor.keepSuffixBytes -= runesBytes(editor.runes[len(editor.runes)-editor.keepSuffix : end]) + editor.keepSuffixBytes -= runesBytes(editor.runes.Slice(editor.runes.Len()-editor.keepSuffix, end)) editor.keepSuffix = tail } } @@ -44,11 +44,11 @@ func (editor *Editor) spliceText(start, end int, replacement []rune) { // runes between them when it has them, else from every rune. func (editor *Editor) rebuildText() { if editor.textBase { - middle := editor.runes[editor.keepPrefix : len(editor.runes)-editor.keepSuffix] + middle := editor.runes.Slice(editor.keepPrefix, editor.runes.Len()-editor.keepSuffix) head := editor.prefixBytes(editor.keepPrefix) editor.text = editor.text[:head] + string(middle) + editor.text[len(editor.text)-editor.keepSuffixBytes:] } else { - editor.text = string(editor.runes) + editor.text = editor.runes.String() } editor.textValid, editor.textBase = true, false } @@ -62,7 +62,7 @@ func (editor *Editor) prefixBytes(index int) int { at, offset = editor.offsets.index, editor.offsets.offset } for ; at < index; at++ { - offset += runeBytes(editor.runes[at]) + offset += runeBytes(editor.runes.At(at)) } editor.offsets = offsetMemo{index: index, offset: offset} return offset @@ -85,16 +85,16 @@ func (editor *Editor) byteAt(index int) int { if index <= at-index { at, offset = 0, 0 } - } else if len(editor.runes)-index < index-at { - at, offset = len(editor.runes), len(editor.text) + } else if editor.runes.Len()-index < index-at { + at, offset = editor.runes.Len(), len(editor.text) } for at < index { - offset += runeBytes(editor.runes[at]) + offset += runeBytes(editor.runes.At(at)) at++ } for at > index { at-- - offset -= runeBytes(editor.runes[at]) + offset -= runeBytes(editor.runes.At(at)) } editor.offsets = offsetMemo{index: at, offset: offset} return offset @@ -107,15 +107,15 @@ func (editor *Editor) byteAt(index int) int { // for a caret that moves or types a little costs a few runes however long the // text is. func (editor *Editor) ByteOffset(index int) int { - index = clamp(index, 0, len(editor.runes)) + index = clamp(index, 0, editor.runes.Len()) value := editor.String() at, offset := editor.offsets.index, editor.offsets.offset if index < at { if index <= at-index { at, offset = 0, 0 } - } else if len(editor.runes)-index < index-at { - at, offset = len(editor.runes), len(value) + } else if editor.runes.Len()-index < index-at { + at, offset = editor.runes.Len(), len(value) } for at < index { _, size := utf8.DecodeRuneInString(value[offset:]) @@ -143,7 +143,7 @@ func (editor *Editor) RuneIndex(offset int) int { at, from = 0, 0 } } else if len(value)-offset < offset-from { - at, from = len(editor.runes), len(value) + at, from = editor.runes.Len(), len(value) } for from < offset { _, size := utf8.DecodeRuneInString(value[from:]) diff --git a/text/store.go b/text/store.go new file mode 100644 index 000000000..94b890dc3 --- /dev/null +++ b/text/store.go @@ -0,0 +1,44 @@ +package text + +import "github.com/vivaui/viva/internal/grapheme" + +// runeStore is the editor's text as runes: what Range, Caret and Selection count. +// The editor reads and changes it only through these methods, so how the text is +// held stays its own business (ADR 0092). +type runeStore struct{ runes []rune } + +// Len is the number of runes. +func (store *runeStore) Len() int { return len(store.runes) } + +// At is the rune at index. +func (store *runeStore) At(index int) rune { return store.runes[index] } + +// Slice is runes [start, end). It is valid until the next change of the text and +// must not be changed. +func (store *runeStore) Slice(start, end int) []rune { return store.runes[start:end] } + +// View is every rune, under Slice's rules: for code that walks the whole text. +func (store *runeStore) View() []rune { return store.runes } + +// Next is the grapheme cluster boundary after start; Prev the one before end. +func (store *runeStore) Next(start int) int { return grapheme.NextRunes(store.runes, start) } +func (store *runeStore) Prev(end int) int { return grapheme.PrevRunes(store.runes, end) } + +// Replace makes runes [start, end) replacement. +func (store *runeStore) Replace(start, end int, replacement []rune) { + delta := len(replacement) - (end - start) + if delta > 0 { + store.runes = append(store.runes, make([]rune, delta)...) + copy(store.runes[end+delta:], store.runes[end:len(store.runes)-delta]) + } else if delta < 0 { + copy(store.runes[start+len(replacement):], store.runes[end:]) + store.runes = store.runes[:len(store.runes)+delta] + } + copy(store.runes[start:], replacement) +} + +// String is the text as UTF-8. +func (store *runeStore) String() string { return string(store.runes) } + +// Reset makes the text value. +func (store *runeStore) Reset(value []rune) { store.runes = value } diff --git a/text/text_cache_test.go b/text/text_cache_test.go index 0d37d53c2..eb947d71e 100644 --- a/text/text_cache_test.go +++ b/text/text_cache_test.go @@ -51,7 +51,7 @@ func TestStringStaysTheTextAcrossEdits(t *testing.T) { if random.IntN(3) == 0 { continue // edits between two Strings still keep the cache right } - if got, want := editor.String(), string(editor.runes); got != want { + if got, want := editor.String(), editor.runes.String(); got != want { t.Fatalf("round %d step %d: String() = %q, the runes spell %q", round, step, got, want) } } diff --git a/text/transaction.go b/text/transaction.go index 2f5bf89e6..e63abaf3a 100644 --- a/text/transaction.go +++ b/text/transaction.go @@ -56,7 +56,7 @@ func (editor *Editor) Transact(apply func(*Editor) error) error { } value := draft.String() after := Range{Start: draft.anchor, End: draft.caret} - target := Range{End: len(editor.runes)} + target := Range{End: editor.runes.Len()} if err := editor.ValidateReplaceRanges([]Replacement{{Range: target, Text: value}}, ReplaceRangesOptions{AfterSelection: &after}); err != nil { return err } diff --git a/text/visual.go b/text/visual.go index c259890be..ea66a5dc3 100644 --- a/text/visual.go +++ b/text/visual.go @@ -15,7 +15,7 @@ func (editor *Editor) stepLeft(caret int) int { if next, ok := editor.visualStep(caret, -1); ok { return next } - return previousBoundary(editor.runes, caret) + return editor.runes.Prev(caret) } // stepRight is stepLeft to the right. @@ -23,7 +23,7 @@ func (editor *Editor) stepRight(caret int) int { if next, ok := editor.visualStep(caret, 1); ok { return next } - return nextBoundary(editor.runes, caret) + return editor.runes.Next(caret) } // visualStep moves the caret to the nearest place to its left or right on the screen in a @@ -35,13 +35,13 @@ func (editor *Editor) stepRight(caret int) int { // are one stop. func (editor *Editor) visualStep(caret, direction int) (int, bool) { lineStart, lineEnd := caret, caret - for lineStart > 0 && editor.runes[lineStart-1] != '\n' { + for lineStart > 0 && editor.runes.At(lineStart-1) != '\n' { lineStart-- } - for lineEnd < len(editor.runes) && editor.runes[lineEnd] != '\n' { + for lineEnd < editor.runes.Len() && editor.runes.At(lineEnd) != '\n' { lineEnd++ } - lineRunes := editor.runes[lineStart:lineEnd] + lineRunes := editor.runes.Slice(lineStart, lineEnd) if !bidi.NeedsBidiRunes(lineRunes) { return 0, false } @@ -125,7 +125,7 @@ func (editor *Editor) visualStep(caret, direction int) (int, bool) { return leading(k) } byteOffset := 0 - for _, r := range editor.runes[lineStart:caret] { + for _, r := range editor.runes.Slice(lineStart, caret) { byteOffset += utf8.RuneLen(r) } current := index(byteOffset) From 59c733f242e7c4d0f60fc9ebdeb95ef007a989d6 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 22 Nov 2026 10:52:55 +0800 Subject: [PATCH 07/64] perf(text): keep the editor's text as UTF-8 leaves The editor kept its text as one []rune (four bytes a character) next to the cached String, and every edit moved the rune array's tail. The rune store now holds UTF-8 in leaves of about 2 KiB, each counting its runes, bytes, UTF-16 units and newlines, with running totals over the leaves: rune index, byte offset, UTF-16 offset and line convert through a binary search and a walk inside one leaf, an edit inside a leaf is made in place, and String rebuilds only the edited span in one copy. ByteOffset, RuneIndex, the UTF-16 conversions, line starts and ends and the line journal read the store instead of walking runes from a remembered offset. The input method planner reads the text, and the text before its tentative suffix, through a small interface instead of materialising every rune once per event. Public API is unchanged (indexes are still runes). Measured on M2 Pro: retained memory 3.3 -> 1.0 bytes per byte of text at 1 MiB and 16 MiB; an insert and delete in a 1 MiB document 254 -> ~150 us; arrow keys on a short mixed line cost ~60 ns more per step. ADR 0092 step 2. --- internal/bidi/bidi.go | 19 -- internal/bidi/bidi_test.go | 13 - text/code.go | 14 +- text/composition.go | 156 ++++-------- text/edit_journal.go | 28 +-- text/editing.go | 18 +- text/editor.go | 64 ++--- text/history_journal.go | 5 +- text/lf_labels.go | 2 +- text/line_journal.go | 29 +-- text/offsets.go | 153 ++---------- text/rune_text.go | 129 ++++++++++ text/store.go | 499 +++++++++++++++++++++++++++++++++++-- text/store_test.go | 141 +++++++++++ text/visual.go | 19 +- 15 files changed, 859 insertions(+), 430 deletions(-) create mode 100644 text/rune_text.go create mode 100644 text/store_test.go diff --git a/internal/bidi/bidi.go b/internal/bidi/bidi.go index 301dfe2aa..ec23a721d 100644 --- a/internal/bidi/bidi.go +++ b/internal/bidi/bidi.go @@ -106,25 +106,6 @@ func NeedsBidi(text string) bool { return false } -// NeedsBidiRunes is NeedsBidi for text already decoded. Callers that hold runes -// and would otherwise convert a line back to a string just to ask use it to -// skip that allocation for every left-to-right line. -func NeedsBidiRunes(text []rune) bool { - for _, r := range text { - switch { - case r < utf8.RuneSelf: - case r <= 0x057F: - case r >= 0x3000 && r <= 0xAFFF: - default: - switch uniprops.Bidi(r) { - case cR, cAL, cAN, cLRE, cLRO, cRLE, cRLO, cPDF, cLRI, cRLI, cFSI, cPDI: - return true - } - } - } - return false -} - // Mirrored returns the character whose glyph is the mirror image of r (rule L4), or r // itself. Apply it to characters at odd levels. func Mirrored(r rune) rune { return uniprops.Mirror(r) } diff --git a/internal/bidi/bidi_test.go b/internal/bidi/bidi_test.go index 9dad4b03f..fcabcff51 100644 --- a/internal/bidi/bidi_test.go +++ b/internal/bidi/bidi_test.go @@ -352,16 +352,3 @@ func FuzzResolve(f *testing.F) { } }) } - -func TestNeedsBidiRunesAgreesWithNeedsBidi(t *testing.T) { - for _, s := range []string{ - "", "hello world", "café 中文 123", "1 + 2 = 3", "a⁧b", "א", "ا", "x١", - "tab\there\n", "‏", "‪", "﷽", "\U00010800", "ééé", "a⁩", "👩‍💻", - "😀中A", "line\nעברית", "\u202eabc", "\ufeff", - } { - runes := []rune(s) - if got, want := NeedsBidiRunes(runes), NeedsBidi(s); got != want { - t.Errorf("%q: NeedsBidiRunes=%v NeedsBidi=%v", s, got, want) - } - } -} diff --git a/text/code.go b/text/code.go index 82ce86c31..7d550d494 100644 --- a/text/code.go +++ b/text/code.go @@ -57,19 +57,13 @@ func isIndentRune(r rune) bool { return r == ' ' || r == '\t' } // lineStartAt is the index of the first rune of the line that contains index. func (editor *Editor) lineStartAt(index int) int { - for index > 0 && editor.runes.At(index-1) != '\n' { - index-- - } - return index + return editor.runes.LineStart(index) } // lineEndAt is the index of the newline that ends the line containing index, or // the length of the text. func (editor *Editor) lineEndAt(index int) int { - for index < editor.runes.Len() && editor.runes.At(index) != '\n' { - index++ - } - return index + return editor.runes.LineEnd(index) } // indentEnd is the index of the first rune of [start, end) that is not a space @@ -196,7 +190,7 @@ func (editor *Editor) InsertNewlineCode(options CodeOptions) { selection := editor.Selection() start := editor.lineStartAt(selection.Start) indentEnd := min(editor.indentEnd(start, selection.Start), selection.Start) - indent := append([]rune(nil), editor.runes.Slice(start, indentEnd)...) + indent := editor.runes.Slice(start, indentEnd) blank := indentEnd == selection.Start // nothing but indentation before the caret extra := false for at := selection.Start; at > start; at-- { @@ -401,7 +395,7 @@ func (editor *Editor) DuplicateLines(up bool) { } first, last := editor.selectedLines() if up { - block := append(append([]rune(nil), editor.runes.Slice(first, last)...), '\n') + block := append(editor.runes.Slice(first, last), '\n') editor.editBlock(Range{Start: first, End: first}, block, editor.anchor, editor.caret) return } diff --git a/text/composition.go b/text/composition.go index a0b9fe487..273d43a7f 100644 --- a/text/composition.go +++ b/text/composition.go @@ -365,7 +365,7 @@ func (editor *Editor) planCompositionEvent(state *compositionState, event Compos case CompositionEmptyCommit: needBase = !state.active } - base := editor.runes.View() + var base runeText = &editor.runes if needBase { var baseOK bool base, baseOK = editor.compositionPlanBase(state) @@ -490,7 +490,7 @@ func (editor *Editor) compositionPlanFits(state *compositionState, plan composit // editor. base is post-rollback text; deleted counts an ordinary pre-start or // explicit deletion before the scalars; grouped counts an implicit selection // deletion that belongs to the first scalar's ordinary unit. -func (editor *Editor) compositionPlanScalars(plan *compositionPlan, base []rune, start int, text []rune, deleted, grouped int) { +func (editor *Editor) compositionPlanScalars(plan *compositionPlan, base runeText, start int, text []rune, deleted, grouped int) { if len(text) == 0 { return } @@ -516,7 +516,7 @@ func (editor *Editor) compositionPlanScalars(plan *compositionPlan, base []rune, shift -= grouped case overwrite: position := cursor - shift - if cursor < len(base)+shift && position >= 0 && position < len(base) && !compositionLineEnd(base[position]) { + if cursor < base.Len()+shift && position >= 0 && position < base.Len() && !compositionLineEnd(base.At(position)) { plan.payload++ plan.steps += 2 } else { @@ -531,53 +531,48 @@ func (editor *Editor) compositionPlanScalars(plan *compositionPlan, base []rune, } } -// compositionPlanBase reconstructs the text after rolling back the owned -// tentative suffix, without touching the live editor. Inactive events use the -// current text directly. -func (editor *Editor) compositionPlanBase(state *compositionState) ([]rune, bool) { +// compositionPlanBase is the text after rolling back the owned tentative +// suffix, without touching the live editor. Inactive events use the current text +// directly. +func (editor *Editor) compositionPlanBase(state *compositionState) (runeText, bool) { if !state.active { - return editor.runes.View(), true + return &editor.runes, true } - return editor.compositionRollbackRunes(state) + return editor.compositionRollback(state) } -// compositionRollbackRunes reconstructs the post-rollback text in one forward -// pass over the final buffer and the owned suffix units. Each unit's recorded -// start is its final rune position; replacing those inserted segments with the -// recorded removed text restores the pre-event buffer without copying the whole -// document once per unit. The returned slice is owned by the caller. -func (editor *Editor) compositionRollbackRunes(state *compositionState) ([]rune, bool) { +// compositionRollback is the post-rollback text, found in one forward pass over +// the owned suffix units. Each unit's recorded start is its final rune position; +// reading those inserted segments as the recorded removed text is the pre-event +// buffer, without copying the document. It is valid until the next edit or +// rollback. +func (editor *Editor) compositionRollback(state *compositionState) (runeText, bool) { if state == nil || !state.active { - return editor.runes.View(), true + return &editor.runes, true } if state.unitStart < 0 || state.unitStart > len(editor.history) { return nil, false } - final := editor.runes.View() - capacity := len(final) - for index := state.unitStart; index < len(editor.history); index++ { - edit := &editor.history[index] - capacity += len(edit.removed) - len(edit.inserted) - } - if capacity < 0 { - capacity = 0 - } - base := make([]rune, 0, capacity) + final := &editor.runes + base := &editor.rollback + *base = rolledBackText{store: final, pieces: base.pieces[:0]} previous := 0 for index := state.unitStart; index < len(editor.history); index++ { edit := &editor.history[index] start := edit.start - if start < previous || start < 0 || start > len(final) || start+len(edit.inserted) > len(final) { + if start < previous || start < 0 || start > final.Len() || start+len(edit.inserted) > final.Len() { return nil, false } - if !runesEqual(final[start:start+len(edit.inserted)], edit.inserted) { - return nil, false + for offset, character := range edit.inserted { + if final.At(start+offset) != character { + return nil, false + } } - base = append(base, final[previous:start]...) - base = append(base, edit.removed...) + base.add(rolledBackPiece{start: previous, length: start - previous}) + base.add(rolledBackPiece{removed: edit.removed, history: true, length: len(edit.removed)}) previous = start + len(edit.inserted) } - base = append(base, final[previous:]...) + base.add(rolledBackPiece{start: previous, length: final.Len() - previous}) return base, true } @@ -588,11 +583,11 @@ func compositionCommittedText(state *compositionState) (string, bool) { if state == nil || state.owner == nil { return "", false } - committed, ok := state.owner.compositionRollbackRunes(state) + committed, ok := state.owner.compositionRollback(state) if !ok { return "", false } - return string(committed), true + return runeTextString(committed), true } func compositionLineEnd(value rune) bool { @@ -627,17 +622,17 @@ func (editor *Editor) compositionRollbackSteps(state *compositionState) int { } func (editor *Editor) compositionReplacementRange(event CompositionEvent) Range { - return editor.compositionReplacementRangeFor(editor.runes.View(), event) + return editor.compositionReplacementRangeFor(&editor.runes, event) } -func (editor *Editor) compositionReplacementRangeFor(base []rune, event CompositionEvent) Range { +func (editor *Editor) compositionReplacementRangeFor(base runeText, event CompositionEvent) Range { if event.HasReplacementUTF16 { return editor.compositionUTF16RangeFor(base, event.ReplacementUTF16) } if event.HasReplacement { - return normalizeRange(event.Replacement, len(base)) + return normalizeRange(event.Replacement, base.Len()) } - if len(base) == editor.runes.Len() { + if base.Len() == editor.runes.Len() { return editor.Selection() } return Range{Start: editor.caret, End: editor.caret} @@ -967,20 +962,20 @@ func (editor *Editor) compositionReplaceAndInsert(target Range, text []rune) { // the pinned source start-from-zero/relative-length conversion; out-of-range or // split-surrogate boundaries fall to the document end as the E1 contract binds. func (editor *Editor) compositionUTF16Range(raw UTF16Range) Range { - return editor.compositionUTF16RangeFor(editor.runes.View(), raw) + return editor.compositionUTF16RangeFor(&editor.runes, raw) } -func (editor *Editor) compositionUTF16RangeFor(text []rune, raw UTF16Range) Range { - total := editor.compositionUTF16Length(text) - start, startOK := editor.compositionUTF16StartIn(text, raw.Start, total) +func (editor *Editor) compositionUTF16RangeFor(text runeText, raw UTF16Range) Range { + total := text.UTF16Offset(text.Len()) + start, startOK := compositionUTF16StartIn(text, raw.Start, total) if !startOK { // An invalid start maps both ends to the document end. - end := len(text) + end := text.Len() return Range{Start: end, End: end} } - end, endOK := editor.compositionUTF16RelativeIn(text, start, raw.Length) + end, endOK := compositionUTF16RelativeIn(text, start, raw.Length, total) if !endOK { - end = len(text) + end = text.Len() } if end < start { end = start @@ -988,77 +983,28 @@ func (editor *Editor) compositionUTF16RangeFor(text []rune, raw UTF16Range) Rang return Range{Start: start, End: end} } -// compositionUTF16Relative converts a nonnegative code-unit length relative to +// compositionUTF16RelativeIn converts a nonnegative code-unit length relative to // an already resolved rune start. It never adds the raw start and length, so a // huge positive length simply falls to the document end instead of overflowing. -func (editor *Editor) compositionUTF16Relative(start, units int) (int, bool) { - return editor.compositionUTF16RelativeIn(editor.runes.View(), start, units) -} - -func (editor *Editor) compositionUTF16RelativeIn(text []rune, start, units int) (int, bool) { +func compositionUTF16RelativeIn(text runeText, start, units, total int) (int, bool) { if units == 0 { return start, true } - if start < 0 || start > len(text) { + if start < 0 || start > text.Len() { return 0, false } - remaining := units - for index := start; index < len(text); index++ { - width := 1 - if text[index] > 0xffff { - width = 2 - } - if remaining < width { - return 0, false - } - remaining -= width - if remaining == 0 { - return index + 1, true - } + from := text.UTF16Offset(start) + if units < 0 || units > total-from { + return 0, false } - return 0, false + return text.RuneAtUTF16(from + units) } -func (editor *Editor) compositionUTF16Start(units, total int) (int, bool) { - return editor.compositionUTF16StartIn(editor.runes.View(), units, total) -} - -func (editor *Editor) compositionUTF16StartIn(text []rune, units, total int) (int, bool) { +// compositionUTF16StartIn converts a code-unit start measured from zero; one +// past the text or inside a surrogate pair is not a start. +func compositionUTF16StartIn(text runeText, units, total int) (int, bool) { if units < 0 || units > total { return 0, false } - consumed := 0 - for index, character := range text { - width := 1 - if character > 0xffff { - width = 2 - } - if consumed == units { - return index, true - } - if consumed+width > units { - // The raw position splits a surrogate pair. - return 0, false - } - consumed += width - if consumed == units { - return index + 1, true - } - } - if consumed == units { - return len(text), true - } - return 0, false -} - -func (editor *Editor) compositionUTF16Length(text []rune) int { - units := 0 - for _, value := range text { - if value > 0xffff { - units += 2 - } else { - units++ - } - } - return units + return text.RuneAtUTF16(units) } diff --git a/text/edit_journal.go b/text/edit_journal.go index 1868494a2..16c02bdf4 100644 --- a/text/edit_journal.go +++ b/text/edit_journal.go @@ -63,31 +63,11 @@ func (editor *Editor) EditsSince(cursor uint64, dst []Edit) ([]Edit, uint64, boo } func (editor *Editor) prepareEdit(start, end int, replacement []rune) Edit { - if editor.journal == nil || !editor.journal.tracking && editor.historyState() == nil { + if editor.journal == nil || !editor.journal.tracking { return Edit{} } - at, offset := editor.offsets.index, editor.offsets.offset - if start < at && start <= at-start { - at, offset = 0, 0 - } else if start >= at && editor.textValid && editor.runes.Len()-start < start-at { - at, offset = editor.runes.Len(), len(editor.text) - } - for at < start { - offset += runeBytes(editor.runes.At(at)) - at++ - } - for at > start { - at-- - offset -= runeBytes(editor.runes.At(at)) - } - editor.offsets = offsetMemo{index: start, offset: offset} - if !editor.journal.tracking { - return Edit{} - } - edit := Edit{Start: offset} - for _, character := range editor.runes.Slice(start, end) { - edit.Removed += runeBytes(character) - } + offset := editor.runes.ByteOffset(start) + edit := Edit{Start: offset, Removed: editor.runes.ByteOffset(end) - offset} for _, character := range replacement { edit.Inserted += runeBytes(character) } @@ -124,7 +104,7 @@ func (editor *Editor) recordBatchEdits(primitives []Edit, contexts []lineContext start := journal.revision lines := journal.lines if lines != nil { - lines.position, lines.line, lines.delivery = 0, 0, nil + lines.delivery = nil } if inverse { for index := len(primitives) - 1; index >= 0; index-- { diff --git a/text/editing.go b/text/editing.go index 87c7ebd3e..6328aca88 100644 --- a/text/editing.go +++ b/text/editing.go @@ -189,18 +189,12 @@ func (editor *Editor) insideCRLF(at int) bool { // lineBoundary finds the logical line's start or the first rune of its LF or // CRLF ending, or the end of the text. func (editor *Editor) lineBoundary(end bool) int { - at := editor.caret - if end { - for at < editor.runes.Len() && editor.runes.At(at) != '\n' { - at++ - } - if at > 0 && at < editor.runes.Len() && editor.runes.At(at-1) == '\r' { - at-- - } - } else { - for at > 0 && editor.runes.At(at-1) != '\n' { - at-- - } + if !end { + return editor.runes.LineStart(editor.caret) + } + at := editor.runes.LineEnd(editor.caret) + if at > 0 && at < editor.runes.Len() && editor.runes.At(at-1) == '\r' { + at-- } return at } diff --git a/text/editor.go b/text/editor.go index 9d9d0f4aa..ec4f755f1 100644 --- a/text/editor.go +++ b/text/editor.go @@ -109,17 +109,16 @@ type Editor struct { text string textValid bool // textBase says text is the value as it was before the edits since, and - // that its first keepPrefix runes and its last keepSuffix runes (the last - // keepSuffixBytes bytes) are still the value's: String then rebuilds only - // what lies between, once, however many edits came between two reads. - textBase bool - keepPrefix, keepSuffix, keepSuffixBytes int - - // offsets remembers the last rune/byte pair ByteOffset and RuneIndex - // resolved, so a caret that moves or types a little is found by walking from - // there instead of from the start; every mutation of runes trims it. - offsets offsetMemo + // that its first keepPrefixBytes and last keepSuffixBytes bytes are still + // the value's: String then rebuilds only what lies between, once, however + // many edits came between two reads. + textBase bool + keepPrefixBytes, keepSuffixBytes int + journal *editJournal + // rollback is the composition planner's reading of the text before the + // tentative suffix, reused from event to event. + rollback rolledBackText history []historyEdit historyIndex int @@ -137,9 +136,9 @@ type Editor struct { // NewEditor creates an editor with its caret at the end of initial text. func NewEditor(initial string) *Editor { - runes := []rune(initial) - end := len(runes) - return &Editor{runes: runeStore{runes: runes}, anchor: end, caret: end} + editor := &Editor{runes: newRuneStore(initial)} + editor.anchor, editor.caret = editor.runes.Len(), editor.runes.Len() + return editor } // String returns the current UTF-8 text. The conversion is cached until the @@ -523,39 +522,14 @@ func (editor *Editor) MoveRight(extend bool) bool { // RuneIndexToUTF16 converts a rune index to a native UTF-16 code-unit index. func (editor *Editor) RuneIndexToUTF16(index int) int { - index = clamp(index, 0, editor.runes.Len()) - units := 0 - for _, value := range editor.runes.Slice(0, index) { - if value > 0xffff { - units += 2 - } else { - units++ - } - } - return units + return editor.runes.UTF16Offset(index) } // UTF16ToRuneIndex converts a native UTF-16 code-unit index to the nearest // preceding rune boundary. func (editor *Editor) UTF16ToRuneIndex(units int) int { - if units <= 0 { - return 0 - } - consumed := 0 - for index, value := range editor.runes.View() { - width := 1 - if value > 0xffff { - width = 2 - } - if consumed+width > units { - return index - } - consumed += width - if consumed == units { - return index + 1 - } - } - return editor.runes.Len() + index, _ := editor.runes.RuneAtUTF16(units) + return index } func (editor *Editor) deleteSelectionOrComposition() bool { @@ -619,7 +593,7 @@ func (editor *Editor) replaceRunes(target Range, replacement []rune, overwrite b } change := textChange{ start: target.Start, - removed: append([]rune(nil), editor.runes.Slice(target.Start, target.End)...), + removed: editor.runes.Slice(target.Start, target.End), inserted: replacement, } edit := editor.prepareEdit(target.Start, target.End, replacement) @@ -634,8 +608,7 @@ func (editor *Editor) replaceRunes(target Range, replacement []rune, overwrite b if lines != nil && lines.labels != nil { lines.labels.ops.replace(lines.labels, context.line, change.removed, replacement) } - editor.spliceText(target.Start, target.End, replacement) - editor.offsets.trim(target.Start) + editor.spliceText(target.Start, target.End) editor.runes.Replace(target.Start, target.End, replacement) editor.recordEdit(edit) if lines != nil { @@ -1008,10 +981,9 @@ func (editor *Editor) replaceExact(start, removed int, replacement []rune) { if lines != nil && lines.labels != nil { lines.labels.ops.replace(lines.labels, context.line, editor.runes.Slice(start, end), replacement) } - editor.spliceText(start, end, replacement) + editor.spliceText(start, end) editor.runes.Replace(start, end, replacement) editor.lastReplaceStart = start - editor.offsets.trim(start) editor.recordEdit(edit) if lines != nil { editor.recordLineContext(edit, context) diff --git a/text/history_journal.go b/text/history_journal.go index 5e1ae4e14..7bd3b4f39 100644 --- a/text/history_journal.go +++ b/text/history_journal.go @@ -189,10 +189,7 @@ func (editor *Editor) historyChangePrimitive(change textChange, kind editKind) ( if editor.historyState() == nil { return Edit{}, false } - position := editor.offsets.offset - if editor.offsets.index != change.start { - position = editor.ByteOffset(change.start) - } + position := editor.runes.ByteOffset(change.start) removed, inserted := historyRuneBytes(change.removed), historyRuneBytes(change.inserted) return Edit{Start: position, Removed: removed, Inserted: inserted}, removed != 0 || inserted != 0 } diff --git a/text/lf_labels.go b/text/lf_labels.go index 3a3222376..deedc0686 100644 --- a/text/lf_labels.go +++ b/text/lf_labels.go @@ -72,7 +72,7 @@ func (editor *Editor) TrackLFLabels(labels []byte, defaultLabel byte, mapper LFL if editor == nil || editor.composing || editor.CanUndo() || editor.CanRedo() || editor.lfLabelState() != nil || editor.journal != nil && editor.journal.private { return false } - if countLabelLF(editor.runes.View()) != len(labels) { + if editor.runes.Newlines() != len(labels) { return false } editor.TrackLineEdits() diff --git a/text/line_journal.go b/text/line_journal.go index 67dc59407..9dcc2d480 100644 --- a/text/line_journal.go +++ b/text/line_journal.go @@ -35,11 +35,10 @@ const ( ) type lineJournal struct { - entries []lineContext - batches map[*Edit][]lineContext - position, line int - delivery *lineDelivery - labels *lfLabelState + entries []lineContext + batches map[*Edit][]lineContext + delivery *lineDelivery + labels *lfLabelState } // TrackLineEdits enables optional LF context on the existing byte journal and @@ -117,25 +116,7 @@ func (editor *Editor) prepareLineContext(start, end int, replacement []rune) lin if editor.journal == nil || editor.journal.lines == nil { return lineContext{} } - lines := editor.journal.lines - position, line := lines.position, lines.line - if position > editor.runes.Len() || start < position && start <= position-start { - position, line = 0, 0 - } - for position < start { - if editor.runes.At(position) == '\n' { - line++ - } - position++ - } - for position > start { - position-- - if editor.runes.At(position) == '\n' { - line-- - } - } - lines.position, lines.line = start, line - return makeLineContext(line, start == 0 || editor.runes.At(start-1) == '\n', editor.runes.Slice(start, end), replacement) + return makeLineContext(editor.runes.Line(start), start == 0 || editor.runes.At(start-1) == '\n', editor.runes.Slice(start, end), replacement) } func makeLineContext(line int, atLineStart bool, removed, inserted []rune) lineContext { diff --git a/text/offsets.go b/text/offsets.go index ff8cb3bdc..c810ebce9 100644 --- a/text/offsets.go +++ b/text/offsets.go @@ -1,163 +1,52 @@ package text -import "unicode/utf8" - -// offsetMemo is one resolved pair of a rune index and the byte offset of that -// rune in String. The zero value is the pair (0, 0), which is always true. -type offsetMemo struct { - index, offset int -} - -// trim drops the pair when an edit at rune index start changed what it counts. -// A pair at or before the edit still holds: nothing before an edit moves. -func (memo *offsetMemo) trim(start int) { - if memo.index > start { - *memo = offsetMemo{} - } -} +import "strings" // spliceText records an edit that replaces runes [start, end) with replacement, -// made before the runes change, against the cached String: the runes before start +// made before the runes change, against the cached String: the bytes before start // and after end are still the cached text's, so the next String keeps them and -// encodes only what changed. Keeping the bytes is a copy, where building the -// text from every rune encodes the whole document; and an input method's many -// small edits between two reads cost one rebuild, not one copy each. -func (editor *Editor) spliceText(start, end int, replacement []rune) { - tail := editor.runes.Len() - end +// copies only what changed from the store. An input method's many small edits +// between two reads cost one rebuild, not one copy each. +func (editor *Editor) spliceText(start, end int) { + head := editor.runes.ByteOffset(start) + tail := editor.runes.Bytes() - editor.runes.ByteOffset(end) switch { case editor.textValid: - editor.keepPrefix, editor.keepSuffix = start, tail - editor.keepSuffixBytes = len(editor.text) - editor.byteAt(start) - runesBytes(editor.runes.Slice(start, end)) + editor.keepPrefixBytes, editor.keepSuffixBytes = head, tail editor.textValid, editor.textBase = false, true case editor.textBase: - editor.keepPrefix = min(editor.keepPrefix, start) - if tail < editor.keepSuffix { - // The edit reaches into the kept tail: what it covers of it is no - // longer the cached text's. - editor.keepSuffixBytes -= runesBytes(editor.runes.Slice(editor.runes.Len()-editor.keepSuffix, end)) - editor.keepSuffix = tail - } + editor.keepPrefixBytes = min(editor.keepPrefixBytes, head) + editor.keepSuffixBytes = min(editor.keepSuffixBytes, tail) } } // rebuildText makes text the value again: from the cached text's kept ends and the -// runes between them when it has them, else from every rune. +// store's bytes between them when it has them, else from the whole store. func (editor *Editor) rebuildText() { if editor.textBase { - middle := editor.runes.Slice(editor.keepPrefix, editor.runes.Len()-editor.keepSuffix) - head := editor.prefixBytes(editor.keepPrefix) - editor.text = editor.text[:head] + string(middle) + editor.text[len(editor.text)-editor.keepSuffixBytes:] + head, tail := editor.keepPrefixBytes, editor.keepSuffixBytes + var builder strings.Builder + builder.Grow(editor.runes.Bytes()) + builder.WriteString(editor.text[:head]) + editor.runes.WriteBytes(&builder, head, editor.runes.Bytes()-tail) + builder.WriteString(editor.text[len(editor.text)-tail:]) + editor.text = builder.String() } else { editor.text = editor.runes.String() } editor.textValid, editor.textBase = true, false } -// prefixBytes is how many bytes the first index runes take, walked from the start -// or from the last offset asked for, which stays valid for the runes before an -// edit. Unlike byteAt it does not read the cached text, which may be stale. -func (editor *Editor) prefixBytes(index int) int { - at, offset := 0, 0 - if editor.offsets.index <= index { - at, offset = editor.offsets.index, editor.offsets.offset - } - for ; at < index; at++ { - offset += runeBytes(editor.runes.At(at)) - } - editor.offsets = offsetMemo{index: index, offset: offset} - return offset -} - -func runesBytes(runes []rune) int { - total := 0 - for _, character := range runes { - total += runeBytes(character) - } - return total -} - -// byteAt is the byte offset of rune index in the cached text, walked from the -// nearest of its start, its end and the last offset asked for, which it then -// remembers. The cached text must be valid. -func (editor *Editor) byteAt(index int) int { - at, offset := editor.offsets.index, editor.offsets.offset - if index < at { - if index <= at-index { - at, offset = 0, 0 - } - } else if editor.runes.Len()-index < index-at { - at, offset = editor.runes.Len(), len(editor.text) - } - for at < index { - offset += runeBytes(editor.runes.At(at)) - at++ - } - for at > index { - at-- - offset -= runeBytes(editor.runes.At(at)) - } - editor.offsets = offsetMemo{index: at, offset: offset} - return offset -} - // ByteOffset converts a rune index, as Caret and Selection count, to the byte // offset of that rune in String: what a component that works on the UTF-8 text -// wants. An index outside the text is clamped. The walk starts from whichever -// of the start of the text, the end and the last answer is nearest, so asking -// for a caret that moves or types a little costs a few runes however long the -// text is. +// wants. An index outside the text is clamped. func (editor *Editor) ByteOffset(index int) int { - index = clamp(index, 0, editor.runes.Len()) - value := editor.String() - at, offset := editor.offsets.index, editor.offsets.offset - if index < at { - if index <= at-index { - at, offset = 0, 0 - } - } else if editor.runes.Len()-index < index-at { - at, offset = editor.runes.Len(), len(value) - } - for at < index { - _, size := utf8.DecodeRuneInString(value[offset:]) - offset += size - at++ - } - for at > index { - _, size := utf8.DecodeLastRuneInString(value[:offset]) - offset -= size - at-- - } - editor.offsets = offsetMemo{index: at, offset: offset} - return offset + return editor.runes.ByteOffset(index) } // RuneIndex converts a byte offset in String to the index of the rune it falls // in: ByteOffset the other way round. An offset inside a multi-byte character // gives the character's index, and one outside the text is clamped. func (editor *Editor) RuneIndex(offset int) int { - value := editor.String() - offset = clamp(offset, 0, len(value)) - at, from := editor.offsets.index, editor.offsets.offset - if offset < from { - if offset <= from-offset { - at, from = 0, 0 - } - } else if len(value)-offset < offset-from { - at, from = editor.runes.Len(), len(value) - } - for from < offset { - _, size := utf8.DecodeRuneInString(value[from:]) - if from+size > offset { - break // offset is inside this rune - } - from += size - at++ - } - for from > offset { - _, size := utf8.DecodeLastRuneInString(value[:from]) - from -= size - at-- - } - editor.offsets = offsetMemo{index: at, offset: from} - return at + return editor.runes.RuneIndex(offset) } diff --git a/text/rune_text.go b/text/rune_text.go new file mode 100644 index 000000000..75b476dae --- /dev/null +++ b/text/rune_text.go @@ -0,0 +1,129 @@ +package text + +import "sort" + +// runeText is text read by rune index without a slice of every rune: the editor's +// store, or the text before an input method's tentative suffix. +type runeText interface { + Len() int + At(index int) rune + // UTF16Offset is the number of UTF-16 units before rune index. + UTF16Offset(index int) int + // RuneAtUTF16 is the rune units UTF-16 units in, and whether units falls on + // a rune boundary. + RuneAtUTF16(units int) (int, bool) +} + +// rolledBackText is the store with the runes of some edits read as the runes they +// replaced: pieces of the store and of history, in order. +type rolledBackText struct { + store *runeStore + pieces []rolledBackPiece + length int +} + +type rolledBackPiece struct { + // at is the piece's first rune in the rolled-back text; start its first rune + // in the store, unless the piece is history's removed runes. + at, start, length int + history bool + removed []rune +} + +func (text *rolledBackText) add(piece rolledBackPiece) { + if piece.length == 0 { + return + } + piece.at = text.length + text.pieces = append(text.pieces, piece) + text.length += piece.length +} + +func (text *rolledBackText) Len() int { return text.length } + +// piece is the index of the piece holding rune index, which is inside the text. +func (text *rolledBackText) piece(index int) int { + return sort.Search(len(text.pieces), func(i int) bool { + return text.pieces[i].at+text.pieces[i].length > index + }) +} + +func (text *rolledBackText) At(index int) rune { + piece := &text.pieces[text.piece(index)] + if piece.history { + return piece.removed[index-piece.at] + } + return text.store.At(piece.start + index - piece.at) +} + +// units is how many UTF-16 units the first count runes of piece take. +func (text *rolledBackText) units(piece *rolledBackPiece, count int) int { + if !piece.history { + return text.store.UTF16Offset(piece.start+count) - text.store.UTF16Offset(piece.start) + } + units := 0 + for _, r := range piece.removed[:count] { + units += utf16Len(r) + } + return units +} + +func (text *rolledBackText) UTF16Offset(index int) int { + units := 0 + for i := range text.pieces { + piece := &text.pieces[i] + if index <= piece.at { + break + } + units += text.units(piece, min(index-piece.at, piece.length)) + } + return units +} + +func (text *rolledBackText) RuneAtUTF16(units int) (int, bool) { + consumed := 0 + for i := range text.pieces { + piece := &text.pieces[i] + width := text.units(piece, piece.length) + if consumed+width <= units { + consumed += width + continue + } + remaining := units - consumed + if !piece.history { + from := text.store.UTF16Offset(piece.start) + index, exact := text.store.RuneAtUTF16(from + remaining) + return piece.at + index - piece.start, exact + } + for offset, r := range piece.removed { + if remaining == 0 { + return piece.at + offset, true + } + if remaining < utf16Len(r) { + return piece.at + offset, false + } + remaining -= utf16Len(r) + } + } + return text.length, consumed == units +} + +// runeTextString is text as a string. +func runeTextString(text runeText) string { + switch text := text.(type) { + case *runeStore: + return text.String() + case *rolledBackText: + var runes []rune + for i := range text.pieces { + piece := &text.pieces[i] + if piece.history { + runes = append(runes, piece.removed...) + } else { + runes = text.store.AppendSlice(runes, piece.start, piece.start+piece.length) + } + } + return string(runes) + } + panic("text: unknown rune text") +} diff --git a/text/store.go b/text/store.go index 94b890dc3..879ab6478 100644 --- a/text/store.go +++ b/text/store.go @@ -1,44 +1,491 @@ package text -import "github.com/vivaui/viva/internal/grapheme" +import ( + "bytes" + "slices" + "sort" + "strings" + "unicode/utf8" -// runeStore is the editor's text as runes: what Range, Caret and Selection count. -// The editor reads and changes it only through these methods, so how the text is -// held stays its own business (ADR 0092). -type runeStore struct{ runes []rune } + "github.com/vivaui/viva/internal/grapheme" +) + +// runeStore is the editor's text: what Range, Caret and Selection count in runes, +// held as UTF-8 in leaves of about leafBytes bytes (ADR 0092). Each leaf knows how +// many runes, UTF-16 units and newlines it holds, and running totals over the +// leaves turn a rune index into a byte offset, a UTF-16 offset or a line in a +// binary search and a walk inside one leaf. An edit rewrites the leaves it +// touches, not the text after it. The editor reads and changes the text only +// through these methods. +type runeStore struct { + leaves []storeLeaf + // sums[i] is the totals before leaf i, valid for i <= summed; an edit lowers + // summed to the first leaf it touched and sums are made again from there + // when next asked for. + sums []storeSums + summed int + total storeSums + cursor storeCursor + scratch []byte + boundaries []rune +} + +type storeLeaf struct { + text []byte + sizes storeSums +} + +type storeSums struct{ runes, bytes, units, newlines int } + +// storeCursor is the last rune found: rune index at byte offset in leaf, so a walk +// that reads neighbours (word and line navigation) decodes from there. +type storeCursor struct{ leaf, index, offset int } + +// leafBytes is a leaf's usual size: an edit grows a leaf to at most twice of it +// before splitting it, and a remainder under a quarter of it joins the next leaf. +const leafBytes = 2048 + +// newRuneStore holds value, each byte that is not UTF-8 read as U+FFFD as a +// conversion to []rune does. +func newRuneStore(value string) runeStore { + var store runeStore + text := []byte(value) + if !utf8.Valid(text) { + text = text[:0:0] + for _, r := range value { + text = utf8.AppendRune(text, r) + } + } + store.leaves = store.split(text) + for index := range store.leaves { + store.total.add(store.leaves[index].sizes) + } + return store +} // Len is the number of runes. -func (store *runeStore) Len() int { return len(store.runes) } +func (store *runeStore) Len() int { return store.total.runes } + +// Bytes is the length of the text in UTF-8. +func (store *runeStore) Bytes() int { return store.total.bytes } + +// Newlines is how many newline runes the text holds. +func (store *runeStore) Newlines() int { return store.total.newlines } // At is the rune at index. -func (store *runeStore) At(index int) rune { return store.runes[index] } +func (store *runeStore) At(index int) rune { + leaf, offset := store.seek(index) + r, _ := utf8.DecodeRune(store.leaves[leaf].text[offset:]) + return r +} -// Slice is runes [start, end). It is valid until the next change of the text and -// must not be changed. -func (store *runeStore) Slice(start, end int) []rune { return store.runes[start:end] } +// Slice is runes [start, end), a slice of its own. +func (store *runeStore) Slice(start, end int) []rune { + return store.AppendSlice(make([]rune, 0, end-start), start, end) +} -// View is every rune, under Slice's rules: for code that walks the whole text. -func (store *runeStore) View() []rune { return store.runes } +// AppendSlice appends runes [start, end) to dst. +func (store *runeStore) AppendSlice(dst []rune, start, end int) []rune { + if start >= end { + return dst + } + leaf, offset := store.seek(start) + for count := end - start; count > 0; { + text := store.leaves[leaf].text + for offset < len(text) && count > 0 { + r, size := utf8.DecodeRune(text[offset:]) + dst = append(dst, r) + offset += size + count-- + } + leaf, offset = leaf+1, 0 + } + return dst +} + +// String is the text. +func (store *runeStore) String() string { + var builder strings.Builder + builder.Grow(store.total.bytes) + store.WriteBytes(&builder, 0, store.total.bytes) + return builder.String() +} + +// WriteBytes writes the text's bytes [from, to) to builder; both are offsets of +// rune starts. +func (store *runeStore) WriteBytes(builder *strings.Builder, from, to int) { + if from >= to { + return + } + store.sum(len(store.leaves)) + leaf := sort.Search(len(store.leaves), func(i int) bool { return store.sums[i+1].bytes > from }) + for offset := from - store.sums[leaf].bytes; from < to; leaf, offset = leaf+1, 0 { + text := store.leaves[leaf].text[offset:] + text = text[:min(len(text), to-from)] + builder.Write(text) + from += len(text) + } +} + +// ByteOffset is the byte offset of rune index; RuneIndex the index of the rune +// byte offset falls in. Both clamp to the text. +func (store *runeStore) ByteOffset(index int) int { + if index <= 0 { + return 0 + } + if index >= store.total.runes { + return store.total.bytes + } + leaf, offset := store.seek(index) + return store.sums[leaf].bytes + offset +} + +func (store *runeStore) RuneIndex(offset int) int { + if offset <= 0 { + return 0 + } + if offset >= store.total.bytes { + return store.total.runes + } + store.sum(len(store.leaves)) + leaf := sort.Search(len(store.leaves), func(i int) bool { return store.sums[i+1].bytes > offset }) // the leaf holding offset + text, index, at := store.leaves[leaf].text, store.sums[leaf].runes, store.sums[leaf].bytes + for i := 0; i < len(text); { + _, size := utf8.DecodeRune(text[i:]) + if at+i+size > offset { + break + } + i += size + index++ + } + return index +} + +// UTF16Offset is the number of UTF-16 units before rune index. +func (store *runeStore) UTF16Offset(index int) int { + if index <= 0 { + return 0 + } + if index >= store.total.runes { + return store.total.units + } + leaf, offset := store.seek(index) + units := store.sums[leaf].units + text := store.leaves[leaf].text + for i := 0; i < offset; { + r, size := utf8.DecodeRune(text[i:]) + units += utf16Len(r) + i += size + } + return units +} + +// RuneAtUTF16 is the index of the rune units UTF-16 units into the text, and +// whether units falls on a rune boundary rather than inside a surrogate pair (the +// index is then the rune holding the pair). +func (store *runeStore) RuneAtUTF16(units int) (index int, exact bool) { + if units <= 0 { + return 0, true + } + if units >= store.total.units { + return store.total.runes, units == store.total.units + } + store.sum(len(store.leaves)) + leaf := sort.Search(len(store.leaves), func(i int) bool { return store.sums[i+1].units > units }) + index, consumed := store.sums[leaf].runes, store.sums[leaf].units + text := store.leaves[leaf].text + for i := 0; i < len(text) && consumed < units; { + r, size := utf8.DecodeRune(text[i:]) + width := utf16Len(r) + if consumed+width > units { + return index, false + } + consumed += width + index++ + i += size + } + return index, true +} + +// LineStart is the index of the first rune of the line holding rune index: just +// after the newline before it, or 0. +func (store *runeStore) LineStart(index int) int { + index = min(index, store.Len()) + if index <= 0 { + return 0 + } + store.sum(len(store.leaves)) + leaf, offset := store.seekEdge(index) + for counted := index; ; leaf-- { + text := store.leaves[leaf].text[:offset] + if at := bytes.LastIndexByte(text, '\n'); at >= 0 { + return counted - utf8.RuneCount(text[at+1:]) + } + if leaf == 0 { + return 0 + } + counted = store.sums[leaf].runes + offset = len(store.leaves[leaf-1].text) + } +} + +// LineEnd is the index of the newline at or after rune index, or the length of +// the text. +func (store *runeStore) LineEnd(index int) int { + if index >= store.Len() { + return store.Len() + } + for leaf, offset := store.seek(max(index, 0)); leaf < len(store.leaves); leaf, offset = leaf+1, 0 { + text := store.leaves[leaf].text[offset:] + if at := bytes.IndexByte(text, '\n'); at >= 0 { + return index + utf8.RuneCount(text[:at]) + } + index += utf8.RuneCount(text) + } + return store.Len() +} + +// Line is how many newlines come before rune index: the line it is on. +func (store *runeStore) Line(index int) int { + if index <= 0 { + return 0 + } + if index >= store.Len() { + return store.Newlines() + } + leaf, offset := store.seek(index) + return store.sums[leaf].newlines + bytes.Count(store.leaves[leaf].text[:offset], newline) +} + +var newline = []byte{'\n'} // Next is the grapheme cluster boundary after start; Prev the one before end. -func (store *runeStore) Next(start int) int { return grapheme.NextRunes(store.runes, start) } -func (store *runeStore) Prev(end int) int { return grapheme.PrevRunes(store.runes, end) } +// A cluster is found in a window of the runes around it, with the context on +// both sides the rules read, widened for a cluster longer than the window. +func (store *runeStore) Next(start int) int { + // Between two ASCII runes other than CR LF there is always a boundary. + if start >= 0 && start < store.Len() && store.At(start) < utf8.RuneSelf { + if start+1 == store.Len() { + return start + 1 + } + if next := store.At(start + 1); next < utf8.RuneSelf && (next != '\n' || store.At(start) != '\r') { + return start + 1 + } + } + for width := 64; ; width *= 4 { + from, to := max(start-width, 0), min(start+width, store.Len()) + store.boundaries = store.AppendSlice(store.boundaries[:0], from, to) + next := grapheme.NextRunes(store.boundaries, start-from) + from + if next < to || to == store.Len() { + return next + } + } +} + +func (store *runeStore) Prev(end int) int { + if end > 0 && end <= store.Len() && store.At(end-1) < utf8.RuneSelf { + if end == 1 { + return 0 + } + if previous := store.At(end - 2); previous < utf8.RuneSelf && (previous != '\r' || store.At(end-1) != '\n') { + return end - 1 + } + } + for width := 64; ; width *= 4 { + from, to := max(end-width, 0), min(end+width, store.Len()) + store.boundaries = store.AppendSlice(store.boundaries[:0], from, to) + previous := grapheme.PrevRunes(store.boundaries, end-from) + from + if previous > from || from == 0 { + return previous + } + } +} // Replace makes runes [start, end) replacement. func (store *runeStore) Replace(start, end int, replacement []rune) { - delta := len(replacement) - (end - start) - if delta > 0 { - store.runes = append(store.runes, make([]rune, delta)...) - copy(store.runes[end+delta:], store.runes[end:len(store.runes)-delta]) - } else if delta < 0 { - copy(store.runes[start+len(replacement):], store.runes[end:]) - store.runes = store.runes[:len(store.runes)+delta] + encoded := store.scratch[:0] + for _, r := range replacement { + encoded = utf8.AppendRune(encoded, r) + } + store.scratch = encoded[:0] + if len(store.leaves) == 0 { + store.leaves = store.split(encoded) + for index := range store.leaves { + store.total.add(store.leaves[index].sizes) + } + return + } + first, startOffset := store.seekEdge(start) + last, endOffset := store.seekEdge(end) + if first == last { + // An edit inside one leaf that stays a leaf's size is made in place; the + // only leaf stays when it is emptied, ready for the next text. + leaf := &store.leaves[first] + if size := len(leaf.text) - (endOffset - startOffset) + len(encoded); (size > 0 || len(store.leaves) == 1) && size <= 2*leafBytes { + removed, added := measure(leaf.text[startOffset:endOffset]), measure(encoded) + leaf.text = slices.Replace(leaf.text, startOffset, endOffset, encoded...) + leaf.sizes.sub(removed) + leaf.sizes.add(added) + store.total.sub(removed) + store.total.add(added) + store.edited(first, startOffset) + return + } + } + // Otherwise the leaves from the one holding start to the one holding end are + // made again from their bytes before start, the replacement and their bytes + // after end. + buffer := append(store.leaves[first].text[:startOffset:startOffset], encoded...) + buffer = append(buffer, store.leaves[last].text[endOffset:]...) + last++ + // A small remainder joins the leaf after it. + if len(buffer) < leafBytes/4 && last < len(store.leaves) && len(buffer)+len(store.leaves[last].text) <= 2*leafBytes { + buffer = append(buffer, store.leaves[last].text...) + last++ + } + made := store.split(buffer) + for index := first; index < last; index++ { + store.total.sub(store.leaves[index].sizes) + } + for index := range made { + store.total.add(made[index].sizes) + } + store.leaves = slices.Replace(store.leaves, first, last, made...) + store.edited(first, 0) +} + +// edited drops what an edit from byte offset in leaf changed: the totals after the +// leaf, and the cursor when it is past the edit. +func (store *runeStore) edited(leaf, offset int) { + if store.summed > leaf { + store.summed = leaf + store.sums = store.sums[:leaf+1] + } + if c := store.cursor; c.leaf > leaf || c.leaf == leaf && c.offset > offset { + store.cursor = storeCursor{leaf: -1} + } +} + +// split cuts text into leaves of about leafBytes on rune boundaries. +func (store *runeStore) split(text []byte) []storeLeaf { + if len(text) == 0 { + return nil + } + count := max((len(text)+leafBytes-1)/leafBytes, 1) + leaves := make([]storeLeaf, 0, count) + for len(text) > 0 { + size := min(len(text), (len(text)+count-len(leaves)-1)/(count-len(leaves))) + for size < len(text) && !utf8.RuneStart(text[size]) { + size++ + } + chunk := append([]byte(nil), text[:size]...) + leaves = append(leaves, storeLeaf{text: chunk, sizes: measure(chunk)}) + text = text[size:] } - copy(store.runes[start:], replacement) + return leaves } -// String is the text as UTF-8. -func (store *runeStore) String() string { return string(store.runes) } +// measure counts text's runes, bytes, UTF-16 units and newlines. +func measure(text []byte) storeSums { + sizes := storeSums{bytes: len(text)} + for i := 0; i < len(text); { + r, size := utf8.DecodeRune(text[i:]) + sizes.runes++ + sizes.units += utf16Len(r) + if r == '\n' { + sizes.newlines++ + } + i += size + } + return sizes +} + +func (sums *storeSums) sub(other storeSums) { + sums.runes -= other.runes + sums.bytes -= other.bytes + sums.units -= other.units + sums.newlines -= other.newlines +} -// Reset makes the text value. -func (store *runeStore) Reset(value []rune) { store.runes = value } +func (sums *storeSums) add(other storeSums) { + sums.runes += other.runes + sums.bytes += other.bytes + sums.units += other.units + sums.newlines += other.newlines +} + +// sum makes the running totals valid up to leaf count. +func (store *runeStore) sum(count int) { + if len(store.sums) == 0 { + store.sums = append(store.sums, storeSums{}) + store.summed = 0 + } + for store.summed < count { + next := store.sums[store.summed] + next.add(store.leaves[store.summed].sizes) + store.sums = append(store.sums[:store.summed+1], next) + store.summed++ + } +} + +// seek finds rune index, which is inside the text: its leaf and byte offset there. +func (store *runeStore) seek(index int) (leaf, offset int) { + c := &store.cursor + if c.leaf >= 0 && c.leaf < len(store.leaves) && c.leaf <= store.summed && len(store.sums) > 0 { + begin := store.sums[c.leaf].runes + if index >= begin && index < begin+store.leaves[c.leaf].sizes.runes { + return store.walk(c.leaf, index) + } + } + store.sum(len(store.leaves)) + leaf = sort.Search(len(store.leaves), func(i int) bool { return store.sums[i+1].runes > index }) + if c.leaf != leaf { + *c = storeCursor{leaf: leaf, index: store.sums[leaf].runes} + } + return store.walk(leaf, index) +} + +// walk finds rune index in leaf from the cursor, the start or the end of it. +func (store *runeStore) walk(leaf, index int) (int, int) { + c := &store.cursor + text := store.leaves[leaf].text + begin := store.sums[leaf].runes + at, offset := c.index, c.offset + if c.leaf != leaf { + at, offset = begin, 0 + } + if end := begin + store.leaves[leaf].sizes.runes; index-begin < abs(index-at) && index-begin <= end-index { + at, offset = begin, 0 + } else if end-index < abs(index-at) { + at, offset = end, len(text) + } + for at < index { + _, size := utf8.DecodeRune(text[offset:]) + offset += size + at++ + } + for at > index { + _, size := utf8.DecodeLastRune(text[:offset]) + offset -= size + at-- + } + *c = storeCursor{leaf: leaf, index: at, offset: offset} + return leaf, offset +} + +// seekEdge is seek for an edge of an edit, which may be the end of the text: the +// end of the last leaf. +func (store *runeStore) seekEdge(index int) (leaf, offset int) { + if index >= store.total.runes { + last := len(store.leaves) - 1 + return last, len(store.leaves[last].text) + } + return store.seek(index) +} + +func abs(value int) int { + if value < 0 { + return -value + } + return value +} diff --git a/text/store_test.go b/text/store_test.go new file mode 100644 index 000000000..6947d6f5c --- /dev/null +++ b/text/store_test.go @@ -0,0 +1,141 @@ +package text + +import ( + "math/rand" + "slices" + "strings" + "testing" + "unicode/utf16" + "unicode/utf8" + + "github.com/vivaui/viva/internal/grapheme" +) + +// TestRuneStoreAgreesWithRunes edits a store and a []rune at random, across leaf +// boundaries and with text that is not UTF-8, and checks every way the editor +// reads the store against the runes. +func TestRuneStoreAgreesWithRunes(t *testing.T) { + alphabet := []rune{'a', 'b', ' ', '\n', '\r', 'é', '中', '😀', 0x301, 0x200d, 0x1f3fd, 0xd800, -1, utf8.MaxRune + 1} + random := rand.New(rand.NewSource(1)) + piece := func(limit int) []rune { + runes := make([]rune, random.Intn(limit)) + for index := range runes { + runes[index] = alphabet[random.Intn(len(alphabet))] + } + return runes + } + valid := func(runes []rune) []rune { + out := make([]rune, len(runes)) + for index, r := range runes { + if !utf8.ValidRune(r) { + r = utf8.RuneError + } + out[index] = r + } + return out + } + var store runeStore + var want []rune + for step := 0; step < 1500; step++ { + start := random.Intn(len(want) + 1) + end := start + random.Intn(len(want)-start+1) + if random.Intn(4) != 0 { + end = min(start+random.Intn(8), len(want)) + } + limit := 16 + if random.Intn(20) == 0 { + limit = 6 * leafBytes + } + replacement := piece(limit) + store.Replace(start, end, replacement) + want = slices.Replace(want, start, end, valid(replacement)...) + + if store.Len() != len(want) || store.String() != string(want) || store.Bytes() != len(string(want)) { + t.Fatalf("step %d: store holds %d runes %q, want %d", step, store.Len(), store.String(), len(want)) + } + if store.Newlines() != countLabelLF(want) { + t.Fatalf("step %d: %d newlines, want %d", step, store.Newlines(), countLabelLF(want)) + } + for probe := 0; probe < 8; probe++ { + index := random.Intn(len(want) + 1) + bytes := len(string(want[:index])) + units := len(utf16.Encode(want[:index])) + if store.ByteOffset(index) != bytes || store.RuneIndex(bytes) != index || store.UTF16Offset(index) != units { + t.Fatalf("step %d: rune %d at byte %d unit %d, want byte %d unit %d", step, index, store.ByteOffset(index), store.UTF16Offset(index), bytes, units) + } + if got, exact := store.RuneAtUTF16(units); got != index || !exact { + t.Fatalf("step %d: unit %d is rune %d, want %d", step, units, got, index) + } + if index < len(want) { + if store.At(index) != want[index] { + t.Fatalf("step %d: rune %d is %q, want %q", step, index, store.At(index), want[index]) + } + if utf8.RuneLen(want[index]) > 1 && store.RuneIndex(bytes+1) != index { + t.Fatalf("step %d: an offset inside rune %d gives %d", step, index, store.RuneIndex(bytes+1)) + } + if want[index] > 0xffff { + if got, exact := store.RuneAtUTF16(units + 1); got != index || exact { + t.Fatalf("step %d: inside a surrogate pair gives %d %v", step, got, exact) + } + } + } + if next := grapheme.NextRunes(want, index); store.Next(index) != next { + t.Fatalf("step %d: cluster after %d ends at %d, want %d", step, index, store.Next(index), next) + } + if previous := grapheme.PrevRunes(want, index); store.Prev(index) != previous { + t.Fatalf("step %d: cluster before %d starts at %d, want %d", step, index, store.Prev(index), previous) + } + lineStart, lineEnd := index, index + for lineStart > 0 && want[lineStart-1] != '\n' { + lineStart-- + } + for lineEnd < len(want) && want[lineEnd] != '\n' { + lineEnd++ + } + if store.LineStart(index) != lineStart || store.LineEnd(index) != lineEnd || store.Line(index) != countLabelLF(want[:index]) { + t.Fatalf("step %d: rune %d on line %d [%d, %d), want %d [%d, %d)", step, index, store.Line(index), store.LineStart(index), store.LineEnd(index), countLabelLF(want[:index]), lineStart, lineEnd) + } + to := index + random.Intn(len(want)-index+1) + if !slices.Equal(store.Slice(index, to), want[index:to]) { + t.Fatalf("step %d: runes [%d, %d) differ", step, index, to) + } + var builder strings.Builder + if store.WriteBytes(&builder, bytes, len(string(want[:to]))); builder.String() != string(want[index:to]) { + t.Fatalf("step %d: bytes of runes [%d, %d) differ", step, index, to) + } + } + if len(want) > 8*leafBytes && random.Intn(3) == 0 { + // Keep the text from growing without bound while it crosses leaves. + store.Replace(0, len(want)/2, nil) + want = want[len(want)/2:] + } + } +} + +// TestRuneStoreRollbackAgreesWithRunes checks the rolled-back reading the input +// method planner uses against the runes it stands for. +func TestRuneStoreRollbackAgreesWithRunes(t *testing.T) { + store := newRuneStore("ab中😀cd\nef😀") + removed := []rune("😀x") + var text rolledBackText + text.store = &store + text.add(rolledBackPiece{start: 0, length: 3}) + text.add(rolledBackPiece{removed: removed, history: true, length: len(removed)}) + text.add(rolledBackPiece{start: 4, length: store.Len() - 4}) + want := append(append([]rune("ab中"), removed...), []rune("cd\nef😀")...) + if text.Len() != len(want) || runeTextString(&text) != string(want) { + t.Fatalf("rolled back to %q, want %q", runeTextString(&text), string(want)) + } + for index := 0; index <= len(want); index++ { + units := len(utf16.Encode(want[:index])) + if index < len(want) && text.At(index) != want[index] { + t.Fatalf("rune %d is %q, want %q", index, text.At(index), want[index]) + } + if text.UTF16Offset(index) != units { + t.Fatalf("rune %d at unit %d, want %d", index, text.UTF16Offset(index), units) + } + if got, exact := text.RuneAtUTF16(units); got != index || !exact { + t.Fatalf("unit %d is rune %d, want %d", units, got, index) + } + } +} diff --git a/text/visual.go b/text/visual.go index ea66a5dc3..4f9cba362 100644 --- a/text/visual.go +++ b/text/visual.go @@ -34,18 +34,12 @@ func (editor *Editor) stepRight(caret int) int { // to the boundary with the next place along the screen; boundaries drawn at the same place // are one stop. func (editor *Editor) visualStep(caret, direction int) (int, bool) { - lineStart, lineEnd := caret, caret - for lineStart > 0 && editor.runes.At(lineStart-1) != '\n' { - lineStart-- - } - for lineEnd < editor.runes.Len() && editor.runes.At(lineEnd) != '\n' { - lineEnd++ - } - lineRunes := editor.runes.Slice(lineStart, lineEnd) - if !bidi.NeedsBidiRunes(lineRunes) { + lineStart, lineEnd := editor.runes.LineStart(caret), editor.runes.LineEnd(caret) + lineOffset := editor.runes.ByteOffset(lineStart) + line := editor.String()[lineOffset:editor.runes.ByteOffset(lineEnd)] + if !bidi.NeedsBidi(line) { return 0, false } - line := string(lineRunes) resolver := &editor.visualResolve paragraph := resolver.Resolve(line, bidi.Auto) runs := resolver.LineRuns(paragraph, 0, len(line), nil) @@ -124,10 +118,7 @@ func (editor *Editor) visualStep(caret, direction int) (int, bool) { } return leading(k) } - byteOffset := 0 - for _, r := range editor.runes.Slice(lineStart, caret) { - byteOffset += utf8.RuneLen(r) - } + byteOffset := editor.runes.ByteOffset(caret) - lineOffset current := index(byteOffset) if current > n || starts[current] != byteOffset { return 0, false From 932c9aae7653841606c3e3c6e6738d1ed911c5ee Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 22 Nov 2026 11:01:15 +0800 Subject: [PATCH 08/64] perf(components): lay out only the lines an edit touched in CodeEditor A CodeEditor laid out every row again whenever Value changed, so one keystroke in a megabyte of text cost about 8.6 ms, longer than a frame. When only the text changed, the editor now finds the edit from the bytes the old and new text share at either end (compared a block at a time), lays out again the logical lines holding it, and moves the rows after them by the bytes and lines it added. Indent guide levels are kept the same way: the edited lines are measured again and the blank lines next to them resolved again. Folds, a change of width, wrap, tab width or representations still take the full layout. The snapshot API is unchanged: callers keep passing Value. Measured on M2 Pro with 1 MiB of text: relayout on edit 8.6 ms -> ~0.11 ms with and without wrapping or indent guides (most of what is left is the benchmark building the new string). ADR 0092 step 3 (CodeEditor part). --- components/code_editor.go | 23 +++- components/code_editor_layout.go | 195 ++++++++++++++++++++++----- components/code_editor_refit_test.go | 58 ++++++++ components/code_editor_test.go | 13 +- 4 files changed, 248 insertions(+), 41 deletions(-) create mode 100644 components/code_editor_refit_test.go diff --git a/components/code_editor.go b/components/code_editor.go index e497dcc58..1fef7b271 100644 --- a/components/code_editor.go +++ b/components/code_editor.go @@ -228,6 +228,14 @@ type CodeEditor struct { shown []string widest int lineCount int + // deadShown counts the entries of shown no row points at any more, left by + // refits; a full layout clears them once they are half of it. + deadShown int + scratchRows []codeRow + // rawIndents is each line's own indentation, -1 when blank, which indents + // resolves blank lines from. + rawIndents []int + scratchIndents []int // What the last paint showed. painted bool @@ -416,8 +424,8 @@ func (editor *CodeEditor) Paint(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx. cols-- } editor.fitWithRepresentations(value, cols, snapshot.Wrap, tabWidth, snapshot.FoldedLines, snapshot.Representations) - if snapshot.ShowIndentGuides && editor.indents == nil { - editor.indents = indentationLevels(editor.text, tabWidth, editor.reps) + if snapshot.ShowIndentGuides { + editor.measureIndents() } editor.content, editor.cellWidth, editor.lineHeight = content, cellWidth, lineHeight @@ -1305,3 +1313,14 @@ func (command CodeEditorCommand) Apply(editor *text.Editor) bool { } return true } + +// measureIndents finds every line's indent guide level once for the laid out +// text; a refit keeps them up to date from then on. +func (editor *CodeEditor) measureIndents() { + if editor.indents != nil { + return + } + editor.rawIndents = appendRawIndents(editor.rawIndents[:0], editor.text, editor.tabWidth, editor.reps) + editor.indents = append(make([]int, 0, len(editor.rawIndents)), editor.rawIndents...) + resolveIndents(editor.indents, editor.rawIndents, 0, len(editor.indents)) +} diff --git a/components/code_editor_layout.go b/components/code_editor_layout.go index b633fe37f..a0b9de986 100644 --- a/components/code_editor_layout.go +++ b/components/code_editor_layout.go @@ -1,6 +1,7 @@ package components import ( + "cmp" "slices" "sort" "strconv" @@ -35,17 +36,10 @@ func codeCells(r rune, column, tabWidth int) int { return text.CellWidth(r) } -// indentationLevels is the leading cells of every line, in the displayed columns -// the layout uses, so a representation that hides or widens a leading tab moves -// the indent guides with the text; a blank line takes the smaller indentation of -// its nearest text lines so guides run through it. -// -// The forward pass stores a blank line as -2-previous, where previous is the -// indentation of the last text line above it (-1 when there is none), so the -// backward pass can resolve it without a second slice. -func indentationLevels(value string, tabWidth int, reps []CodeRepresentation) []int { - levels := make([]int, 0, strings.Count(value, "\n")+1) - previous := -1 +// appendRawIndents appends the leading cells of each line of value, or -1 for a +// blank line, in the displayed columns the layout uses, so a representation that +// hides or widens a leading tab moves the indent guides with the text. +func appendRawIndents(dst []int, value string, tabWidth int, reps []CodeRepresentation) []int { for line := range strings.SplitSeq(value, "\n") { column, blank := 0, true leading: @@ -59,31 +53,50 @@ func indentationLevels(value string, tabWidth int, reps []CodeRepresentation) [] } } if blank { - levels = append(levels, -2-previous) - continue + column = -1 } - levels = append(levels, column) - previous = column + dst = append(dst, column) } - next := -1 - for index := len(levels) - 1; index >= 0; index-- { - if levels[index] >= 0 { - next = levels[index] + return dst +} + +// resolveIndents writes levels[from:to] from the raw indentation of every line: +// a text line keeps its own, and a blank line takes the smaller of the nearest +// text lines above and below it, or the one there is, or 0. levels may be raw. +func resolveIndents(levels, raw []int, from, to int) { + for index := from; index < to; { + if raw[index] >= 0 { + levels[index] = raw[index] + index++ continue } - above := -2 - levels[index] + start, end := index, index + for start > 0 && raw[start-1] < 0 { + start-- + } + for end < len(raw) && raw[end] < 0 { + end++ + } + above, below := -1, -1 + if start > 0 { + above = raw[start-1] + } + if end < len(raw) { + below = raw[end] + } + level := 0 switch { - case above >= 0 && next >= 0: - levels[index] = min(above, next) + case above >= 0 && below >= 0: + level = min(above, below) case above >= 0: - levels[index] = above - case next >= 0: - levels[index] = next - default: - levels[index] = 0 + level = above + case below >= 0: + level = below + } + for ; index < min(end, to); index++ { + levels[index] = level } } - return levels } func representationOf(reps []CodeRepresentation, character rune) (CodeRepresentation, bool) { @@ -127,16 +140,19 @@ func (editor *CodeEditor) fitWithFolds(value string, cols int, wrap bool, tabWid } func (editor *CodeEditor) fitWithRepresentations(value string, cols int, wrap bool, tabWidth int, folds []CodeEditorFoldRange, reps []CodeRepresentation) { - if editor.fitted && editor.cols == cols && editor.wrap == wrap && editor.tabWidth == tabWidth && editor.text == value && slices.Equal(editor.foldInput, folds) && slices.Equal(editor.reps, reps) { - return + if editor.fitted && editor.cols == cols && editor.wrap == wrap && editor.tabWidth == tabWidth && slices.Equal(editor.foldInput, folds) && slices.Equal(editor.reps, reps) { + if editor.text == value || editor.refit(value) { + return + } } editor.fitted, editor.cols, editor.wrap, editor.tabWidth, editor.text = true, cols, wrap, tabWidth, value editor.foldInput = append(editor.foldInput[:0], folds...) editor.reps = append(editor.reps[:0], reps...) editor.folds = editor.folds[:0] editor.rows = editor.rows[:0] - editor.indents = nil + editor.indents, editor.rawIndents = nil, editor.rawIndents[:0] editor.shown = editor.shown[:0] + editor.deadShown = 0 editor.widest = 0 if len(value) > 1<<30 { // Rows are indexed with 32 bits; a text this long is not an editor's. @@ -182,6 +198,123 @@ func (editor *CodeEditor) fitWithRepresentations(value string, cols int, wrap bo editor.runLine = -1 } +// refit lays out again only the logical lines an edit touched, when the text is +// all that changed: the rows before them stand, and the rows after them move by +// the bytes and lines the edit added. It reports false when the text needs a full +// layout instead. +func (editor *CodeEditor) refit(value string) bool { + old := editor.text + if len(editor.folds) > 0 || len(value) > 1<<30 || editor.deadShown > 64 && editor.deadShown > len(editor.shown)/2 { + return false + } + prefix := commonPrefix(old, value) + suffix := commonSuffix(old[prefix:], value[prefix:]) + // The edit replaced old[prefix:len(old)-suffix]; the lines holding it are laid + // out again whole, from the start of the first to the line break after the last. + from := strings.LastIndexByte(old[:prefix], '\n') + 1 + oldTo := len(old) + if newline := strings.IndexByte(old[len(old)-suffix:], '\n'); newline >= 0 { + oldTo = len(old) - suffix + newline + } + delta := len(value) - len(old) + newTo := oldTo + delta + + first, _ := slices.BinarySearchFunc(editor.rows, int32(from), func(row codeRow, at int32) int { return cmp.Compare(row.lineStart, at) }) + last, _ := slices.BinarySearchFunc(editor.rows, int32(oldTo), func(row codeRow, at int32) int { return cmp.Compare(row.lineStart, at+1) }) + // Every logical line has a row, so the first row from the line's start is it. + line := int(editor.rows[first].line) + lostWidest := false + for _, row := range editor.rows[first:last] { + lostWidest = lostWidest || int(row.cells) == editor.widest + if row.shown >= 0 { + editor.deadShown++ + } + } + lines := strings.Count(value[from:newTo], "\n") - strings.Count(old[from:oldTo], "\n") + + // The new lines are laid out after the rows, then moved into place. + editor.text = value + tail := len(editor.rows) + for start := from; ; line++ { + end := newTo + if newline := strings.IndexByte(value[start:newTo], '\n'); newline >= 0 { + end = start + newline + } + rowEnd := end + if end < len(value) && end > start && value[end-1] == '\r' { + rowEnd-- + } + editor.appendLine(value, start, rowEnd, line) + if end >= newTo { + break + } + start = end + 1 + } + made := len(editor.rows) - tail + editor.rows = slices.Grow(editor.rows, made) + editor.scratchRows = append(editor.scratchRows[:0], editor.rows[tail:]...) + editor.rows = slices.Replace(editor.rows[:tail], first, last, editor.scratchRows...) + for index := first + made; index < len(editor.rows); index++ { + row := &editor.rows[index] + row.start += int32(delta) + row.end += int32(delta) + row.lineStart += int32(delta) + row.line += int32(lines) + } + if lostWidest { + editor.widest = 0 + for _, row := range editor.rows { + editor.widest = max(editor.widest, int(row.cells)) + } + } + editor.lineCount += lines + if editor.indents != nil { + // The indentation of the edited lines is measured again, and blank lines + // next to them, which take it from the nearest text lines, resolved again. + firstLine := int(editor.rows[first].line) + oldEnd := firstLine + strings.Count(old[from:oldTo], "\n") + 1 + editor.scratchIndents = appendRawIndents(editor.scratchIndents[:0], value[from:newTo], editor.tabWidth, editor.reps) + editor.rawIndents = slices.Replace(editor.rawIndents, firstLine, oldEnd, editor.scratchIndents...) + editor.indents = slices.Replace(editor.indents, firstLine, oldEnd, editor.scratchIndents...) + before, after := firstLine, firstLine+len(editor.scratchIndents) + for before > 0 && editor.rawIndents[before-1] < 0 { + before-- + } + for after < len(editor.rawIndents) && editor.rawIndents[after] < 0 { + after++ + } + resolveIndents(editor.indents, editor.rawIndents, before, after) + } + editor.runLine = -1 + return true +} + +// commonPrefix is how many leading bytes a and b share, compared a block at a time. +func commonPrefix(a, b string) int { + const block = 1024 + n, at := min(len(a), len(b)), 0 + for at+block <= n && a[at:at+block] == b[at:at+block] { + at += block + } + for at < n && a[at] == b[at] { + at++ + } + return at +} + +// commonSuffix is how many trailing bytes a and b share. +func commonSuffix(a, b string) int { + const block = 1024 + n, at := min(len(a), len(b)), 0 + for at+block <= n && a[len(a)-at-block:len(a)-at] == b[len(b)-at-block:len(b)-at] { + at += block + } + for at < n && a[len(a)-at-1] == b[len(b)-at-1] { + at++ + } + return at +} + // SoftWrapOffsets returns byte offsets where the last painted editor would // wrap its text at its current content width. It does not change the live // editor's rows, scroll position, or selection. diff --git a/components/code_editor_refit_test.go b/components/code_editor_refit_test.go new file mode 100644 index 000000000..261aee7b1 --- /dev/null +++ b/components/code_editor_refit_test.go @@ -0,0 +1,58 @@ +package components + +import ( + "math/rand" + "slices" + "testing" +) + +// TestCodeEditorRefitMatchesFullLayout edits text at random and checks that laying +// out only the edited lines gives the rows a layout of the whole text gives. +func TestCodeEditorRefitMatchesFullLayout(t *testing.T) { + pieces := []string{"a", "bc ", "\n", "\r\n", "\t", "中文", "é", " word ", "\n\n", "x\ty"} + random := rand.New(rand.NewSource(1)) + reps := []CodeRepresentation{{Character: ' ', Label: "·"}} + for _, wrap := range []bool{false, true} { + for _, represented := range []bool{false, true} { + var live CodeEditor + value := "" + var layoutReps []CodeRepresentation + if represented { + layoutReps = reps + } + for step := 0; step < 2000; step++ { + start := random.Intn(len(value) + 1) + end := min(start+random.Intn(6), len(value)) + insert := "" + for range random.Intn(4) { + insert += pieces[random.Intn(len(pieces))] + } + if represented && random.Intn(5) == 0 { + insert += " " + } + value = value[:start] + insert + value[end:] + live.fitWithRepresentations(value, 7, wrap, 4, nil, layoutReps) + live.measureIndents() + var fresh CodeEditor + fresh.fitWithRepresentations(value, 7, wrap, 4, nil, layoutReps) + fresh.measureIndents() + if !slices.Equal(live.indents, fresh.indents) { + t.Fatalf("wrap=%v step %d: indents %v, want %v for %q", wrap, step, live.indents, fresh.indents, value) + } + if len(live.rows) != len(fresh.rows) || live.widest != fresh.widest || live.lineCount != fresh.lineCount { + t.Fatalf("wrap=%v step %d: %d rows widest %d lines %d, want %d rows widest %d lines %d for %q", + wrap, step, len(live.rows), live.widest, live.lineCount, len(fresh.rows), fresh.widest, fresh.lineCount, value) + } + for index := range fresh.rows { + got, want := live.rows[index], fresh.rows[index] + if got.start != want.start || got.end != want.end || got.lineStart != want.lineStart || got.line != want.line || got.cells != want.cells || live.rowText(got) != fresh.rowText(want) { + t.Fatalf("wrap=%v step %d: row %d is %+v %q, want %+v %q", wrap, step, index, got, live.rowText(got), want, fresh.rowText(want)) + } + } + if len(value) > 400 { + value = value[len(value)/2:] + } + } + } + } +} diff --git a/components/code_editor_test.go b/components/code_editor_test.go index 5fc3dbb60..73e147072 100644 --- a/components/code_editor_test.go +++ b/components/code_editor_test.go @@ -1318,19 +1318,16 @@ func benchmarkCodeEditorPaintSteady(b *testing.B, wrapSymbol bool) { } // BenchmarkCodeEditorRelayoutOnEdit is the cost of a keystroke in a megabyte of -// text: the rows are laid out again for the new text. +// text: the rows of the edited line are laid out again for the new text. func BenchmarkCodeEditorRelayoutOnEdit(b *testing.B) { base := strings.Repeat("key: value # comment with some 中文 and a long tail to wrap around the edge of the box\n", 12000) b.SetBytes(int64(len(base))) - for _, wrap := range []bool{false, true} { - name := "no wrap" - if wrap { - name = "wrap" - } - b.Run(name, func(b *testing.B) { + for _, mode := range []string{"no wrap", "wrap", "indent guides"} { + b.Run(mode, func(b *testing.B) { f := newCodeFixture(base) f.bounds = gfx.Rect{Width: 900, Height: 600} - f.snapshot.Wrap = wrap + f.snapshot.Wrap = mode == "wrap" + f.snapshot.ShowIndentGuides = mode == "indent guides" f.paint() b.ReportAllocs() toggle := false From b2bc112e40e15bd5503a04aa87ea7be53dbaf41d Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 22 Nov 2026 11:15:02 +0800 Subject: [PATCH 09/64] fix(text): build a new editor's text with one copy and keep it inlinable 59c733f2 made NewEditor copy its argument twice (to bytes, then into a leaf), rebuild String from the leaves on first read, and grow past the inlining budget, so a short-lived editor no longer stayed on the stack: TestDefaultStateSnapshotPreservesConstructionAllocations went from 2 allocations to 6. Leaves are now cut straight from the string, a UTF-8 initial text is kept as the cached String, and NewEditor is a small wrapper the compiler inlines. --- text/editor.go | 12 ++++++++++-- text/store.go | 26 ++++++++++++++------------ text/store_test.go | 2 +- 3 files changed, 25 insertions(+), 15 deletions(-) diff --git a/text/editor.go b/text/editor.go index ec4f755f1..60b6d899f 100644 --- a/text/editor.go +++ b/text/editor.go @@ -136,11 +136,19 @@ type Editor struct { // NewEditor creates an editor with its caret at the end of initial text. func NewEditor(initial string) *Editor { - editor := &Editor{runes: newRuneStore(initial)} - editor.anchor, editor.caret = editor.runes.Len(), editor.runes.Len() + editor := new(Editor) + editor.start(initial) return editor } +// start gives a new editor its text, with the caret at the end. A UTF-8 initial +// text is already what String returns. +func (editor *Editor) start(initial string) { + editor.runes, editor.textValid = newRuneStore(initial) + editor.text = initial + editor.anchor, editor.caret = editor.runes.Len(), editor.runes.Len() +} + // String returns the current UTF-8 text. The conversion is cached until the // text next changes, so repeated calls between edits allocate nothing. // Like all Editor methods, it is not safe for concurrent use. The returned diff --git a/text/store.go b/text/store.go index 879ab6478..baf3d6f66 100644 --- a/text/store.go +++ b/text/store.go @@ -46,21 +46,22 @@ type storeCursor struct{ leaf, index, offset int } const leafBytes = 2048 // newRuneStore holds value, each byte that is not UTF-8 read as U+FFFD as a -// conversion to []rune does. -func newRuneStore(value string) runeStore { - var store runeStore - text := []byte(value) - if !utf8.Valid(text) { - text = text[:0:0] +// conversion to []rune does; valid says value was UTF-8, so it is the text. +func newRuneStore(value string) (store runeStore, valid bool) { + valid = utf8.ValidString(value) + if valid { + store.leaves = splitLeaves(value) + } else { + var text []byte for _, r := range value { text = utf8.AppendRune(text, r) } + store.leaves = splitLeaves(text) } - store.leaves = store.split(text) for index := range store.leaves { store.total.add(store.leaves[index].sizes) } - return store + return store, valid } // Len is the number of runes. @@ -309,7 +310,7 @@ func (store *runeStore) Replace(start, end int, replacement []rune) { } store.scratch = encoded[:0] if len(store.leaves) == 0 { - store.leaves = store.split(encoded) + store.leaves = splitLeaves(encoded) for index := range store.leaves { store.total.add(store.leaves[index].sizes) } @@ -343,7 +344,7 @@ func (store *runeStore) Replace(start, end int, replacement []rune) { buffer = append(buffer, store.leaves[last].text...) last++ } - made := store.split(buffer) + made := splitLeaves(buffer) for index := first; index < last; index++ { store.total.sub(store.leaves[index].sizes) } @@ -366,8 +367,9 @@ func (store *runeStore) edited(leaf, offset int) { } } -// split cuts text into leaves of about leafBytes on rune boundaries. -func (store *runeStore) split(text []byte) []storeLeaf { +// splitLeaves cuts text into leaves of about leafBytes on rune boundaries, each +// a copy of its bytes. +func splitLeaves[T string | []byte](text T) []storeLeaf { if len(text) == 0 { return nil } diff --git a/text/store_test.go b/text/store_test.go index 6947d6f5c..80c54d70f 100644 --- a/text/store_test.go +++ b/text/store_test.go @@ -115,7 +115,7 @@ func TestRuneStoreAgreesWithRunes(t *testing.T) { // TestRuneStoreRollbackAgreesWithRunes checks the rolled-back reading the input // method planner uses against the runes it stands for. func TestRuneStoreRollbackAgreesWithRunes(t *testing.T) { - store := newRuneStore("ab中😀cd\nef😀") + store, _ := newRuneStore("ab中😀cd\nef😀") removed := []rune("😀x") var text rolledBackText text.store = &store From 488544f91218ff66f8d4901fdf1932889b98f4fd Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 22 Nov 2026 11:15:02 +0800 Subject: [PATCH 10/64] fix(app): show a focus change the paint itself made in the same frame A newly appearing Autofocus hit, a paint-time RequestFocus or ReleaseFocus, or a ReturnFocus scope closing moved the focus only when publish synced it, after the frame was painted: the frame showed the old focus and nothing painted again until the next event. repaint now settles the focus before publishing (sync, and paint again if the focus moved, at most twice), covering the cases it already handled for carried requests and modal scopes. The hit comparison is remembered for the paint, so settling and publishing compare the list once. --- app/painter.go | 94 +++++++++++++++++++---------- app/painter_focus_converge_test.go | 97 ++++++++++++++++++++++++++++++ 2 files changed, 159 insertions(+), 32 deletions(-) create mode 100644 app/painter_focus_converge_test.go diff --git a/app/painter.go b/app/painter.go index 03d8d69bf..f0186e675 100644 --- a/app/painter.go +++ b/app/painter.go @@ -92,8 +92,15 @@ type painter struct { publishedComposing bool publishedTextField bool hitsPublished bool - labelNames map[gfx.ID]string - labelNamePeak int + // hitsSame remembers, for the canvas as painted, whether its hits equal + // publishedHits (0 unknown, 1 equal, 2 different), so the focus settling + // and the publish of one paint compare the list once. + hitsSame uint8 + // focusSynced says the focus was synced with the canvas as painted, so the + // publish need not sync it again. + focusSynced bool + labelNames map[gfx.ID]string + labelNamePeak int // controls draws the window buttons of a custom titlebar, on platforms where // Viva does; it is nil otherwise. controls *windowControls @@ -886,23 +893,7 @@ func (painter *painter) repaint() (platform.Frame, error) { painter.noteFrameStart() } painter.paintCanvas() - if !painter.focus.PendingFocus().IsZero() || painter.focus.Carries() || !painter.canvas.FocusOnce().IsZero() { - before, beforeVisible := painter.focus.Focused(), painter.focus.KeyboardFocus() - painter.focus.Sync(painter.canvas) - if painter.focus.Focused() != before || painter.focus.KeyboardFocus() != beforeVisible { - painter.paintCanvas() - } - } - if painter.paint != nil && painter.canvas.TrappedFocusScope() != painter.focus.Router().ActiveScope() { - // A modal just opened or closed, which moves focus into it or back - // out. Settle that now and paint once more so this frame already - // shows the new focus instead of lagging a repaint behind. - before := painter.focus.Focused() - painter.focus.Sync(painter.canvas) - if painter.focus.Focused() != before { - painter.paintCanvas() - } - } + painter.settleFocus() frame, err := painter.publish() if err != nil { return platform.Frame{}, err @@ -925,7 +916,46 @@ func (painter *painter) repaintAfterInput() (platform.Frame, error) { return painter.repaint() } +// maxFocusPasses bounds the paints settleFocus adds to one frame: a page whose +// every paint moves the focus somewhere new shows the last move. +const maxFocusPasses = 2 + +// settleFocus applies the focus changes the paint itself made, by an Autofocus +// hit that appeared, a focus request or release, a returning scope that closed, +// a modal that opened or closed, or a request carried from the event, and paints +// again when the focus moved, so the frame shows the focus it routes keys to. +func (painter *painter) settleFocus() { + if painter.paint == nil { + return + } + for range maxFocusPasses { + if !painter.regionsNeedSync() { + return + } + before, beforeVisible := painter.focus.Focused(), painter.focus.KeyboardFocus() + painter.focus.Sync(painter.canvas) + painter.focusSynced = true + if painter.focus.Focused() == before && painter.focus.KeyboardFocus() == beforeVisible { + return + } + painter.paintCanvas() + } +} + +// regionsNeedSync reports whether the canvas as painted asks for something the +// focus and the input regions do not reflect yet. A paint that asks to take the +// focus away changes routing without changing a hit. The regions are built from +// a subset of the hit fields: a label, value or description change feeds the +// semantic payload but leaves every region as it was, so it needs no sync. +func (painter *painter) regionsNeedSync() bool { + if !painter.canvas.FocusRelease().IsZero() || !painter.canvas.FocusOnce().IsZero() || painter.focus.Carries() { + return true + } + return !painter.hitStructuresUnchanged() && !painter.regionStructuresUnchanged() +} + func (painter *painter) paintCanvas() { + painter.hitsSame, painter.focusSynced = 0, false if painter.paint == nil { return } @@ -971,17 +1001,14 @@ func (painter *painter) publish() (platform.Frame, error) { frame.NativeViews = views } - // A paint that asks to take the focus away changes routing without changing a hit. - // The regions the router keeps are built from a subset of the hit fields: a label, - // value or description change feeds the semantic payload but leaves every region - // as it was, so it must not rebuild them. + // A repaint settled the focus already; a publish of a canvas painted outside + // repaint syncs it here. hitStructuresUnchanged := painter.hitStructuresUnchanged() - regionsUnchanged := (hitStructuresUnchanged || painter.regionStructuresUnchanged()) && - painter.canvas.FocusRelease().IsZero() && painter.canvas.FocusOnce().IsZero() && !painter.focus.Carries() - if regionsUnchanged { - painter.reusedHits++ - } else { + if !painter.focusSynced && painter.regionsNeedSync() { painter.focus.Sync(painter.canvas) + painter.focusSynced = true + } else if !painter.focusSynced { + painter.reusedHits++ } if err := painter.syncCursor(); err != nil { return platform.Frame{}, err @@ -1432,11 +1459,13 @@ func (painter *painter) hitStructuresUnchanged() bool { if !painter.structuresUnchanged() { return false } - hits := painter.canvas.Hits() - if len(hits) != len(painter.publishedHits) { - return false + if painter.hitsSame == 0 { + painter.hitsSame = 2 + if hits := painter.canvas.Hits(); len(hits) == len(painter.publishedHits) && sameHits(painter.publishedHits, hits) { + painter.hitsSame = 1 + } } - return sameHits(painter.publishedHits, hits) + return painter.hitsSame == 1 } // regionStructuresUnchanged reports whether the paint produced the same input @@ -1538,6 +1567,7 @@ func sameHits(published, current []gfx.Hit) bool { // region and semantic mirror when nothing that feeds them changed. func (painter *painter) recordHitStructures() { painter.publishedHits = append(painter.publishedHits[:0], painter.canvas.Hits()...) + painter.hitsSame = 1 painter.publishedFocus = painter.focus.Focused() painter.publishedTrap = painter.canvas.TrappedFocusScope() painter.publishedInitial = painter.canvas.InitialFocus() diff --git a/app/painter_focus_converge_test.go b/app/painter_focus_converge_test.go new file mode 100644 index 000000000..7629d19f7 --- /dev/null +++ b/app/painter_focus_converge_test.go @@ -0,0 +1,97 @@ +package app + +import ( + "fmt" + "testing" + + "github.com/vivaui/viva/gfx" +) + +// A focus change the paint itself causes, by a newly appearing Autofocus hit, a +// RequestFocus, a ReleaseFocus or a ReturnFocus scope closing, must show in the +// frame that paint publishes: the runtime paints again with the new focus before +// publishing, instead of leaving the old focus on screen until another event. +func TestPaintTimeFocusChangesShowInTheSameFrame(t *testing.T) { + const field, other, trigger, inside = 10, 11, 12, 13 + for _, test := range []struct { + name string + before func(canvas *gfx.Canvas) + after func(canvas *gfx.Canvas) + want gfx.ID + }{ + { + name: "autofocus", + after: func(canvas *gfx.Canvas) { + canvas.HitWithOptions(gfx.Item(field), gfx.Rect{Y: 30, Width: 80, Height: 20}, "Field", gfx.HitOptions{Role: gfx.RoleTextField, Autofocus: true}) + }, + want: gfx.Item(field), + }, + { + name: "request", + after: func(canvas *gfx.Canvas) { + canvas.HitWithOptions(gfx.Item(field), gfx.Rect{Y: 30, Width: 80, Height: 20}, "Field", gfx.HitOptions{Role: gfx.RoleTextField}) + canvas.RequestFocus(gfx.Item(field)) + }, + want: gfx.Item(field), + }, + { + name: "release", + before: func(canvas *gfx.Canvas) { canvas.RequestFocus(gfx.Item(other)) }, + after: func(canvas *gfx.Canvas) { canvas.ReleaseFocus(gfx.Item(other)) }, + want: gfx.ID{}, + }, + { + name: "return", + before: func(canvas *gfx.Canvas) { + canvas.PushFocusScope(gfx.Item(100)) + canvas.ReturnFocus(gfx.Item(100)) + canvas.HitWithOptions(gfx.Item(inside), gfx.Rect{Y: 60, Width: 80, Height: 20}, "Inside", gfx.HitOptions{Role: gfx.RoleButton}) + canvas.PopFocusScope() + canvas.RequestFocus(gfx.Item(inside)) + }, + after: func(*gfx.Canvas) {}, // the scope closes + want: gfx.Item(trigger), + }, + } { + t.Run(test.name, func(t *testing.T) { + var canvas gfx.Canvas + stage, paints := 0, 0 + config := Config{Title: "converge", Width: 200, Height: 100} + config.Paint = func(canvas *gfx.Canvas, size gfx.Size) { + paints++ + canvas.HitWithOptions(gfx.Item(other), gfx.Rect{Width: 80, Height: 20}, "Other", gfx.HitOptions{Role: gfx.RoleButton}) + canvas.HitWithOptions(gfx.Item(trigger), gfx.Rect{X: 100, Width: 80, Height: 20}, "Trigger", gfx.HitOptions{Role: gfx.RoleButton}) + switch { + case stage == 1 && test.before != nil: + test.before(canvas) + case stage == 2: + test.after(canvas) + } + // What the frame shows depends on the focus the paint was told. + canvas.Label(fmt.Sprint(canvas.Focused()), gfx.Rect{Y: 80, Width: 200, Height: 20}, gfx.TextStyle{Size: 12}) + } + painter := newTestPainter(t, &canvas, config) + if test.name == "return" { + painter.focus.Apply(gfx.EventResult{Focus: gfx.Item(trigger)}) + } + stage = 1 + if _, err := painter.resize(size(201, 100)); err != nil { + t.Fatal(err) + } + stage, paints = 2, 0 + if _, err := painter.resize(size(202, 100)); err != nil { + t.Fatal(err) + } + if painter.focus.Focused() != test.want { + t.Fatalf("focus is %v, want %v", painter.focus.Focused(), test.want) + } + labels := painter.frame.Labels() + if shown := labels[len(labels)-1].Value; shown != fmt.Sprint(test.want) { + t.Fatalf("the published frame shows focus %q, want %q", shown, fmt.Sprint(test.want)) + } + if paints > 3 { + t.Fatalf("one repaint painted %d times", paints) + } + }) + } +} From 07475285367eaea511b6f41348232dcb300ff9f0 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 22 Nov 2026 11:19:55 +0800 Subject: [PATCH 11/64] perf(interaction): keep the input regions once, in the router Focus.Sync built the regions in a slice of its own and Router.SetRegions copied them into another, compared against the previous list, so every interactive element was held twice (48 bytes each) and each change was copied. Focus now builds the list in the router's own buffer (Router.RegionBuffer) and the router keeps it as given. The equality shortcut goes with the copy; the painter already skips Sync when the regions' inputs are unchanged, so it only saved a rescan for the focused slot. --- internal/input/input.go | 20 +++++++++----------- internal/interaction/focus.go | 15 +++++++-------- 2 files changed, 16 insertions(+), 19 deletions(-) diff --git a/internal/input/input.go b/internal/input/input.go index 79b55079a..fcbd1c841 100644 --- a/internal/input/input.go +++ b/internal/input/input.go @@ -1,8 +1,6 @@ package input import ( - "slices" - "github.com/vivaui/viva/gfx" ) @@ -145,16 +143,16 @@ type Router struct { returnFocus Target } -// SetRegions replaces paint-order hit regions while preserving a still-valid -// focused target. Destination storage is reused across calls. +// RegionBuffer is the router's region list emptied, to build the next list in +// and hand back with SetRegions, so the regions are kept once and never copied. +// The router routes nothing until it has them back. +func (router *Router) RegionBuffer() []Region { return router.regions[:0] } + +// SetRegions replaces the paint-order hit regions, preserving a still-valid +// focused target. The router keeps regions as given, without a copy: the caller +// must not change the slice afterwards. func (router *Router) SetRegions(regions []Region) { - // A repaint that declares the same regions (the common steady state) needs - // no copy and no focus rescan: the retained list already routes input and - // the focused slot is still valid. - if len(router.regions) == len(regions) && slices.Equal(router.regions, regions) { - return - } - router.regions = append(router.regions[:0], regions...) + router.regions = regions router.focusedSlot = 0 if !router.focused.IsZero() { for index, region := range router.regions { diff --git a/internal/interaction/focus.go b/internal/interaction/focus.go index 0daab6a09..588b7d5af 100644 --- a/internal/interaction/focus.go +++ b/internal/interaction/focus.go @@ -13,7 +13,6 @@ import ( // focus results from event handlers. The zero value is ready to use. type Focus struct { router input.Router - regions []input.Region focused gfx.ID keyboardFocus bool pendingFocus gfx.ID @@ -105,14 +104,14 @@ func (f *Focus) WasPainted(id gfx.ID) bool { // target. Callers paint again when the focused target changed. func (f *Focus) Sync(canvas *gfx.Canvas) { before := f.focused - f.regions = f.regions[:0] + regions := f.router.RegionBuffer() hits := canvas.Hits() for index := range hits { hit := &hits[index] if hit.Container { continue // semantic regions are not interaction targets } - f.regions = append(f.regions, input.Region{ + regions = append(regions, input.Region{ Target: input.Target(hit.ID), Bounds: input.Rect{X: hit.Bounds.X, Y: hit.Bounds.Y, Width: hit.Bounds.Width, Height: hit.Bounds.Height}, Scope: hit.Scope, @@ -135,10 +134,10 @@ func (f *Focus) Sync(canvas *gfx.Canvas) { // the layers composite in: a popup on a higher layer is often painted // before the field it covers. The front-most region must be the one on the // highest layer, and within a layer the last declared. - if !slices.IsSortedFunc(f.regions, compareRegionLayers) { - slices.SortStableFunc(f.regions, compareRegionLayers) + if !slices.IsSortedFunc(regions, compareRegionLayers) { + slices.SortStableFunc(regions, compareRegionLayers) } - f.router.SetRegions(f.regions) + f.router.SetRegions(regions) f.syncReturns(canvas.FocusReturns(), before) f.router.SetActiveScope(canvas.TrappedFocusScope(), input.Target(canvas.InitialFocus())) f.applyAutofocus(hits) @@ -218,7 +217,7 @@ func (f *Focus) noteInside() { } var scope gfx.ID if !f.focused.IsZero() { - for _, region := range f.regions { + for _, region := range f.router.Regions() { if region.Target == input.Target(f.focused) { scope = region.Scope break @@ -277,7 +276,7 @@ func (f *Focus) Refresh() { f.refresh() } // Trim releases capacity left behind by a previous, much larger page. func (f *Focus) Trim() { - f.regions = trimCapacity(f.regions) + f.router.SetRegions(trimCapacity(f.router.Regions())) f.painted = trimCapacity(f.painted) f.scratch = trimCapacity(f.scratch) } From 6c3389170ed80a229287fdee725ccad79e0567e5 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 22 Nov 2026 11:37:38 +0800 Subject: [PATCH 12/64] perf(linux): let every window draw with one Vulkan device Each window made its own Vulkan instance, chose a physical device, and created a logical device and queue, so a second window paid the driver start-up again and kept a second device resident. Windows now share a process-level vulkanDevice: the first window creates the instance, chooses the device for its surface and creates it; later windows make only their surface on that instance and check the queue can present to it; the last window to close destroys it. The windows render on the application's one loop thread, so the queue needs no lock. A device loss retires the device for every window: the window that finds out makes itself again on a new device, and others keep the old one until their own next call reports the loss, then release it (the last release destroys it) and join the new one. A surface loss still rebuilds only that window. Offscreen renderers keep a device of their own. Measured on the Linux test machine (lavapipe): a second window's renderer opens in 7.7 ms instead of 13.7 ms, and each extra window adds 1.9 MB resident instead of 6.4 MB. A shared VkPipelineCache was tried and gave nothing measurable over Mesa's shader cache, so it is not added. Also give TestPresentOutOfDateRebuilds' fake renderer the framebuffer its command buffer records into; 0a34cdec made present record lazily and the fake had none, so the test panicked. ADR 0093 decision 3. --- internal/platform/linux/api_linux_test.go | 19 +- .../platform/linux/cpu_window_linux_test.go | 10 +- internal/platform/linux/offscreen_linux.go | 10 +- .../platform/linux/vulkan_device_linux.go | 248 ++++++++++++++++++ .../linux/vulkan_device_linux_test.go | 69 +++++ internal/platform/linux/vulkan_linux.go | 176 +++---------- internal/platform/linux/vulkan_loss.go | 7 + internal/platform/linux/vulkan_probe_linux.go | 10 +- 8 files changed, 383 insertions(+), 166 deletions(-) create mode 100644 internal/platform/linux/vulkan_device_linux.go create mode 100644 internal/platform/linux/vulkan_device_linux_test.go diff --git a/internal/platform/linux/api_linux_test.go b/internal/platform/linux/api_linux_test.go index d89055b80..966d15127 100644 --- a/internal/platform/linux/api_linux_test.go +++ b/internal/platform/linux/api_linux_test.go @@ -611,13 +611,13 @@ func writeVulkanManifest(t *testing.T, dir string) { // rendering failure: the application must be able to tell them apart and the text // must say what to install. Any other enumeration result stays a real failure. func TestUnusableVulkanDriverIsNamedAndSaysWhatToInstall(t *testing.T) { - renderer := func(status int32) *vulkanRenderer { - return &vulkanRenderer{api: &vulkanAPI{ + device := func(status int32) *vulkanDevice { + return &vulkanDevice{api: &vulkanAPI{ enumeratePhysicalDevices: func(uintptr, *uint32, *uintptr) int32 { return status }, }} } for _, status := range []int32{vkErrorInitializationFailed, vkErrorIncompatibleDriver} { - err := renderer(status).selectDevice() + err := device(status).selectPhysical(0) if !errors.Is(err, platform.ErrNoGraphics) { t.Errorf("result %d: %v does not wrap platform.ErrNoGraphics", status, err) } @@ -628,18 +628,19 @@ func TestUnusableVulkanDriverIsNamedAndSaysWhatToInstall(t *testing.T) { t.Errorf("result %d: %q does not report the Vulkan result", status, err) } } - if err := renderer(-1).selectDevice(); errors.Is(err, platform.ErrNoGraphics) { + if err := device(-1).selectPhysical(0); errors.Is(err, platform.ErrNoGraphics) { t.Errorf("a real failure is reported as no graphics: %v", err) } } func newSuboptimalTestRenderer(acquireStatus, presentStatus int32, recreations *int) *vulkanRenderer { return &vulkanRenderer{ - device: 10, - queue: 20, - swapchain: 30, - commands: []uintptr{40}, - fence: 50, + device: 10, + queue: 20, + swapchain: 30, + commands: []uintptr{40}, + framebuffers: []uintptr{45}, + fence: 50, api: &vulkanAPI{ waitForFences: func(uintptr, uint32, *uintptr, uint32, uint64) int32 { return vkSuccess }, resetFences: func(uintptr, uint32, *uintptr) int32 { return vkSuccess }, diff --git a/internal/platform/linux/cpu_window_linux_test.go b/internal/platform/linux/cpu_window_linux_test.go index 26286e31b..7e3ca62f0 100644 --- a/internal/platform/linux/cpu_window_linux_test.go +++ b/internal/platform/linux/cpu_window_linux_test.go @@ -246,7 +246,7 @@ func BenchmarkCPUWindowPresent(b *testing.B) { }) } -// fakeVulkanAPI answers just enough for selectDevice: the given physical +// fakeVulkanAPI answers just enough for selectPhysical: the given physical // devices in order and one graphics family that presents everywhere. func fakeVulkanAPI(devices []uintptr, kinds map[uintptr]uint32) *vulkanAPI { return &vulkanAPI{ @@ -289,12 +289,12 @@ func TestSelectDevicePrefersHardwareAndReportsSoftware(t *testing.T) { {"hardware first", []uintptr{22, 11}, map[uintptr]uint32{22: hardware, 11: vkPhysicalDeviceTypeCPU}, 22, false}, {"only software", []uintptr{11}, map[uintptr]uint32{11: vkPhysicalDeviceTypeCPU}, 11, true}, } { - renderer := &vulkanRenderer{api: fakeVulkanAPI(test.devices, test.kinds), instance: 1, surface: 2} - if err := renderer.selectDevice(); err != nil { + device := &vulkanDevice{api: fakeVulkanAPI(test.devices, test.kinds), instance: 1} + if err := device.selectPhysical(2); err != nil { t.Fatalf("%s: %v", test.name, err) } - if renderer.physical != test.physical || renderer.software != test.software { - t.Errorf("%s: device %d software=%v, want %d software=%v", test.name, renderer.physical, renderer.software, test.physical, test.software) + if device.physical != test.physical || device.software != test.software { + t.Errorf("%s: device %d software=%v, want %d software=%v", test.name, device.physical, device.software, test.physical, test.software) } } } diff --git a/internal/platform/linux/offscreen_linux.go b/internal/platform/linux/offscreen_linux.go index 5860d349e..8e425978a 100644 --- a/internal/platform/linux/offscreen_linux.go +++ b/internal/platform/linux/offscreen_linux.go @@ -101,15 +101,11 @@ func (offscreen *Offscreen) Close() { } func (renderer *vulkanRenderer) initializeOffscreen() error { - if err := renderer.createInstance(nil); err != nil { - return err - } - if err := renderer.selectDevice(); err != nil { - return err - } - if err := renderer.createDevice(nil); err != nil { + device := vulkanDevice{api: renderer.api} + if err := device.open(); err != nil { return err } + renderer.adopt(&device) if err := renderer.scene.upload(renderer, nil, render.Update{Rebuild: true}); err != nil { return err } diff --git a/internal/platform/linux/vulkan_device_linux.go b/internal/platform/linux/vulkan_device_linux.go new file mode 100644 index 000000000..139854258 --- /dev/null +++ b/internal/platform/linux/vulkan_device_linux.go @@ -0,0 +1,248 @@ +package linux + +import ( + "encoding/binary" + "fmt" + "sync" + "unsafe" +) + +// vulkanDevice is a Vulkan instance, the physical device chosen on it, the +// logical device and its graphics queue: what a renderer draws with, apart from +// its surface, swapchain and the objects it draws (ADR 0093). Every window of +// the process shares one (acquireWindowDevice), so a second window costs no +// instance, device or driver start-up; an offscreen renderer owns its own. +// +// A shared device's queue is used without a lock: the windows render on the +// application's one loop thread, which is all the external synchronisation +// Vulkan asks for. +type vulkanDevice struct { + api *vulkanAPI + instance, physical, handle, queue uintptr + queueFamily uint32 + // software is set when the device is a CPU rasterizer (lavapipe); dualSource + // when it was created with dual-source blending. + software, dualSource bool + features [vkFeatureCount]uint32 + // users counts the renderers holding the window device; lost says the + // device was lost, so no renderer acquires it again. + users int + lost bool +} + +// windowDevice is the device the windows draw with, made by the first window +// and destroyed when the last one releases it. +var windowDevice struct { + sync.Mutex + current *vulkanDevice +} + +// acquireWindowDevice returns the window device, with its instance made; the +// window makes its surface on that instance and then attaches it. +func acquireWindowDevice(api *vulkanAPI) (*vulkanDevice, error) { + windowDevice.Lock() + defer windowDevice.Unlock() + device := windowDevice.current + if device == nil { + device = &vulkanDevice{api: api} + surfaceExtension := append([]byte("VK_KHR_surface"), 0) + xcbExtension := append([]byte("VK_KHR_xcb_surface"), 0) + if err := device.createInstance([]*byte{&surfaceExtension[0], &xcbExtension[0]}); err != nil { + return nil, err + } + windowDevice.current = device + } + device.users++ + return device, nil +} + +// attach makes sure the device can present to surface: the first window chooses +// the physical device for its surface and creates the logical device; a later +// one checks that the chosen queue can present to its surface too. +func (device *vulkanDevice) attach(surface uintptr) error { + windowDevice.Lock() + defer windowDevice.Unlock() + if device.handle != 0 { + var supported uint32 + if status := device.api.getSurfaceSupport(device.physical, device.queueFamily, surface, &supported); status != vkSuccess || supported == 0 { + return fmt.Errorf("linux: the Vulkan device the other windows draw with cannot present to this window (result %d)", status) + } + return nil + } + if err := device.selectPhysical(surface); err != nil { + return err + } + swapExtension := append([]byte("VK_KHR_swapchain"), 0) + return device.createLogical([]*byte{&swapExtension[0]}) +} + +// release gives the window device back; the last renderer to hold it destroys +// it, after destroying every object it made on it. +func (device *vulkanDevice) release() { + windowDevice.Lock() + defer windowDevice.Unlock() + if device.users--; device.users > 0 { + return + } + if windowDevice.current == device { + windowDevice.current = nil + } + device.destroy() +} + +// markLost retires a lost device: the renderers that hold it release it as they +// find out, and the first to make itself again gets a new one. +func (device *vulkanDevice) markLost() { + windowDevice.Lock() + defer windowDevice.Unlock() + device.lost = true + if windowDevice.current == device { + windowDevice.current = nil + } +} + +// open makes a device a renderer owns, with no surface to present to. +func (device *vulkanDevice) open() error { + err := device.createInstance(nil) + if err == nil { + err = device.selectPhysical(0) + } + if err == nil { + err = device.createLogical(nil) + } + if err != nil { + device.destroy() + } + return err +} + +// destroy destroys the logical device and the instance. +func (device *vulkanDevice) destroy() { + if device.handle != 0 { + device.api.destroyDevice(device.handle, nil) + } + if device.instance != 0 { + device.api.destroyInstance(device.instance, nil) + } + *device = vulkanDevice{api: device.api, users: device.users, lost: device.lost} +} + +// createInstance creates the Vulkan instance with the given extensions: the +// window path needs the surface ones, an offscreen renderer none. +func (device *vulkanDevice) createInstance(extensions []*byte) error { + applicationName := append([]byte("Viva"), 0) + engineName := append([]byte("Viva"), 0) + application := vkApplicationInfo{SType: vkStructureApplicationInfo, Application: &applicationName[0], Engine: &engineName[0], APIVersion: 1 << 22} + instanceInfo := vkInstanceCreateInfo{SType: vkStructureInstanceCreateInfo, Application: &application, ExtensionCount: uint32(len(extensions))} + if len(extensions) > 0 { + instanceInfo.Extensions = uintptr(unsafe.Pointer(&extensions[0])) + } + switch status := device.api.createInstance(&instanceInfo, nil, &device.instance); status { + case vkSuccess: + return nil + case vkErrorIncompatibleDriver, vkErrorInitializationFailed: + return noVulkan(fmt.Sprintf("Vulkan has no driver (result %d)", status), nil) + default: + return vkCheck(status, "create instance") + } +} + +// createLogical creates the logical device and its graphics queue on the +// selected physical device and queue family. +func (device *vulkanDevice) createLogical(extensions []*byte) error { + priority := float32(1) + queueInfo := vkDeviceQueueCreateInfo{SType: vkStructureDeviceQueueCreateInfo, Family: device.queueFamily, Count: 1, Priorities: &priority} + deviceInfo := vkDeviceCreateInfo{SType: vkStructureDeviceCreateInfo, QueueCount: 1, Queues: &queueInfo, ExtensionCount: uint32(len(extensions))} + // Dual-source blending (a core feature of nearly every desktop device) blends the + // per-channel coverage of LCD text; without it text is blended in grayscale. + var supported [vkFeatureCount]uint32 + device.api.getPhysicalDeviceFeatures(device.physical, &supported) + if supported[vkFeatureDualSourceBlend] != 0 { + device.features[vkFeatureDualSourceBlend] = 1 + deviceInfo.Features = uintptr(unsafe.Pointer(&device.features)) + device.dualSource = true + } + if len(extensions) > 0 { + deviceInfo.Extensions = uintptr(unsafe.Pointer(&extensions[0])) + } + if err := vkCheck(device.api.createDevice(device.physical, &deviceInfo, nil, &device.handle), "create device"); err != nil { + device.dualSource = false + return err + } + device.api.getDeviceQueue(device.handle, device.queueFamily, 0, &device.queue) + if device.queue == 0 { + return fmt.Errorf("linux: Vulkan returned no graphics queue") + } + return nil +} + +func (device *vulkanDevice) selectPhysical(surface uintptr) error { + var deviceCount uint32 + // A loader whose installed drivers fail to initialize fails enumeration with + // VK_ERROR_INITIALIZATION_FAILED, not only with the + // VK_ERROR_INCOMPATIBLE_DRIVER an empty driver list gives. Both are a machine + // with no usable Vulkan driver and need the same advice as one without a + // loader; any other result is a real failure. + switch status := device.api.enumeratePhysicalDevices(device.instance, &deviceCount, nil); status { + case vkSuccess: + case vkErrorInitializationFailed, vkErrorIncompatibleDriver: + return noVulkan(fmt.Sprintf("Vulkan has no driver (result %d)", status), nil) + default: + return vkCheck(status, "count physical devices") + } + if deviceCount == 0 { + return noVulkan("Vulkan reports no device", nil) + } + if deviceCount > 32 { + return fmt.Errorf("linux: Vulkan physical device count %d", deviceCount) + } + devices := make([]uintptr, deviceCount) + if err := vkCheck(device.api.enumeratePhysicalDevices(device.instance, &deviceCount, &devices[0]), "enumerate physical devices"); err != nil { + return err + } + // A CPU rasterizer (lavapipe) is not a hardware accelerator: the CPU + // renderer draws a changed region only, while software Vulkan redraws the + // whole window every frame. Prefer a hardware device; remember the software + // one in case no hardware device can present. + var softwareDevice uintptr + var softwareFamily uint32 + for _, candidate := range devices[:deviceCount] { + var familyCount uint32 + device.api.getQueueFamilyProperties(candidate, &familyCount, nil) + if familyCount == 0 || familyCount > 64 { + continue + } + families := make([]vkQueueFamilyProperties, familyCount) + device.api.getQueueFamilyProperties(candidate, &familyCount, &families[0]) + for index, family := range families[:familyCount] { + if family.Flags&vkQueueGraphics == 0 || family.Count == 0 { + continue + } + var supported uint32 + if surface == 0 || device.api.getSurfaceSupport(candidate, uint32(index), surface, &supported) == vkSuccess && supported != 0 { + if device.physicalDeviceIsCPU(candidate) { + if softwareDevice == 0 { + softwareDevice, softwareFamily = candidate, uint32(index) + } + continue + } + device.physical, device.queueFamily, device.software = candidate, uint32(index), false + return nil + } + } + } + if softwareDevice != 0 { + device.physical, device.queueFamily, device.software = softwareDevice, softwareFamily, true + return nil + } + return noVulkan("no Vulkan graphics queue can present to XCB", nil) +} + +// physicalDeviceIsCPU reports whether physical is a CPU rasterizer, such as +// Mesa's lavapipe: VkPhysicalDeviceType CPU. Its properties struct is 824 bytes +// and deviceType sits at offset 16. +func (device *vulkanDevice) physicalDeviceIsCPU(physical uintptr) bool { + var properties [vkPropertiesSize]byte + device.api.getPhysicalDeviceProperties(physical, &properties) + return binary.LittleEndian.Uint32(properties[vkPropertiesDeviceTypeOffset:]) == vkPhysicalDeviceTypeCPU +} diff --git a/internal/platform/linux/vulkan_device_linux_test.go b/internal/platform/linux/vulkan_device_linux_test.go new file mode 100644 index 000000000..836fc6f89 --- /dev/null +++ b/internal/platform/linux/vulkan_device_linux_test.go @@ -0,0 +1,69 @@ +package linux + +import "testing" + +// Windows draw with one Vulkan device: the second window makes no instance or +// device of its own, closing one window leaves the others drawing, and the +// device goes when the last window does. +func TestWindowsShareOneVulkanDevice(t *testing.T) { + _, first := newWindowRenderer(t, nil) + _, second := newWindowRenderer(t, nil) + if first.shared == nil || first.shared != second.shared || first.device != second.device || first.instance != second.instance { + t.Fatalf("windows draw with devices %p and %p", first.shared, second.shared) + } + shared := first.shared + if err := first.present(); err != nil { + t.Fatal(err) + } + if err := second.present(); err != nil { + t.Fatal(err) + } + second.close() + if shared.users != 1 || shared.handle == 0 { + t.Fatalf("closing one window left %d users, device %d", shared.users, shared.handle) + } + if err := first.present(); err != nil { + t.Fatalf("the remaining window cannot draw: %v", err) + } + first.close() + if shared.handle != 0 || shared.instance != 0 || windowDevice.current != nil { + t.Fatal("the device outlived its last window") + } +} + +// A lost device is lost for every window. The window that finds out first makes +// itself again on a new device; another keeps the old one until it finds out +// too, and then joins the new one. +func TestALostDeviceIsReplacedForEveryWindow(t *testing.T) { + _, first := newWindowRenderer(t, nil) + _, second := newWindowRenderer(t, nil) + old := first.shared + loseOnce := func(renderer *vulkanRenderer) { + present := renderer.api.queuePresent + lost := true + renderer.api.queuePresent = func(queue uintptr, info *vkPresentInfo) int32 { + if lost { + lost = false + return vkErrorDeviceLost + } + return present(queue, info) + } + } + loseOnce(first) + if err := first.present(); err != nil { + t.Fatalf("present after a lost device: %v", err) + } + if first.shared == old || !old.lost || second.shared != old { + t.Fatalf("after the loss the windows draw with %p and %p (old %p, lost %v)", first.shared, second.shared, old, old.lost) + } + loseOnce(second) + if err := second.present(); err != nil { + t.Fatalf("present after the other window replaced the device: %v", err) + } + if second.shared != first.shared || old.handle != 0 { + t.Fatalf("the second window draws with %p, not the new %p; old device %d", second.shared, first.shared, old.handle) + } + if err := first.present(); err != nil { + t.Fatal(err) + } +} diff --git a/internal/platform/linux/vulkan_linux.go b/internal/platform/linux/vulkan_linux.go index 3c0019ad4..d2a5512cb 100644 --- a/internal/platform/linux/vulkan_linux.go +++ b/internal/platform/linux/vulkan_linux.go @@ -1,7 +1,6 @@ package linux import ( - "encoding/binary" "errors" "fmt" "math" @@ -430,6 +429,10 @@ type vulkanRenderer struct { // the CPU renderer draws such a window instead (window_renderer_linux.go). software bool enabledFeatures [vkFeatureCount]uint32 + // shared is the process's window device the renderer draws with, which it + // releases instead of destroying; nil for a renderer that owns its device + // (offscreen). instance through enabledFeatures are copied from it. + shared *vulkanDevice // scale is device pixels per logical pixel: width and height are device // pixels, a scene is in logical pixels. Zero means 1. scale float32 @@ -657,22 +660,19 @@ func newVulkanRenderer(connection uintptr, window, width, height uint32, scale f } func (renderer *vulkanRenderer) initialize(connection uintptr, window uint32) error { - surfaceExtension := append([]byte("VK_KHR_surface"), 0) - xcbExtension := append([]byte("VK_KHR_xcb_surface"), 0) - if err := renderer.createInstance([]*byte{&surfaceExtension[0], &xcbExtension[0]}); err != nil { + shared, err := acquireWindowDevice(renderer.api) + if err != nil { return err } + renderer.shared, renderer.instance = shared, shared.instance surfaceInfo := vkXcbSurfaceCreateInfo{SType: vkStructureXcbSurfaceCreateInfo, Connection: connection, Window: window} if err := vkCheck(renderer.api.createXcbSurface(renderer.instance, &surfaceInfo, nil, &renderer.surface), "create XCB surface"); err != nil { return err } - if err := renderer.selectDevice(); err != nil { - return err - } - swapExtension := append([]byte("VK_KHR_swapchain"), 0) - if err := renderer.createDevice([]*byte{&swapExtension[0]}); err != nil { + if err := shared.attach(renderer.surface); err != nil { return err } + renderer.adopt(shared) if len(renderer.text.labels) > 0 { if err := renderer.text.initialize(renderer); err != nil { return err @@ -695,126 +695,6 @@ func (renderer *vulkanRenderer) initialize(connection uintptr, window uint32) er return vkCheck(renderer.api.createFence(renderer.device, &fenceInfo, nil, &renderer.fence), "create frame fence") } -// createInstance creates the Vulkan instance with the given extensions: the -// window path needs the surface ones, an offscreen renderer none. -func (renderer *vulkanRenderer) createInstance(extensions []*byte) error { - applicationName := append([]byte("Viva"), 0) - engineName := append([]byte("Viva"), 0) - application := vkApplicationInfo{SType: vkStructureApplicationInfo, Application: &applicationName[0], Engine: &engineName[0], APIVersion: 1 << 22} - instanceInfo := vkInstanceCreateInfo{SType: vkStructureInstanceCreateInfo, Application: &application, ExtensionCount: uint32(len(extensions))} - if len(extensions) > 0 { - instanceInfo.Extensions = uintptr(unsafe.Pointer(&extensions[0])) - } - switch status := renderer.api.createInstance(&instanceInfo, nil, &renderer.instance); status { - case vkSuccess: - return nil - case vkErrorIncompatibleDriver, vkErrorInitializationFailed: - return noVulkan(fmt.Sprintf("Vulkan has no driver (result %d)", status), nil) - default: - return vkCheck(status, "create instance") - } -} - -// createDevice creates the logical device and its graphics queue on the -// selected physical device and queue family. -func (renderer *vulkanRenderer) createDevice(extensions []*byte) error { - priority := float32(1) - queueInfo := vkDeviceQueueCreateInfo{SType: vkStructureDeviceQueueCreateInfo, Family: renderer.queueFamily, Count: 1, Priorities: &priority} - deviceInfo := vkDeviceCreateInfo{SType: vkStructureDeviceCreateInfo, QueueCount: 1, Queues: &queueInfo, ExtensionCount: uint32(len(extensions))} - // Dual-source blending (a core feature of nearly every desktop device) blends the - // per-channel coverage of LCD text; without it text is blended in grayscale. - var supported [vkFeatureCount]uint32 - renderer.api.getPhysicalDeviceFeatures(renderer.physical, &supported) - if supported[vkFeatureDualSourceBlend] != 0 { - renderer.enabledFeatures[vkFeatureDualSourceBlend] = 1 - deviceInfo.Features = uintptr(unsafe.Pointer(&renderer.enabledFeatures)) - renderer.dualSource = true - } - if len(extensions) > 0 { - deviceInfo.Extensions = uintptr(unsafe.Pointer(&extensions[0])) - } - if err := vkCheck(renderer.api.createDevice(renderer.physical, &deviceInfo, nil, &renderer.device), "create device"); err != nil { - renderer.dualSource = false - return err - } - renderer.api.getDeviceQueue(renderer.device, renderer.queueFamily, 0, &renderer.queue) - if renderer.queue == 0 { - return fmt.Errorf("linux: Vulkan returned no graphics queue") - } - return nil -} - -func (renderer *vulkanRenderer) selectDevice() error { - var deviceCount uint32 - // A loader whose installed drivers fail to initialize fails enumeration with - // VK_ERROR_INITIALIZATION_FAILED, not only with the - // VK_ERROR_INCOMPATIBLE_DRIVER an empty driver list gives. Both are a machine - // with no usable Vulkan driver and need the same advice as one without a - // loader; any other result is a real failure. - switch status := renderer.api.enumeratePhysicalDevices(renderer.instance, &deviceCount, nil); status { - case vkSuccess: - case vkErrorInitializationFailed, vkErrorIncompatibleDriver: - return noVulkan(fmt.Sprintf("Vulkan has no driver (result %d)", status), nil) - default: - return vkCheck(status, "count physical devices") - } - if deviceCount == 0 { - return noVulkan("Vulkan reports no device", nil) - } - if deviceCount > 32 { - return fmt.Errorf("linux: Vulkan physical device count %d", deviceCount) - } - devices := make([]uintptr, deviceCount) - if err := vkCheck(renderer.api.enumeratePhysicalDevices(renderer.instance, &deviceCount, &devices[0]), "enumerate physical devices"); err != nil { - return err - } - // A CPU rasterizer (lavapipe) is not a hardware accelerator: the CPU - // renderer draws a changed region only, while software Vulkan redraws the - // whole window every frame. Prefer a hardware device; remember the software - // one in case no hardware device can present. - var softwareDevice uintptr - var softwareFamily uint32 - for _, device := range devices[:deviceCount] { - var familyCount uint32 - renderer.api.getQueueFamilyProperties(device, &familyCount, nil) - if familyCount == 0 || familyCount > 64 { - continue - } - families := make([]vkQueueFamilyProperties, familyCount) - renderer.api.getQueueFamilyProperties(device, &familyCount, &families[0]) - for index, family := range families[:familyCount] { - if family.Flags&vkQueueGraphics == 0 || family.Count == 0 { - continue - } - var supported uint32 - if renderer.surface == 0 || renderer.api.getSurfaceSupport(device, uint32(index), renderer.surface, &supported) == vkSuccess && supported != 0 { - if renderer.physicalDeviceIsCPU(device) { - if softwareDevice == 0 { - softwareDevice, softwareFamily = device, uint32(index) - } - continue - } - renderer.physical, renderer.queueFamily, renderer.software = device, uint32(index), false - return nil - } - } - } - if softwareDevice != 0 { - renderer.physical, renderer.queueFamily, renderer.software = softwareDevice, softwareFamily, true - return nil - } - return noVulkan("no Vulkan graphics queue can present to XCB", nil) -} - -// physicalDeviceIsCPU reports whether the device is a CPU rasterizer, such as -// Mesa's lavapipe: VkPhysicalDeviceType CPU. Its properties struct is 824 bytes -// and deviceType sits at offset 16. -func (renderer *vulkanRenderer) physicalDeviceIsCPU(device uintptr) bool { - var properties [vkPropertiesSize]byte - renderer.api.getPhysicalDeviceProperties(device, &properties) - return binary.LittleEndian.Uint32(properties[vkPropertiesDeviceTypeOffset:]) == vkPhysicalDeviceTypeCPU -} - func (renderer *vulkanRenderer) createSwapchain() (err error) { oldSwapchain := renderer.swapchain renderer.swapchain = 0 @@ -1182,6 +1062,11 @@ func (renderer *vulkanRenderer) recoverFrom(err error, losses int) (retry bool, if err == nil || !isGraphicsLoss(err) || renderer.connection == 0 || losses >= maxLossRecoveries { return false, err } + if isDeviceLoss(err) && renderer.shared != nil { + // Every window drawing with the device has lost it; the next to make + // itself again gets a new one. + renderer.shared.markLost() + } if recoverErr := renderer.recoverDevice(); recoverErr != nil { return false, errors.Join(err, recoverErr) } @@ -1563,15 +1448,32 @@ func (renderer *vulkanRenderer) close() { if renderer.imageAvailable != 0 { renderer.api.destroySemaphore(renderer.device, renderer.imageAvailable, nil) } - renderer.api.destroyDevice(renderer.device, nil) } + renderer.dropDevice() + renderer.api = nil // the function table is the process's: see loadVulkan +} + +// adopt makes the renderer draw with device's instance, queue and features. +func (renderer *vulkanRenderer) adopt(device *vulkanDevice) { + renderer.instance, renderer.physical, renderer.device, renderer.queue = device.instance, device.physical, device.handle, device.queue + renderer.queueFamily, renderer.software, renderer.dualSource = device.queueFamily, device.software, device.dualSource + renderer.enabledFeatures = device.features +} + +// dropDevice is the last step of a teardown, once every object the renderer +// made on the device is destroyed: the window's surface goes, and the device is +// released, or destroyed when the renderer owns it. +func (renderer *vulkanRenderer) dropDevice() { if renderer.surface != 0 && renderer.instance != 0 { renderer.api.destroySurface(renderer.instance, renderer.surface, nil) } - if renderer.instance != 0 { - renderer.api.destroyInstance(renderer.instance, nil) + if renderer.shared != nil { + renderer.shared.release() + renderer.shared = nil + return } - renderer.api = nil // the function table is the process's: see loadVulkan + owned := vulkanDevice{api: renderer.api, instance: renderer.instance, handle: renderer.device} + owned.destroy() } // noVulkan is the error for a machine that cannot draw: it wraps @@ -1640,14 +1542,8 @@ func (renderer *vulkanRenderer) releaseDevice() { if renderer.imageAvailable != 0 { renderer.api.destroySemaphore(renderer.device, renderer.imageAvailable, nil) } - renderer.api.destroyDevice(renderer.device, nil) - } - if renderer.surface != 0 && renderer.instance != 0 { - renderer.api.destroySurface(renderer.instance, renderer.surface, nil) - } - if renderer.instance != 0 { - renderer.api.destroyInstance(renderer.instance, nil) } + renderer.dropDevice() renderer.instance, renderer.surface, renderer.physical, renderer.device, renderer.queue = 0, 0, 0, 0, 0 renderer.fence, renderer.renderFinished, renderer.imageAvailable = 0, 0, 0 renderer.dualSource = false diff --git a/internal/platform/linux/vulkan_loss.go b/internal/platform/linux/vulkan_loss.go index 9b952f204..a49f3bea8 100644 --- a/internal/platform/linux/vulkan_loss.go +++ b/internal/platform/linux/vulkan_loss.go @@ -33,3 +33,10 @@ func isGraphicsLoss(err error) bool { var result *vulkanResultError return errors.As(err, &result) && (result.status == vkErrorDeviceLost || result.status == vkErrorSurfaceLost) } + +// isDeviceLoss reports whether err says the device itself was lost, not only a +// window's surface. +func isDeviceLoss(err error) bool { + var result *vulkanResultError + return errors.As(err, &result) && result.status == vkErrorDeviceLost +} diff --git a/internal/platform/linux/vulkan_probe_linux.go b/internal/platform/linux/vulkan_probe_linux.go index 13f9e18a8..8d9d55d54 100644 --- a/internal/platform/linux/vulkan_probe_linux.go +++ b/internal/platform/linux/vulkan_probe_linux.go @@ -27,19 +27,19 @@ func vulkanDeviceIsSoftware() bool { softwareProbe.software = true return } - renderer := &vulkanRenderer{api: api} - if err := renderer.createInstance(nil); err != nil { + probe := vulkanDevice{api: api} + if err := probe.createInstance(nil); err != nil { softwareProbe.software = true return } - defer api.destroyInstance(renderer.instance, nil) + defer api.destroyInstance(probe.instance, nil) var count uint32 - if api.enumeratePhysicalDevices(renderer.instance, &count, nil) != vkSuccess || count == 0 || count > 32 { + if api.enumeratePhysicalDevices(probe.instance, &count, nil) != vkSuccess || count == 0 || count > 32 { softwareProbe.software = true return } devices := make([]uintptr, count) - if api.enumeratePhysicalDevices(renderer.instance, &count, &devices[0]) != vkSuccess { + if api.enumeratePhysicalDevices(probe.instance, &count, &devices[0]) != vkSuccess { softwareProbe.software = true return } From a96c67332f9eaed43376541beadce97908fa6425 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 22 Nov 2026 13:01:26 +0800 Subject: [PATCH 13/64] feat(base): respond to the window's and a container's width with From Pages had no shared way to change their layout with their size: each wrote its own `if c.Bounds().Width < N`, and nothing could ask how wide the part of the page an element sits in is. Box.From(breakpoint, change) applies change, made of the Box's own methods, from that breakpoint on, mobile first: ui.Column(c).Gap(8).From(ui.Medium, func(b ui.Box) { b.Row().Gap(16) }) The breakpoints are Material 3's window size classes (Compact, Medium, Expanded, Large, ExtraLarge: 0, 600, 840, 1200, 1600), measured on the page, and Width(n), measured on the nearest Container: a Column whose width comes from where it is placed, never from what it holds (CSS's inline-size containment). Container queries are answered from the Container's last layout; when the layout gives another answer the page is declared again within the same Draw, reusing the Memo retry, and the containment makes the second answer agree. A steady paint declares once and allocates nothing. Ctx.SizeClass and Ctx.AtLeast answer the same questions for code that branches. Row and Column may now change a Row's or a Column's direction, the change From is most often asked for. The paired Motty commit lays out the remote tools' toolbar with it. --- base/box.go | 14 ++++ base/frame.go | 1 + base/layout.go | 5 ++ base/page.go | 16 +++-- base/responsive.go | 152 +++++++++++++++++++++++++++++++++++++++ base/responsive_test.go | 155 ++++++++++++++++++++++++++++++++++++++++ ui/facade.go | 7 ++ ui/vocab.go | 14 ++++ 8 files changed, 360 insertions(+), 4 deletions(-) create mode 100644 base/responsive.go create mode 100644 base/responsive_test.go diff --git a/base/box.go b/base/box.go index 9370c14d1..faeea0961 100644 --- a/base/box.go +++ b/base/box.go @@ -52,6 +52,20 @@ func (b Box) Children(fn func()) Box { return b } +// Row and Column change the direction a Row or a Column lays its children out +// in: what a responsive change (From) does to turn a narrow column into a wide +// row. Other elements keep the direction they were made with. +func (b Box) Row() Box { b.setDirection(row); return b } +func (b Box) Column() Box { b.setDirection(column); return b } + +func (b Box) setDirection(d direction) { + n := b.N() + if n.Kind != kindContainer || n.Dir != row && n.Dir != column { + panic("ui: Row and Column change the direction of a Row or a Column, not of another element") + } + n.Dir = d +} + // Rect is where the element ended up: valid once the page has been laid out // (inside a Draw, after End; or from a Begin/End pair). func (b Box) Rect() Rect { return b.N().Rect } diff --git a/base/frame.go b/base/frame.go index ced2c0644..887a2db43 100644 --- a/base/frame.go +++ b/base/frame.go @@ -198,6 +198,7 @@ type Extra struct { edges [4]float32 // an absolute element's distance from its container's top, right, bottom, left within Rect // what a Popup is kept inside, when not the frame; empty for the frame moves bool // the element's rectangle moves a custom-titlebar window (MovesWindow) + contained bool // a Container: its width does not come from its children (responsive.go) scrollManual bool // ScrollAt: the application owns the offset and wheel input nativeView gfx.NativeViewID // the native view that fills the element (NativeView) bind int32 // 1 + the index of the element's binding in frame.binds, or 0 (see bind.go) diff --git a/base/layout.go b/base/layout.go index 7e642c9cc..cb6865200 100644 --- a/base/layout.go +++ b/base/layout.go @@ -193,6 +193,11 @@ func (f *Frame) measureContainer(n *Node, axis int) { } is, ie := n.Inset(axis) n.Pref[axis] = total + is + ie + if axis == AxisX && n.Ext != 0 && f.Exts[n.Ext].contained { + // A Container is as wide as it is placed, not as what it holds, so the + // queries inside it cannot change the width they read. + n.Pref[axis] = is + ie + } if n.Flags&flagScroll == 0 { return } diff --git a/base/page.go b/base/page.go index 7f789625e..91c462c0b 100644 --- a/base/page.go +++ b/base/page.go @@ -299,10 +299,15 @@ type Page struct { memoBoxes []memoBox memoChecks []memoCheckOf recording []*memoEntry // the Memos being declared, outermost first - retry bool // a Memo's copy failed: the paint is done again - overlay bool // the last paint declared an open Popover, Modal, Menu or Select - lists []listDecl - listRows []int32 // the row containers of this paint's Lists + retry bool // a Memo's copy failed, or a container query was answered wrong: the paint is done again + // containers are this paint's Containers, answers the container queries + // asked of them, and containerWidths the Containers' widths at the last + // layout, which the queries read (responsive.go). + containers, containerWidths []containerWidth + answers []containerAnswer + overlay bool // the last paint declared an open Popover, Modal, Menu or Select + lists []listDecl + listRows []int32 // the row containers of this paint's Lists baseText window.TextInputProvider baseScroll func(gfx.ScrollEvent) gfx.EventResult @@ -819,6 +824,9 @@ func (p *Page) paintOnce(Surface *gfx.Canvas, bounds Rect, View func(C)) { p.Nodes = append(p.Nodes[:0], protoNode{scope: p.root, named: true, parentNode: -1}) // node 0, the root column View(&p.ctx) f.End() + if p.settleContainers() { + p.retry = true + } if s := p.drag; s != nil && s.epoch != p.epoch { s.Cancel() } diff --git a/base/responsive.go b/base/responsive.go new file mode 100644 index 000000000..8dae7184d --- /dev/null +++ b/base/responsive.go @@ -0,0 +1,152 @@ +package base + +import ( + "math" + + "github.com/vivaui/viva/gfx" +) + +// Breakpoint is where a responsive change begins (From, AtLeast): a window size +// class, which measures the page's width, or Width(n), which measures the +// nearest Container's. +type Breakpoint uint32 + +// The window size classes (Material 3's window size classes), named by the +// devices they fit; each begins at its width in logical pixels. +const ( + Compact Breakpoint = 0 // phones held upright + Medium Breakpoint = 600 // phones on their side, tablets held upright, narrow windows + Expanded Breakpoint = 840 // tablets on their side, most desktop windows + Large Breakpoint = 1200 // large desktop windows + ExtraLarge Breakpoint = 1600 // wide screens +) + +// containerQuery marks a Breakpoint that measures the nearest Container. +const containerQuery Breakpoint = 1 << 31 + +// Width is the breakpoint at which the nearest Container is n logical pixels +// wide inside its padding, as a CSS container query's min-width. +func Width(n float32) Breakpoint { + return containerQuery | Breakpoint(min(math.Ceil(float64(max(n, 0))), float64(containerQuery-1))) +} + +func (bp Breakpoint) minimum() float32 { return float32(bp &^ containerQuery) } + +// SizeClass is the window size class the page's width is in: Compact, Medium, +// Expanded, Large or ExtraLarge. +func (c *Ctx) SizeClass() Breakpoint { + width := c.f.Bounds().Width + for _, class := range [...]Breakpoint{ExtraLarge, Large, Expanded, Medium} { + if width >= class.minimum() { + return class + } + } + return Compact +} + +// AtLeast reports whether the page, or for Width the nearest Container around +// what is declared next, is at least as wide as bp. +func (c *Ctx) AtLeast(bp Breakpoint) bool { return c.page.reaches(bp, c.f.Parent) } + +// From applies change to the element when it is at least as wide as bp: the +// page, for a window size class, or the nearest Container around the element, +// for Width. Declare the narrowest form first and widen it with From, smallest +// breakpoint first, as mobile-first styles do; change uses the Box's own +// methods. +// +// ui.Column(c).Gap(8).From(ui.Medium, func(b ui.Box) { b.Row().Gap(16) }) +func (b Box) From(bp Breakpoint, change func(Box)) Box { + if b.f.page.reaches(bp, b.N().Parent) { + change(b) + } + return b +} + +// Container is a Column that Width breakpoints inside it measure. Its width +// comes from where it is placed, never from what it holds (CSS's inline-size +// containment), so what its queries change cannot change the width they read. +func Container(c C) Box { + b := Column(c) + c.f.Extra(b.i).contained = true + named := c.page.Nodes[b.i] + id := c.page.ID(Place{Node: named.parentNode, scope: named.parentScope, Name: named.Name}) + c.page.containers = append(c.page.containers, containerWidth{node: b.i, id: id}) + return b +} + +// containerWidth is a Container: its element this paint, its identity across +// paints, and its width inside its padding the last time it was laid out. +type containerWidth struct { + node int32 + id gfx.ID + width float32 +} + +// containerAnswer is a container query asked this paint and the answer it got, +// checked against the layout once it is done. +type containerAnswer struct { + node int32 + minimum float32 + yes bool +} + +// reaches answers bp for an element whose parent is parent. +func (p *Page) reaches(bp Breakpoint, parent int32) bool { + if bp&containerQuery == 0 { + return p.ctx.f.Bounds().Width >= bp.minimum() + } + f := p.ctx.f + node := parent + for node >= 0 && (f.Nodes[node].Ext == 0 || !f.Exts[f.Nodes[node].Ext].contained) { + node = f.Nodes[node].Parent + } + if node < 0 { + return false // no Container around it: nothing to measure + } + width, known := p.lastContainerWidth(p.containerID(node)) + yes := known && width >= bp.minimum() + p.answers = append(p.answers, containerAnswer{node: node, minimum: bp.minimum(), yes: yes}) + return yes +} + +// containerID is the identity of the Container that is element node. +func (p *Page) containerID(node int32) gfx.ID { + for _, container := range p.containers { + if container.node == node { + return container.id + } + } + return gfx.ID{} +} + +func (p *Page) lastContainerWidth(id gfx.ID) (float32, bool) { + for _, entry := range p.containerWidths { + if entry.id == id { + return entry.width, true + } + } + return 0, false +} + +// settleContainers keeps each Container's laid-out width for the next paint and +// reports whether a container query asked this paint got another answer than +// the layout gives: the paint is done again, which then answers from these +// widths. A Container's width does not depend on what it holds, so the second +// paint agrees. +func (p *Page) settleContainers() (again bool) { + f := p.ctx.f + p.containerWidths = p.containerWidths[:0] + for _, container := range p.containers { + n := &f.Nodes[container.node] + container.width = max(n.Rect.Width-n.PadX(), 0) + p.containerWidths = append(p.containerWidths, container) + } + for _, answer := range p.answers { + n := &f.Nodes[answer.node] + if (max(n.Rect.Width-n.PadX(), 0) >= answer.minimum) != answer.yes { + again = true + } + } + p.containers, p.answers = p.containers[:0], p.answers[:0] + return again +} diff --git a/base/responsive_test.go b/base/responsive_test.go new file mode 100644 index 000000000..4ebdb9810 --- /dev/null +++ b/base/responsive_test.go @@ -0,0 +1,155 @@ +package base + +import ( + "testing" + + "github.com/vivaui/viva/gfx" +) + +// The window size class is a function of the page's width alone, and AtLeast +// agrees with it at every class's first pixel and the one before it. +func TestSizeClassFollowsThePageWidth(t *testing.T) { + theme := gfx.LightTheme() + page := NewPage(PageConfig{Theme: &theme}) + canvas := testCanvas() + classes := []Breakpoint{Compact, Medium, Expanded, Large, ExtraLarge} + for index, class := range classes { + for _, width := range []float32{class.minimum(), class.minimum() - 1} { + if width < 0 { + continue + } + want := class + if width < class.minimum() { + want = classes[index-1] + } + var got Breakpoint + var reached []bool + page.Draw(canvas, gfx.Rect{Width: width, Height: 100}, func(c C) { + got = c.SizeClass() + reached = reached[:0] + for _, other := range classes { + reached = append(reached, c.AtLeast(other)) + } + }) + if got != want { + t.Fatalf("a page %v wide is in class %d, want %d", width, got, want) + } + for i, other := range classes { + if reached[i] != (other <= want) { + t.Fatalf("a page %v wide: AtLeast(%d) = %v, but its class is %d", width, other, reached[i], want) + } + } + } + } +} + +// From changes an element from its breakpoint on: a column of two blocks below +// Medium stacks them, and from Medium lays them side by side. +func TestFromTurnsAColumnIntoARowAtItsBreakpoint(t *testing.T) { + theme := gfx.LightTheme() + page := NewPage(PageConfig{Theme: &theme}) + canvas := testCanvas() + var first, second Box + view := func(c C) { + Column(c).Gap(8).From(Medium, func(b Box) { b.Row().Gap(16) }).Children(func() { + first = Column(c).Size(100, 40) + second = Column(c).Size(100, 40) + }) + } + page.Draw(canvas, gfx.Rect{Width: Medium.minimum() - 1, Height: 300}, view) + a, b := first.Rect(), second.Rect() + if b.Y < a.Y+a.Height || b.X != a.X { + t.Fatalf("below Medium the blocks are at %v and %v, want the second under the first", a, b) + } + page.Draw(canvas, gfx.Rect{Width: Medium.minimum(), Height: 300}, view) + a, b = first.Rect(), second.Rect() + if b.X < a.X+a.Width || b.Y != a.Y { + t.Fatalf("from Medium the blocks are at %v and %v, want them side by side", a, b) + } +} + +// A container query reads the Container's width, not the window's, and is +// answered right in the first paint: the same card stacks in a narrow sidebar +// and lies in a row in the wide main area. Later paints declare the page once. +func TestContainerQueryIsAnsweredInTheFirstPaint(t *testing.T) { + theme := gfx.LightTheme() + page := NewPage(PageConfig{Theme: &theme}) + canvas := testCanvas() + type card struct{ first, second Box } + var narrow, wide card + declarations := 0 + cardIn := func(c C, into *card) { + Column(c).From(Width(480), func(b Box) { b.Row() }).Children(func() { + into.first = Column(c).Size(100, 40) + into.second = Column(c).Size(100, 40) + }) + } + view := func(c C) { + declarations++ + Row(c).Fill().Children(func() { + Container(c).Width(240).Children(func() { cardIn(c, &narrow) }) + Container(c).Grow(1).Children(func() { cardIn(c, &wide) }) + }) + } + bounds := gfx.Rect{Width: 1000, Height: 400} + page.Draw(canvas, bounds, view) + stacked := func(k card) bool { return k.second.Rect().Y >= k.first.Rect().Y+k.first.Rect().Height } + if !stacked(narrow) || stacked(wide) { + t.Fatalf("first paint: narrow card stacked=%v, wide card stacked=%v; want the narrow one stacked and the wide one in a row", stacked(narrow), stacked(wide)) + } + declarations = 0 + page.Draw(canvas, bounds, view) + if declarations != 1 { + t.Fatalf("a steady paint declared the page %d times", declarations) + } + if !stacked(narrow) || stacked(wide) { + t.Fatal("a steady paint changed the answers") + } +} + +// A Container's width comes from where it is placed, never from what it holds, +// so what a query changes inside it cannot change what the query reads. +func TestContainerWidthDoesNotFollowItsContent(t *testing.T) { + theme := gfx.LightTheme() + page := NewPage(PageConfig{Theme: &theme}) + canvas := testCanvas() + var container Box + inner := float32(100) + view := func(c C) { + Row(c).Fill().Children(func() { + container = Container(c).Pad(4).Children(func() { Column(c).Size(inner, 20) }) + }) + } + bounds := gfx.Rect{Width: 800, Height: 100} + page.Draw(canvas, bounds, view) + before := container.Rect().Width + inner = 500 + page.Draw(canvas, bounds, view) + if after := container.Rect().Width; after != before { + t.Fatalf("the container is %v wide holding 100 and %v holding 500", before, after) + } +} + +// Responsive changes cost nothing once warm. +func TestResponsivePaintDoesNotAllocate(t *testing.T) { + theme := gfx.LightTheme() + page := NewPage(PageConfig{Theme: &theme}) + canvas := testCanvas() + view := func(c C) { + Row(c).Fill().Children(func() { + Container(c).Grow(1).Children(func() { + Column(c).Gap(8).From(Medium, func(b Box) { b.Row().Gap(16) }). + From(Width(480), func(b Box) { b.Pad(12) }).Children(func() { + Column(c).Size(100, 40) + }) + }) + }) + } + bounds := gfx.Rect{Width: 900, Height: 300} + for range 3 { + page.Draw(canvas, bounds, view) + } + if allocations := testing.AllocsPerRun(50, func() { page.Draw(canvas, bounds, view) }); allocations != 0 { + t.Fatalf("a steady responsive paint allocated %v times", allocations) + } +} diff --git a/ui/facade.go b/ui/facade.go index 0e492360a..c0d5d57a6 100644 --- a/ui/facade.go +++ b/ui/facade.go @@ -117,6 +117,13 @@ func Flow(c C) Box { return base.Flow(c) } func Grid(c C, minCell float32) Box { return base.Grid(c, minCell) } +// Container is a Column that Width breakpoints inside it measure; its width +// comes from where it is placed, never from what it holds. +func Container(c C) Box { return base.Container(c) } + +// Width is the breakpoint at which the nearest Container is n logical pixels wide. +func Width(n float32) Breakpoint { return base.Width(n) } + func CustomLayout(c C, layout Layout) Box { return base.CustomLayout(c, layout) } func Scroll(c C) Box { useScroll(); return base.Scroll(c) } diff --git a/ui/vocab.go b/ui/vocab.go index 5fbb92e37..2b09d7d27 100644 --- a/ui/vocab.go +++ b/ui/vocab.go @@ -11,6 +11,20 @@ import ( // package base's names, the behavior layer's vocabulary; ui re-exports them as // the permanent application facade. type Color = base.Color + +// Breakpoint is where a responsive change begins (Box.From, C.AtLeast): a window +// size class, or Width(n) for the nearest Container. +type Breakpoint = base.Breakpoint + +// The window size classes, by the page's width in logical pixels. +const ( + Compact = base.Compact // from 0: phones held upright + Medium = base.Medium // from 600: phones on their side, tablets held upright, narrow windows + Expanded = base.Expanded // from 840: tablets on their side, most desktop windows + Large = base.Large // from 1200: large desktop windows + ExtraLarge = base.ExtraLarge // from 1600: wide screens +) + type Rect = base.Rect type Size = base.Size type Point = base.Point From 05804abe4331d40ebc272a55536c6070820e90db Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 22 Nov 2026 13:09:52 +0800 Subject: [PATCH 14/64] feat(base): hide an element with Hide, show it again with Show A responsive change could alter an element but not take it away: hiding meant wrapping it in an if, which the narrow layout of a Container cannot do, as a container query is answered with From. Box.Hide takes the element out of the page as CSS's display: none: at End, before layout, it is detached from its container, so it takes no room, is not painted and gives no hit, focus region or accessibility node. What it holds is still declared and keeps its identities and state, and Show undoes it: ui.Text(c, host.Address).Hide().From(ui.Expanded, func(b ui.Box) { b.Show() }) ADR 0094. --- base/frame.go | 5 ++++ base/hidden.go | 63 +++++++++++++++++++++++++++++++++++++++++ base/responsive_test.go | 40 ++++++++++++++++++++++++++ 3 files changed, 108 insertions(+) create mode 100644 base/hidden.go diff --git a/base/frame.go b/base/frame.go index 887a2db43..96681f28b 100644 --- a/base/frame.go +++ b/base/frame.go @@ -199,6 +199,7 @@ type Extra struct { within Rect // what a Popup is kept inside, when not the frame; empty for the frame moves bool // the element's rectangle moves a custom-titlebar window (MovesWindow) contained bool // a Container: its width does not come from its children (responsive.go) + hidden bool // Hide: the element and what it holds are taken out of the page (hidden.go) scrollManual bool // ScrollAt: the application owns the offset and wheel input nativeView gfx.NativeViewID // the native view that fills the element (NativeView) bind int32 // 1 + the index of the element's binding in frame.binds, or 0 (see bind.go) @@ -247,6 +248,7 @@ type Frame struct { Images []gfx.Bitmap // what each Image element draws, indexed by its aux Exts []Extra // exts[0] is never written: an element without extras points at it Floats []int32 // the Popups, which belong to no container + hidden []int32 // the elements Hide was called on, taken out of the page at End States []stateLooks // what Hover, Pressed and Focus declared, by element Draws []drawHooks // what Draw and DrawOver declared, by element memoDepth int // how many Memos of a page are recording what is declared now @@ -342,6 +344,7 @@ func (View *View) Begin(Surface *gfx.Canvas, Palette Theme, bounds Rect) *Frame clear(f.Binds) // a binding holds pointers into the model: not past the frame f.Binds = f.Binds[:0] f.Floats = f.Floats[:0] + f.hidden = f.hidden[:0] f.States, f.Gradients, f.Stops = f.States[:0], f.Gradients[:0], f.Stops[:0] clear(f.Draws) // a callback holds what it captured: not past the frame it was declared in f.Draws = f.Draws[:0] @@ -378,6 +381,7 @@ func (f *Frame) End() { f.done = true f.checkHits() f.checkAttributes() + f.detachHidden() f.applyRecipes() f.resolveTables() f.resolveDialogFocus() @@ -459,6 +463,7 @@ func (f *Frame) trim() { f.Draws = trimFlexCapacity(f.Draws) f.Binds = trimFlexCapacity(f.Binds) f.Floats = trimFlexCapacity(f.Floats) + f.hidden = trimFlexCapacity(f.hidden) f.Lines = trimFlexCapacity(f.Lines) f.Ellipses = trimFlexCapacity(f.Ellipses) f.Wraps = trimFlexCapacity(f.Wraps) diff --git a/base/hidden.go b/base/hidden.go new file mode 100644 index 000000000..01a176fc3 --- /dev/null +++ b/base/hidden.go @@ -0,0 +1,63 @@ +package base + +import "slices" + +// Hide takes the element out of the page: it and what it holds take no room, are +// not painted, take no pointer, keyboard or focus, and are not in the +// accessibility tree, as CSS's display: none. What it holds is still declared, +// so the controls in it keep their identities and state, and a responsive change +// shows it again: +// +// ui.Text(c, host.Address).Hide().From(ui.Expanded, func(b ui.Box) { b.Show() }) +func (b Box) Hide() Box { + if b.i == 0 { + panic("ui: the page's root cannot be hidden") + } + extra := b.f.Extra(b.i) + if !extra.hidden { + extra.hidden = true + b.f.hidden = append(b.f.hidden, b.i) + } + return b +} + +// Show undoes Hide. +func (b Box) Show() Box { + if n := b.N(); n.Ext != 0 { + b.f.Exts[n.Ext].hidden = false + } + return b +} + +// detachHidden takes the elements still hidden out of their containers, or out +// of the popups, before the page is laid out: layout and paint walk the tree +// from the root, so a detached subtree is neither laid out nor painted, and so +// gives no hit. +func (f *Frame) detachHidden() { + for _, i := range f.hidden { + n := &f.Nodes[i] + if n.Ext == 0 || !f.Exts[n.Ext].hidden { + continue + } + if n.Parent < 0 { + if at := slices.Index(f.Floats, i); at >= 0 { + f.Floats = slices.Delete(f.Floats, at, at+1) + } + continue + } + parent := &f.Nodes[n.Parent] + previous := int32(-1) + for c := parent.First; c >= 0 && c != i; c = f.Nodes[c].Next { + previous = c + } + if previous < 0 { + parent.First = n.Next + } else { + f.Nodes[previous].Next = n.Next + } + if parent.Last == i { + parent.Last = previous + } + n.Next = -1 + } +} diff --git a/base/responsive_test.go b/base/responsive_test.go index 4ebdb9810..4bb568a12 100644 --- a/base/responsive_test.go +++ b/base/responsive_test.go @@ -153,3 +153,43 @@ func TestResponsivePaintDoesNotAllocate(t *testing.T) { t.Fatalf("a steady responsive paint allocated %v times", allocations) } } + +// A hidden element takes no room, paints no hit and so takes no pointer or +// focus, while what it holds keeps its identity; From can show it again. +func TestHideTakesAnElementOutOfThePage(t *testing.T) { + theme := gfx.LightTheme() + page := NewPage(PageConfig{Theme: &theme}) + canvas := testCanvas() + var before, after Box + var buttonID gfx.ID + view := func(c C) { + Column(c).Children(func() { + before = Column(c).Size(100, 40) + Row(c).Height(40).Hide().From(Expanded, func(b Box) { b.Show() }).Children(func() { + button := Button(c, "Details") + buttonID = button.N().ID + }) + after = Column(c).Size(100, 40) + }) + } + hasHit := func() bool { + for _, hit := range canvas.Hits() { + if hit.ID == buttonID { + return true + } + } + return false + } + page.Draw(canvas, gfx.Rect{Width: Expanded.minimum() - 1, Height: 400}, view) + hiddenID := buttonID + if gap := after.Rect().Y - (before.Rect().Y + before.Rect().Height); gap != 0 || hasHit() { + t.Fatalf("hidden: the next block is %v below the first, hit painted %v; want 0 and none", gap, hasHit()) + } + page.Draw(canvas, gfx.Rect{Width: Expanded.minimum(), Height: 400}, view) + if gap := after.Rect().Y - (before.Rect().Y + before.Rect().Height); gap != 40 || !hasHit() { + t.Fatalf("shown: the next block is %v below the first, hit painted %v; want 40 and one", gap, hasHit()) + } + if buttonID != hiddenID { + t.Fatal("the button changed identity when it was shown") + } +} From 75a50706104ad819ab0e691e8d6f19650d88d3df Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 22 Nov 2026 13:12:47 +0800 Subject: [PATCH 15/64] fix(app): read the titlebar insets from the window, not the platform app.TitlebarInsets answered per platform, the same for every window and at every moment, so a page kept room for the traffic lights or the window buttons in full screen, where they are not on its strip, and in windows whose titlebar is the system's. The runtime now hands each paint the insets of the window it paints (Canvas.TitlebarInsets, ui.C.TitlebarInsets): the platform's buttons for a custom titlebar, none in full screen or under a system titlebar. app.TitlebarInsets is removed; the paired Motty commit reads the insets from the canvas. ADR 0094. --- app/painter.go | 23 ++++++++++++++++---- app/titlebar_insets_test.go | 37 +++++++++++++++++++++++++++++++++ app/window_controls_darwin.go | 9 ++++---- app/window_controls_none.go | 9 ++++---- app/window_controls_test.go | 2 +- app/window_controls_viva.go | 9 ++++---- base/page.go | 5 +++++ cmd/titlebar-demo/main.go | 2 +- examples/guides/windows/main.go | 2 +- gfx/canvas.go | 16 ++++++++++++++ 10 files changed, 92 insertions(+), 22 deletions(-) create mode 100644 app/titlebar_insets_test.go diff --git a/app/painter.go b/app/painter.go index f0186e675..380b76c2e 100644 --- a/app/painter.go +++ b/app/painter.go @@ -23,9 +23,12 @@ import ( // native label list, so an unchanged repaint performs no renderer work. type painter struct { fullscreen bool - paint func(canvas *gfx.Canvas, size gfx.Size) - onPointer func(gfx.PointerEvent) gfx.EventResult - onKey func(gfx.KeyEvent) gfx.EventResult + // customTitlebar says the page draws the window's titlebar strip itself + // (WindowCustomTitlebar), so the window buttons cover part of it. + customTitlebar bool + paint func(canvas *gfx.Canvas, size gfx.Size) + onPointer func(gfx.PointerEvent) gfx.EventResult + onKey func(gfx.KeyEvent) gfx.EventResult // onDeactivate is the application's, called after a window loses the // activation and the keys that were down are released. onDeactivate func() gfx.EventResult @@ -179,7 +182,8 @@ func newPainterWithClock(canvas *gfx.Canvas, config *Config, clock func() time.D } return value } - if config.WindowMode == WindowCustomTitlebar && controlsDrawnByViva { + painter.customTitlebar = config.WindowMode == WindowCustomTitlebar + if painter.customTitlebar && controlsDrawnByViva { painter.controls = newWindowControls(config) } if _, err := painter.publish(); err != nil { @@ -916,6 +920,16 @@ func (painter *painter) repaintAfterInput() (platform.Frame, error) { return painter.repaint() } +// titlebarInsets is how much of the titlebar strip the page draws the window +// buttons cover now: none for a window whose titlebar is the system's, and none +// in full screen, where the buttons are not shown on the strip. +func (painter *painter) titlebarInsets() (leading, trailing float32) { + if !painter.customTitlebar || painter.fullscreen { + return 0, 0 + } + return platformTitlebarInsets() +} + // maxFocusPasses bounds the paints settleFocus adds to one frame: a page whose // every paint moves the focus somewhere new shows the last move. const maxFocusPasses = 2 @@ -967,6 +981,7 @@ func (painter *painter) paintCanvas() { painter.canvas.SetInteraction(painter.pointer.Hovered(), painter.pointer.Pressed(), focused, visible) painter.canvas.SetHoveredRole(painter.pointer.HoveredRole()) painter.canvas.SetPointerOnSurface(painter.onSurface) + painter.canvas.SetTitlebarInsets(painter.titlebarInsets()) painter.canvas.SetScroll(painter.scrollX, painter.scrollY) painter.canvas.BeginFrame() painter.paint(painter.canvas, painter.size) diff --git a/app/titlebar_insets_test.go b/app/titlebar_insets_test.go new file mode 100644 index 000000000..a0121a5e4 --- /dev/null +++ b/app/titlebar_insets_test.go @@ -0,0 +1,37 @@ +//go:build darwin || windows || linux + +package app + +import ( + "testing" + + "github.com/vivaui/viva/gfx" +) + +// The page reads how much of its titlebar strip the window buttons cover from +// the window it paints: the platform's buttons in a custom titlebar, nothing in +// full screen, where they leave the strip, and nothing under a system titlebar. +func TestTitlebarInsetsFollowTheWindow(t *testing.T) { + read := func(mode WindowMode, fullscreen bool) (float32, float32) { + var canvas gfx.Canvas + var leading, trailing float32 + config := Config{Title: "insets", Width: 400, Height: 300, WindowMode: mode, TitlebarHeight: 36} + config.Paint = func(canvas *gfx.Canvas, size gfx.Size) { leading, trailing = canvas.TitlebarInsets() } + painter := newTestPainter(t, &canvas, config) + painter.fullscreenHandler(nil)(fullscreen) + if _, err := painter.repaint(); err != nil { + t.Fatal(err) + } + return leading, trailing + } + wantLeading, wantTrailing := platformTitlebarInsets() + if leading, trailing := read(WindowCustomTitlebar, false); leading != wantLeading || trailing != wantTrailing { + t.Fatalf("custom titlebar: insets %v, %v, want the platform's %v, %v", leading, trailing, wantLeading, wantTrailing) + } + if leading, trailing := read(WindowCustomTitlebar, true); leading != 0 || trailing != 0 { + t.Fatalf("full screen: insets %v, %v, want none", leading, trailing) + } + if leading, trailing := read(WindowTitled, false); leading != 0 || trailing != 0 { + t.Fatalf("system titlebar: insets %v, %v, want none", leading, trailing) + } +} diff --git a/app/window_controls_darwin.go b/app/window_controls_darwin.go index e79cf95bb..32c52f754 100644 --- a/app/window_controls_darwin.go +++ b/app/window_controls_darwin.go @@ -5,8 +5,7 @@ package app // controlsDrawnByViva is false on macOS: the system draws the traffic lights. const controlsDrawnByViva = false -// TitlebarInsets is how much of a WindowCustomTitlebar's strip the system or Viva -// covers with window buttons: leading at the start of the strip, trailing at its -// end, in logical pixels. An application keeps its own content clear of both. -// On macOS the traffic lights are the system's, at the leading end. -func TitlebarInsets() (leading, trailing float32) { return 70, 0 } +// platformTitlebarInsets is how much of a WindowCustomTitlebar's strip the +// window buttons cover while they show: leading at the start of the strip, +// trailing at its end, in logical pixels. On macOS the traffic lights are the system's, at the leading end. +func platformTitlebarInsets() (leading, trailing float32) { return 70, 0 } diff --git a/app/window_controls_none.go b/app/window_controls_none.go index e7d243258..81d48ba51 100644 --- a/app/window_controls_none.go +++ b/app/window_controls_none.go @@ -5,8 +5,7 @@ package app // controlsDrawnByViva is false where there is no native window to give controls. const controlsDrawnByViva = false -// TitlebarInsets is how much of a WindowCustomTitlebar's strip the system or Viva -// covers with window buttons: leading at the start of the strip, trailing at its -// end, in logical pixels. An application keeps its own content clear of both. -// There is none here. -func TitlebarInsets() (leading, trailing float32) { return 0, 0 } +// platformTitlebarInsets is how much of a WindowCustomTitlebar's strip the +// window buttons cover while they show: leading at the start of the strip, +// trailing at its end, in logical pixels. There is none here. +func platformTitlebarInsets() (leading, trailing float32) { return 0, 0 } diff --git a/app/window_controls_test.go b/app/window_controls_test.go index a904112a8..a380350d0 100644 --- a/app/window_controls_test.go +++ b/app/window_controls_test.go @@ -87,7 +87,7 @@ func TestWindowButtonsSitAtTheTrailingEndOfTheStripAndAreAsTallAsIt(t *testing.T t.Fatalf("%s is on layer %d, want the top one", want.name, hit.Layer) } } - if leading, trailing := TitlebarInsets(); trailing != 0 && trailing != 3*WindowControlWidth || leading != 0 && leading != 70 { + if leading, trailing := fixture.canvas.TitlebarInsets(); trailing != 0 && trailing != 3*WindowControlWidth || leading != 0 && leading != 70 { t.Fatalf("insets = %v, %v", leading, trailing) } } diff --git a/app/window_controls_viva.go b/app/window_controls_viva.go index 8a86fd0c0..e8a1982c1 100644 --- a/app/window_controls_viva.go +++ b/app/window_controls_viva.go @@ -6,8 +6,7 @@ package app // close buttons for a window without a titlebar, so Viva draws them. const controlsDrawnByViva = true -// TitlebarInsets is how much of a WindowCustomTitlebar's strip the system or Viva -// covers with window buttons: leading at the start of the strip, trailing at its -// end, in logical pixels. An application keeps its own content clear of both. -// Here the buttons are Viva's, at the trailing end. -func TitlebarInsets() (leading, trailing float32) { return 0, 3 * WindowControlWidth } +// platformTitlebarInsets is how much of a WindowCustomTitlebar's strip the +// window buttons cover while they show: leading at the start of the strip, +// trailing at its end, in logical pixels. Here the buttons are Viva's, at the trailing end. +func platformTitlebarInsets() (leading, trailing float32) { return 0, 3 * WindowControlWidth } diff --git a/base/page.go b/base/page.go index 91c462c0b..7c506b479 100644 --- a/base/page.go +++ b/base/page.go @@ -121,6 +121,11 @@ func (c *Ctx) Theme() *Theme { return &c.f.Palette } // Bounds is the rectangle the page is laid out in, as the window gave it. func (c *Ctx) Bounds() Rect { return c.f.Bounds() } +// TitlebarInsets is how much of the titlebar strip the window buttons cover, at +// its leading and trailing ends: zero for a system titlebar and in full screen. +// A page that draws a WindowCustomTitlebar keeps its strip's content clear of it. +func (c *Ctx) TitlebarInsets() (leading, trailing float32) { return c.f.Surface.TitlebarInsets() } + // Canvas is the page's canvas, for measuring text or components before declaring // them and for reading pointer/focus state. Declare elements through C and paint // through Draw; do not paint from here. diff --git a/cmd/titlebar-demo/main.go b/cmd/titlebar-demo/main.go index b749f9250..3c9f0a5e4 100644 --- a/cmd/titlebar-demo/main.go +++ b/cmd/titlebar-demo/main.go @@ -31,7 +31,7 @@ func main() { WindowMode: app.WindowCustomTitlebar, TitlebarHeight: stripHeight, ClearColor: app.Color{Red: 0.09, Green: 0.1, Blue: 0.13, Alpha: 1}, Paint: func(canvas *gfx.Canvas, size gfx.Size) { - leading, _ := app.TitlebarInsets() + leading, _ := canvas.TitlebarInsets() canvas.MoveRegion(gfx.Rect{Width: size.Width, Height: stripHeight}) canvas.Fill(gfx.Rect{Width: size.Width, Height: stripHeight}, gfx.Color{Red: 0.14, Green: 0.16, Blue: 0.22, Alpha: 1}) canvas.Label("drag the strip; double-click maximizes", gfx.Rect{X: leading + 14, Y: 9, Width: 400, Height: 20}, gfx.TextStyle{Size: 13, Color: ink}) diff --git a/examples/guides/windows/main.go b/examples/guides/windows/main.go index 5da5ce405..74cedd8cc 100644 --- a/examples/guides/windows/main.go +++ b/examples/guides/windows/main.go @@ -17,7 +17,7 @@ type notes struct { func (state *notes) page(c ui.C) { // The bar is as tall as the title bar and leaves room for the window buttons // on whichever side the platform puts them. - leading, trailing := app.TitlebarInsets() + leading, trailing := c.TitlebarInsets() ui.Column(c).Fill().Children(func() { ui.Row(c).Height(28).PadRight(trailing).PadLeft(leading).Items(ui.Center).MovesWindow().Children(func() { ui.Text(c, "Notes").Muted() diff --git a/gfx/canvas.go b/gfx/canvas.go index 6ed8793e8..dfc6a22b1 100644 --- a/gfx/canvas.go +++ b/gfx/canvas.go @@ -763,6 +763,8 @@ type Canvas struct { // it. A menu row uses it to tell the menu's own padding from the world outside // the menu. onSurface bool + // titlebarLeading and titlebarTrailing are the window's TitlebarInsets. + titlebarLeading, titlebarTrailing float32 // prevHovered is the hit the pointer was on at the end of the previous // paint, which is what HoverCrossed compares against. prevHovered ID @@ -2084,6 +2086,20 @@ func (canvas *Canvas) SetPointerOnSurface(on bool) { canvas.onSurface = on } +// TitlebarInsets is how much of the titlebar strip a page draws itself the +// window buttons cover: leading at its start, trailing at its end, in logical +// pixels. Both are zero for a window whose titlebar is the system's and for one +// in full screen. A page keeps the strip's own content clear of them. +func (canvas *Canvas) TitlebarInsets() (leading, trailing float32) { + return canvas.titlebarLeading, canvas.titlebarTrailing +} + +// SetTitlebarInsets records the window's TitlebarInsets; the runtime calls it +// before each paint. +func (canvas *Canvas) SetTitlebarInsets(leading, trailing float32) { + canvas.titlebarLeading, canvas.titlebarTrailing = leading, trailing +} + // HoverCrossed reports whether the pointer reached a different hit since the // previous paint. Lists use it to move their current row onto the row the // pointer entered, without letting a pointer that rests in place take the row From e52205d2babc9a1bae1ee08b608070fdb3e0aed1 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 22 Nov 2026 14:20:49 +0800 Subject: [PATCH 16/64] fix(cmd/viva): regenerate the component recipes 98bab0a9, c9b165f1, 932c9aae and later commits changed popover, select, hierarchy menu and code editor components without running tools/componentgen, so TestGeneratedRecipesAreCurrent and TestInstalledRecipesMatchReferenceSource failed on every main run since 98bab0a9. --- cmd/viva/components_gen.go | 6 +- cmd/viva/templates/code_editor.go.txt | 23 ++- cmd/viva/templates/code_editor_layout.go.txt | 195 ++++++++++++++++--- cmd/viva/templates/hierarchy_menu.go.txt | 20 +- cmd/viva/templates/multi_select.go.txt | 20 +- cmd/viva/templates/popover.go.txt | 31 +++ cmd/viva/templates/single_select.go.txt | 8 +- 7 files changed, 234 insertions(+), 69 deletions(-) diff --git a/cmd/viva/components_gen.go b/cmd/viva/components_gen.go index 3663142e3..3da3a6345 100644 --- a/cmd/viva/components_gen.go +++ b/cmd/viva/components_gen.go @@ -138,7 +138,7 @@ var componentRequires = map[string][]string{ "find-bar": {"button", "dialog", "input", "toggle", "tree"}, "go-to-line": {"button", "find-bar", "input"}, "graph": {"graph-sim"}, - "hierarchy-menu": {"checkbox", "dialog", "dropdown-menu", "tree"}, + "hierarchy-menu": {"checkbox", "dialog", "dropdown-menu", "popover", "tree"}, "hover-card": {"dialog", "popover"}, "input": {"textarea"}, "input-group": {"button", "input", "spinner", "textarea"}, @@ -149,7 +149,7 @@ var componentRequires = map[string][]string{ "marker": {"spinner"}, "menubar": {"dialog", "direction", "dropdown-menu", "hover-card", "popover"}, "metric-card": {"card"}, - "multi-select": {"checkbox", "combobox", "dialog", "dropdown-menu", "input", "tree"}, + "multi-select": {"checkbox", "combobox", "dialog", "dropdown-menu", "input", "popover", "tree"}, "native-select": {"input", "tree"}, "navigation-menu": {"dialog", "direction", "hover-card", "tree"}, "pagination": {"breadcrumb", "tree"}, @@ -161,7 +161,7 @@ var componentRequires = map[string][]string{ "select": {"checkbox", "dialog", "dropdown-menu", "input", "popover", "tree"}, "sheet": {"button", "dialog"}, "sidebar": {"button"}, - "single-select": {"checkbox", "dialog", "dropdown-menu", "hierarchy-menu", "input", "tree"}, + "single-select": {"checkbox", "dialog", "dropdown-menu", "hierarchy-menu", "input", "popover", "tree"}, "slider": {"button", "direction"}, "sonner": {"toast"}, "split-button": {"button", "button-group", "tree"}, diff --git a/cmd/viva/templates/code_editor.go.txt b/cmd/viva/templates/code_editor.go.txt index 654d25cf8..9db91b741 100644 --- a/cmd/viva/templates/code_editor.go.txt +++ b/cmd/viva/templates/code_editor.go.txt @@ -228,6 +228,14 @@ type CodeEditor struct { shown []string widest int lineCount int + // deadShown counts the entries of shown no row points at any more, left by + // refits; a full layout clears them once they are half of it. + deadShown int + scratchRows []codeRow + // rawIndents is each line's own indentation, -1 when blank, which indents + // resolves blank lines from. + rawIndents []int + scratchIndents []int // What the last paint showed. painted bool @@ -416,8 +424,8 @@ func (editor *CodeEditor) Paint(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx. cols-- } editor.fitWithRepresentations(value, cols, snapshot.Wrap, tabWidth, snapshot.FoldedLines, snapshot.Representations) - if snapshot.ShowIndentGuides && editor.indents == nil { - editor.indents = indentationLevels(editor.text, tabWidth, editor.reps) + if snapshot.ShowIndentGuides { + editor.measureIndents() } editor.content, editor.cellWidth, editor.lineHeight = content, cellWidth, lineHeight @@ -1305,3 +1313,14 @@ func (command CodeEditorCommand) Apply(editor *text.Editor) bool { } return true } + +// measureIndents finds every line's indent guide level once for the laid out +// text; a refit keeps them up to date from then on. +func (editor *CodeEditor) measureIndents() { + if editor.indents != nil { + return + } + editor.rawIndents = appendRawIndents(editor.rawIndents[:0], editor.text, editor.tabWidth, editor.reps) + editor.indents = append(make([]int, 0, len(editor.rawIndents)), editor.rawIndents...) + resolveIndents(editor.indents, editor.rawIndents, 0, len(editor.indents)) +} diff --git a/cmd/viva/templates/code_editor_layout.go.txt b/cmd/viva/templates/code_editor_layout.go.txt index 527c91970..e6791b1fc 100644 --- a/cmd/viva/templates/code_editor_layout.go.txt +++ b/cmd/viva/templates/code_editor_layout.go.txt @@ -1,6 +1,7 @@ package {{PACKAGE}} import ( + "cmp" "slices" "sort" "strconv" @@ -35,17 +36,10 @@ func codeCells(r rune, column, tabWidth int) int { return text.CellWidth(r) } -// indentationLevels is the leading cells of every line, in the displayed columns -// the layout uses, so a representation that hides or widens a leading tab moves -// the indent guides with the text; a blank line takes the smaller indentation of -// its nearest text lines so guides run through it. -// -// The forward pass stores a blank line as -2-previous, where previous is the -// indentation of the last text line above it (-1 when there is none), so the -// backward pass can resolve it without a second slice. -func indentationLevels(value string, tabWidth int, reps []CodeRepresentation) []int { - levels := make([]int, 0, strings.Count(value, "\n")+1) - previous := -1 +// appendRawIndents appends the leading cells of each line of value, or -1 for a +// blank line, in the displayed columns the layout uses, so a representation that +// hides or widens a leading tab moves the indent guides with the text. +func appendRawIndents(dst []int, value string, tabWidth int, reps []CodeRepresentation) []int { for line := range strings.SplitSeq(value, "\n") { column, blank := 0, true leading: @@ -59,31 +53,50 @@ func indentationLevels(value string, tabWidth int, reps []CodeRepresentation) [] } } if blank { - levels = append(levels, -2-previous) - continue + column = -1 } - levels = append(levels, column) - previous = column + dst = append(dst, column) } - next := -1 - for index := len(levels) - 1; index >= 0; index-- { - if levels[index] >= 0 { - next = levels[index] + return dst +} + +// resolveIndents writes levels[from:to] from the raw indentation of every line: +// a text line keeps its own, and a blank line takes the smaller of the nearest +// text lines above and below it, or the one there is, or 0. levels may be raw. +func resolveIndents(levels, raw []int, from, to int) { + for index := from; index < to; { + if raw[index] >= 0 { + levels[index] = raw[index] + index++ continue } - above := -2 - levels[index] + start, end := index, index + for start > 0 && raw[start-1] < 0 { + start-- + } + for end < len(raw) && raw[end] < 0 { + end++ + } + above, below := -1, -1 + if start > 0 { + above = raw[start-1] + } + if end < len(raw) { + below = raw[end] + } + level := 0 switch { - case above >= 0 && next >= 0: - levels[index] = min(above, next) + case above >= 0 && below >= 0: + level = min(above, below) case above >= 0: - levels[index] = above - case next >= 0: - levels[index] = next - default: - levels[index] = 0 + level = above + case below >= 0: + level = below + } + for ; index < min(end, to); index++ { + levels[index] = level } } - return levels } func representationOf(reps []CodeRepresentation, character rune) (CodeRepresentation, bool) { @@ -127,16 +140,19 @@ func (editor *CodeEditor) fitWithFolds(value string, cols int, wrap bool, tabWid } func (editor *CodeEditor) fitWithRepresentations(value string, cols int, wrap bool, tabWidth int, folds []CodeEditorFoldRange, reps []CodeRepresentation) { - if editor.fitted && editor.cols == cols && editor.wrap == wrap && editor.tabWidth == tabWidth && editor.text == value && slices.Equal(editor.foldInput, folds) && slices.Equal(editor.reps, reps) { - return + if editor.fitted && editor.cols == cols && editor.wrap == wrap && editor.tabWidth == tabWidth && slices.Equal(editor.foldInput, folds) && slices.Equal(editor.reps, reps) { + if editor.text == value || editor.refit(value) { + return + } } editor.fitted, editor.cols, editor.wrap, editor.tabWidth, editor.text = true, cols, wrap, tabWidth, value editor.foldInput = append(editor.foldInput[:0], folds...) editor.reps = append(editor.reps[:0], reps...) editor.folds = editor.folds[:0] editor.rows = editor.rows[:0] - editor.indents = nil + editor.indents, editor.rawIndents = nil, editor.rawIndents[:0] editor.shown = editor.shown[:0] + editor.deadShown = 0 editor.widest = 0 if len(value) > 1<<30 { // Rows are indexed with 32 bits; a text this long is not an editor's. @@ -182,6 +198,123 @@ func (editor *CodeEditor) fitWithRepresentations(value string, cols int, wrap bo editor.runLine = -1 } +// refit lays out again only the logical lines an edit touched, when the text is +// all that changed: the rows before them stand, and the rows after them move by +// the bytes and lines the edit added. It reports false when the text needs a full +// layout instead. +func (editor *CodeEditor) refit(value string) bool { + old := editor.text + if len(editor.folds) > 0 || len(value) > 1<<30 || editor.deadShown > 64 && editor.deadShown > len(editor.shown)/2 { + return false + } + prefix := commonPrefix(old, value) + suffix := commonSuffix(old[prefix:], value[prefix:]) + // The edit replaced old[prefix:len(old)-suffix]; the lines holding it are laid + // out again whole, from the start of the first to the line break after the last. + from := strings.LastIndexByte(old[:prefix], '\n') + 1 + oldTo := len(old) + if newline := strings.IndexByte(old[len(old)-suffix:], '\n'); newline >= 0 { + oldTo = len(old) - suffix + newline + } + delta := len(value) - len(old) + newTo := oldTo + delta + + first, _ := slices.BinarySearchFunc(editor.rows, int32(from), func(row codeRow, at int32) int { return cmp.Compare(row.lineStart, at) }) + last, _ := slices.BinarySearchFunc(editor.rows, int32(oldTo), func(row codeRow, at int32) int { return cmp.Compare(row.lineStart, at+1) }) + // Every logical line has a row, so the first row from the line's start is it. + line := int(editor.rows[first].line) + lostWidest := false + for _, row := range editor.rows[first:last] { + lostWidest = lostWidest || int(row.cells) == editor.widest + if row.shown >= 0 { + editor.deadShown++ + } + } + lines := strings.Count(value[from:newTo], "\n") - strings.Count(old[from:oldTo], "\n") + + // The new lines are laid out after the rows, then moved into place. + editor.text = value + tail := len(editor.rows) + for start := from; ; line++ { + end := newTo + if newline := strings.IndexByte(value[start:newTo], '\n'); newline >= 0 { + end = start + newline + } + rowEnd := end + if end < len(value) && end > start && value[end-1] == '\r' { + rowEnd-- + } + editor.appendLine(value, start, rowEnd, line) + if end >= newTo { + break + } + start = end + 1 + } + made := len(editor.rows) - tail + editor.rows = slices.Grow(editor.rows, made) + editor.scratchRows = append(editor.scratchRows[:0], editor.rows[tail:]...) + editor.rows = slices.Replace(editor.rows[:tail], first, last, editor.scratchRows...) + for index := first + made; index < len(editor.rows); index++ { + row := &editor.rows[index] + row.start += int32(delta) + row.end += int32(delta) + row.lineStart += int32(delta) + row.line += int32(lines) + } + if lostWidest { + editor.widest = 0 + for _, row := range editor.rows { + editor.widest = max(editor.widest, int(row.cells)) + } + } + editor.lineCount += lines + if editor.indents != nil { + // The indentation of the edited lines is measured again, and blank lines + // next to them, which take it from the nearest text lines, resolved again. + firstLine := int(editor.rows[first].line) + oldEnd := firstLine + strings.Count(old[from:oldTo], "\n") + 1 + editor.scratchIndents = appendRawIndents(editor.scratchIndents[:0], value[from:newTo], editor.tabWidth, editor.reps) + editor.rawIndents = slices.Replace(editor.rawIndents, firstLine, oldEnd, editor.scratchIndents...) + editor.indents = slices.Replace(editor.indents, firstLine, oldEnd, editor.scratchIndents...) + before, after := firstLine, firstLine+len(editor.scratchIndents) + for before > 0 && editor.rawIndents[before-1] < 0 { + before-- + } + for after < len(editor.rawIndents) && editor.rawIndents[after] < 0 { + after++ + } + resolveIndents(editor.indents, editor.rawIndents, before, after) + } + editor.runLine = -1 + return true +} + +// commonPrefix is how many leading bytes a and b share, compared a block at a time. +func commonPrefix(a, b string) int { + const block = 1024 + n, at := min(len(a), len(b)), 0 + for at+block <= n && a[at:at+block] == b[at:at+block] { + at += block + } + for at < n && a[at] == b[at] { + at++ + } + return at +} + +// commonSuffix is how many trailing bytes a and b share. +func commonSuffix(a, b string) int { + const block = 1024 + n, at := min(len(a), len(b)), 0 + for at+block <= n && a[len(a)-at-block:len(a)-at] == b[len(b)-at-block:len(b)-at] { + at += block + } + for at < n && a[len(a)-at-1] == b[len(b)-at-1] { + at++ + } + return at +} + // SoftWrapOffsets returns byte offsets where the last painted editor would // wrap its text at its current content width. It does not change the live // editor's rows, scroll position, or selection. diff --git a/cmd/viva/templates/hierarchy_menu.go.txt b/cmd/viva/templates/hierarchy_menu.go.txt index f1658df89..e7815fbd5 100644 --- a/cmd/viva/templates/hierarchy_menu.go.txt +++ b/cmd/viva/templates/hierarchy_menu.go.txt @@ -187,7 +187,7 @@ func PaintHierarchyMenu(canvas *gfx.Canvas, theme gfx.Theme, anchor gfx.Rect, m } popup := gfx.Rect{X: left, Y: anchor.Y + anchor.Height + 6, Width: widths[l], Height: height} if l == first { - placePopupBelow(&popup, anchor, height, o.Viewport) + placeList(&popup, anchor, height, o.Viewport) } else { prev, trigger := m.Panels[l-1], m.Triggers[l-1] popup.X, popup.Y = prev.X+prev.Width-4, trigger.Y-4 @@ -407,24 +407,6 @@ func panelWidths(m *HierarchyMenuState, canvas *gfx.Canvas, theme gfx.Theme, anc return widths, left, reverse } -// placePopupBelow keeps a popup inside the viewport: above the anchor when that -// holds a usable row and below does not fit, shortened to what room is left. -func placePopupBelow(popup *gfx.Rect, anchor gfx.Rect, height float32, viewport gfx.Rect) { - if viewport.Height > 0 { - top, bottom := viewport.Y+1, viewport.Y+viewport.Height-1 - if popup.Y+popup.Height > bottom { - // Prefer the room above the anchor, but only when it holds a usable - // row; otherwise the list scrolls inside what is left below. - if above := anchor.Y - 6 - top; above >= min(height, 40) { - popup.Height = min(height, above) - popup.Y = anchor.Y - popup.Height - 6 - } - } - popup.Y = max(top, min(popup.Y, bottom-1)) - popup.Height = max(1, min(popup.Height, bottom-popup.Y)) - } -} - // unionRect is the smallest rect holding both; the first rect starts it. func unionRect(a, b gfx.Rect, first bool) gfx.Rect { if first { diff --git a/cmd/viva/templates/multi_select.go.txt b/cmd/viva/templates/multi_select.go.txt index 5caf7dfaa..dbb1311b0 100644 --- a/cmd/viva/templates/multi_select.go.txt +++ b/cmd/viva/templates/multi_select.go.txt @@ -131,24 +131,18 @@ func PaintMultiSelect(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, s *M } height := float32(max(1, min(len(choices), rows))*32 + 8) layout.Popup = gfx.Rect{X: bounds.X, Y: bounds.Y + bounds.Height + 6, Width: bounds.Width, Height: height} - if o.Viewport.Height > 0 { - top, bottom := o.Viewport.Y+1, o.Viewport.Y+o.Viewport.Height-1 - if layout.Popup.Y+layout.Popup.Height > bottom { - // Prefer room above for at least one usable row. Otherwise scroll - // inside the space left below, even when that is less than a row. - if above := bounds.Y - 6 - top; above >= min(height, 40) { - layout.Popup.Height = min(height, above) - layout.Popup.Y = bounds.Y - layout.Popup.Height - 6 - } - } - layout.Popup.Y = max(top, min(layout.Popup.Y, bottom-1)) - layout.Popup.Height = max(1, min(layout.Popup.Height, bottom-layout.Popup.Y)) - } + placeList(&layout.Popup, bounds, height, o.Viewport) if floating { canvas.PushOverlayClip(o.Viewport) defer canvas.PopOverlayClip() } canvas.Block(layout.Popup) + // The list enters and leaves as a select's does: faded and slid from the + // trigger's side, its last frame kept while it leaves. + side := popupSideOf(layout.Popup, bounds) + canvas.BeginPresence(overlayKey(o.TriggerID, o.DismissID, o.Scope), overlaySurfacePart, + popupPresence(theme, overlayDuration, side), popupPivot(layout.Popup, side, bounds)) + defer canvas.EndPresence() canvas.Container(layout.Popup, gfx.RoleListBox, o.Label) paintPopupSurface(canvas, &theme, layout.Popup, gfx.ShadowMD) s.ScrollArea().BarID = o.ScrollID diff --git a/cmd/viva/templates/popover.go.txt b/cmd/viva/templates/popover.go.txt index 1c448f250..af6c75dcf 100644 --- a/cmd/viva/templates/popover.go.txt +++ b/cmd/viva/templates/popover.go.txt @@ -298,6 +298,10 @@ type OverlayPlacement struct { AlignOffset float32 // Margin is the distance the overlay keeps from the viewport's edges. Margin float32 + // Fit shortens the overlay to the room on the side it ends up on, as the + // positioner's size step does for a list that scrolls, instead of shifting + // it back over its anchor. The side is chosen first, by the same flip. + Fit bool } // PlaceOverlay returns where an overlay of size goes beside anchor inside @@ -322,9 +326,36 @@ func PlaceOverlay(anchor gfx.Rect, size gfx.Size, viewport gfx.Rect, placement O bounds, side = flipped, opposite } } + if placement.Fit { + switch side { + case OverlayBottom: + size.Height = min(size.Height, max(bottom-(anchor.Y+anchor.Height+placement.SideOffset), 1)) + case OverlayTop: + size.Height = min(size.Height, max(anchor.Y-placement.SideOffset-top, 1)) + case OverlayRight: + size.Width = min(size.Width, max(right-(anchor.X+anchor.Width+placement.SideOffset), 1)) + case OverlayLeft: + size.Width = min(size.Width, max(anchor.X-placement.SideOffset-left, 1)) + } + bounds = overlayBeside(anchor, size, side, placement) + } return overlayClamp(bounds, viewport, placement.Margin), side } +// placeList puts a select's or a combobox's list, of its own left and width and +// of height, under the trigger: flipped above when that has more room, and +// shortened to the room it has, so the list scrolls instead of covering the +// trigger. It is PlaceOverlay's rule, the one every popup of the theme follows. +func placeList(popup *gfx.Rect, trigger gfx.Rect, height float32, viewport gfx.Rect) { + if viewport.Width <= 0 || viewport.Height <= 0 { + return + } + anchor := gfx.Rect{X: popup.X, Y: trigger.Y, Width: popup.Width, Height: trigger.Height} + *popup, _ = PlaceOverlay(anchor, gfx.Size{Width: popup.Width, Height: height}, viewport, OverlayPlacement{ + Side: OverlayBottom, Align: OverlayAlignStart, SideOffset: 6, Margin: 1, Fit: true, + }) +} + func overlayOpposite(side OverlaySide) OverlaySide { switch side { case OverlayTop: diff --git a/cmd/viva/templates/single_select.go.txt b/cmd/viva/templates/single_select.go.txt index 93c6ad336..0c58a5df0 100644 --- a/cmd/viva/templates/single_select.go.txt +++ b/cmd/viva/templates/single_select.go.txt @@ -172,12 +172,18 @@ func PaintSingleSelect(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, s * layout.Popup.X = max(o.Viewport.X+1, min(layout.Popup.X, o.Viewport.X+o.Viewport.Width-1-layout.Popup.Width)) } } - placePopupBelow(&layout.Popup, bounds, height, o.Viewport) + placeList(&layout.Popup, bounds, height, o.Viewport) if floating { canvas.PushOverlayClip(o.Viewport) defer canvas.PopOverlayClip() } canvas.Block(layout.Popup) + // The list enters and leaves as a select's does: faded and slid from the + // trigger's side, its last frame kept while it leaves. + side := popupSideOf(layout.Popup, bounds) + canvas.BeginPresence(overlayKey(o.TriggerID, o.DismissID, o.Scope), overlaySurfacePart, + popupPresence(theme, overlayDuration, side), popupPivot(layout.Popup, side, bounds)) + defer canvas.EndPresence() canvas.Container(layout.Popup, gfx.RoleListBox, o.Label) paintPopupSurface(canvas, &theme, layout.Popup, gfx.ShadowMD) s.Scroll.BarID = o.ScrollID From 6915b4a88d808b7b72e12ee07f2367240337d0ba Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 22 Nov 2026 14:46:08 +0800 Subject: [PATCH 17/64] fix(input): keep the focus on its region when the regions are set again 07475285 dropped Router.SetRegions' early return for an unchanged list, which had also kept focusedSlot; every repaint then put the focus on the target's first region. A target with two focusable regions sent Tab from its second region back to its first, so traversal looped there and never reached the controls after it (Motty's TestWorkspaceTemplateManagementThroughKeyboard). SetRegions now keeps the slot while it still holds the focused target, and searches only when it does not. --- internal/input/input.go | 24 +++++++++++++++++------- internal/input/input_test.go | 31 ++++++++++++++++++++++++++++++- 2 files changed, 47 insertions(+), 8 deletions(-) diff --git a/internal/input/input.go b/internal/input/input.go index fcbd1c841..dbfcef394 100644 --- a/internal/input/input.go +++ b/internal/input/input.go @@ -153,16 +153,26 @@ func (router *Router) RegionBuffer() []Region { return router.regions[:0] } // must not change the slice afterwards. func (router *Router) SetRegions(regions []Region) { router.regions = regions + if router.focused.IsZero() { + router.focusedSlot = 0 + return + } + // A target can have several regions; the focus stays on the one it was on + // while that one still holds it, so Tab goes on from there instead of + // starting over from the target's first region. + if slot := router.focusedSlot; slot > 0 && int(slot) <= len(regions) { + if region := regions[slot-1]; region.Target == router.focused && router.focusAvailableRegion(region) { + return + } + } router.focusedSlot = 0 - if !router.focused.IsZero() { - for index, region := range router.regions { - if region.Target == router.focused && router.focusAvailableRegion(region) { - router.focusedSlot = uint32(index + 1) - break - } + for index, region := range router.regions { + if region.Target == router.focused && router.focusAvailableRegion(region) { + router.focusedSlot = uint32(index + 1) + break } } - if !router.focused.IsZero() && router.focusedSlot == 0 { + if router.focusedSlot == 0 { router.focused = gfx.ID{} } } diff --git a/internal/input/input_test.go b/internal/input/input_test.go index 90d09114e..73fa983b8 100644 --- a/internal/input/input_test.go +++ b/internal/input/input_test.go @@ -2,7 +2,10 @@ package input import "github.com/vivaui/viva/gfx" -import "testing" +import ( + "slices" + "testing" +) func TestHitTestUsesFrontToBackOrderAndSkipsDisabled(t *testing.T) { var router Router @@ -507,3 +510,29 @@ func TestPressAtWalksFromTheFrontAndFindsTheWindowMoveRegion(t *testing.T) { } } } + +// A target with two focusable regions keeps the focus on the region it is on +// when the same regions are declared again, so Tab from the second region goes +// on to the next target instead of back to the first region. +func TestRepeatedRegionsKeepTheFocusedSlot(t *testing.T) { + var router Router + regions := func() []Region { + return []Region{ + {Target: gfx.Item(1), Bounds: Rect{Width: 10, Height: 10}, Focusable: true}, + {Target: gfx.Item(2), Bounds: Rect{X: 20, Width: 10, Height: 10}, Focusable: true}, + {Target: gfx.Item(1), Bounds: Rect{X: 40, Width: 10, Height: 10}, Focusable: true}, + {Target: gfx.Item(3), Bounds: Rect{X: 60, Width: 10, Height: 10}, Focusable: true}, + } + } + router.SetRegions(regions()) + var visited []gfx.ID + for range 4 { + router.KeyDown(KeyEvent{Key: KeyTab}) + router.SetRegions(regions()) // the repaint that follows each key + focused, _ := router.Focused() + visited = append(visited, focused) + } + if !slices.Contains(visited, gfx.Item(3)) { + t.Fatalf("Tab visited %v and never reached the last target", visited) + } +} From a274103ae97fb5caf9c60b9946a47af4c2a913e6 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 22 Nov 2026 18:18:50 +0800 Subject: [PATCH 18/64] feat(app): read fingers as touch screens do: taps, pans, flings, long presses A finger's press was read as a mouse's: it pressed at once, so a swipe over a list pressed and clicked what it started on, nothing scrolled, and there was no long press. Pointer events now say what they come from (gfx.PointerDevice: mouse, touch, pen) and which finger (PointerID), and the runtime reads a finger as Android and UIKit do (interaction.Touch, shared by the native runtime and the browser's): - a still finger presses after a 100 ms tap timeout, or as it lifts sooner (a tap), so a pan that starts at once presses nothing; - moving more than 8 px first makes it a pan that scrolls what was under it, the content following the finger; - lifting while moving flings with UIScrollView's deceleration, asking for frames only while it moves and allocating nothing per frame; - held still for 500 ms it ends the primary press and is a secondary press, which opens context menus; - a slider or a divider presses at once and takes the drag; - quick taps in one place count as a double tap; a finger hovers only while it touches. Mouse and pen input is unchanged. The browser maps pointerType and pointerId. Windows, Linux, the browser and phones install the touch runtime; macOS, which has no touch screen, does not link it. hello grows by about 500 bytes of code (its stripped size by one page). Windows and Linux still report touch as the mouse their systems promote it to; their native touch events are the next step. ADR 0095 phase 1. --- app/driver.go | 31 ++++ app/painter.go | 38 +++- app/touch.go | 134 ++++++++++++++ app/touch_install.go | 7 + app/touch_test.go | 236 ++++++++++++++++++++++++ gfx/input.go | 20 ++ internal/interaction/touch.go | 275 ++++++++++++++++++++++++++++ internal/platform/contract.go | 4 + internal/platform/web/painter.go | 40 +++- internal/platform/web/touch.go | 103 +++++++++++ internal/platform/web/touch_test.go | 72 ++++++++ internal/platform/web/web.go | 10 + 12 files changed, 959 insertions(+), 11 deletions(-) create mode 100644 app/touch.go create mode 100644 app/touch_install.go create mode 100644 app/touch_test.go create mode 100644 internal/interaction/touch.go create mode 100644 internal/platform/web/touch.go create mode 100644 internal/platform/web/touch_test.go diff --git a/app/driver.go b/app/driver.go index fc9271b5e..e0ee01339 100644 --- a/app/driver.go +++ b/app/driver.go @@ -420,6 +420,37 @@ func (driver *Driver) Cancel() error { return driver.pointer(platform.PointerCancel, 0, 0, gfx.PointerButtonNone, 0) } +// TouchDown puts finger id on the screen at a point, TouchMove moves it and +// TouchUp lifts it: the touches a phone or a touch screen reports. The runtime +// reads them as it reads a finger in a window: a press waits for its tap +// timeout, a finger that moves pans and flings, and one held still is a +// secondary press. Advance moves the time a finger is held. +func (driver *Driver) TouchDown(id int32, x, y float32) error { + return driver.touch(platform.PointerDown, id, x, y) +} + +// TouchMove moves finger id to a point. +func (driver *Driver) TouchMove(id int32, x, y float32) error { + return driver.touch(platform.PointerMove, id, x, y) +} + +// TouchUp lifts finger id at a point. +func (driver *Driver) TouchUp(id int32, x, y float32) error { + return driver.touch(platform.PointerUp, id, x, y) +} + +func (driver *Driver) touch(kind platform.PointerEventKind, id int32, x, y float32) error { + if err := driver.Pump(); err != nil { + return err + } + origin := driver.origin + _, err := driver.painter.pointerEvent(platform.PointerEvent{ + Kind: kind, Button: gfx.PointerButtonPrimary, Modifiers: driver.heldModifiers(), X: x, Y: y, + ScreenX: origin.X + x, ScreenY: origin.Y + y, Device: gfx.PointerTouch, PointerID: id, + }) + return err +} + // Press presses a pointer button at a point (moving there first) as a lone // click. func (driver *Driver) Press(x, y float32, button gfx.PointerButton) error { diff --git a/app/painter.go b/app/painter.go index 380b76c2e..80e649ee1 100644 --- a/app/painter.go +++ b/app/painter.go @@ -23,6 +23,8 @@ import ( // native label list, so an unchanged repaint performs no renderer work. type painter struct { fullscreen bool + // touch reads a finger's presses, pans and flings (touch.go). + touch touchState // customTitlebar says the page draws the window's titlebar strip itself // (WindowCustomTitlebar), so the window buttons cover part of it. customTitlebar bool @@ -230,6 +232,15 @@ func (painter *painter) pressAt(x, y float32) platform.PressKind { // backdrop would, and the second is the same press aimed at what the overlay // was covering, once the paint has taken it away. func (painter *painter) pointerEvent(event platform.PointerEvent) (platform.Frame, error) { + if event.Device == gfx.PointerTouch && touchRuntime.event != nil { + return touchRuntime.event(painter, event) + } + return painter.pointerInput(event) +} + +// pointerInput is pointerEvent for a press the runtime reads as it comes: a +// mouse's or a pen's, or a finger's once touchEvent decided it is a press. +func (painter *painter) pointerInput(event platform.PointerEvent) (platform.Frame, error) { if event.Kind == platform.PointerDown { painter.tap.Cancel() painter.pointerOutside = false @@ -346,14 +357,14 @@ func (painter *painter) pointerStep(event platform.PointerEvent) (result gfx.Eve result = painter.onPointer(gfx.PointerEvent{ Kind: gfx.PointerEventKind(event.Kind), Button: event.Button, Modifiers: gfx.Modifiers(event.Modifiers), X: event.X, Y: event.Y, ScreenX: event.ScreenX, ScreenY: event.ScreenY, Viewport: painter.size, Target: target, Captured: captured, - ClickCount: event.ClickCount, + ClickCount: event.ClickCount, Device: event.Device, PointerID: event.PointerID, }) } if !result.Handled && pointerIsDelivered(event.Kind, target, captured) { if painter.deliverPointer(gfx.PointerEvent{ Kind: gfx.PointerEventKind(event.Kind), Button: event.Button, Modifiers: gfx.Modifiers(event.Modifiers), X: event.X, Y: event.Y, ScreenX: event.ScreenX, ScreenY: event.ScreenY, Viewport: painter.size, Target: target, Captured: captured, - ClickCount: event.ClickCount, + ClickCount: event.ClickCount, Device: event.Device, PointerID: event.PointerID, }) { result.Handled, result.Repaint = true, true } @@ -780,9 +791,20 @@ func (painter *painter) fileDrop(event platform.FileDropEvent) (platform.Frame, func (painter *painter) scroll(event platform.ScrollEvent) (platform.Frame, error) { painter.tap.Cancel() - if event.DeltaY == 0 && event.DeltaX == 0 { + painter.touch.StopFling() // a wheel or a touchpad takes over from a fling + if !painter.applyScroll(event) { return platform.Frame{}, nil } + return painter.repaintAfterInput() +} + +// applyScroll gives a scroll to the application, or scrolls the page itself when +// the application leaves it, and reports whether anything changed that needs a +// repaint. +func (painter *painter) applyScroll(event platform.ScrollEvent) bool { + if event.DeltaY == 0 && event.DeltaX == 0 { + return false + } target := gfx.ID{} if hit, ok := painter.focus.Router().HitTest(event.X, event.Y); ok { target = hit @@ -800,10 +822,7 @@ func (painter *painter) scroll(event platform.ScrollEvent) (platform.Frame, erro painter.scrollX = max(0, painter.scrollX+event.DeltaX) painter.scrollY = max(0, painter.scrollY+event.DeltaY) } - if painter.scrollX == beforeX && painter.scrollY == beforeY && !focusChanged && !response.Repaint { - return platform.Frame{}, nil - } - return painter.repaintAfterInput() + return painter.scrollX != beforeX || painter.scrollY != beforeY || focusChanged || response.Repaint } // initialTextInput is the native editor the first paint already calls for: a @@ -893,6 +912,11 @@ func (painter *painter) deliverPointer(event gfx.PointerEvent) bool { // repaint reruns the paint callback with current interaction state and // synchronizes the result with the retained renderer. func (painter *painter) repaint() (platform.Frame, error) { + if touchRuntime.advance != nil { + if frame, done, err := touchRuntime.advance(painter); done { + return frame, err + } + } if painter.noteFrameStart != nil { painter.noteFrameStart() } diff --git a/app/touch.go b/app/touch.go new file mode 100644 index 000000000..69a58a2c9 --- /dev/null +++ b/app/touch.go @@ -0,0 +1,134 @@ +package app + +import ( + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/input" + "github.com/vivaui/viva/internal/interaction" + "github.com/vivaui/viva/internal/platform" +) + +// touchRuntime is how the painter reads fingers. The platforms that report them +// install it (touch_install.go); where none does, macOS, it stays nil and none of +// the code is linked: a finger's event there is read as a mouse's. +var touchRuntime struct { + event func(*painter, platform.PointerEvent) (platform.Frame, error) + advance func(*painter) (platform.Frame, bool, error) +} + +// installTouch makes the painter read fingers. +func installTouch() { + touchRuntime.event = (*painter).touchEvent + touchRuntime.advance = (*painter).advanceTouch +} + +// touchState carries out what interaction.Touch reads a finger as. +type touchState struct { + interaction.Touch + id int32 + modifiers input.Modifiers + screenDX, screenDY float32 // screen position less window position + advancing bool // a timed step is being carried out: repaint must not start another +} + +// touchEvent reads one event of a finger. +func (painter *painter) touchEvent(event platform.PointerEvent) (platform.Frame, error) { + t := &painter.touch + now := painter.canvas.Now() + var step interaction.TouchStep + switch event.Kind { + case platform.PointerDown: + if !t.Active() || event.PointerID == t.id { + t.id, t.modifiers = event.PointerID, event.Modifiers + t.screenDX, t.screenDY = event.ScreenX-event.X, event.ScreenY-event.Y + } + step = t.Down(event.PointerID, event.X, event.Y, now, painter.claimsDrag(event.X, event.Y)) + case platform.PointerMove: + step = t.Move(event.PointerID, event.X, event.Y, now) + case platform.PointerUp: + step = t.Up(event.PointerID, event.X, event.Y, now) + case platform.PointerCancel, platform.PointerExit: + step = t.Cancel() + } + return painter.carryTouch(step) +} + +// claimsDrag reports whether what is under a finger takes a moving finger as a +// drag rather than letting it scroll: a slider, a split view's divider. +func (painter *painter) claimsDrag(x, y float32) bool { + region, ok, _ := painter.focus.Router().PointerAt(x, y, false) + return ok && (region.Role == gfx.RoleSlider || region.Role == gfx.RoleSeparator) +} + +// carryTouch carries out a step in the order TouchStep gives, as the presses of +// a mouse at the finger, and asks for the frame the step wants. +func (painter *painter) carryTouch(step interaction.TouchStep) (platform.Frame, error) { + t := &painter.touch + event := platform.PointerEvent{ + Button: gfx.PointerButtonPrimary, Modifiers: t.modifiers, X: step.X, Y: step.Y, + ScreenX: step.X + t.screenDX, ScreenY: step.Y + t.screenDY, Device: gfx.PointerTouch, PointerID: t.id, + } + var frame platform.Frame + var err error + send := func(kind platform.PointerEventKind, button gfx.PointerButton, clicks int) { + if err != nil { + return + } + event.Kind, event.Button, event.ClickCount = kind, button, clicks + frame, err = painter.pointerInput(event) + } + if step.Cancel { + send(platform.PointerCancel, gfx.PointerButtonPrimary, 0) + } + if step.Press { + send(platform.PointerDown, gfx.PointerButtonPrimary, step.Clicks) + } + if step.Move { + send(platform.PointerMove, gfx.PointerButtonNone, 0) + } + if step.Release { + send(platform.PointerUp, gfx.PointerButtonPrimary, step.Clicks) + } + if step.Secondary { + send(platform.PointerDown, gfx.PointerButtonSecondary, 1) + send(platform.PointerUp, gfx.PointerButtonSecondary, 1) + } + if step.Lift { + send(platform.PointerExit, gfx.PointerButtonNone, 0) + } + if err != nil { + return platform.Frame{}, err + } + if step.Scrolls() { + moved := painter.applyScroll(platform.ScrollEvent{X: step.ScrollAtX, Y: step.ScrollAtY, DeltaX: step.ScrollX, DeltaY: step.ScrollY, Precise: true}) + if !moved { + t.FlingBlocked() // at the end of what it scrolls + step.Wake = false + } else if !t.advancing { + frame, err = painter.repaintAfterInput() + } + } + if step.Wake && painter.scheduleFrame != nil { + painter.scheduleFrame(step.WakeAfter) + } + return frame, err +} + +// advanceTouch carries out what a finger's time brings, at the start of a +// repaint: a still finger's press, its secondary press, the next step of a +// fling. It reports a frame when the step repainted itself; a fling's step is +// painted by the repaint it runs in. +func (painter *painter) advanceTouch() (platform.Frame, bool, error) { + t := &painter.touch + if t.advancing || !t.Active() { + return platform.Frame{}, false, nil + } + t.advancing = true + defer func() { t.advancing = false }() + step := t.Advance(painter.canvas.Now()) + if step.Cancel || step.Press || step.Secondary { + frame, err := painter.carryTouch(step) + return frame, true, err + } + _, err := painter.carryTouch(step) + return platform.Frame{}, err != nil, err +} diff --git a/app/touch_install.go b/app/touch_install.go new file mode 100644 index 000000000..8bd19641b --- /dev/null +++ b/app/touch_install.go @@ -0,0 +1,7 @@ +//go:build !darwin + +package app + +// Windows, Linux, the browser and phones report fingers: their windows read them +// (touch.go). macOS has no touch screen, and a touchpad is a precise wheel there. +func init() { installTouch() } diff --git a/app/touch_test.go b/app/touch_test.go new file mode 100644 index 000000000..c2f6e28b0 --- /dev/null +++ b/app/touch_test.go @@ -0,0 +1,236 @@ +package app + +import ( + "testing" + "time" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/interaction" +) + +// The touch runtime is tested on every platform, macOS included, where a +// window does not install it. +func init() { installTouch() } + +// touchFixture is a window with a button and a slider over a page that scrolls, +// which records the clicks, presses and scrolls a finger causes. +type touchFixture struct { + driver *Driver + clicks, secondary, presses int + pressed bool + scrolled float32 + scrolls int +} + +const ( + touchButton = 1 + touchSlider = 2 +) + +func newTouchFixture(t *testing.T) *touchFixture { + t.Helper() + f := &touchFixture{} + config := Config{Title: "touch", Width: 400, Height: 400} + config.Paint = func(canvas *gfx.Canvas, size gfx.Size) { + canvas.HitWithOptions(gfx.Item(touchButton), gfx.Rect{X: 20, Y: 20, Width: 200, Height: 60}, "Button", gfx.HitOptions{Role: gfx.RoleButton}) + canvas.HitWithOptions(gfx.Item(touchSlider), gfx.Rect{X: 20, Y: 200, Width: 200, Height: 30}, "Slider", gfx.HitOptions{Role: gfx.RoleSlider}) + f.pressed = canvas.Pressed() == gfx.Item(touchButton) + if canvas.Clicked(gfx.Item(touchButton)) { + f.clicks++ + } + } + config.OnPointer = func(event gfx.PointerEvent) gfx.EventResult { + if event.Kind == gfx.PointerDown && event.Device == gfx.PointerTouch { + f.presses++ + if event.Button == gfx.PointerButtonSecondary { + f.secondary++ + } + } + return gfx.EventResult{} + } + config.OnScroll = func(event gfx.ScrollEvent) gfx.EventResult { + f.scrolls++ + f.scrolled += event.DeltaY + return gfx.EventResult{Handled: true, Repaint: true} + } + driver, err := NewDriver(config, nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(driver.Close) + f.driver = driver + return f +} + +func (f *touchFixture) must(t *testing.T, err error) { + t.Helper() + if err != nil { + t.Fatal(err) + } +} + +// A finger lifted where it went down is a tap: one click, and no hover left +// behind, as a finger hovers only while it touches. +func TestATapClicksOnceAndLeavesNoHover(t *testing.T) { + f := newTouchFixture(t) + f.must(t, f.driver.TouchDown(1, 50, 50)) + if f.presses != 0 { + t.Fatal("a finger pressed before it was clear it was not a pan") + } + f.must(t, f.driver.TouchUp(1, 51, 50)) + if f.clicks != 1 || f.presses != 1 { + t.Fatalf("a tap clicked %d times after %d presses, want 1 and 1", f.clicks, f.presses) + } + if hovered := f.driver.Snapshot().Hovered; !hovered.IsZero() { + t.Fatalf("a lifted finger left %v hovered", hovered) + } +} + +// A finger held still presses after the tap timeout, so the control shows it is +// pressed while the finger stays, and clicks when it lifts. +func TestAHeldFingerPressesThenClicks(t *testing.T) { + f := newTouchFixture(t) + f.must(t, f.driver.TouchDown(1, 50, 50)) + f.must(t, f.driver.Advance(interaction.TouchTapTimeout+time.Millisecond)) + if f.presses != 1 || !f.pressed { + t.Fatalf("after the tap timeout: %d presses, pressed=%v; want the button pressed", f.presses, f.pressed) + } + f.must(t, f.driver.TouchUp(1, 50, 50)) + if f.clicks != 1 { + t.Fatalf("lifting the held finger clicked %d times", f.clicks) + } +} + +// A finger that moves at once scrolls what is under it and never presses or +// clicks the button it started on; the content follows the finger. +func TestAPanScrollsAndNeverPresses(t *testing.T) { + f := newTouchFixture(t) + f.must(t, f.driver.TouchDown(1, 50, 300)) + for y := float32(290); y >= 200; y -= 10 { + f.must(t, f.driver.TouchMove(1, 50, y)) + } + f.must(t, f.driver.Advance(time.Second)) // a pan held long does not press either + f.must(t, f.driver.TouchMove(1, 50, 200)) + f.must(t, f.driver.TouchUp(1, 50, 200)) + if f.presses != 0 || f.clicks != 0 { + t.Fatalf("a pan pressed %d times and clicked %d", f.presses, f.clicks) + } + if f.scrolled < 100-interaction.TouchSlop || f.scrolled > 100 { + t.Fatalf("a finger moved up 100 scrolled the content %v down, want it to follow the finger", f.scrolled) + } +} + +// A finger lifted while moving flings: the content goes on scrolling, slows +// down and stops, asking for frames only while it moves. +func TestALiftedMovingFingerFlingsAndStops(t *testing.T) { + f := newTouchFixture(t) + f.must(t, f.driver.TouchDown(1, 50, 380)) + y := float32(380) + for range 10 { + f.must(t, f.driver.Advance(10*time.Millisecond)) + y -= 20 // 2000 logical pixels a second + f.must(t, f.driver.TouchMove(1, 50, y)) + } + f.must(t, f.driver.TouchUp(1, 50, y)) + panned, steps := f.scrolled, f.scrolls + f.must(t, f.driver.Advance(200*time.Millisecond)) + if f.scrolled <= panned || f.scrolls <= steps { + t.Fatal("the content stopped when the finger lifted") + } + f.must(t, f.driver.Advance(10*time.Second)) + settled, settledSteps := f.scrolled, f.scrolls + if f.driver.Transitioning() { + t.Fatal("a fling still asks for frames after it stopped") + } + f.must(t, f.driver.Advance(time.Second)) + if f.scrolled != settled || f.scrolls != settledSteps { + t.Fatal("the fling never stopped") + } + if f.scrolled-panned > 2000 { + t.Fatalf("a fling at 2000/s went %v further, more than a second at full speed", f.scrolled-panned) + } +} + +// A finger held still past the long press is a secondary press, as a right +// click: what opens context menus. The primary press it began as clicks nothing. +func TestALongPressIsASecondaryPress(t *testing.T) { + f := newTouchFixture(t) + var events []gfx.PointerEvent + record := f.driver.painter.onPointer + f.driver.painter.onPointer = func(event gfx.PointerEvent) gfx.EventResult { + events = append(events, event) + return record(event) + } + f.must(t, f.driver.TouchDown(1, 50, 50)) + f.must(t, f.driver.Advance(interaction.TouchLongPress+50*time.Millisecond)) + if f.secondary != 1 || f.pressed { + t.Fatalf("a long press made %d secondary presses and left the button pressed=%v, want 1 and released", f.secondary, f.pressed) + } + // The application sees the primary press end before the secondary one + // begins: a drag it was following does not go on under the menu. + ended := false + for _, event := range events { + if event.Kind == gfx.PointerExit { + ended = true + } + if event.Kind == gfx.PointerDown && event.Button == gfx.PointerButtonSecondary && !ended { + t.Fatalf("the secondary press began while the primary one was held: %+v", events) + } + } + f.must(t, f.driver.TouchUp(1, 50, 50)) + if f.clicks != 0 { + t.Fatalf("a long press also clicked %d times", f.clicks) + } +} + +// A slider takes a moving finger as a drag: it presses at once instead of +// waiting to see whether the finger pans. +func TestASliderPressesAtOnce(t *testing.T) { + f := newTouchFixture(t) + f.must(t, f.driver.TouchDown(1, 50, 210)) + if f.presses != 1 { + t.Fatalf("a finger on a slider pressed %d times at once, want 1", f.presses) + } + f.must(t, f.driver.TouchMove(1, 120, 210)) + f.must(t, f.driver.TouchUp(1, 120, 210)) + if f.scrolls != 0 { + t.Fatal("dragging a slider scrolled the page") + } +} + +// Two quick taps in one place are a double tap, counted as a double click. +func TestTwoQuickTapsAreADoubleTap(t *testing.T) { + var counts []int + f := newTouchFixture(t) + f.driver.painter.onPointer = func(event gfx.PointerEvent) gfx.EventResult { + if event.Kind == gfx.PointerDown { + counts = append(counts, event.ClickCount) + } + return gfx.EventResult{} + } + f.must(t, f.driver.TouchDown(1, 50, 50)) + f.must(t, f.driver.TouchUp(1, 50, 50)) + f.must(t, f.driver.Advance(100*time.Millisecond)) + f.must(t, f.driver.TouchDown(1, 52, 51)) + f.must(t, f.driver.TouchUp(1, 52, 51)) + if len(counts) != 2 || counts[0] != 1 || counts[1] != 2 { + t.Fatalf("two quick taps counted %v, want [1 2]", counts) + } +} + +// A fling's frames allocate nothing. +func TestAFlingStepDoesNotAllocate(t *testing.T) { + f := newTouchFixture(t) + f.must(t, f.driver.TouchDown(1, 50, 380)) + y := float32(380) + for range 10 { + f.must(t, f.driver.Advance(10*time.Millisecond)) + y -= 30 + f.must(t, f.driver.TouchMove(1, 50, y)) + } + f.must(t, f.driver.TouchUp(1, 50, y)) + f.must(t, f.driver.Advance(50*time.Millisecond)) + if allocations := testing.AllocsPerRun(20, func() { _ = f.driver.Advance(frameInterval) }); allocations != 0 { + t.Fatalf("a fling frame allocated %v times", allocations) + } +} diff --git a/gfx/input.go b/gfx/input.go index ad5a30819..e70ec538b 100644 --- a/gfx/input.go +++ b/gfx/input.go @@ -91,6 +91,22 @@ const ( PointerButtonForward ) +// PointerDevice is what a pointer event comes from, as the Pointer Events +// standard's pointerType: it decides whether the pointer hovers and how a press +// that moves is read. +type PointerDevice uint8 + +const ( + // PointerMouse is a mouse or a touchpad: it hovers, and a press acts at once. + PointerMouse PointerDevice = iota + // PointerTouch is a finger on a screen: it hovers only while it touches, a + // press that moves at once scrolls instead of pressing, and a long press is a + // secondary press. + PointerTouch + // PointerPen is a stylus: it hovers over the screen and presses as a mouse. + PointerPen +) + // PointerEvent is delivered in logical window pixels. Target is the stable hit // ID under the pointer, or the press target while Captured is true. Viewport is // the current logical window size, allowing coordinate-driven controls to @@ -116,6 +132,10 @@ type PointerEvent struct { Target ID Captured bool ClickCount int + // Device is what the event comes from, and PointerID tells apart the + // fingers or pens touching at once; a mouse is pointer 0. + Device PointerDevice + PointerID int32 } // Win32Key is the Windows console INPUT_RECORD data of a key event: the diff --git a/internal/interaction/touch.go b/internal/interaction/touch.go new file mode 100644 index 000000000..2e49a9a53 --- /dev/null +++ b/internal/interaction/touch.go @@ -0,0 +1,275 @@ +package interaction + +import ( + "math" + "time" +) + +// A finger is read as the platforms read it (Android's ViewConfiguration and +// GestureDetector, UIKit's scroll views): its press waits until it is clearly +// not the start of a pan, a pan scrolls what is under it and flings on when the +// finger leaves moving, and a press held still is a secondary press. +const ( + // TouchSlop is how far a finger moves, in logical pixels, before its press + // becomes a pan. + TouchSlop = 8 + // TouchTapTimeout is how long a still finger waits before it presses, so a + // pan that starts at once presses nothing (Android's TAP_TIMEOUT). + TouchTapTimeout = 100 * time.Millisecond + // TouchLongPress is how long a still finger presses before it is a secondary + // press. + TouchLongPress = 500 * time.Millisecond + // touchDoubleTap and touchDoubleTapSlop are how soon and how near a tap + // follows the last one to count as its second. + touchDoubleTap = 300 * time.Millisecond + touchDoubleTapSlop = 24 + // flingMinVelocity is the speed, in logical pixels a second, a lifted finger + // needs to fling; a fling stops below flingStopVelocity. + flingMinVelocity = 50 + flingStopVelocity = 10 + // flingDecay is how much of a fling's speed is left after a millisecond: + // UIScrollView's normal deceleration rate. + flingDecay = 0.998 + // velocityWindow is how much of a pan's recent motion its speed is read from. + velocityWindow = 100 * time.Millisecond +) + +type touchPhase uint8 + +const ( + touchIdle touchPhase = iota + touchPending // down, not yet a press nor a pan + touchPressed // delivered as a primary press + touchPanning // scrolling what was under it when it went down + touchLong // delivered as a secondary press; the rest of it is ignored +) + +// TouchStep is what one event or moment of a finger means to the runtime. The +// runtime carries it out in the order of the fields: it ends the primary press +// (Cancel), presses (Press), moves the press (Move), releases it (Release), +// presses and releases the secondary button (Secondary), takes the hover away +// (Lift), and scrolls (ScrollX, ScrollY at ScrollAtX, ScrollAtY). +type TouchStep struct { + Cancel, Press, Move, Release, Secondary, Lift bool + // X and Y are where the press, its move, its release or the secondary press + // is, and Clicks the press's count among quick taps (2 for a double tap). + X, Y float32 + Clicks int + // ScrollX and ScrollY scroll the content under ScrollAtX, ScrollAtY. + ScrollX, ScrollY float32 + ScrollAtX, ScrollAtY float32 + // Wake asks for a frame after WakeAfter, when Advance has more to do. + Wake bool + WakeAfter time.Duration +} + +// Scrolls reports whether the step scrolls. +func (s TouchStep) Scrolls() bool { return s.ScrollX != 0 || s.ScrollY != 0 } + +type touchSample struct { + x, y float32 + at time.Duration +} + +// Touch follows the one finger that presses or pans; a second finger ends what +// the first was doing. The zero value is ready to use. It keeps no clock: the +// runtime gives it the time of each event and asks it to Advance at the frames +// it asked for. +type Touch struct { + phase touchPhase + id int32 + down time.Duration + startX, startY float32 + lastX, lastY float32 + samples [8]touchSample + sampled int + lastTap time.Duration + lastTapX, lastTapY float32 + clicks int + pressDue, longPressDue bool + flinging bool + flingVX, flingVY float32 // the finger's velocity, logical pixels a second + flingAt time.Duration +} + +// Active reports whether a finger is down or a fling moves. +func (t *Touch) Active() bool { return t.phase != touchIdle || t.flinging } + +// Down is finger id touching at x, y. claimsDrag says what is under it takes a +// moving finger as a drag (a slider, a divider): it presses at once. +func (t *Touch) Down(id int32, x, y float32, now time.Duration, claimsDrag bool) TouchStep { + if t.phase != touchIdle && id != t.id { + return t.Cancel() // a second finger is not a press: the first one's gesture ends + } + t.flinging = false + t.phase, t.id, t.down = touchPending, id, now + t.startX, t.startY, t.lastX, t.lastY = x, y, x, y + t.sampled = 0 + t.sample(x, y, now) + t.pressDue, t.longPressDue = true, true + if claimsDrag { + return t.press(now) + } + return TouchStep{Wake: true, WakeAfter: TouchTapTimeout} +} + +// Move is finger id moving to x, y. +func (t *Touch) Move(id int32, x, y float32, now time.Duration) TouchStep { + if t.phase == touchIdle || id != t.id { + return TouchStep{} + } + t.sample(x, y, now) + moved := math.Hypot(float64(x-t.startX), float64(y-t.startY)) > TouchSlop + switch t.phase { + case touchPending: + if !moved { + return TouchStep{} + } + t.phase, t.pressDue, t.longPressDue = touchPanning, false, false + return t.pan(x, y) + case touchPanning: + return t.pan(x, y) + case touchPressed: + if moved { + t.longPressDue = false + } + t.lastX, t.lastY = x, y + return TouchStep{Move: true, X: x, Y: y} + } + return TouchStep{} +} + +// Up is finger id lifting at x, y. +func (t *Touch) Up(id int32, x, y float32, now time.Duration) TouchStep { + if t.phase == touchIdle || id != t.id { + return TouchStep{} + } + phase := t.phase + t.phase, t.pressDue, t.longPressDue = touchIdle, false, false + switch phase { + case touchPending: // lifted before it pressed: a tap + return TouchStep{Press: true, Release: true, Lift: true, X: x, Y: y, Clicks: t.tapCount(x, y, now)} + case touchPressed: + return TouchStep{Release: true, Lift: true, X: x, Y: y, Clicks: t.clicks} + case touchPanning: + vx, vy := t.velocity(now) + if math.Hypot(float64(vx), float64(vy)) >= flingMinVelocity { + t.flinging, t.flingVX, t.flingVY, t.flingAt = true, vx, vy, now + return TouchStep{Wake: true} + } + case touchLong: + return TouchStep{Lift: true, X: x, Y: y} + } + return TouchStep{} +} + +// Cancel ends what the finger was doing without a click: the platform took it, +// or a second finger came. +func (t *Touch) Cancel() TouchStep { + phase := t.phase + t.phase, t.pressDue, t.longPressDue, t.flinging = touchIdle, false, false, false + if phase != touchPressed { + return TouchStep{} + } + return TouchStep{Cancel: true, Lift: true, X: t.lastX, Y: t.lastY} +} + +// StopFling ends a fling, as a wheel or a touchpad taking over does. +func (t *Touch) StopFling() { t.flinging = false } + +// Advance is what the finger's time brings at now: a still finger's press once +// its tap timeout passed, its secondary press once it was held long enough, and +// the next step of a fling. +func (t *Touch) Advance(now time.Duration) TouchStep { + switch { + case t.phase == touchPending && t.pressDue && now-t.down >= TouchTapTimeout: + return t.press(now) + case t.phase == touchPressed && t.longPressDue && now-t.down >= TouchLongPress: + // Held still: the press becomes a secondary press, as a right click. + t.longPressDue, t.phase = false, touchLong + return TouchStep{Cancel: true, Secondary: true, X: t.lastX, Y: t.lastY, Clicks: 1} + case t.flinging: + return t.fling(now) + } + return TouchStep{} +} + +// Fling reports a fling that moved nothing, at the end of what it scrolls: it +// stops. +func (t *Touch) FlingBlocked() { t.flinging = false } + +func (t *Touch) press(now time.Duration) TouchStep { + t.phase, t.pressDue = touchPressed, false + step := TouchStep{Press: true, X: t.lastX, Y: t.lastY, Clicks: t.tapCount(t.lastX, t.lastY, now)} + if t.longPressDue { + step.Wake, step.WakeAfter = true, max(TouchLongPress-(now-t.down), 0) + } + return step +} + +// pan scrolls what was under the finger when it went down by how far the finger +// moved: the content follows it. +func (t *Touch) pan(x, y float32) TouchStep { + step := TouchStep{ScrollX: t.lastX - x, ScrollY: t.lastY - y, ScrollAtX: t.startX, ScrollAtY: t.startY} + t.lastX, t.lastY = x, y + return step +} + +// fling moves a fling on by the time since its last step, slowing it as +// UIScrollView does, and asks for the next frame while it still moves. +func (t *Touch) fling(now time.Duration) TouchStep { + elapsed := now - t.flingAt + if elapsed <= 0 { + return TouchStep{Wake: true} + } + t.flingAt = now + seconds := float32(elapsed.Seconds()) + step := TouchStep{ScrollX: -t.flingVX * seconds, ScrollY: -t.flingVY * seconds, ScrollAtX: t.startX, ScrollAtY: t.startY} + decay := float32(math.Pow(flingDecay, float64(elapsed)/float64(time.Millisecond))) + t.flingVX, t.flingVY = t.flingVX*decay, t.flingVY*decay + if math.Hypot(float64(t.flingVX), float64(t.flingVY)) < flingStopVelocity { + t.flinging = false + } else { + step.Wake = true + } + return step +} + +func (t *Touch) sample(x, y float32, at time.Duration) { + copy(t.samples[1:], t.samples[:len(t.samples)-1]) + t.samples[0] = touchSample{x: x, y: y, at: at} + t.sampled = min(t.sampled+1, len(t.samples)) +} + +// velocity is the finger's speed over its recent motion, in logical pixels a +// second; a finger that stopped before it lifted has none. +func (t *Touch) velocity(now time.Duration) (float32, float32) { + if t.sampled < 2 || now-t.samples[0].at > velocityWindow/2 { + return 0, 0 + } + newest, oldest := t.samples[0], t.samples[0] + for _, sample := range t.samples[1:t.sampled] { + if newest.at-sample.at > velocityWindow { + break + } + oldest = sample + } + seconds := float32((newest.at - oldest.at).Seconds()) + if seconds <= 0 { + return 0, 0 + } + return (newest.x - oldest.x) / seconds, (newest.y - oldest.y) / seconds +} + +// tapCount numbers this press among quick taps close together, as a double +// click is counted. +func (t *Touch) tapCount(x, y float32, now time.Duration) int { + if t.clicks > 0 && now-t.lastTap <= touchDoubleTap && + math.Hypot(float64(x-t.lastTapX), float64(y-t.lastTapY)) <= touchDoubleTapSlop { + t.clicks = t.clicks%3 + 1 + } else { + t.clicks = 1 + } + t.lastTap, t.lastTapX, t.lastTapY = now, x, y + return t.clicks +} diff --git a/internal/platform/contract.go b/internal/platform/contract.go index 8f3e40edd..6925a6ad9 100644 --- a/internal/platform/contract.go +++ b/internal/platform/contract.go @@ -492,6 +492,10 @@ type PointerEvent struct { // ClickCount is the number of consecutive presses this Down or Up belongs // to (2 for a double click). Move and Exit events leave it 0. ClickCount int + // Device is what the event comes from (gfx.PointerDevice), and PointerID + // tells apart the fingers or pens touching at once. + Device gfx.PointerDevice + PointerID int32 } // Size is a window client size in logical pixels. diff --git a/internal/platform/web/painter.go b/internal/platform/web/painter.go index 384b9f88c..942c7cc87 100644 --- a/internal/platform/web/painter.go +++ b/internal/platform/web/painter.go @@ -4,6 +4,7 @@ package web import ( "math" + "time" "unicode/utf8" "github.com/vivaui/viva/gfx" @@ -17,6 +18,10 @@ import ( // painter coordinates the immediate canvas vocabulary with the shared input // router, mirroring the native app painter without any platform coupling. type painter struct { + // touch reads a finger's presses, pans and flings (touch.go), and + // scheduleFrame asks the runtime for a frame after a delay. + touch touchState + scheduleFrame func(time.Duration) config *Config canvas *gfx.Canvas focus interaction.Focus @@ -375,6 +380,18 @@ type droppedFile struct{ platform.FileRef } // events leave the default canvas offset untouched; an unused gesture can be // forwarded to an embedding page. func (p *painter) wheel(event gfx.ScrollEvent) (handled, changed bool) { + p.touch.StopFling() // a wheel or a touchpad takes over from a fling + handled, changed = p.scrollBy(event) + if changed { + p.repaint() + } + return handled, changed +} + +// scrollBy gives a scroll to the application, or scrolls the page itself when +// the application leaves it, and reports whether it was taken and whether +// anything changed that needs a repaint. +func (p *painter) scrollBy(event gfx.ScrollEvent) (handled, changed bool) { p.tap.Cancel() if event.DeltaX == 0 && event.DeltaY == 0 { return false, false @@ -399,9 +416,6 @@ func (p *painter) wheel(event gfx.ScrollEvent) (handled, changed bool) { moved = p.scrollX != beforeX || p.scrollY != beforeY } changed = moved || focusChanged || response.Repaint - if changed { - p.repaint() - } return response.Handled || response.Repaint || focusChanged, changed } @@ -479,6 +493,7 @@ func (p *painter) deliverPointer(event gfx.PointerEvent) bool { // focus while the router syncs, so the frame is painted a second time to show // the new focus rather than lag behind it. func (p *painter) repaint() { + p.advanceTouch() for pass := 0; ; pass++ { p.paint() before := p.focus.Focused() @@ -644,6 +659,15 @@ func roundPresenceRect(rect gfx.Rect) gfx.Rect { // state changed. A nonzero press target captures move and up delivery until the // press ends, while hover continues to track the actual hit target. func (p *painter) pointerEvent(event gfx.PointerEvent) bool { + if event.Device == gfx.PointerTouch { + return p.touchEvent(event) + } + return p.pointerInput(event) +} + +// pointerInput is pointerEvent for a press read as it comes: a mouse's or a +// pen's, or a finger's once touchEvent decided it is a press. +func (p *painter) pointerInput(event gfx.PointerEvent) bool { if event.Kind == gfx.PointerDown { p.tap.Cancel() } @@ -704,10 +728,18 @@ func (p *painter) pointerEvent(event gfx.PointerEvent) bool { // release will follow, so the press ends here and the application is told the // pointer is gone. func (p *painter) pointerCancel(event gfx.PointerEvent) bool { + if event.Device == gfx.PointerTouch { + return p.carryTouch(p.touch.Cancel()) + } + return p.endPress(event) +} + +// endPress ends a press whose release will not come. +func (p *painter) endPress(event gfx.PointerEvent) bool { p.pointerOutside = false p.pointer.Up() event.Kind = gfx.PointerExit - return p.pointerEvent(event) + return p.pointerInput(event) } // pointerStep is one pass of a pointer event through hit testing, the press diff --git a/internal/platform/web/touch.go b/internal/platform/web/touch.go new file mode 100644 index 000000000..441b97878 --- /dev/null +++ b/internal/platform/web/touch.go @@ -0,0 +1,103 @@ +//go:build js && wasm + +package web + +import ( + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/interaction" +) + +// touchState carries out what interaction.Touch reads a finger as, as the native +// runtime does (app/touch.go). +type touchState struct { + interaction.Touch + id int32 + modifiers gfx.Modifiers + advancing bool // a timed step is being carried out: repaint must not start another +} + +// touchEvent reads one event of a finger and reports whether rendering state +// changed. +func (p *painter) touchEvent(event gfx.PointerEvent) bool { + t := &p.touch + now := p.canvas.Now() + var step interaction.TouchStep + switch event.Kind { + case gfx.PointerDown: + if !t.Active() || event.PointerID == t.id { + t.id, t.modifiers = event.PointerID, event.Modifiers + } + step = t.Down(event.PointerID, event.X, event.Y, now, p.claimsDrag(event.X, event.Y)) + case gfx.PointerMove: + step = t.Move(event.PointerID, event.X, event.Y, now) + case gfx.PointerUp: + step = t.Up(event.PointerID, event.X, event.Y, now) + case gfx.PointerExit: + step = t.Cancel() + } + return p.carryTouch(step) +} + +// claimsDrag reports whether what is under a finger takes a moving finger as a +// drag rather than letting it scroll: a slider, a split view's divider. +func (p *painter) claimsDrag(x, y float32) bool { + region, ok, _ := p.focus.Router().PointerAt(x, y, false) + return ok && (region.Role == gfx.RoleSlider || region.Role == gfx.RoleSeparator) +} + +// carryTouch carries out a step in the order TouchStep gives, as the presses of +// a mouse at the finger, and asks for the frame the step wants. +func (p *painter) carryTouch(step interaction.TouchStep) bool { + t := &p.touch + event := gfx.PointerEvent{Button: gfx.PointerButtonPrimary, Modifiers: t.modifiers, X: step.X, Y: step.Y, Device: gfx.PointerTouch, PointerID: t.id} + changed := false + send := func(kind gfx.PointerEventKind, button gfx.PointerButton, clicks int) { + event.Kind, event.Button, event.ClickCount = kind, button, clicks + changed = p.pointerInput(event) || changed + } + if step.Cancel { + changed = p.endPress(event) || changed + } + if step.Press { + send(gfx.PointerDown, gfx.PointerButtonPrimary, step.Clicks) + } + if step.Move { + send(gfx.PointerMove, gfx.PointerButtonNone, 0) + } + if step.Release { + send(gfx.PointerUp, gfx.PointerButtonPrimary, step.Clicks) + } + if step.Secondary { + send(gfx.PointerDown, gfx.PointerButtonSecondary, 1) + send(gfx.PointerUp, gfx.PointerButtonSecondary, 1) + } + if step.Lift { + send(gfx.PointerExit, gfx.PointerButtonNone, 0) + } + if step.Scrolls() { + _, moved := p.scrollBy(gfx.ScrollEvent{Modifiers: t.modifiers, X: step.ScrollAtX, Y: step.ScrollAtY, DeltaX: step.ScrollX, DeltaY: step.ScrollY, Precise: true}) + if !moved { + t.FlingBlocked() // at the end of what it scrolls + step.Wake = false + } else if !t.advancing { + p.repaint() // a fling's step is painted by the repaint it runs in + } + changed = changed || moved + } + if step.Wake && p.scheduleFrame != nil { + p.scheduleFrame(step.WakeAfter) + } + return changed +} + +// advanceTouch carries out what a finger's time brings, at the start of a +// repaint: a still finger's press, its secondary press, the next step of a fling. +func (p *painter) advanceTouch() { + t := &p.touch + if t.advancing || !t.Active() { + return + } + t.advancing = true + defer func() { t.advancing = false }() + p.carryTouch(t.Advance(p.canvas.Now())) +} diff --git a/internal/platform/web/touch_test.go b/internal/platform/web/touch_test.go new file mode 100644 index 000000000..4aa49477c --- /dev/null +++ b/internal/platform/web/touch_test.go @@ -0,0 +1,72 @@ +//go:build js && wasm + +package web + +import ( + "testing" + "time" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/interaction" +) + +// The browser runtime reads a finger as the native one does: a tap clicks, a +// pan scrolls without pressing, and a held finger presses after its timeout. +func TestBrowserTouchTapsPansAndPresses(t *testing.T) { + var canvas gfx.Canvas + now := time.Duration(0) + canvas.SetClock(func() time.Duration { return now }) + clicks, presses := 0, 0 + scrolled := float32(0) + config := Config{ + Paint: func(canvas *gfx.Canvas, _ gfx.Size) { + canvas.HitWithOptions(gfx.Item(1), gfx.Rect{Width: 200, Height: 200}, "Button", gfx.HitOptions{Role: gfx.RoleButton}) + if canvas.Clicked(gfx.Item(1)) { + clicks++ + } + }, + OnPointer: func(event gfx.PointerEvent) gfx.EventResult { + if event.Kind == gfx.PointerDown { + presses++ + } + return gfx.EventResult{} + }, + OnScroll: func(event gfx.ScrollEvent) gfx.EventResult { + scrolled += event.DeltaY + return gfx.EventResult{Handled: true, Repaint: true} + }, + } + painter := newPainter(&canvas, &config) + painter.width, painter.height = 400, 400 + painter.repaint() + touch := func(kind gfx.PointerEventKind, x, y float32) { + painter.pointerEvent(gfx.PointerEvent{Kind: kind, Button: gfx.PointerButtonPrimary, X: x, Y: y, Device: gfx.PointerTouch, PointerID: 7}) + } + + touch(gfx.PointerDown, 50, 50) + touch(gfx.PointerUp, 50, 50) + if clicks != 1 { + t.Fatalf("a tap clicked %d times", clicks) + } + + presses = 0 + touch(gfx.PointerDown, 50, 150) + touch(gfx.PointerMove, 50, 120) + touch(gfx.PointerMove, 50, 100) + touch(gfx.PointerUp, 50, 100) + if presses != 0 || scrolled < 40 { + t.Fatalf("a pan pressed %d times and scrolled %v", presses, scrolled) + } + + now += time.Second + touch(gfx.PointerDown, 50, 50) + now += interaction.TouchTapTimeout + time.Millisecond + painter.repaint() // the frame the runtime asked for at the tap timeout + if presses != 1 { + t.Fatalf("a held finger pressed %d times after its tap timeout", presses) + } + touch(gfx.PointerUp, 50, 50) + if clicks != 2 { + t.Fatalf("lifting the held finger left %d clicks, want 2", clicks) + } +} diff --git a/internal/platform/web/web.go b/internal/platform/web/web.go index dfb061cf8..43601c3b4 100644 --- a/internal/platform/web/web.go +++ b/internal/platform/web/web.go @@ -227,6 +227,7 @@ func (runtime *runtime) mount() { }) runtime.metrics = newTextMetrics(runtime.measurer) runtime.painter = newPainter(runtime.canvas, &runtime.config) + runtime.painter.scheduleFrame = runtime.scheduleFrame runtime.a11y.setActions( func(id gfx.ID) { // The painter repaints its own canvas; the runtime still has to @@ -896,7 +897,16 @@ func pointerEvent(kind gfx.PointerEventKind, event js.Value) gfx.PointerEvent { if kind == gfx.PointerDown || kind == gfx.PointerUp { clicks = max(event.Get("detail").Int(), 1) } + device := gfx.PointerMouse + switch event.Get("pointerType").String() { + case "touch": + device = gfx.PointerTouch + case "pen": + device = gfx.PointerPen + } return gfx.PointerEvent{ + Device: device, + PointerID: int32(event.Get("pointerId").Int()), Kind: kind, Button: button, Modifiers: webModifiers(event.Get("shiftKey").Bool(), event.Get("ctrlKey").Bool(), event.Get("altKey").Bool(), event.Get("metaKey").Bool()), From 961088c1f0615607d8c92ab7a33a517e30a4cf32 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 22 Nov 2026 18:35:36 +0800 Subject: [PATCH 19/64] fix(dmg): convert the image only once the disk image service let go of it On hosted macOS runners hdiutil convert kept failing with "Resource temporarily unavailable" after the writable image was detached, even through ten retries over 45 seconds (TestBuiltImageHoldsTheLayoutTheFinderReads failed four times on main since 3a8af08c). Detaching returns before the service releases the file, so retrying on time alone guessed. The build now waits until hdiutil info no longer lists the image, up to two minutes, and reports what still holds it if it never lets go. --- tools/dmg/build.go | 35 +++++++++++++++++++++++++++++++++++ tools/dmg/busy_test.go | 20 ++++++++++++++++++++ 2 files changed, 55 insertions(+) diff --git a/tools/dmg/build.go b/tools/dmg/build.go index 41fa11467..1a74f2f91 100644 --- a/tools/dmg/build.go +++ b/tools/dmg/build.go @@ -69,6 +69,12 @@ func Build(options Options) error { if err := settle(writable, options, app); err != nil { return err } + // Detaching returns before the disk image service lets go of the file; + // converting it while the service still holds it fails with "Resource + // temporarily unavailable", which hosted runners show for over a minute. + if err := released(writable); err != nil { + return err + } // Write beside the target first so a failure leaves the previous image alone. temporary := strings.TrimSuffix(options.Image, ".dmg") + ".viva-tmp.dmg" @@ -220,6 +226,35 @@ func detach(mount, device string) error { return err } +// releaseAttempts and releaseWait bound how long released waits for the disk +// image service: up to two minutes. +const ( + releaseAttempts = 120 + releaseWait = time.Second +) + +// released waits until no attached image is the file at image, as hdiutil info +// lists them. It reports the list when the image is still attached at the end. +func released(image string) error { + path := image + if resolved, err := filepath.EvalSymlinks(image); err == nil { + path = resolved + } + var attached string + for attempt := 0; attempt < releaseAttempts; attempt++ { + out, err := hdiutilOutput("info", "-plist") + if err != nil { + return err + } + if !strings.Contains(out, ""+path+"") && !strings.Contains(out, ""+image+"") { + return nil + } + attached = out + pause(releaseWait) + } + return fmt.Errorf("the disk image service still holds %s after detaching it:\n%s", image, attached) +} + func hdiutil(arguments ...string) error { _, err := hdiutilOutput(arguments...) return err diff --git a/tools/dmg/busy_test.go b/tools/dmg/busy_test.go index b5617c561..f8021b8a9 100644 --- a/tools/dmg/busy_test.go +++ b/tools/dmg/busy_test.go @@ -97,3 +97,23 @@ func TestHdiutilReportsOtherFailuresAtOnce(t *testing.T) { }) } } + +// The image is converted only once the disk image service has let go of it: +// released waits while hdiutil info still lists it, and says so if it never +// does. +func TestReleasedWaitsUntilTheImageIsNoLongerAttached(t *testing.T) { + const image = "/tmp/viva-release-test/writable.dmg" + held := reply{"image-path" + image + "", nil} + free := reply{"", nil} + runs, waits := stub(t, []reply{held, held, free}) + if err := released(image); err != nil { + t.Fatal(err) + } + if len(*runs) != 3 || len(*waits) != 2 { + t.Fatalf("%d checks and %d waits, want 3 and 2", len(*runs), len(*waits)) + } + stub(t, []reply{held}) + if err := released(image); err == nil || !strings.Contains(err.Error(), image) { + t.Fatalf("an image that stays attached gave %v", err) + } +} From 5021f7b3a20886dc39c0e68bf3c69b02d104cb1f Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 22 Nov 2026 19:14:13 +0800 Subject: [PATCH 20/64] build: keep macOS-only code out of iOS builds GOOS=ios also satisfies the darwin build constraint, so every AppKit, FSEvents and Dock file was compiled for iOS and the build failed at the first of them. Files that belong to macOS alone now say so: the whole internal/platform/darwin package, the audio and file-watch backends, the darwin hooks of app, the proxy, headless and visual-parity tools and their tests carry `&& !ios`. Where iOS then has nothing of its own yet, app/ios_unsupported.go reports that the system does not offer it (the clipboard, dialogs, notifications, the cursor, global shortcuts, fonts, the native run loop), each moving out as the backend lands (ADR 0095); the touch runtime is installed on iOS as on every platform but macOS. `GOOS=ios go build ./...` and `go vet ./...` now pass; the desktop builds are unchanged: macOS, Linux, Windows and browser vet pass, and hello for macOS is the same size, 4,442,994 bytes. ADR 0095 W0 (iOS part). --- app/application_reopen_darwin.go | 2 +- app/backend_darwin.go | 2 + app/clipboard_html_darwin.go | 2 +- app/file_icon_darwin.go | 2 +- app/file_icon_darwin_test.go | 2 +- app/fonts_darwin_test.go | 2 +- app/global_shortcut_darwin.go | 2 + app/initial_bitmap_headless_test.go | 2 +- app/ios_unsupported.go | 80 +++++++++++++++++++ app/keepawake_darwin.go | 2 +- app/platform_darwin.go | 2 +- app/proxy/native_darwin.go | 2 +- app/proxy/native_unsupported.go | 2 +- app/scheme_darwin.go | 2 +- app/system_darwin.go | 2 +- app/system_darwin_test.go | 2 +- app/touch_install.go | 2 +- app/window_controls_darwin.go | 2 +- audio/output_darwin.c | 2 +- audio/output_darwin.go | 2 +- audio/output_other.go | 2 +- components/markdown_italic_darwin_test.go | 2 +- headless/render_darwin.go | 2 +- internal/filewatch/watch_darwin.c | 2 +- internal/filewatch/watch_darwin.go | 2 +- internal/filewatch/watch_darwin.h | 2 + internal/filewatch/watch_other.go | 2 +- .../darwin/accessibility_darwin_test.go | 2 + internal/platform/darwin/bitmap_reuse_test.go | 2 +- .../darwin/bitmap_stage_bench_test.go | 2 +- internal/platform/darwin/callback.go | 2 +- .../platform/darwin/callback_handle_test.go | 2 +- .../darwin/clipboard_files_darwin_test.go | 2 +- .../platform/darwin/clipboard_html_darwin.go | 2 +- .../darwin/clipboard_html_darwin_test.go | 2 +- .../platform/darwin/clipboard_image_darwin.go | 2 +- .../darwin/clipboard_image_darwin_test.go | 2 +- .../darwin/clipboard_watch_darwin_test.go | 2 +- internal/platform/darwin/composite_test.go | 2 +- .../composition_tentative_darwin_test.go | 2 + .../darwin/cursor_image_darwin_test.go | 2 +- .../platform/darwin/cursor_owner_darwin.h | 2 + .../darwin/cursor_owner_darwin_test.go | 2 +- internal/platform/darwin/dock_badge_darwin.go | 2 +- internal/platform/darwin/dock_badge_darwin.h | 2 + internal/platform/darwin/dock_badge_darwin.m | 2 + .../platform/darwin/dock_badge_darwin_test.go | 2 + .../platform/darwin/dock_progress_darwin.go | 2 +- .../platform/darwin/dock_progress_darwin.h | 2 + .../platform/darwin/dock_progress_darwin.m | 2 + .../darwin/dock_progress_darwin_test.go | 2 + .../darwin/dock_reopen_darwin_test.go | 2 + internal/platform/darwin/drag_darwin.go | 2 +- .../platform/darwin/editor_baseline_test.go | 2 +- internal/platform/darwin/fidelity_test.go | 2 +- .../platform/darwin/file_drop_darwin_test.go | 2 + internal/platform/darwin/file_icon_darwin.go | 2 +- internal/platform/darwin/file_icon_darwin.h | 2 + internal/platform/darwin/file_icon_darwin.m | 2 + .../platform/darwin/font_file_vivahead.go | 2 +- .../platform/darwin/font_register_darwin.go | 2 +- .../platform/darwin/global_shortcut_darwin.go | 2 + .../platform/darwin/global_shortcut_darwin.m | 2 + .../darwin/global_shortcut_darwin_test.go | 2 + .../platform/darwin/image_shading_test.go | 2 +- .../platform/darwin/interface_font_test.go | 2 +- .../platform/darwin/interface_weight_test.go | 2 +- .../label_invalid_utf8_vivahead_test.go | 2 +- internal/platform/darwin/ligature_test.go | 2 +- .../darwin/live_resize_darwin_test.go | 2 + internal/platform/darwin/main_darwin_test.go | 2 +- internal/platform/darwin/main_menu_darwin.h | 2 + internal/platform/darwin/main_menu_darwin.m | 2 + .../platform/darwin/main_menu_darwin_test.go | 2 +- .../darwin/mainpump/mainpump_darwin.go | 2 +- internal/platform/darwin/menu_bar_darwin.go | 2 +- internal/platform/darwin/menu_bar_darwin.h | 2 + internal/platform/darwin/menu_bar_darwin.m | 2 + .../darwin/modifier_taps_darwin_test.go | 2 + .../platform/darwin/mono_fallback_test.go | 2 +- internal/platform/darwin/mono_family.go | 2 +- .../platform/darwin/mono_family_grid_test.go | 2 +- .../darwin/mono_installed_fallback_test.go | 2 +- .../darwin/native_label_text_darwin_test.go | 2 +- internal/platform/darwin/offscreen.go | 2 +- internal/platform/darwin/offscreen_test.go | 2 +- internal/platform/darwin/open_file_darwin.go | 2 +- .../platform/darwin/open_file_darwin_test.go | 2 +- internal/platform/darwin/open_url_darwin.go | 2 +- .../platform/darwin/open_url_darwin_test.go | 2 +- internal/platform/darwin/open_with_darwin.go | 2 +- .../platform/darwin/open_with_darwin_test.go | 2 +- internal/platform/darwin/platform.go | 2 +- internal/platform/darwin/post_darwin.go | 2 +- internal/platform/darwin/post_darwin.h | 2 + internal/platform/darwin/post_darwin.m | 2 + internal/platform/darwin/post_darwin_test.go | 2 +- internal/platform/darwin/probe.go | 2 +- internal/platform/darwin/proxy_darwin.go | 2 +- internal/platform/darwin/proxy_darwin.h | 2 + internal/platform/darwin/proxy_darwin.m | 2 + internal/platform/darwin/proxy_darwin_test.go | 2 +- internal/platform/darwin/quad_render_test.go | 2 +- internal/platform/darwin/quad_test.go | 2 +- .../platform/darwin/quit_request_darwin.go | 2 +- .../darwin/quit_request_darwin_test.go | 2 +- .../platform/darwin/rectangle_buffer_test.go | 2 +- internal/platform/darwin/reference_text.go | 2 +- .../platform/darwin/renderer_recovery_test.go | 2 +- internal/platform/darwin/reopen_darwin.go | 2 +- .../platform/darwin/reopen_darwin_test.go | 2 +- internal/platform/darwin/save_panel_darwin.h | 2 + internal/platform/darwin/save_panel_darwin.m | 2 + .../platform/darwin/save_panel_darwin_test.go | 2 +- internal/platform/darwin/secret_darwin.go | 2 +- internal/platform/darwin/secret_darwin.h | 2 + internal/platform/darwin/secret_darwin.m | 2 + internal/platform/darwin/shader.go | 2 +- .../platform/darwin/shader_target_test.go | 2 +- internal/platform/darwin/sharpness_test.go | 2 +- internal/platform/darwin/sleep_darwin.go | 2 +- internal/platform/darwin/sleep_darwin.h | 2 + internal/platform/darwin/sleep_darwin.m | 2 + internal/platform/darwin/sleep_darwin_test.go | 2 +- .../platform/darwin/status_item_darwin.go | 2 +- internal/platform/darwin/status_item_darwin.h | 2 + internal/platform/darwin/status_item_darwin.m | 2 + .../darwin/status_item_darwin_test.go | 2 +- internal/platform/darwin/system_darwin.go | 2 +- internal/platform/darwin/system_darwin.h | 2 + internal/platform/darwin/system_darwin.m | 2 + .../platform/darwin/system_darwin_test.go | 2 +- .../darwin/testdata/reopen_bridge/main.go | 2 +- .../testdata/tentative_bridge_darwin.go | 2 + .../testdata/tentative_bridge_darwin_test.go | 2 + internal/platform/darwin/text.go | 2 +- internal/platform/darwin/text_bench_test.go | 2 +- internal/platform/darwin/text_engine.go | 2 +- .../platform/darwin/text_engine_bench_test.go | 2 +- .../platform/darwin/text_engine_start_test.go | 2 +- internal/platform/darwin/text_engine_test.go | 2 +- .../darwin/text_italic_regression_test.go | 2 +- .../darwin/text_run_regression_test.go | 2 +- .../darwin/text_selection_darwin_test.go | 2 + internal/platform/darwin/text_test.go | 2 +- .../darwin/text_weight_regression_test.go | 2 +- .../darwin/traffic_lights_darwin_test.go | 2 + internal/platform/darwin/web_darwin.go | 2 +- internal/platform/darwin/web_darwin.h | 2 + internal/platform/darwin/web_darwin.m | 2 + .../darwin/window_close_darwin_test.go | 2 + .../platform/darwin/window_icon_darwin.go | 2 +- .../platform/darwin/window_size_darwin.go | 2 + .../darwin/window_size_darwin_test.go | 2 + tools/visualparity/compare.go | 2 +- tools/visualparity/facts.go | 2 +- tools/visualparity/ink.go | 2 +- tools/visualparity/main.go | 2 +- tools/visualparity/measure_darwin.go | 2 +- tools/visualparity/metrics.go | 2 +- tools/visualparity/parity_test.go | 2 +- tools/visualparity/pixels.go | 2 +- tools/visualparity/render.go | 2 +- tools/visualparity/scenes.go | 2 +- 164 files changed, 291 insertions(+), 115 deletions(-) create mode 100644 app/ios_unsupported.go diff --git a/app/application_reopen_darwin.go b/app/application_reopen_darwin.go index d26da8b51..c96ac3476 100644 --- a/app/application_reopen_darwin.go +++ b/app/application_reopen_darwin.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package app diff --git a/app/backend_darwin.go b/app/backend_darwin.go index 5dd6512cb..372b0c627 100644 --- a/app/backend_darwin.go +++ b/app/backend_darwin.go @@ -1,3 +1,5 @@ +//go:build !ios + package app import ( diff --git a/app/clipboard_html_darwin.go b/app/clipboard_html_darwin.go index 2d2a93461..54b8685bc 100644 --- a/app/clipboard_html_darwin.go +++ b/app/clipboard_html_darwin.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package app diff --git a/app/file_icon_darwin.go b/app/file_icon_darwin.go index dc2b28c05..fe20db433 100644 --- a/app/file_icon_darwin.go +++ b/app/file_icon_darwin.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package app diff --git a/app/file_icon_darwin_test.go b/app/file_icon_darwin_test.go index 6dea0bc2b..793fd5989 100644 --- a/app/file_icon_darwin_test.go +++ b/app/file_icon_darwin_test.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package app diff --git a/app/fonts_darwin_test.go b/app/fonts_darwin_test.go index 489e6a9f7..a8bcf0b3b 100644 --- a/app/fonts_darwin_test.go +++ b/app/fonts_darwin_test.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package app diff --git a/app/global_shortcut_darwin.go b/app/global_shortcut_darwin.go index a9bef4dd6..d98343dfe 100644 --- a/app/global_shortcut_darwin.go +++ b/app/global_shortcut_darwin.go @@ -1,3 +1,5 @@ +//go:build !ios + package app import darwinplatform "github.com/vivaui/viva/internal/platform/darwin" diff --git a/app/initial_bitmap_headless_test.go b/app/initial_bitmap_headless_test.go index 15b1c3198..db3d7a026 100644 --- a/app/initial_bitmap_headless_test.go +++ b/app/initial_bitmap_headless_test.go @@ -1,4 +1,4 @@ -//go:build darwin && vivahead +//go:build darwin && vivahead && !ios package app diff --git a/app/ios_unsupported.go b/app/ios_unsupported.go new file mode 100644 index 000000000..4f981e037 --- /dev/null +++ b/app/ios_unsupported.go @@ -0,0 +1,80 @@ +//go:build ios + +package app + +import ( + "fmt" + "os" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/platform" +) + +// Until the iOS backend provides them (ADR 0095), the platform's native hooks +// report that the system does not offer them: what a window and a UIKit host +// give, such as the clipboard, the cursor, dialogs and notifications, is added +// here one by one, and each moves out of this file as it lands. + +func runNative(platform.Config) error { return fmt.Errorf("%w: the iOS backend", ErrUnsupported) } +func runNativeApplication(platform.ApplicationStart) error { + return fmt.Errorf("%w: the iOS backend", ErrUnsupported) +} + +func currentPlatform() Platform { return PlatformUnknown } + +func nativeReduceMotion() bool { return false } +func nativeTextEngine() gfx.TextEngine { return nil } +func nativePreferredLanguages() []string { return languagesFromEnvironment(os.Getenv) } +func nativeClipboardText() (string, error) { return "", ErrUnsupported } +func nativeSetClipboardText(string) error { return ErrUnsupported } +func nativeHasClipboardImage() bool { return false } +func nativeClipboardImagePNG() ([]byte, error) { return nil, ErrUnsupported } +func nativeSetClipboardImage([]byte) error { return ErrUnsupported } +func nativeClipboardFiles() ([]string, error) { return nil, ErrUnsupported } +func nativeSetClipboardFiles([]string) error { return ErrUnsupported } +func nativeSetClipboardHTML(html, alt string) error { return ErrUnsupported } +func nativeOnClipboardChange(func()) error { return ErrUnsupported } +func nativeSetCursor(Cursor) error { return ErrUnsupported } +func nativeSetCursorImage(*gfx.CursorImage) error { return ErrUnsupported } +func nativeOpenFiles(OpenFileOptions) ([]string, error) { return nil, ErrUnsupported } +func nativeOpenDirectory(OpenDirectoryOptions) (string, error) { return "", ErrUnsupported } +func nativeSaveFile(SaveFileOptions) (string, error) { return "", ErrUnsupported } +func nativeSaveFileWithCheckbox(SaveFileOptions, SaveFileCheckbox) (SaveFileSelection, error) { + return SaveFileSelection{}, ErrUnsupported +} +func nativeOpenURL(string) error { return ErrUnsupported } +func nativeRevealPath(string) error { return ErrUnsupported } +func nativePlaySystemSound(SystemSound) error { return ErrUnsupported } +func nativeSendNotification(Notification) error { return ErrUnsupported } +func nativeStoreSecret(string, string, []byte) error { return ErrSecretStoreUnavailable } +func nativeLoadSecret(string, string) ([]byte, error) { return nil, ErrSecretStoreUnavailable } +func nativeDeleteSecret(string, string) error { return ErrSecretStoreUnavailable } + +func nativeEnableCrashDumps(string) (string, error) { return "", ErrUnsupported } +func nativeShowFatalError(string, string) {} + +func nativeMonospaceFamilies() []string { return nil } +func nativeFontFamilies() []string { return nil } +func nativeFontWeights(string) []int { return nil } + +func nativeAppearance() Appearance { return AppearanceUnknown } +func nativeWatchAppearance() {} +func nativeSetAppearance(Appearance) {} + +func nativeStartFileDrag([]string, FileDragEffect) (FileDragEffect, error) { + return FileDragNone, ErrUnsupported +} + +func nativeFileIcon(string, int) ([]byte, error) { return nil, ErrUnsupported } +func nativeRegisterGlobalShortcut(GlobalShortcut, func()) (func(), error) { return nil, ErrUnsupported } +func nativePreventSleep(string) (func(), error) { return nil, ErrSleepPreventionUnavailable } +func nativeSchemeHandlerAvailable(string) (bool, error) { return false, ErrUnsupported } +func nativeOpenInBrowser(string) error { return fmt.Errorf("%w: OpenPathInBrowser", ErrUnsupported) } +func nativeOpenWith(_, _ string) error { return fmt.Errorf("%w: OpenWith", ErrUnsupported) } + +func setReopenHandler(*Config, *Window) {} + +// No window buttons: the system owns the window. +const controlsDrawnByViva = false + +func platformTitlebarInsets() (leading, trailing float32) { return 0, 0 } diff --git a/app/keepawake_darwin.go b/app/keepawake_darwin.go index 5e1c3c8c8..cc54b135b 100644 --- a/app/keepawake_darwin.go +++ b/app/keepawake_darwin.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package app diff --git a/app/platform_darwin.go b/app/platform_darwin.go index 192697546..6be9f5dc7 100644 --- a/app/platform_darwin.go +++ b/app/platform_darwin.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package app diff --git a/app/proxy/native_darwin.go b/app/proxy/native_darwin.go index b88aa6eea..9ddc908a3 100644 --- a/app/proxy/native_darwin.go +++ b/app/proxy/native_darwin.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package proxy diff --git a/app/proxy/native_unsupported.go b/app/proxy/native_unsupported.go index 5488aa63a..52c3320db 100644 --- a/app/proxy/native_unsupported.go +++ b/app/proxy/native_unsupported.go @@ -1,4 +1,4 @@ -//go:build !darwin && !windows && !linux && !(js && wasm) +//go:build (!darwin || ios) && !windows && !linux && !(js && wasm) package proxy diff --git a/app/scheme_darwin.go b/app/scheme_darwin.go index c4e096d8b..e7ad0eb5c 100644 --- a/app/scheme_darwin.go +++ b/app/scheme_darwin.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package app diff --git a/app/system_darwin.go b/app/system_darwin.go index 04427ae52..1e2604007 100644 --- a/app/system_darwin.go +++ b/app/system_darwin.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package app diff --git a/app/system_darwin_test.go b/app/system_darwin_test.go index e89a97e85..28567327e 100644 --- a/app/system_darwin_test.go +++ b/app/system_darwin_test.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package app diff --git a/app/touch_install.go b/app/touch_install.go index 8bd19641b..e25a1c19e 100644 --- a/app/touch_install.go +++ b/app/touch_install.go @@ -1,4 +1,4 @@ -//go:build !darwin +//go:build !darwin || ios package app diff --git a/app/window_controls_darwin.go b/app/window_controls_darwin.go index 32c52f754..790bc97a4 100644 --- a/app/window_controls_darwin.go +++ b/app/window_controls_darwin.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package app diff --git a/audio/output_darwin.c b/audio/output_darwin.c index a6b7abd37..06a55966c 100644 --- a/audio/output_darwin.c +++ b/audio/output_darwin.c @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios #include #include diff --git a/audio/output_darwin.go b/audio/output_darwin.go index 02350392e..aab4564b9 100644 --- a/audio/output_darwin.go +++ b/audio/output_darwin.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package audio diff --git a/audio/output_other.go b/audio/output_other.go index e0d684d44..8ee0327d8 100644 --- a/audio/output_other.go +++ b/audio/output_other.go @@ -1,4 +1,4 @@ -//go:build !darwin && !windows && !linux +//go:build (!darwin || ios) && !windows && !linux package audio diff --git a/components/markdown_italic_darwin_test.go b/components/markdown_italic_darwin_test.go index a6de54095..8875cdb17 100644 --- a/components/markdown_italic_darwin_test.go +++ b/components/markdown_italic_darwin_test.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package components diff --git a/headless/render_darwin.go b/headless/render_darwin.go index 6a56c65c3..a3ea6c820 100644 --- a/headless/render_darwin.go +++ b/headless/render_darwin.go @@ -1,4 +1,4 @@ -//go:build darwin && vivahead +//go:build darwin && vivahead && !ios package headless diff --git a/internal/filewatch/watch_darwin.c b/internal/filewatch/watch_darwin.c index 5795f1e4f..f0b046b58 100644 --- a/internal/filewatch/watch_darwin.c +++ b/internal/filewatch/watch_darwin.c @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios #include #include diff --git a/internal/filewatch/watch_darwin.go b/internal/filewatch/watch_darwin.go index 6aa26bba8..cb4768c86 100644 --- a/internal/filewatch/watch_darwin.go +++ b/internal/filewatch/watch_darwin.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package filewatch diff --git a/internal/filewatch/watch_darwin.h b/internal/filewatch/watch_darwin.h index 8a6c60a89..56b062f38 100644 --- a/internal/filewatch/watch_darwin.h +++ b/internal/filewatch/watch_darwin.h @@ -1,3 +1,5 @@ +//go:build !ios + #ifndef VIVA_FILEWATCH_DARWIN_H #define VIVA_FILEWATCH_DARWIN_H diff --git a/internal/filewatch/watch_other.go b/internal/filewatch/watch_other.go index a132ecd4a..07ca12d54 100644 --- a/internal/filewatch/watch_other.go +++ b/internal/filewatch/watch_other.go @@ -1,4 +1,4 @@ -//go:build !linux && !darwin && !windows +//go:build !linux && (!darwin || ios) && !windows package filewatch diff --git a/internal/platform/darwin/accessibility_darwin_test.go b/internal/platform/darwin/accessibility_darwin_test.go index 8a4fe95d6..e0da990b5 100644 --- a/internal/platform/darwin/accessibility_darwin_test.go +++ b/internal/platform/darwin/accessibility_darwin_test.go @@ -1,3 +1,5 @@ +//go:build !ios + package darwin import ( diff --git a/internal/platform/darwin/bitmap_reuse_test.go b/internal/platform/darwin/bitmap_reuse_test.go index 5bae990ad..feacd14f7 100644 --- a/internal/platform/darwin/bitmap_reuse_test.go +++ b/internal/platform/darwin/bitmap_reuse_test.go @@ -1,4 +1,4 @@ -//go:build darwin && vivahead +//go:build darwin && vivahead && !ios package darwin diff --git a/internal/platform/darwin/bitmap_stage_bench_test.go b/internal/platform/darwin/bitmap_stage_bench_test.go index b5e0976e5..07dd94cc5 100644 --- a/internal/platform/darwin/bitmap_stage_bench_test.go +++ b/internal/platform/darwin/bitmap_stage_bench_test.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/callback.go b/internal/platform/darwin/callback.go index f6693b104..3fa07fa43 100644 --- a/internal/platform/darwin/callback.go +++ b/internal/platform/darwin/callback.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/callback_handle_test.go b/internal/platform/darwin/callback_handle_test.go index 232f862ec..1355641d9 100644 --- a/internal/platform/darwin/callback_handle_test.go +++ b/internal/platform/darwin/callback_handle_test.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/clipboard_files_darwin_test.go b/internal/platform/darwin/clipboard_files_darwin_test.go index cc8e3e0ca..dd67ccfac 100644 --- a/internal/platform/darwin/clipboard_files_darwin_test.go +++ b/internal/platform/darwin/clipboard_files_darwin_test.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/clipboard_html_darwin.go b/internal/platform/darwin/clipboard_html_darwin.go index 77d192176..cbf1c0960 100644 --- a/internal/platform/darwin/clipboard_html_darwin.go +++ b/internal/platform/darwin/clipboard_html_darwin.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/clipboard_html_darwin_test.go b/internal/platform/darwin/clipboard_html_darwin_test.go index 5ea73e263..2b4b0ddd6 100644 --- a/internal/platform/darwin/clipboard_html_darwin_test.go +++ b/internal/platform/darwin/clipboard_html_darwin_test.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/clipboard_image_darwin.go b/internal/platform/darwin/clipboard_image_darwin.go index ad65f2a32..c440e7ac1 100644 --- a/internal/platform/darwin/clipboard_image_darwin.go +++ b/internal/platform/darwin/clipboard_image_darwin.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/clipboard_image_darwin_test.go b/internal/platform/darwin/clipboard_image_darwin_test.go index 7e5f583f9..e4ad50a2c 100644 --- a/internal/platform/darwin/clipboard_image_darwin_test.go +++ b/internal/platform/darwin/clipboard_image_darwin_test.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/clipboard_watch_darwin_test.go b/internal/platform/darwin/clipboard_watch_darwin_test.go index 7a12d665a..98013b746 100644 --- a/internal/platform/darwin/clipboard_watch_darwin_test.go +++ b/internal/platform/darwin/clipboard_watch_darwin_test.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/composite_test.go b/internal/platform/darwin/composite_test.go index 1dbe0b70f..971c15f93 100644 --- a/internal/platform/darwin/composite_test.go +++ b/internal/platform/darwin/composite_test.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/composition_tentative_darwin_test.go b/internal/platform/darwin/composition_tentative_darwin_test.go index fb1d1ad05..b17f9cbb4 100644 --- a/internal/platform/darwin/composition_tentative_darwin_test.go +++ b/internal/platform/darwin/composition_tentative_darwin_test.go @@ -1,3 +1,5 @@ +//go:build !ios + package darwin import ( diff --git a/internal/platform/darwin/cursor_image_darwin_test.go b/internal/platform/darwin/cursor_image_darwin_test.go index a4853d340..cea473acb 100644 --- a/internal/platform/darwin/cursor_image_darwin_test.go +++ b/internal/platform/darwin/cursor_image_darwin_test.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/cursor_owner_darwin.h b/internal/platform/darwin/cursor_owner_darwin.h index 34e43c88f..0653b957d 100644 --- a/internal/platform/darwin/cursor_owner_darwin.h +++ b/internal/platform/darwin/cursor_owner_darwin.h @@ -1,3 +1,5 @@ +//go:build !ios + #ifndef VIVA_CURSOR_OWNER_DARWIN_H #define VIVA_CURSOR_OWNER_DARWIN_H diff --git a/internal/platform/darwin/cursor_owner_darwin_test.go b/internal/platform/darwin/cursor_owner_darwin_test.go index 95cf3e166..b0ec2c161 100644 --- a/internal/platform/darwin/cursor_owner_darwin_test.go +++ b/internal/platform/darwin/cursor_owner_darwin_test.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/dock_badge_darwin.go b/internal/platform/darwin/dock_badge_darwin.go index 48a17de6e..f250c3b40 100644 --- a/internal/platform/darwin/dock_badge_darwin.go +++ b/internal/platform/darwin/dock_badge_darwin.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/dock_badge_darwin.h b/internal/platform/darwin/dock_badge_darwin.h index 58f785c07..e88dfa609 100644 --- a/internal/platform/darwin/dock_badge_darwin.h +++ b/internal/platform/darwin/dock_badge_darwin.h @@ -1,3 +1,5 @@ +//go:build !ios + #ifndef VIVA_DOCK_BADGE_DARWIN_H #define VIVA_DOCK_BADGE_DARWIN_H diff --git a/internal/platform/darwin/dock_badge_darwin.m b/internal/platform/darwin/dock_badge_darwin.m index f367549d0..ce6f25c04 100644 --- a/internal/platform/darwin/dock_badge_darwin.m +++ b/internal/platform/darwin/dock_badge_darwin.m @@ -1,3 +1,5 @@ +//go:build !ios + #include "dock_badge_darwin.h" #import diff --git a/internal/platform/darwin/dock_badge_darwin_test.go b/internal/platform/darwin/dock_badge_darwin_test.go index e45bc549c..8f640a2d1 100644 --- a/internal/platform/darwin/dock_badge_darwin_test.go +++ b/internal/platform/darwin/dock_badge_darwin_test.go @@ -1,3 +1,5 @@ +//go:build !ios + package darwin import ( diff --git a/internal/platform/darwin/dock_progress_darwin.go b/internal/platform/darwin/dock_progress_darwin.go index 1b7c4054f..215321cfe 100644 --- a/internal/platform/darwin/dock_progress_darwin.go +++ b/internal/platform/darwin/dock_progress_darwin.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/dock_progress_darwin.h b/internal/platform/darwin/dock_progress_darwin.h index 47b5104c1..18d2f4e16 100644 --- a/internal/platform/darwin/dock_progress_darwin.h +++ b/internal/platform/darwin/dock_progress_darwin.h @@ -1,3 +1,5 @@ +//go:build !ios + #ifndef VIVA_DOCK_PROGRESS_DARWIN_H #define VIVA_DOCK_PROGRESS_DARWIN_H diff --git a/internal/platform/darwin/dock_progress_darwin.m b/internal/platform/darwin/dock_progress_darwin.m index 6accdfb5b..e875bab87 100644 --- a/internal/platform/darwin/dock_progress_darwin.m +++ b/internal/platform/darwin/dock_progress_darwin.m @@ -1,3 +1,5 @@ +//go:build !ios + #include "dock_progress_darwin.h" #import diff --git a/internal/platform/darwin/dock_progress_darwin_test.go b/internal/platform/darwin/dock_progress_darwin_test.go index 9275b1f76..78f79841d 100644 --- a/internal/platform/darwin/dock_progress_darwin_test.go +++ b/internal/platform/darwin/dock_progress_darwin_test.go @@ -1,3 +1,5 @@ +//go:build !ios + package darwin import ( diff --git a/internal/platform/darwin/dock_reopen_darwin_test.go b/internal/platform/darwin/dock_reopen_darwin_test.go index a72cd6e17..dd43b0f90 100644 --- a/internal/platform/darwin/dock_reopen_darwin_test.go +++ b/internal/platform/darwin/dock_reopen_darwin_test.go @@ -1,3 +1,5 @@ +//go:build !ios + package darwin import ( diff --git a/internal/platform/darwin/drag_darwin.go b/internal/platform/darwin/drag_darwin.go index 2b8f77bbc..1842a1f5b 100644 --- a/internal/platform/darwin/drag_darwin.go +++ b/internal/platform/darwin/drag_darwin.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/editor_baseline_test.go b/internal/platform/darwin/editor_baseline_test.go index b1d47d722..106d0fc94 100644 --- a/internal/platform/darwin/editor_baseline_test.go +++ b/internal/platform/darwin/editor_baseline_test.go @@ -1,4 +1,4 @@ -//go:build darwin && vivahead +//go:build darwin && vivahead && !ios package darwin diff --git a/internal/platform/darwin/fidelity_test.go b/internal/platform/darwin/fidelity_test.go index 234a3bffe..f26e88814 100644 --- a/internal/platform/darwin/fidelity_test.go +++ b/internal/platform/darwin/fidelity_test.go @@ -1,4 +1,4 @@ -//go:build darwin && vivahead +//go:build darwin && vivahead && !ios package darwin diff --git a/internal/platform/darwin/file_drop_darwin_test.go b/internal/platform/darwin/file_drop_darwin_test.go index 50d2d61cc..55552209e 100644 --- a/internal/platform/darwin/file_drop_darwin_test.go +++ b/internal/platform/darwin/file_drop_darwin_test.go @@ -1,3 +1,5 @@ +//go:build !ios + package darwin import ( diff --git a/internal/platform/darwin/file_icon_darwin.go b/internal/platform/darwin/file_icon_darwin.go index 35b394af0..e9f15f89a 100644 --- a/internal/platform/darwin/file_icon_darwin.go +++ b/internal/platform/darwin/file_icon_darwin.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/file_icon_darwin.h b/internal/platform/darwin/file_icon_darwin.h index a021ab1f9..84526cbef 100644 --- a/internal/platform/darwin/file_icon_darwin.h +++ b/internal/platform/darwin/file_icon_darwin.h @@ -1,3 +1,5 @@ +//go:build !ios + #ifndef VIVA_FILE_ICON_DARWIN_H #define VIVA_FILE_ICON_DARWIN_H diff --git a/internal/platform/darwin/file_icon_darwin.m b/internal/platform/darwin/file_icon_darwin.m index 9a0a9af86..a2a5a2ca6 100644 --- a/internal/platform/darwin/file_icon_darwin.m +++ b/internal/platform/darwin/file_icon_darwin.m @@ -1,3 +1,5 @@ +//go:build !ios + #include "file_icon_darwin.h" #import diff --git a/internal/platform/darwin/font_file_vivahead.go b/internal/platform/darwin/font_file_vivahead.go index 86142cb79..c023eb68e 100644 --- a/internal/platform/darwin/font_file_vivahead.go +++ b/internal/platform/darwin/font_file_vivahead.go @@ -1,4 +1,4 @@ -//go:build darwin && vivahead +//go:build darwin && vivahead && !ios package darwin diff --git a/internal/platform/darwin/font_register_darwin.go b/internal/platform/darwin/font_register_darwin.go index 3d0af5cda..b4636c02f 100644 --- a/internal/platform/darwin/font_register_darwin.go +++ b/internal/platform/darwin/font_register_darwin.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/global_shortcut_darwin.go b/internal/platform/darwin/global_shortcut_darwin.go index 2653e006b..6e55d9827 100644 --- a/internal/platform/darwin/global_shortcut_darwin.go +++ b/internal/platform/darwin/global_shortcut_darwin.go @@ -1,3 +1,5 @@ +//go:build !ios + package darwin /* diff --git a/internal/platform/darwin/global_shortcut_darwin.m b/internal/platform/darwin/global_shortcut_darwin.m index 9e4e31098..069e454cb 100644 --- a/internal/platform/darwin/global_shortcut_darwin.m +++ b/internal/platform/darwin/global_shortcut_darwin.m @@ -1,3 +1,5 @@ +//go:build !ios + #import #import #include diff --git a/internal/platform/darwin/global_shortcut_darwin_test.go b/internal/platform/darwin/global_shortcut_darwin_test.go index 33e3bbdc3..9a046ecef 100644 --- a/internal/platform/darwin/global_shortcut_darwin_test.go +++ b/internal/platform/darwin/global_shortcut_darwin_test.go @@ -1,3 +1,5 @@ +//go:build !ios + package darwin import ( diff --git a/internal/platform/darwin/image_shading_test.go b/internal/platform/darwin/image_shading_test.go index 7dbc8406b..1ab675dad 100644 --- a/internal/platform/darwin/image_shading_test.go +++ b/internal/platform/darwin/image_shading_test.go @@ -1,4 +1,4 @@ -//go:build darwin && vivahead +//go:build darwin && vivahead && !ios package darwin diff --git a/internal/platform/darwin/interface_font_test.go b/internal/platform/darwin/interface_font_test.go index cab53960c..bda6409f5 100644 --- a/internal/platform/darwin/interface_font_test.go +++ b/internal/platform/darwin/interface_font_test.go @@ -1,4 +1,4 @@ -//go:build darwin && vivahead +//go:build darwin && vivahead && !ios package darwin diff --git a/internal/platform/darwin/interface_weight_test.go b/internal/platform/darwin/interface_weight_test.go index 4f6759623..886ad6122 100644 --- a/internal/platform/darwin/interface_weight_test.go +++ b/internal/platform/darwin/interface_weight_test.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/label_invalid_utf8_vivahead_test.go b/internal/platform/darwin/label_invalid_utf8_vivahead_test.go index a71256d9d..0c7dd3c70 100644 --- a/internal/platform/darwin/label_invalid_utf8_vivahead_test.go +++ b/internal/platform/darwin/label_invalid_utf8_vivahead_test.go @@ -1,4 +1,4 @@ -//go:build darwin && vivahead +//go:build darwin && vivahead && !ios package darwin diff --git a/internal/platform/darwin/ligature_test.go b/internal/platform/darwin/ligature_test.go index 6c45cbc8a..4f32901ce 100644 --- a/internal/platform/darwin/ligature_test.go +++ b/internal/platform/darwin/ligature_test.go @@ -1,4 +1,4 @@ -//go:build darwin && vivahead +//go:build darwin && vivahead && !ios package darwin diff --git a/internal/platform/darwin/live_resize_darwin_test.go b/internal/platform/darwin/live_resize_darwin_test.go index 6447b9efc..6e34bb75f 100644 --- a/internal/platform/darwin/live_resize_darwin_test.go +++ b/internal/platform/darwin/live_resize_darwin_test.go @@ -1,3 +1,5 @@ +//go:build !ios + package darwin import ( diff --git a/internal/platform/darwin/main_darwin_test.go b/internal/platform/darwin/main_darwin_test.go index 61e4f45cb..2649f8b8e 100644 --- a/internal/platform/darwin/main_darwin_test.go +++ b/internal/platform/darwin/main_darwin_test.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/main_menu_darwin.h b/internal/platform/darwin/main_menu_darwin.h index 7c9704e16..ae0c0eb70 100644 --- a/internal/platform/darwin/main_menu_darwin.h +++ b/internal/platform/darwin/main_menu_darwin.h @@ -1,3 +1,5 @@ +//go:build !ios + #ifndef VIVA_MAIN_MENU_DARWIN_H #define VIVA_MAIN_MENU_DARWIN_H diff --git a/internal/platform/darwin/main_menu_darwin.m b/internal/platform/darwin/main_menu_darwin.m index 2825c3126..a3bfddd8c 100644 --- a/internal/platform/darwin/main_menu_darwin.m +++ b/internal/platform/darwin/main_menu_darwin.m @@ -1,3 +1,5 @@ +//go:build !ios + #include "main_menu_darwin.h" #include "menu_bar_darwin.h" diff --git a/internal/platform/darwin/main_menu_darwin_test.go b/internal/platform/darwin/main_menu_darwin_test.go index 4165becc9..d1339f6dd 100644 --- a/internal/platform/darwin/main_menu_darwin_test.go +++ b/internal/platform/darwin/main_menu_darwin_test.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/mainpump/mainpump_darwin.go b/internal/platform/darwin/mainpump/mainpump_darwin.go index 080106157..fd912a0cf 100644 --- a/internal/platform/darwin/mainpump/mainpump_darwin.go +++ b/internal/platform/darwin/mainpump/mainpump_darwin.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios // Package mainpump lets a test binary serve the main dispatch queue. // diff --git a/internal/platform/darwin/menu_bar_darwin.go b/internal/platform/darwin/menu_bar_darwin.go index ed83ac01b..a37741039 100644 --- a/internal/platform/darwin/menu_bar_darwin.go +++ b/internal/platform/darwin/menu_bar_darwin.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/menu_bar_darwin.h b/internal/platform/darwin/menu_bar_darwin.h index 2a90d3b24..ada9b80f7 100644 --- a/internal/platform/darwin/menu_bar_darwin.h +++ b/internal/platform/darwin/menu_bar_darwin.h @@ -1,3 +1,5 @@ +//go:build !ios + #ifndef VIVA_MENU_BAR_DARWIN_H #define VIVA_MENU_BAR_DARWIN_H diff --git a/internal/platform/darwin/menu_bar_darwin.m b/internal/platform/darwin/menu_bar_darwin.m index 91ee12711..44d7d1499 100644 --- a/internal/platform/darwin/menu_bar_darwin.m +++ b/internal/platform/darwin/menu_bar_darwin.m @@ -1,3 +1,5 @@ +//go:build !ios + #import #include "menu_bar_darwin.h" diff --git a/internal/platform/darwin/modifier_taps_darwin_test.go b/internal/platform/darwin/modifier_taps_darwin_test.go index 349c48b9c..a2d91732c 100644 --- a/internal/platform/darwin/modifier_taps_darwin_test.go +++ b/internal/platform/darwin/modifier_taps_darwin_test.go @@ -1,3 +1,5 @@ +//go:build !ios + package darwin import ( diff --git a/internal/platform/darwin/mono_fallback_test.go b/internal/platform/darwin/mono_fallback_test.go index b0daaa4ab..00916a26c 100644 --- a/internal/platform/darwin/mono_fallback_test.go +++ b/internal/platform/darwin/mono_fallback_test.go @@ -1,4 +1,4 @@ -//go:build darwin && vivahead +//go:build darwin && vivahead && !ios package darwin diff --git a/internal/platform/darwin/mono_family.go b/internal/platform/darwin/mono_family.go index 9fb858e4a..3c56e52c2 100644 --- a/internal/platform/darwin/mono_family.go +++ b/internal/platform/darwin/mono_family.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/mono_family_grid_test.go b/internal/platform/darwin/mono_family_grid_test.go index 46b8e881b..4c4788a25 100644 --- a/internal/platform/darwin/mono_family_grid_test.go +++ b/internal/platform/darwin/mono_family_grid_test.go @@ -1,4 +1,4 @@ -//go:build darwin && vivahead +//go:build darwin && vivahead && !ios package darwin diff --git a/internal/platform/darwin/mono_installed_fallback_test.go b/internal/platform/darwin/mono_installed_fallback_test.go index 7aebf7ca9..39d52c3fc 100644 --- a/internal/platform/darwin/mono_installed_fallback_test.go +++ b/internal/platform/darwin/mono_installed_fallback_test.go @@ -1,4 +1,4 @@ -//go:build darwin && vivahead +//go:build darwin && vivahead && !ios package darwin diff --git a/internal/platform/darwin/native_label_text_darwin_test.go b/internal/platform/darwin/native_label_text_darwin_test.go index 13eb8a251..278282cef 100644 --- a/internal/platform/darwin/native_label_text_darwin_test.go +++ b/internal/platform/darwin/native_label_text_darwin_test.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/offscreen.go b/internal/platform/darwin/offscreen.go index 5b6d34bcc..864595eaf 100644 --- a/internal/platform/darwin/offscreen.go +++ b/internal/platform/darwin/offscreen.go @@ -1,4 +1,4 @@ -//go:build darwin && vivahead +//go:build darwin && vivahead && !ios package darwin diff --git a/internal/platform/darwin/offscreen_test.go b/internal/platform/darwin/offscreen_test.go index ebade6311..3407b2acc 100644 --- a/internal/platform/darwin/offscreen_test.go +++ b/internal/platform/darwin/offscreen_test.go @@ -1,4 +1,4 @@ -//go:build darwin && vivahead +//go:build darwin && vivahead && !ios package darwin diff --git a/internal/platform/darwin/open_file_darwin.go b/internal/platform/darwin/open_file_darwin.go index 2bde6dd2b..e4a29efb2 100644 --- a/internal/platform/darwin/open_file_darwin.go +++ b/internal/platform/darwin/open_file_darwin.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/open_file_darwin_test.go b/internal/platform/darwin/open_file_darwin_test.go index 01330847a..4f6389cec 100644 --- a/internal/platform/darwin/open_file_darwin_test.go +++ b/internal/platform/darwin/open_file_darwin_test.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/open_url_darwin.go b/internal/platform/darwin/open_url_darwin.go index 052eb6ac5..79b3dbb89 100644 --- a/internal/platform/darwin/open_url_darwin.go +++ b/internal/platform/darwin/open_url_darwin.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/open_url_darwin_test.go b/internal/platform/darwin/open_url_darwin_test.go index af35e53d0..93ee8c707 100644 --- a/internal/platform/darwin/open_url_darwin_test.go +++ b/internal/platform/darwin/open_url_darwin_test.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/open_with_darwin.go b/internal/platform/darwin/open_with_darwin.go index 53f3d8b58..68cc5bd5f 100644 --- a/internal/platform/darwin/open_with_darwin.go +++ b/internal/platform/darwin/open_with_darwin.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/open_with_darwin_test.go b/internal/platform/darwin/open_with_darwin_test.go index cf2c1ca0c..bb7342c52 100644 --- a/internal/platform/darwin/open_with_darwin_test.go +++ b/internal/platform/darwin/open_with_darwin_test.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/platform.go b/internal/platform/darwin/platform.go index 84397da87..e1d19e72c 100644 --- a/internal/platform/darwin/platform.go +++ b/internal/platform/darwin/platform.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios // Package darwin implements the native macOS application and Metal backend. package darwin diff --git a/internal/platform/darwin/post_darwin.go b/internal/platform/darwin/post_darwin.go index cb569c759..86221a13b 100644 --- a/internal/platform/darwin/post_darwin.go +++ b/internal/platform/darwin/post_darwin.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/post_darwin.h b/internal/platform/darwin/post_darwin.h index f4f4c5cf1..50532c706 100644 --- a/internal/platform/darwin/post_darwin.h +++ b/internal/platform/darwin/post_darwin.h @@ -1,3 +1,5 @@ +//go:build !ios + #ifndef VIVA_POST_DARWIN_H #define VIVA_POST_DARWIN_H diff --git a/internal/platform/darwin/post_darwin.m b/internal/platform/darwin/post_darwin.m index 6a490a354..7b373fb44 100644 --- a/internal/platform/darwin/post_darwin.m +++ b/internal/platform/darwin/post_darwin.m @@ -1,3 +1,5 @@ +//go:build !ios + #import #include "post_darwin.h" diff --git a/internal/platform/darwin/post_darwin_test.go b/internal/platform/darwin/post_darwin_test.go index 27a9283ab..a329b552d 100644 --- a/internal/platform/darwin/post_darwin_test.go +++ b/internal/platform/darwin/post_darwin_test.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/probe.go b/internal/platform/darwin/probe.go index 1adbe5345..483de187c 100644 --- a/internal/platform/darwin/probe.go +++ b/internal/platform/darwin/probe.go @@ -1,4 +1,4 @@ -//go:build darwin && vivahead +//go:build darwin && vivahead && !ios package darwin diff --git a/internal/platform/darwin/proxy_darwin.go b/internal/platform/darwin/proxy_darwin.go index 043e02b63..9b2d287d3 100644 --- a/internal/platform/darwin/proxy_darwin.go +++ b/internal/platform/darwin/proxy_darwin.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/proxy_darwin.h b/internal/platform/darwin/proxy_darwin.h index e58f22888..6a8342222 100644 --- a/internal/platform/darwin/proxy_darwin.h +++ b/internal/platform/darwin/proxy_darwin.h @@ -1,3 +1,5 @@ +//go:build !ios + #ifndef VIVA_PROXY_DARWIN_H #define VIVA_PROXY_DARWIN_H diff --git a/internal/platform/darwin/proxy_darwin.m b/internal/platform/darwin/proxy_darwin.m index eff703cdd..052e189d9 100644 --- a/internal/platform/darwin/proxy_darwin.m +++ b/internal/platform/darwin/proxy_darwin.m @@ -1,3 +1,5 @@ +//go:build !ios + #import #import diff --git a/internal/platform/darwin/proxy_darwin_test.go b/internal/platform/darwin/proxy_darwin_test.go index 959de7e98..415818d59 100644 --- a/internal/platform/darwin/proxy_darwin_test.go +++ b/internal/platform/darwin/proxy_darwin_test.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/quad_render_test.go b/internal/platform/darwin/quad_render_test.go index 3f140620e..d2a0c6adb 100644 --- a/internal/platform/darwin/quad_render_test.go +++ b/internal/platform/darwin/quad_render_test.go @@ -1,4 +1,4 @@ -//go:build darwin && vivahead +//go:build darwin && vivahead && !ios package darwin diff --git a/internal/platform/darwin/quad_test.go b/internal/platform/darwin/quad_test.go index 9626df2c2..2f627529f 100644 --- a/internal/platform/darwin/quad_test.go +++ b/internal/platform/darwin/quad_test.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/quit_request_darwin.go b/internal/platform/darwin/quit_request_darwin.go index eb5d913d0..95f900427 100644 --- a/internal/platform/darwin/quit_request_darwin.go +++ b/internal/platform/darwin/quit_request_darwin.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/quit_request_darwin_test.go b/internal/platform/darwin/quit_request_darwin_test.go index 187c99c7d..3c241457f 100644 --- a/internal/platform/darwin/quit_request_darwin_test.go +++ b/internal/platform/darwin/quit_request_darwin_test.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/rectangle_buffer_test.go b/internal/platform/darwin/rectangle_buffer_test.go index 8ec7ff719..75caf530a 100644 --- a/internal/platform/darwin/rectangle_buffer_test.go +++ b/internal/platform/darwin/rectangle_buffer_test.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/reference_text.go b/internal/platform/darwin/reference_text.go index 286f35fa7..501de075c 100644 --- a/internal/platform/darwin/reference_text.go +++ b/internal/platform/darwin/reference_text.go @@ -1,4 +1,4 @@ -//go:build darwin && vivahead +//go:build darwin && vivahead && !ios package darwin diff --git a/internal/platform/darwin/renderer_recovery_test.go b/internal/platform/darwin/renderer_recovery_test.go index 42387e168..f00751e6a 100644 --- a/internal/platform/darwin/renderer_recovery_test.go +++ b/internal/platform/darwin/renderer_recovery_test.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/reopen_darwin.go b/internal/platform/darwin/reopen_darwin.go index 4b8c843d2..8c5d4a490 100644 --- a/internal/platform/darwin/reopen_darwin.go +++ b/internal/platform/darwin/reopen_darwin.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/reopen_darwin_test.go b/internal/platform/darwin/reopen_darwin_test.go index 5249fc26e..cf4b7f611 100644 --- a/internal/platform/darwin/reopen_darwin_test.go +++ b/internal/platform/darwin/reopen_darwin_test.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/save_panel_darwin.h b/internal/platform/darwin/save_panel_darwin.h index dad39ea63..cb4a749de 100644 --- a/internal/platform/darwin/save_panel_darwin.h +++ b/internal/platform/darwin/save_panel_darwin.h @@ -1,3 +1,5 @@ +//go:build !ios + #ifndef VIVA_SAVE_PANEL_DARWIN_H #define VIVA_SAVE_PANEL_DARWIN_H diff --git a/internal/platform/darwin/save_panel_darwin.m b/internal/platform/darwin/save_panel_darwin.m index 5f8ba990c..69f1d4a16 100644 --- a/internal/platform/darwin/save_panel_darwin.m +++ b/internal/platform/darwin/save_panel_darwin.m @@ -1,3 +1,5 @@ +//go:build !ios + #import "save_panel_darwin.h" void viva_configure_save_panel(NSSavePanel *panel, NSString *name, NSArray *allowed) { diff --git a/internal/platform/darwin/save_panel_darwin_test.go b/internal/platform/darwin/save_panel_darwin_test.go index 11822623f..b8984d7e8 100644 --- a/internal/platform/darwin/save_panel_darwin_test.go +++ b/internal/platform/darwin/save_panel_darwin_test.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/secret_darwin.go b/internal/platform/darwin/secret_darwin.go index ad4b09a9a..cae1c86bf 100644 --- a/internal/platform/darwin/secret_darwin.go +++ b/internal/platform/darwin/secret_darwin.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/secret_darwin.h b/internal/platform/darwin/secret_darwin.h index bbce0e469..cb4c95548 100644 --- a/internal/platform/darwin/secret_darwin.h +++ b/internal/platform/darwin/secret_darwin.h @@ -1,3 +1,5 @@ +//go:build !ios + #ifndef VIVA_SECRET_DARWIN_H #define VIVA_SECRET_DARWIN_H diff --git a/internal/platform/darwin/secret_darwin.m b/internal/platform/darwin/secret_darwin.m index d386bdb46..7f3854dfe 100644 --- a/internal/platform/darwin/secret_darwin.m +++ b/internal/platform/darwin/secret_darwin.m @@ -1,3 +1,5 @@ +//go:build !ios + #import #import diff --git a/internal/platform/darwin/shader.go b/internal/platform/darwin/shader.go index 2c28b2f8a..dc36ad3f5 100644 --- a/internal/platform/darwin/shader.go +++ b/internal/platform/darwin/shader.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/shader_target_test.go b/internal/platform/darwin/shader_target_test.go index cc8ba50a4..cb3ac3856 100644 --- a/internal/platform/darwin/shader_target_test.go +++ b/internal/platform/darwin/shader_target_test.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/sharpness_test.go b/internal/platform/darwin/sharpness_test.go index 33ef4ea91..8188c95aa 100644 --- a/internal/platform/darwin/sharpness_test.go +++ b/internal/platform/darwin/sharpness_test.go @@ -1,4 +1,4 @@ -//go:build darwin && vivahead +//go:build darwin && vivahead && !ios package darwin diff --git a/internal/platform/darwin/sleep_darwin.go b/internal/platform/darwin/sleep_darwin.go index fee0f6421..fd8b2ba47 100644 --- a/internal/platform/darwin/sleep_darwin.go +++ b/internal/platform/darwin/sleep_darwin.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/sleep_darwin.h b/internal/platform/darwin/sleep_darwin.h index d407b1158..74e9e1df6 100644 --- a/internal/platform/darwin/sleep_darwin.h +++ b/internal/platform/darwin/sleep_darwin.h @@ -1,3 +1,5 @@ +//go:build !ios + #ifndef VIVA_SLEEP_DARWIN_H #define VIVA_SLEEP_DARWIN_H diff --git a/internal/platform/darwin/sleep_darwin.m b/internal/platform/darwin/sleep_darwin.m index 27911a5ca..0b49d76ec 100644 --- a/internal/platform/darwin/sleep_darwin.m +++ b/internal/platform/darwin/sleep_darwin.m @@ -1,3 +1,5 @@ +//go:build !ios + #import #import diff --git a/internal/platform/darwin/sleep_darwin_test.go b/internal/platform/darwin/sleep_darwin_test.go index 578dd8868..f2d83ae3f 100644 --- a/internal/platform/darwin/sleep_darwin_test.go +++ b/internal/platform/darwin/sleep_darwin_test.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/status_item_darwin.go b/internal/platform/darwin/status_item_darwin.go index 83922d8ef..f22d0aa04 100644 --- a/internal/platform/darwin/status_item_darwin.go +++ b/internal/platform/darwin/status_item_darwin.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/status_item_darwin.h b/internal/platform/darwin/status_item_darwin.h index ebc524646..499ed9b7d 100644 --- a/internal/platform/darwin/status_item_darwin.h +++ b/internal/platform/darwin/status_item_darwin.h @@ -1,3 +1,5 @@ +//go:build !ios + #ifndef VIVA_STATUS_ITEM_DARWIN_H #define VIVA_STATUS_ITEM_DARWIN_H diff --git a/internal/platform/darwin/status_item_darwin.m b/internal/platform/darwin/status_item_darwin.m index 75b3d3de2..eae46fb5f 100644 --- a/internal/platform/darwin/status_item_darwin.m +++ b/internal/platform/darwin/status_item_darwin.m @@ -1,3 +1,5 @@ +//go:build !ios + #import #import diff --git a/internal/platform/darwin/status_item_darwin_test.go b/internal/platform/darwin/status_item_darwin_test.go index 50582a53d..fcce84784 100644 --- a/internal/platform/darwin/status_item_darwin_test.go +++ b/internal/platform/darwin/status_item_darwin_test.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/system_darwin.go b/internal/platform/darwin/system_darwin.go index 4577f0f5e..8782a3937 100644 --- a/internal/platform/darwin/system_darwin.go +++ b/internal/platform/darwin/system_darwin.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/system_darwin.h b/internal/platform/darwin/system_darwin.h index bd5de21b5..a4fcbc157 100644 --- a/internal/platform/darwin/system_darwin.h +++ b/internal/platform/darwin/system_darwin.h @@ -1,3 +1,5 @@ +//go:build !ios + #ifndef VIVA_SYSTEM_DARWIN_H #define VIVA_SYSTEM_DARWIN_H diff --git a/internal/platform/darwin/system_darwin.m b/internal/platform/darwin/system_darwin.m index fbecc0ec7..9f72b8d1e 100644 --- a/internal/platform/darwin/system_darwin.m +++ b/internal/platform/darwin/system_darwin.m @@ -1,3 +1,5 @@ +//go:build !ios + #import #import #import diff --git a/internal/platform/darwin/system_darwin_test.go b/internal/platform/darwin/system_darwin_test.go index 0e0fa2897..a3ba24d74 100644 --- a/internal/platform/darwin/system_darwin_test.go +++ b/internal/platform/darwin/system_darwin_test.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/testdata/reopen_bridge/main.go b/internal/platform/darwin/testdata/reopen_bridge/main.go index 7303e1d77..ee3702c18 100644 --- a/internal/platform/darwin/testdata/reopen_bridge/main.go +++ b/internal/platform/darwin/testdata/reopen_bridge/main.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios // This subprocess exercises the real Cocoa/Go bridge and exits without input. package main diff --git a/internal/platform/darwin/testdata/tentative_bridge_darwin.go b/internal/platform/darwin/testdata/tentative_bridge_darwin.go index f05712445..4ca43a516 100644 --- a/internal/platform/darwin/testdata/tentative_bridge_darwin.go +++ b/internal/platform/darwin/testdata/tentative_bridge_darwin.go @@ -1,3 +1,5 @@ +//go:build !ios + package darwin /* diff --git a/internal/platform/darwin/testdata/tentative_bridge_darwin_test.go b/internal/platform/darwin/testdata/tentative_bridge_darwin_test.go index 2b8b4bde1..0ffb57ff8 100644 --- a/internal/platform/darwin/testdata/tentative_bridge_darwin_test.go +++ b/internal/platform/darwin/testdata/tentative_bridge_darwin_test.go @@ -1,3 +1,5 @@ +//go:build !ios + package darwin import ( diff --git a/internal/platform/darwin/text.go b/internal/platform/darwin/text.go index da642d066..814e913cb 100644 --- a/internal/platform/darwin/text.go +++ b/internal/platform/darwin/text.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/text_bench_test.go b/internal/platform/darwin/text_bench_test.go index 47183ab23..ffdcc2e68 100644 --- a/internal/platform/darwin/text_bench_test.go +++ b/internal/platform/darwin/text_bench_test.go @@ -1,4 +1,4 @@ -//go:build darwin && vivahead +//go:build darwin && vivahead && !ios package darwin diff --git a/internal/platform/darwin/text_engine.go b/internal/platform/darwin/text_engine.go index c18a7294a..346f59d22 100644 --- a/internal/platform/darwin/text_engine.go +++ b/internal/platform/darwin/text_engine.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/text_engine_bench_test.go b/internal/platform/darwin/text_engine_bench_test.go index c25b0c3bd..61065d767 100644 --- a/internal/platform/darwin/text_engine_bench_test.go +++ b/internal/platform/darwin/text_engine_bench_test.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/text_engine_start_test.go b/internal/platform/darwin/text_engine_start_test.go index 4b0895d81..07b2e86bd 100644 --- a/internal/platform/darwin/text_engine_start_test.go +++ b/internal/platform/darwin/text_engine_start_test.go @@ -1,4 +1,4 @@ -//go:build darwin && vivahead +//go:build darwin && vivahead && !ios package darwin diff --git a/internal/platform/darwin/text_engine_test.go b/internal/platform/darwin/text_engine_test.go index 10f7ec68d..248c95a67 100644 --- a/internal/platform/darwin/text_engine_test.go +++ b/internal/platform/darwin/text_engine_test.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/text_italic_regression_test.go b/internal/platform/darwin/text_italic_regression_test.go index 1e5723eef..79666a086 100644 --- a/internal/platform/darwin/text_italic_regression_test.go +++ b/internal/platform/darwin/text_italic_regression_test.go @@ -1,4 +1,4 @@ -//go:build darwin && vivahead +//go:build darwin && vivahead && !ios package darwin diff --git a/internal/platform/darwin/text_run_regression_test.go b/internal/platform/darwin/text_run_regression_test.go index c2abbbdcf..d2a8e9d59 100644 --- a/internal/platform/darwin/text_run_regression_test.go +++ b/internal/platform/darwin/text_run_regression_test.go @@ -1,4 +1,4 @@ -//go:build darwin && vivahead +//go:build darwin && vivahead && !ios package darwin diff --git a/internal/platform/darwin/text_selection_darwin_test.go b/internal/platform/darwin/text_selection_darwin_test.go index 941eb2f08..676e70f74 100644 --- a/internal/platform/darwin/text_selection_darwin_test.go +++ b/internal/platform/darwin/text_selection_darwin_test.go @@ -1,3 +1,5 @@ +//go:build !ios + package darwin import ( diff --git a/internal/platform/darwin/text_test.go b/internal/platform/darwin/text_test.go index 2e5846871..592f57176 100644 --- a/internal/platform/darwin/text_test.go +++ b/internal/platform/darwin/text_test.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/text_weight_regression_test.go b/internal/platform/darwin/text_weight_regression_test.go index 4f150f3ae..f9f61850d 100644 --- a/internal/platform/darwin/text_weight_regression_test.go +++ b/internal/platform/darwin/text_weight_regression_test.go @@ -1,4 +1,4 @@ -//go:build darwin && vivahead +//go:build darwin && vivahead && !ios package darwin diff --git a/internal/platform/darwin/traffic_lights_darwin_test.go b/internal/platform/darwin/traffic_lights_darwin_test.go index ea3c53586..94dbdc018 100644 --- a/internal/platform/darwin/traffic_lights_darwin_test.go +++ b/internal/platform/darwin/traffic_lights_darwin_test.go @@ -1,3 +1,5 @@ +//go:build !ios + package darwin import ( diff --git a/internal/platform/darwin/web_darwin.go b/internal/platform/darwin/web_darwin.go index 656b0c9a8..1bfe7f33f 100644 --- a/internal/platform/darwin/web_darwin.go +++ b/internal/platform/darwin/web_darwin.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/web_darwin.h b/internal/platform/darwin/web_darwin.h index 06db1fb49..5847f4ea8 100644 --- a/internal/platform/darwin/web_darwin.h +++ b/internal/platform/darwin/web_darwin.h @@ -1,3 +1,5 @@ +//go:build !ios + #ifndef VIVA_INTERNAL_PLATFORM_DARWIN_WEB_H #define VIVA_INTERNAL_PLATFORM_DARWIN_WEB_H diff --git a/internal/platform/darwin/web_darwin.m b/internal/platform/darwin/web_darwin.m index 1ebeb914e..1459e1bad 100644 --- a/internal/platform/darwin/web_darwin.m +++ b/internal/platform/darwin/web_darwin.m @@ -1,3 +1,5 @@ +//go:build !ios + #import #import #import diff --git a/internal/platform/darwin/window_close_darwin_test.go b/internal/platform/darwin/window_close_darwin_test.go index 2d71394fc..5fe70722e 100644 --- a/internal/platform/darwin/window_close_darwin_test.go +++ b/internal/platform/darwin/window_close_darwin_test.go @@ -1,3 +1,5 @@ +//go:build !ios + package darwin import ( diff --git a/internal/platform/darwin/window_icon_darwin.go b/internal/platform/darwin/window_icon_darwin.go index d54d5deb9..41a38d64a 100644 --- a/internal/platform/darwin/window_icon_darwin.go +++ b/internal/platform/darwin/window_icon_darwin.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package darwin diff --git a/internal/platform/darwin/window_size_darwin.go b/internal/platform/darwin/window_size_darwin.go index 5f16d051a..d34097416 100644 --- a/internal/platform/darwin/window_size_darwin.go +++ b/internal/platform/darwin/window_size_darwin.go @@ -1,3 +1,5 @@ +//go:build !ios + package darwin /* diff --git a/internal/platform/darwin/window_size_darwin_test.go b/internal/platform/darwin/window_size_darwin_test.go index c00f05939..a455cd678 100644 --- a/internal/platform/darwin/window_size_darwin_test.go +++ b/internal/platform/darwin/window_size_darwin_test.go @@ -1,3 +1,5 @@ +//go:build !ios + package darwin import ( diff --git a/tools/visualparity/compare.go b/tools/visualparity/compare.go index 2c497e43c..a8c7b315b 100644 --- a/tools/visualparity/compare.go +++ b/tools/visualparity/compare.go @@ -1,4 +1,4 @@ -//go:build darwin || windows || linux +//go:build (darwin || windows || linux) && !ios package main diff --git a/tools/visualparity/facts.go b/tools/visualparity/facts.go index f71c08883..84db9c899 100644 --- a/tools/visualparity/facts.go +++ b/tools/visualparity/facts.go @@ -1,4 +1,4 @@ -//go:build darwin || windows || linux +//go:build (darwin || windows || linux) && !ios package main diff --git a/tools/visualparity/ink.go b/tools/visualparity/ink.go index 6c4535b0c..05cef8dc5 100644 --- a/tools/visualparity/ink.go +++ b/tools/visualparity/ink.go @@ -1,4 +1,4 @@ -//go:build darwin || windows || linux +//go:build (darwin || windows || linux) && !ios package main diff --git a/tools/visualparity/main.go b/tools/visualparity/main.go index 5209e95c1..264497ef3 100644 --- a/tools/visualparity/main.go +++ b/tools/visualparity/main.go @@ -1,4 +1,4 @@ -//go:build darwin || windows || linux +//go:build (darwin || windows || linux) && !ios // Command visualparity measures how alike Viva looks on macOS, Windows and Linux. // diff --git a/tools/visualparity/measure_darwin.go b/tools/visualparity/measure_darwin.go index 1dca3fde2..ad0ed1091 100644 --- a/tools/visualparity/measure_darwin.go +++ b/tools/visualparity/measure_darwin.go @@ -1,4 +1,4 @@ -//go:build darwin +//go:build darwin && !ios package main diff --git a/tools/visualparity/metrics.go b/tools/visualparity/metrics.go index 344d02440..e61cdbca5 100644 --- a/tools/visualparity/metrics.go +++ b/tools/visualparity/metrics.go @@ -1,4 +1,4 @@ -//go:build darwin || windows || linux +//go:build (darwin || windows || linux) && !ios package main diff --git a/tools/visualparity/parity_test.go b/tools/visualparity/parity_test.go index 1bd26b1fd..12c191e3a 100644 --- a/tools/visualparity/parity_test.go +++ b/tools/visualparity/parity_test.go @@ -1,4 +1,4 @@ -//go:build darwin || windows || linux +//go:build (darwin || windows || linux) && !ios package main diff --git a/tools/visualparity/pixels.go b/tools/visualparity/pixels.go index 461fb35fc..bb2546c19 100644 --- a/tools/visualparity/pixels.go +++ b/tools/visualparity/pixels.go @@ -1,4 +1,4 @@ -//go:build darwin || windows || linux +//go:build (darwin || windows || linux) && !ios package main diff --git a/tools/visualparity/render.go b/tools/visualparity/render.go index b522905e1..62644a73c 100644 --- a/tools/visualparity/render.go +++ b/tools/visualparity/render.go @@ -1,4 +1,4 @@ -//go:build darwin || windows || linux +//go:build (darwin || windows || linux) && !ios package main diff --git a/tools/visualparity/scenes.go b/tools/visualparity/scenes.go index af726d86c..37ae234f6 100644 --- a/tools/visualparity/scenes.go +++ b/tools/visualparity/scenes.go @@ -1,4 +1,4 @@ -//go:build darwin || windows || linux +//go:build (darwin || windows || linux) && !ios package main From 838a96b903a4247670b74c5d94a0aa2ae92d38e7 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 22 Nov 2026 19:44:02 +0800 Subject: [PATCH 21/64] refactor(darwin): split the text and rendering core out of native.m native.m held, in one 8,700-line file, the system fonts and shaped lines, the label textures, the Metal pipelines and scene encoding, and the AppKit view, window and application that use them. The window, the offscreen renderer and the native editor all draw through the same code, but nothing said so, and nothing but AppKit could reach it. The first part moves, without a change of behavior, into core_text.m (fonts, shaped lines, the monospace fallbacks, the editor's line and its texture) and core_render.m (pipelines, label reuse and hashing, the label layer and the encoding of a scene); core.h declares what they share, and the counters the render code keeps are defined there. The native test programs, which include native.m as one translation unit, include the two new files too. hello for macOS is 4,288 bytes larger (4,442,994 to 4,447,282): its functions are no longer inlined across files. ADR 0095 W1, step 1. --- internal/platform/darwin/core.h | 249 ++ internal/platform/darwin/core_render.m | 1215 ++++++++ internal/platform/darwin/core_text.m | 1284 ++++++++ internal/platform/darwin/native.m | 2635 +---------------- .../platform/darwin/testdata/dock_reopen.m | 2 + internal/platform/darwin/testdata/file_drop.m | 2 + .../platform/darwin/testdata/live_resize.m | 2 + .../platform/darwin/testdata/modifier_taps.m | 2 + .../platform/darwin/testdata/text_selection.m | 2 + .../platform/darwin/testdata/traffic_lights.m | 2 + .../platform/darwin/testdata/window_close.m | 2 + .../darwin/testdata/window_notification.m | 2 + .../platform/darwin/testdata/window_size.m | 2 + 13 files changed, 2790 insertions(+), 2611 deletions(-) create mode 100644 internal/platform/darwin/core.h create mode 100644 internal/platform/darwin/core_render.m create mode 100644 internal/platform/darwin/core_text.m diff --git a/internal/platform/darwin/core.h b/internal/platform/darwin/core.h new file mode 100644 index 000000000..0a07c2a1f --- /dev/null +++ b/internal/platform/darwin/core.h @@ -0,0 +1,249 @@ +// The text and rendering core of the native backend, shared by the window, the +// offscreen renderer and the native editor: system fonts, shaped lines, label +// textures, pipelines and the encoding of a scene. Functions that were private +// to the file they came from are declared here so the files that were split +// from it can reach them. +#ifndef VIVA_INTERNAL_PLATFORM_DARWIN_CORE_H +#define VIVA_INTERNAL_PLATFORM_DARWIN_CORE_H + +#import +#include +#import +#import +#import + +#include +#include +#include +#include + +#include "native.h" +#include "label_geometry.h" + +typedef struct { + viva_text_line *shaped; + NSString *grid; + CGFloat cell; +} viva_editor_line; + +typedef struct { + BOOL onGrid; + BOOL includesHan; + int privateUse; +} viva_mono_family_traits; + +@interface VivaTextLayer : NSObject { + NSString *_value; + NSRect _frame; + NSRect _clip; // where the label may paint, when _clipped + BOOL _clipped; + CGFloat _fontSize; + CGFloat _fontWeight; + BOOL _italic; + CGFloat _red; + CGFloat _green; + CGFloat _blue; + CGFloat _alpha; + CGFloat _lastScale; + size_t _textureWidth; + size_t _textureHeight; + CGFloat _originX; // where the text starts within the frame, logical pixels + CGFloat _originY; + uint64_t _hash; + uint32_t _fontGeneration; // the interface font generation the picture was made in + BOOL _mono; + int _monoFace; + CGFloat _cellWidth; + CGFloat _baseline; + NSData *_utf8; // the text as bytes, to slice into runs; only for run labels + viva_text_run *_runs; // owned copy; NULL for an ordinary label + size_t _runCount; + NSData *_bitmap; + uint32_t _bitmapWidth; + uint32_t _bitmapHeight; + uint32_t _bitmapStride; + uint64_t _bitmapID; + uint32_t _bitmapVersion; + float _imageRadius; + id _texture; + NSMutableArray> *_additionalTextures; + // A text label wider than a texture holds is rasterized in part: its textures hold the + // device pixels _windowLeft to _windowRight of it, on the _windowPixelScale grid and + // counted from the frame's left edge. Unset, the texture holds the whole label. + BOOL _windowed; + size_t _windowLeft; + size_t _windowRight; + CGFloat _windowPixelScale; + BOOL _hasQuad; + // The shape the label's picture is drawn into this frame, and the colour + // multiplied into each of its corners (viva_text_label.quad, .tint). An + // ordinary label holds the corners of its box and opaque white. + float _quad[8]; + float _tint[16]; +} +- (instancetype)initWithConfig:(viva_text_label)config; +- (BOOL)matchesConfig:(viva_text_label)config; +- (uint64_t)contentHash; +- (BOOL)contentMatchesSizeAgnostic:(viva_text_label)config; +- (void)updateFrame:(NSRect)frame; +- (void)updateClipFromConfig:(viva_text_label)config; +- (void)updateQuadFromConfig:(viva_text_label)config; +- (const float *)quad; +- (const float *)tint; +- (float)imageRadius; +- (NSRect)frame; +- (BOOL)clipped; +- (NSRect)clip; +- (BOOL)forceTextureRebuildWithDevice:(id)device scale:(CGFloat)scale viewport:(NSSize)viewport; +- (void)markContentRebuild; +- (BOOL)rebuildWithDevice:(id)device scale:(CGFloat)scale viewport:(NSSize)viewport; +- (BOOL)refreshWindowWithDevice:(id)device scale:(CGFloat)scale viewport:(NSSize)viewport; +- (void)drawLineInContext:(CGContextRef)context pixelScale:(CGFloat)pixelScale; +- (void)drawRunsInContext:(CGContextRef)context pixelScale:(CGFloat)pixelScale; +- (id)textureAtIndex:(NSUInteger)index; +- (NSUInteger)textureCount; +- (NSRect)quadAtIndex:(NSUInteger)index; +- (NSRect)textureFrameAtIndex:(NSUInteger)index; +- (CGFloat)rasterWidthScale:(CGFloat)scale; +@end + +extern int vivaTerminalCells(uint32_t character); + + +extern uint64_t viva_gpu_submission_count; +extern uint64_t viva_gpu_draw_call_count; +extern uint64_t viva_rectangle_instance_count; +extern uint64_t viva_gpu_uploaded_bytes; +extern uint64_t viva_gpu_full_rebuild_count; +extern uint64_t viva_gpu_partial_update_count; +extern uint64_t viva_text_texture_rebuild_count; +extern uint64_t viva_label_texture_rebuild_count; +extern uint64_t viva_label_update_count; +extern NSUInteger viva_label_initial_count; + + +NSRange viva_clamp_range(NSRange range, NSUInteger length); +CTFontRef viva_system_font(CGFloat size, CGFloat weight); +CTFontRef viva_system_font_style(CGFloat size, CGFloat weight, BOOL italic); +CFIndex viva_cluster_start(CFStringRef string, size_t offset); +viva_text_line *viva_shared_text_line(NSString *shown, CGFloat fontSize, CGFloat weight); +viva_text_line *viva_shared_text_line_style(NSString *shown, CGFloat fontSize, CGFloat weight, BOOL italic); +BOOL viva_run_needs_slant(CTRunRef run); +void viva_draw_text_line(CGContextRef context, const viva_text_line *line, CGColorRef color, CGFloat x, CGFloat baseline); +void viva_editor_line_free(viva_editor_line line); +BOOL viva_editor_line_made(viva_editor_line line); +NSUInteger viva_terminal_step(NSString *shown, NSUInteger at, int *cells); +NSUInteger viva_terminal_column(NSString *shown, NSUInteger index); +CGFloat viva_text_offset(viva_editor_line line, NSUInteger index, BOOL terminal); +size_t viva_text_spans(viva_editor_line line, NSRange range, BOOL terminal, double *spans, size_t capacity); +NSUInteger viva_text_index_at(viva_editor_line line, NSString *shown, CGFloat x, BOOL terminal); +NSObject *viva_mono_family_lock(void); +void viva_mono_face_traits(int face, NSString **family, BOOL *classic, NSArray **fallbacks); +BOOL viva_mono_font_on_a_grid(NSFont *font); +NSFont *viva_mono_base_font(CGFloat size, CGFloat weight, NSString *family, BOOL classic); +NSFont *viva_mono_font_primary(CGFloat size, CGFloat weight, int face); +NSFont *viva_mono_font(CGFloat size, CGFloat weight, int face); +NSObject *viva_mono_fallback_lock(void); +NSFont *viva_mono_family_font(NSString *family, CGFloat size, CGFloat weight); +NSFont *viva_mono_replacement_font(NSString *family, CGFloat size, BOOL bold); +BOOL viva_mono_font_covers(CTFontRef font, NSString *value); +BOOL viva_mono_draws_han(CTFontRef font); +int viva_mono_private_use(CTFontRef font); +viva_mono_family_traits viva_mono_family_traits_of(NSString *family); +BOOL viva_mono_family_better(viva_mono_family_traits candidate, NSString *family, + viva_mono_family_traits best, NSString *bestFamily); +NSString *viva_mono_find_family(NSString *cluster); +NSString *viva_mono_face_fallback(NSString *cluster, int face); +NSString *viva_mono_fallback_family(NSString *cluster); +BOOL viva_mono_is_last_resort_name(CFStringRef name); +BOOL viva_mono_font_is_last_resort(CTFontRef font); +CTLineRef viva_mono_fallback_line(NSString *value, NSFont *base, int face, CGColorRef color); +void viva_prepare_text_context(CGContextRef context, CGFloat scale); +void viva_draw_terminal_preedit( + CGContextRef context, NSString *shown, CGFloat fontSize, int monoFace, + NSColor *color, CGFloat cellWidth, CGFloat baseline +); +viva_editor_line viva_new_editor_line(NSString *shown, CGFloat fontSize, CGFloat fontWeight, BOOL terminal, CGFloat cellWidth); +CGFloat viva_editor_alignment_inset(viva_editor_line line, CGFloat width, int alignment, BOOL terminal); +CGFloat viva_editor_visible_caret(CGFloat offset, CGFloat width, int alignment, BOOL terminal); +CGFloat viva_baseline(CGFloat height, CGFloat fontSize, CGFloat pixelScale); +CGFloat viva_fixed_baseline(CGFloat height, CGFloat fromTop, CGFloat pixelScale); +id viva_text_input_texture( + id device, + CGFloat scale, + NSString *shown, + CGFloat fontSize, + CGFloat fontWeight, + NSColor *color, + NSSize frameSize, + NSRange selectedRange, + BOOL hasMarked, + NSRange markedRange, + BOOL caretVisible, + BOOL terminal, + BOOL hideNativeOverlays, + int monoFace, + CGFloat cellWidth, + CGFloat cellBaseline, + int alignment +); +id viva_create_pipeline( + id device, + id library, + NSString *vertexName, + NSString *fragmentName, + NSError **error +); +uint64_t viva_hash_bytes(uint64_t hash, const void *data, size_t length); +float viva_quantized_origin(float value); +uint64_t viva_label_content_hash(viva_text_label config); +NSData *viva_downsample_bitmap(NSData *source, uint32_t sourceWidth, uint32_t sourceHeight, uint32_t sourceStride, size_t width, size_t height); +void viva_bitmap_texture_extent(NSRect frame, CGFloat scale, size_t sourceWidth, size_t sourceHeight, size_t *width, size_t *height); +BOOL viva_bitmap_extent_stale(size_t have, size_t need); +BOOL viva_label_visible_span(const float *quad, const float *tint, BOOL clipped, NSRect clip, NSSize viewport, + size_t full, size_t *left, size_t *right); +void viva_label_window(size_t full, size_t limit, BOOL visible, size_t left, size_t right, + size_t *windowLeft, size_t *windowRight); +int viva_update_label_layers( + NSArray *previous, + const viva_text_label *labels, + NSUInteger count, + id device, + CGFloat scale, + NSSize viewport, + NSMutableArray **updated +); +void viva_label_box_quad(float *quad, float x, float y, float width, float height); +void viva_label_plain_tint(float *tint); +size_t viva_label_tile_mesh( + const float *quad, + const float *tint, + NSRect frame, + NSRect tile, + NSRect texture, + viva_label_vertex *vertices +); +void viva_encode_input( + id encoder, + id textPipeline, + id inputTexture, + NSRect inputFrame, + NSSize viewport +); +void viva_encode_scene( + id encoder, + id rectanglePipeline, + id textPipeline, + id rectangleBuffer, + const viva_composite_command *commands, + NSUInteger commandCount, + NSArray *labels, + id inputTexture, + NSRect inputFrame, + uint16_t inputLayer, + NSSize viewport, + NSUInteger targetWidth, + NSUInteger targetHeight +); + +#endif diff --git a/internal/platform/darwin/core_render.m b/internal/platform/darwin/core_render.m new file mode 100644 index 000000000..7481f3d36 --- /dev/null +++ b/internal/platform/darwin/core_render.m @@ -0,0 +1,1215 @@ +#import "core.h" +#include "label_geometry.h" + +uint64_t viva_gpu_submission_count; +uint64_t viva_gpu_draw_call_count; +uint64_t viva_rectangle_instance_count; +uint64_t viva_gpu_uploaded_bytes; +uint64_t viva_gpu_full_rebuild_count; +uint64_t viva_gpu_partial_update_count; +uint64_t viva_text_texture_rebuild_count; +uint64_t viva_label_texture_rebuild_count; +uint64_t viva_label_update_count; +NSUInteger viva_label_initial_count; + +// viva_fragment_blends_premultiplied says how a fragment function's output must +// be blended. Rectangles output a straight color and blend with SourceAlpha. +// Text returns texels CoreGraphics already multiplied by coverage, so it blends +// with One; SourceAlpha would multiply by alpha twice and thin every glyph edge +// by roughly a fifth. +int viva_fragment_blends_premultiplied(const char *fragmentName) { + return fragmentName != NULL && strcmp(fragmentName, "viva_text_fragment") == 0; +} + +id viva_create_pipeline( + id device, + id library, + NSString *vertexName, + NSString *fragmentName, + NSError **error +) { + BOOL premultipliedSource = viva_fragment_blends_premultiplied(fragmentName.UTF8String) != 0; + id vertex = [library newFunctionWithName:vertexName]; + id fragment = [library newFunctionWithName:fragmentName]; + if (vertex == nil || fragment == nil) { + [fragment release]; + [vertex release]; + return nil; + } + MTLRenderPipelineDescriptor *descriptor = + [[[MTLRenderPipelineDescriptor alloc] init] autorelease]; + descriptor.vertexFunction = vertex; + descriptor.fragmentFunction = fragment; + descriptor.colorAttachments[0].pixelFormat = MTLPixelFormatBGRA8Unorm; + descriptor.colorAttachments[0].blendingEnabled = YES; + descriptor.colorAttachments[0].rgbBlendOperation = MTLBlendOperationAdd; + descriptor.colorAttachments[0].alphaBlendOperation = MTLBlendOperationAdd; + descriptor.colorAttachments[0].sourceRGBBlendFactor = + premultipliedSource ? MTLBlendFactorOne : MTLBlendFactorSourceAlpha; + descriptor.colorAttachments[0].destinationRGBBlendFactor = MTLBlendFactorOneMinusSourceAlpha; + descriptor.colorAttachments[0].sourceAlphaBlendFactor = MTLBlendFactorOne; + descriptor.colorAttachments[0].destinationAlphaBlendFactor = MTLBlendFactorOneMinusSourceAlpha; + id pipeline = [device + newRenderPipelineStateWithDescriptor:descriptor + error:error]; + [fragment release]; + [vertex release]; + return pipeline; +} + +uint64_t viva_hash_bytes(uint64_t hash, const void *data, size_t length) { + const unsigned char *bytes = (const unsigned char *)data; + for (size_t index = 0; index < length; index++) { + hash = (hash ^ bytes[index]) * 1099511628211ULL; + } + return hash; +} + +// viva_plan_label_reuse decides which old label texture each new label can take +// over. source[i] is the index of the old label new label i reuses, or -1 when +// it needs a texture of its own. A label first looks at its own index (the +// common case: nothing moved), then at any unused old label with the same +// hash anywhere (a list or terminal that scrolled). Each old label is used at +// most once. Equal hashes only propose a match; the caller confirms it. +int viva_plan_label_reuse( + const uint64_t *old_hashes, + size_t old_count, + const uint64_t *new_hashes, + size_t new_count, + int64_t *source +) { + if ((new_count > 0 && source == NULL) || (old_count > 0 && old_hashes == NULL) || (new_count > 0 && new_hashes == NULL)) { + return 1; + } + size_t table_size = 16; + while (table_size < old_count * 2) { + table_size <<= 1; + } + int64_t *heads = malloc(table_size * sizeof(int64_t)); + int64_t *next = malloc(MAX(old_count, 1) * sizeof(int64_t)); + unsigned char *taken = calloc(MAX(old_count, 1), 1); + if (heads == NULL || next == NULL || taken == NULL) { + free(heads); + free(next); + free(taken); + return 2; + } + for (size_t slot = 0; slot < table_size; slot++) { + heads[slot] = -1; + } + for (size_t old = 0; old < old_count; old++) { + size_t slot = (size_t)(old_hashes[old] & (table_size - 1)); + next[old] = heads[slot]; + heads[slot] = (int64_t)old; + } + for (size_t index = 0; index < new_count; index++) { + source[index] = -1; + if (index < old_count && !taken[index] && old_hashes[index] == new_hashes[index]) { + source[index] = (int64_t)index; + taken[index] = 1; + } + } + for (size_t index = 0; index < new_count; index++) { + if (source[index] >= 0) { + continue; + } + size_t slot = (size_t)(new_hashes[index] & (table_size - 1)); + for (int64_t old = heads[slot]; old >= 0; old = next[old]) { + if (!taken[old] && old_hashes[old] == new_hashes[index]) { + source[index] = old; + taken[old] = 1; + break; + } + } + } + free(heads); + free(next); + free(taken); + return 0; +} + +// viva_quantized_origin is a label's sub-pixel origin to a sixteenth of a logical pixel, +// finer than Core Graphics places a glyph (a fifth of a device pixel at best), so labels +// that differ by less share a texture. +float viva_quantized_origin(float value) { + return roundf(value * 16.0f) / 16.0f; +} + +// viva_label_content_hash identifies what a label looks like: its text, runs, +// font and color. Position and layer are not part of it. Labels with equal +// hashes are candidates for sharing one texture; matchesConfig confirms. +uint64_t viva_label_content_hash(viva_text_label config) { + uint64_t hash = 14695981039346656037ULL; + hash = viva_hash_bytes(hash, config.utf8, config.utf8_length); + // Bitmap textures retain their source dimensions. Resizing their draw quad + // must find the same texture when Go omits an unchanged pixel payload. + BOOL bitmap = (config.flags & VIVA_LABEL_BITMAP) != 0; + float values[] = {bitmap ? 0 : config.width, bitmap ? 0 : config.height, config.font_size, config.font_weight, + config.red, config.green, config.blue, config.alpha, config.cell_width, + viva_quantized_origin(config.origin_x), viva_quantized_origin(config.origin_y), config.baseline}; + hash = viva_hash_bytes(hash, values, sizeof(values)); + uint32_t contentFlags = config.flags & ~VIVA_LABEL_CLIPPED; + hash = viva_hash_bytes(hash, &contentFlags, sizeof(contentFlags)); + hash = viva_hash_bytes(hash, &config.mono_face, sizeof(config.mono_face)); + hash = viva_hash_bytes(hash, &config.font_generation, sizeof(config.font_generation)); + if (config.runs != NULL) { + hash = viva_hash_bytes(hash, config.runs, config.run_count * sizeof(viva_text_run)); + } + uint64_t bitmapIdentity[] = { + config.bitmap_id, + config.bitmap_version, + config.bitmap_width, + config.bitmap_height, + config.bitmap_stride, + }; + hash = viva_hash_bytes(hash, bitmapIdentity, sizeof(bitmapIdentity)); + if (config.bitmap != NULL && config.bitmap_id == 0) { + hash = viva_hash_bytes(hash, config.bitmap, config.bitmap_length); + } + return hash; +} + + +NSData *viva_downsample_bitmap(NSData *source, uint32_t sourceWidth, uint32_t sourceHeight, uint32_t sourceStride, size_t width, size_t height) { + if (source == nil || width == 0 || height == 0 || width > sourceWidth || height > sourceHeight || sourceStride < sourceWidth * 4) { + return nil; + } + if (sourceHeight - 1 > SIZE_MAX / sourceStride || source.length < (size_t)(sourceHeight - 1) * sourceStride + (size_t)sourceWidth * 4 || width > SIZE_MAX / 4 || height > SIZE_MAX / (width * 4)) { + return nil; + } + size_t rowBytes = width * 4; + NSMutableData *pixels = [[NSMutableData alloc] initWithLength:height * rowBytes]; + if (pixels == nil) { + return nil; + } + CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); + CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, source.bytes, source.length, NULL); + CGImageRef image = provider == NULL ? NULL : CGImageCreate( + sourceWidth, sourceHeight, 8, 32, sourceStride, colorSpace, + kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little, + provider, NULL, true, kCGRenderingIntentDefault); + CGContextRef context = image == NULL ? NULL : CGBitmapContextCreate( + pixels.mutableBytes, width, height, 8, rowBytes, colorSpace, + kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little); + if (context != NULL) { + CGContextSetInterpolationQuality(context, kCGInterpolationHigh); + CGContextDrawImage(context, CGRectMake(0, 0, width, height), image); + } + if (context != NULL) { + CGContextRelease(context); + } + if (image != NULL) { + CGImageRelease(image); + } + if (provider != NULL) { + CGDataProviderRelease(provider); + } + CGColorSpaceRelease(colorSpace); + if (context == NULL) { + [pixels release]; + return nil; + } + return pixels; +} + +// viva_bitmap_texture_extent is the size of the texture an image label is drawn from: the +// stored image, averaged down to the device pixels the label covers when it is drawn smaller +// than it is stored. internal/platform.BitmapTextureExtent computes the same size. +void viva_bitmap_texture_extent(NSRect frame, CGFloat scale, size_t sourceWidth, size_t sourceHeight, size_t *width, size_t *height) { + CGFloat pixelScale = MAX(scale, 1.0); + size_t shownWidth = (size_t)MAX(1.0, floor((frame.origin.x + frame.size.width) * pixelScale + 0.5) - floor(frame.origin.x * pixelScale + 0.5)); + size_t shownHeight = (size_t)MAX(1.0, floor((frame.origin.y + frame.size.height) * pixelScale + 0.5) - floor(frame.origin.y * pixelScale + 0.5)); + *width = sourceWidth; + *height = sourceHeight; + if (shownWidth <= sourceWidth && shownHeight <= sourceHeight && (shownWidth < sourceWidth || shownHeight < sourceHeight)) { + *width = shownWidth; + *height = shownHeight; + } +} + +// viva_bitmap_extent_stale reports whether a texture of one dimension no longer suits an image +// that needs another: smaller than needed would blur it, and more than twice as large would +// alias it. Between those the texture stays, so an animated size does not rebuild every frame. +// internal/platform.BitmapTextureStale applies the same rule. +BOOL viva_bitmap_extent_stale(size_t have, size_t need) { + return need > have || have >= 2 * need; +} + +// VIVA_LABEL_TEXTURE_LIMIT is the widest and tallest texture a label is rasterized into, in +// pixels: the 2D texture limit of every Metal device Viva runs on. +#define VIVA_LABEL_TEXTURE_LIMIT 16384 +#define VIVA_LABEL_TILE_WIDTH (VIVA_LABEL_TEXTURE_LIMIT - 2) + +// viva_label_visible_span clips the destination triangles to the clip and viewport, +// then maps their visible UV range to source pixels, at most full. +// NO when none of the label can be seen. +BOOL viva_label_visible_span(const float *quad, const float *tint, BOOL clipped, NSRect clip, NSSize viewport, + size_t full, size_t *left, size_t *right) { + NSRect visible = NSMakeRect(0, 0, viewport.width, viewport.height); + if (clipped) { + visible = NSIntersectionRect(visible, clip); + } + if (NSIsEmptyRect(visible)) { + return NO; + } + float sourceLeft, sourceRight; + if (!viva_label_source_span(quad, tint, NSMinX(visible), NSMinY(visible), NSMaxX(visible), NSMaxY(visible), &sourceLeft, &sourceRight)) { + return NO; + } + CGFloat from = floor((double)sourceLeft * full); + CGFloat to = ceil((double)sourceRight * full); + *left = (size_t)MIN(MAX(from, 0), (CGFloat)full); + *right = (size_t)MIN(MAX(to, 0), (CGFloat)full); + return *right > *left; +} + +// viva_label_window chooses the device pixels of a label full pixels wide that a texture of +// at most limit pixels holds. The visible span left to right is kept with as much margin on +// both sides as the span itself, so a scroll of up to a viewport keeps the texture; at an +// end of the label the margin goes to the other side. A span wider than limit is split +// across textures, without a margin. A label none of which is visible keeps its start. +void viva_label_window(size_t full, size_t limit, BOOL visible, size_t left, size_t right, + size_t *windowLeft, size_t *windowRight) { + size_t width = MIN(full, limit); + if (!visible) { + *windowLeft = 0; + *windowRight = width; + return; + } + size_t span = right - left; + if (span >= width) { + *windowLeft = left; + *windowRight = right; + return; + } + size_t margin = MIN(span, (width - span) / 2); + width = span + 2 * margin; + size_t low = left > margin ? left - margin : 0; + if (low + width > full) { + low = full - width; + } + *windowLeft = low; + *windowRight = low + width; +} + +@implementation VivaTextLayer + +- (instancetype)initWithConfig:(viva_text_label)config { + self = [super init]; + if (self != nil) { + // Bitmap labels carry no UTF-8 buffer. Give them an explicit empty + // string so image-only labels can still own a Metal texture. + if (config.utf8_length == 0) { + _value = [@"" retain]; + } else if (config.utf8 == NULL) { + [self release]; + return nil; + } else { + _value = [[NSString alloc] initWithBytes:config.utf8 + length:config.utf8_length + encoding:NSUTF8StringEncoding]; + } + if (_value == nil) { + [self release]; + return nil; + } + _frame = NSMakeRect(config.x, config.y, config.width, config.height); + [self updateClipFromConfig:config]; + [self updateQuadFromConfig:config]; + _fontSize = config.font_size; + _fontWeight = config.font_weight; + _italic = (config.flags & VIVA_LABEL_ITALIC) != 0; + _red = config.red; + _green = config.green; + _blue = config.blue; + _alpha = config.alpha; + _lastScale = 0; + _originX = viva_quantized_origin(config.origin_x); + _originY = viva_quantized_origin(config.origin_y); + _hash = viva_label_content_hash(config); + _fontGeneration = config.font_generation; + _mono = (config.flags & VIVA_LABEL_MONO) != 0; + _monoFace = config.mono_face; + _cellWidth = config.cell_width; + _baseline = config.baseline; + if (config.run_count > 0 && config.runs != NULL) { + _runs = malloc(config.run_count * sizeof(viva_text_run)); + if (_runs == NULL) { + [self release]; + return nil; + } + memcpy(_runs, config.runs, config.run_count * sizeof(viva_text_run)); + _runCount = config.run_count; + _utf8 = [[NSData alloc] initWithBytes:config.utf8 length:config.utf8_length]; + } + if ((config.flags & VIVA_LABEL_BITMAP) != 0) { + // An image the Go side did not send has nothing to draw from: fail the update + // rather than keep a layer that renders blank. + if (config.bitmap == NULL) { + [self release]; + return nil; + } + _bitmap = [[NSData alloc] initWithBytes:config.bitmap length:config.bitmap_length]; + _bitmapWidth = config.bitmap_width; + _bitmapHeight = config.bitmap_height; + _bitmapStride = config.bitmap_stride; + _bitmapID = config.bitmap_id; + _bitmapVersion = config.bitmap_version; + } + } + return self; +} + +- (void)dealloc { + [_texture release]; + [_additionalTextures release]; + [_value release]; + [_utf8 release]; + [_bitmap release]; + free(_runs); + [super dealloc]; +} + +- (uint64_t)contentHash { + return _hash; +} + +- (BOOL)matchesConfig:(viva_text_label)config { + if (![self contentMatchesSizeAgnostic:config]) { + return NO; + } + if (_bitmap != nil) { + return YES; + } + return _frame.size.width == config.width && _frame.size.height == config.height; +} + +- (BOOL)contentMatchesSizeAgnostic:(viva_text_label)config { + // Content identity: font, color, and text. Position never matters (the + // quad supplies it each draw); size matters only for texel alignment, + // which live resize may temporarily relax. + if (_fontSize != config.font_size || _fontWeight != config.font_weight || _fontGeneration != config.font_generation) { + return NO; + } + if (_italic != ((config.flags & VIVA_LABEL_ITALIC) != 0)) { + return NO; + } + if (_originX != viva_quantized_origin(config.origin_x) || _originY != viva_quantized_origin(config.origin_y)) { + return NO; + } + if (_red != config.red || _green != config.green || + _blue != config.blue || _alpha != config.alpha) { + return NO; + } + if (_mono != ((config.flags & VIVA_LABEL_MONO) != 0) || + _monoFace != config.mono_face || _cellWidth != config.cell_width || _baseline != config.baseline || + _runCount != (config.runs == NULL ? 0 : config.run_count) || + (_runCount > 0 && memcmp(_runs, config.runs, _runCount * sizeof(viva_text_run)) != 0)) { + return NO; + } + BOOL bitmap = (config.flags & VIVA_LABEL_BITMAP) != 0; + if ((_bitmap != nil) != bitmap) { + return NO; + } + if (bitmap) { + if (_bitmapWidth != config.bitmap_width || _bitmapHeight != config.bitmap_height || + _bitmapStride != config.bitmap_stride || _bitmapID != config.bitmap_id || + _bitmapVersion != config.bitmap_version || _bitmap.length != config.bitmap_length) { + return NO; + } + if (config.bitmap_upload != 0 && (config.bitmap == NULL || memcmp(_bitmap.bytes, config.bitmap, config.bitmap_length) != 0)) { + return NO; + } + } + size_t valueLength = [_value lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; + if (config.utf8_length != valueLength) { + return NO; + } + if (config.utf8_length == 0) { + return YES; + } + if (config.utf8 == NULL) { + return NO; + } + return memcmp(config.utf8, [_value UTF8String], config.utf8_length) == 0; +} + +- (void)updateClipFromConfig:(viva_text_label)config { + _clipped = (config.flags & VIVA_LABEL_CLIPPED) != 0; + _clip = _clipped ? NSMakeRect(config.clip_x, config.clip_y, config.clip_width, config.clip_height) : NSZeroRect; +} + +- (void)updateQuadFromConfig:(viva_text_label)config { + // The quad is where the label lands, not what it looks like: it changes + // every frame of an animation while the texture stays the same one. + BOOL hasQuad = NO; + for (int index = 0; index < 8; index++) { + _quad[index] = config.quad[index]; + hasQuad = hasQuad || config.quad[index] != 0; + } + for (int index = 0; index < 16; index++) { + _tint[index] = config.tint[index]; + } + _hasQuad = hasQuad; + _imageRadius = hasQuad ? 0 : config.image_radius; + if (hasQuad) { + return; + } + // An ordinary label keeps its box as the quad and opaque white as its tint, + // so the renderer has no case to special-case per frame. + _quad[0] = config.x; + _quad[1] = config.y; + _quad[2] = config.x + config.width; + _quad[3] = config.y; + _quad[4] = config.x; + _quad[5] = config.y + config.height; + _quad[6] = config.x + config.width; + _quad[7] = config.y + config.height; + for (int index = 0; index < 16; index++) { + _tint[index] = 1; + } + if (config.image_fade > 0) { + // Fade is draw-time: it scales the premultiplied tint, so the picture's + // texture is untouched. + float alpha = 1 - config.image_fade; + for (int index = 0; index < 16; index++) { + _tint[index] *= alpha; + } + } +} + +- (const float *)quad { + return _quad; +} + +- (const float *)tint { + return _tint; +} + +- (float)imageRadius { + return _imageRadius; +} + +- (BOOL)clipped { + return _clipped; +} + +- (NSRect)clip { + return _clip; +} + +- (void)updateFrame:(NSRect)frame { + _frame = frame; +} + +- (BOOL)forceTextureRebuildWithDevice:(id)device scale:(CGFloat)scale viewport:(NSSize)viewport { + _lastScale = 0; + return [self rebuildWithDevice:device scale:scale viewport:viewport]; +} + +- (void)markContentRebuild { + viva_label_texture_rebuild_count++; +} + +// refreshWindowWithDevice rasterizes a label held in part again when the part of it that +// can be seen in viewport is no longer all in its texture: it moved, or its clip or the +// viewport did. Any other label is left as it is. +- (BOOL)refreshWindowWithDevice:(id)device scale:(CGFloat)scale viewport:(NSSize)viewport { + CGFloat widthScale = [self rasterWidthScale:scale]; + if (_texture == nil || _lastScale != scale || + viva_bitmap_extent_stale((size_t)ceil(_frame.size.width * _windowPixelScale), (size_t)ceil(_frame.size.width * widthScale))) { + _lastScale = 0; + BOOL rebuilt = [self rebuildWithDevice:device scale:scale viewport:viewport]; + if (rebuilt) [self markContentRebuild]; + return rebuilt; + } + if (!_windowed) { + return YES; + } + size_t full = (size_t)MAX(1.0, ceil(_frame.size.width * _windowPixelScale)); + size_t left = 0, right = 0; + if (!viva_label_visible_span(_quad, _tint, _clipped, _clip, viewport, full, &left, &right) || + (left >= _windowLeft && right <= _windowRight)) { + return YES; + } + _lastScale = 0; + if (![self rebuildWithDevice:device scale:scale viewport:viewport]) { + return NO; + } + [self markContentRebuild]; + return YES; +} + +- (CGFloat)rasterWidthScale:(CGFloat)scale { + CGFloat pixelScale = ceil(scale); + if (!_hasQuad || _frame.size.width <= 0) { + return pixelScale; + } + CGFloat top = hypot((double)_quad[2] - _quad[0], (double)_quad[3] - _quad[1]); + CGFloat bottom = hypot((double)_quad[6] - _quad[4], (double)_quad[7] - _quad[5]); + return MIN(pixelScale, MAX(1, ceil(MAX(top, bottom) * pixelScale)) / _frame.size.width); +} + +- (BOOL)rebuildWithDevice:(id)device scale:(CGFloat)scale viewport:(NSSize)viewport { + size_t wantWidth = 0, wantHeight = 0; + if (_bitmap != nil) { + viva_bitmap_texture_extent(_frame, scale, _bitmapWidth, _bitmapHeight, &wantWidth, &wantHeight); + } + if (_texture != nil && (_bitmap != nil + ? !viva_bitmap_extent_stale(_textureWidth, wantWidth) && !viva_bitmap_extent_stale(_textureHeight, wantHeight) + : _lastScale == scale)) { + return YES; + } + if (_bitmap != nil) { + if (_bitmapWidth == 0 || _bitmapHeight == 0 || + _bitmapStride < (size_t)_bitmapWidth * 4 || _bitmapHeight - 1 > SIZE_MAX / _bitmapStride || + _bitmap.length < (size_t)(_bitmapHeight - 1) * _bitmapStride + (size_t)_bitmapWidth * 4) { + return NO; + } + size_t uploadWidth = _bitmapWidth, uploadHeight = _bitmapHeight; + NSData *uploadData = _bitmap; + uint32_t uploadStride = _bitmapStride; + if (wantWidth != _bitmapWidth || wantHeight != _bitmapHeight) { + NSData *reduced = viva_downsample_bitmap(_bitmap, _bitmapWidth, _bitmapHeight, _bitmapStride, wantWidth, wantHeight); + if (reduced == nil) { + return NO; + } + uploadData = reduced; + uploadWidth = wantWidth; + uploadHeight = wantHeight; + uploadStride = (uint32_t)(wantWidth * 4); + } + MTLTextureDescriptor *descriptor = [MTLTextureDescriptor + texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm + width:uploadWidth + height:uploadHeight + mipmapped:NO]; + descriptor.storageMode = MTLStorageModeShared; + descriptor.usage = MTLTextureUsageShaderRead; + id texture = [device newTextureWithDescriptor:descriptor]; + if (texture != nil) { + [texture replaceRegion:MTLRegionMake2D(0, 0, uploadWidth, uploadHeight) + mipmapLevel:0 + withBytes:uploadData.bytes + bytesPerRow:uploadStride]; + } + if (uploadData != _bitmap) { + [uploadData release]; + } + if (texture == nil) { + return NO; + } + [_texture release]; + _texture = texture; + _textureWidth = uploadWidth; + _textureHeight = uploadHeight; + _lastScale = scale; + return YES; + } + // Rasterize on the integer physical-pixel grid: a fractional frame origin + // must not bleed anti-aliasing across texel boundaries. + CGFloat pixelScale = ceil(scale); + CGFloat widthScale = [self rasterWidthScale:scale]; + size_t fullWidth = (size_t)MAX(1.0, ceil(_frame.size.width * widthScale)); + size_t pixelHeight = (size_t)MAX(1.0, ceil(_frame.size.height * pixelScale)); + if (pixelHeight > VIVA_LABEL_TEXTURE_LIMIT) { + return NO; + } + // A line wider than a texture holds (a long line laid out at its full width and + // scrolled) is rasterized only around the part of it that can be seen. + BOOL windowed = fullWidth > VIVA_LABEL_TEXTURE_LIMIT; + size_t windowLeft = 0, windowRight = fullWidth; + if (windowed) { + size_t left = 0, right = 0; + BOOL visible = viva_label_visible_span(_quad, _tint, _clipped, _clip, viewport, fullWidth, &left, &right); + viva_label_window(fullWidth, VIVA_LABEL_TEXTURE_LIMIT, visible, left, right, &windowLeft, &windowRight); + } + id texture = nil; + NSMutableArray> *additionalTextures = nil; + for (size_t tileLeft = windowLeft; tileLeft < windowRight;) { + size_t tileRight = tileLeft + MIN(windowRight - tileLeft, VIVA_LABEL_TILE_WIDTH); + size_t textureLeft = tileLeft > 0 ? tileLeft - 1 : 0; + size_t textureRight = MIN(tileRight + 1, fullWidth); + size_t pixelWidth = textureRight - textureLeft; + size_t rowBytes = pixelWidth * 4; + if (pixelHeight > SIZE_MAX / rowBytes) { + [texture release]; + [additionalTextures release]; + return NO; + } + void *pixels = calloc(pixelHeight, rowBytes); + if (pixels == NULL) { + [texture release]; + [additionalTextures release]; + return NO; + } + CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); + CGContextRef context = CGBitmapContextCreate( + pixels, pixelWidth, pixelHeight, 8, rowBytes, colorSpace, + kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little + ); + CGColorSpaceRelease(colorSpace); + if (context == NULL) { + free(pixels); + [texture release]; + [additionalTextures release]; + return NO; + } + viva_prepare_text_context(context, pixelScale); + CGContextScaleCTM(context, widthScale / pixelScale, 1); + if (textureLeft > 0) { + CGContextTranslateCTM(context, -(CGFloat)textureLeft / widthScale, 0); + } + if (_runCount > 0) { + [self drawRunsInContext:context pixelScale:pixelScale]; + } else { + [self drawLineInContext:context pixelScale:pixelScale]; + } + MTLTextureDescriptor *descriptor = [MTLTextureDescriptor + texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm + width:pixelWidth + height:pixelHeight + mipmapped:NO]; + descriptor.storageMode = MTLStorageModeShared; + descriptor.usage = MTLTextureUsageShaderRead; + id nextTexture = [device newTextureWithDescriptor:descriptor]; + if (nextTexture != nil) { + [nextTexture replaceRegion:MTLRegionMake2D(0, 0, pixelWidth, pixelHeight) + mipmapLevel:0 withBytes:pixels bytesPerRow:rowBytes]; + } + CGContextRelease(context); + free(pixels); + if (nextTexture == nil) { + [texture release]; + [additionalTextures release]; + return NO; + } + if (texture == nil) { + texture = nextTexture; + } else { + if (additionalTextures == nil) { + additionalTextures = [[NSMutableArray alloc] init]; + if (additionalTextures == nil) { + [nextTexture release]; + [texture release]; + return NO; + } + } + [additionalTextures addObject:nextTexture]; + [nextTexture release]; + } + tileLeft = tileRight; + } + [_texture release]; + _texture = texture; + [_additionalTextures release]; + _additionalTextures = additionalTextures; + _lastScale = scale; + _windowed = windowed; + _windowLeft = windowLeft; + _windowRight = windowRight; + _windowPixelScale = widthScale; + return YES; +} + +// drawLineInContext draws an ordinary label: one line in one font and color, +// vertically centered. +- (void)drawLineInContext:(CGContextRef)context pixelScale:(CGFloat)pixelScale { + CGColorRef foreground = CGColorCreateSRGB(_red, _green, _blue, _alpha); + CGFloat baseline = _baseline > 0 + ? viva_fixed_baseline(_frame.size.height, _baseline, pixelScale) + : viva_baseline(_frame.size.height, _fontSize, pixelScale); + // Text laid out at a fraction of a pixel below the frame: Core Graphics puts a baseline + // on the next device row down (it floors in its y-up space, so AppKit does), and a + // glyph at a fraction of a pixel across (it quantizes the position, in drawing the line). + baseline -= ceil(_originY * pixelScale - 1e-4) / pixelScale; + if (_mono) { + // A fixed-pitch label is not proportional text: it keeps its own advances. + // The line carries the face's font (the NSFont itself: looking it up again by + // name fails for the monospaced system font at a weight, whose name is private + // to that instance, and CoreText answers with Times New Roman) and, for the + // clusters no family of it draws, the installed fallback. + CTLineRef line = viva_mono_fallback_line(_value, viva_mono_font(_fontSize, _fontWeight, _monoFace), _monoFace, foreground); + if (line != NULL) { + CGContextSetTextPosition(context, _originX, baseline); + CTLineDraw(line, context); + CFRelease(line); + } + } else { + viva_text_line *shaped = viva_shared_text_line_style(_value, _fontSize, _fontWeight, _italic); + if (shaped != NULL) { + viva_draw_text_line(context, shaped, foreground, _originX, baseline); + viva_text_line_release(shaped); + } + } + CFRelease(foreground); +} + +// drawRunsInContext draws a fixed-pitch grid line. Every run is shaped on its +// own and placed at its cell, so colors, wide characters and glyphs that come +// from fallback fonts cannot push later text off its column. All runs share +// one baseline taken from the base font. +- (void)drawRunsInContext:(CGContextRef)context pixelScale:(CGFloat)pixelScale { + NSFont *baseFont = viva_mono_font(_fontSize, _fontWeight, _monoFace); + CGFloat baseline = _baseline > 0 + ? viva_fixed_baseline(_frame.size.height, _baseline, pixelScale) + : viva_baseline(_frame.size.height, _fontSize, pixelScale); + CGFloat hairline = 1.0 / pixelScale; + const unsigned char *bytes = (const unsigned char *)_utf8.bytes; + size_t length = _utf8.length; + size_t offset = 0; + + // Fonts differ only by weight and slant; a line rarely has more than a few. + enum { kFontCache = 4, kMaxGlyphRun = 256 }; + CTFontRef cachedFont[kFontCache] = {NULL}; + float cachedWeight[kFontCache] = {0}; + BOOL cachedItalic[kFontCache] = {NO}; + int cacheCount = 0; + + for (size_t index = 0; index < _runCount; index++) { + const viva_text_run *run = &_runs[index]; + if (run->bytes > length - offset) { + break; + } + const unsigned char *start = bytes + offset; + size_t count = run->bytes; + offset += count; + BOOL italic = (run->flags & VIVA_RUN_ITALIC) != 0; + CTFontRef font = NULL; + for (int slot = 0; slot < cacheCount; slot++) { + if (cachedWeight[slot] == run->weight && cachedItalic[slot] == italic) { + font = cachedFont[slot]; + break; + } + } + if (font == NULL) { + NSFont *native = viva_mono_font(_fontSize, run->weight, _monoFace); + font = (CTFontRef)CFRetain(native); + if (italic) { + CGAffineTransform slant = CGAffineTransformMake(1, 0, 0.2126, 1, 0, 0); + CTFontRef slanted = CTFontCreateCopyWithAttributes(font, _fontSize, &slant, NULL); + if (slanted != NULL) { + CFRelease(font); + font = slanted; + } + } + if (cacheCount < kFontCache) { + cachedFont[cacheCount] = font; + cachedWeight[cacheCount] = run->weight; + cachedItalic[cacheCount] = italic; + cacheCount++; + } + } + CGColorRef foreground = CGColorCreateSRGB(run->red, run->green, run->blue, run->alpha); + CGFloat cellLeft = (CGFloat)run->column * _cellWidth; + CGFloat span = (CGFloat)run->cells * _cellWidth; + BOOL ascii = YES; + for (size_t at = 0; ascii && at < count; at++) { + ascii = start[at] >= 0x20 && start[at] < 0x7F; + } + if ((run->flags & VIVA_RUN_LIGATURES) != 0 && count > 0) { + // A ligature run is shaped as one line and scaled to its cells, so + // the font's substitutions survive and the run still ends where + // the grid says it does. + NSString *shown = [[NSString alloc] initWithBytes:start + length:count + encoding:NSUTF8StringEncoding]; + if (shown != nil) { + CTLineRef line = viva_mono_fallback_line(shown, (NSFont *)font, _monoFace, foreground); + if (line != NULL) { + CGFloat width = CTLineGetTypographicBounds(line, NULL, NULL, NULL); + if (width > 0 && span > 0) { + CGContextSaveGState(context); + CGContextTranslateCTM(context, cellLeft, baseline); + CGContextScaleCTM(context, span / width, 1); + CGContextSetTextPosition(context, 0, 0); + CTLineDraw(line, context); + CGContextRestoreGState(context); + } + CFRelease(line); + } + [shown release]; + } + } else if (ascii) { + // Plain ASCII needs no shaping in a fixed-pitch font: map the + // characters to glyphs and put glyph i exactly on cell i. The run + // is drawn in pieces of kMaxGlyphRun, every glyph still on its + // own cell. + UniChar characters[kMaxGlyphRun]; + CGGlyph glyphs[kMaxGlyphRun]; + CGPoint positions[kMaxGlyphRun]; + CGContextSetFillColorWithColor(context, foreground); + // Glyph positions are relative to the text position. + CGContextSetTextPosition(context, 0, 0); + for (size_t first = 0; first < count; first += kMaxGlyphRun) { + size_t piece = count - first; + if (piece > kMaxGlyphRun) { + piece = kMaxGlyphRun; + } + for (size_t at = 0; at < piece; at++) { + characters[at] = start[first + at]; + positions[at] = CGPointMake(cellLeft + (CGFloat)(first + at) * _cellWidth, baseline); + } + CTFontGetGlyphsForCharacters(font, characters, glyphs, (CFIndex)piece); + CTFontDrawGlyphs(font, glyphs, positions, (CFIndex)piece, context); + } + } else { + NSString *shown = [[NSString alloc] initWithBytes:start + length:count + encoding:NSUTF8StringEncoding]; + if (shown == nil) { + CFRelease(foreground); + continue; + } + CTLineRef line = viva_mono_fallback_line(shown, (NSFont *)font, _monoFace, foreground); + if (line == NULL) { + [shown release]; + CFRelease(foreground); + continue; + } + CGFloat x = cellLeft; + if (run->cells > 0) { + CFRange cluster = CFStringGetRangeOfComposedCharactersAtIndex((CFStringRef)shown, 0); + if (cluster.length == (CFIndex)shown.length) { + // A lone character takes the middle of its cells, so wide + // characters and symbols from other fonts sit evenly. + CGFloat width = CTLineGetTypographicBounds(line, NULL, NULL, NULL); + x = cellLeft + (span - width) / 2; + } + } + CGContextSetTextPosition(context, x, baseline); + CTLineDraw(line, context); + CFRelease(line); + [shown release]; + } + + if ((run->flags & (VIVA_RUN_UNDERLINE | VIVA_RUN_STRIKE)) != 0 && span > 0) { + CGContextSetFillColorWithColor(context, foreground); + CGFloat thickness = MAX(hairline, CTFontGetUnderlineThickness(font)); + thickness = ceil(thickness * pixelScale) / pixelScale; + if ((run->flags & VIVA_RUN_UNDERLINE) != 0) { + CGFloat y = baseline + CTFontGetUnderlinePosition(font) - thickness / 2; + y = floor(y * pixelScale) / pixelScale; + CGContextFillRect(context, CGRectMake(cellLeft, y, span, thickness)); + } + if ((run->flags & VIVA_RUN_STRIKE) != 0) { + CGFloat y = baseline + CTFontGetXHeight(font) * 0.5 - thickness / 2; + y = floor(y * pixelScale) / pixelScale; + CGContextFillRect(context, CGRectMake(cellLeft, y, span, thickness)); + } + } + + CFRelease(foreground); + } + for (int slot = 0; slot < cacheCount; slot++) { + CFRelease(cachedFont[slot]); + } +} + +- (id)textureAtIndex:(NSUInteger)index { + return index == 0 ? _texture : [_additionalTextures objectAtIndex:index - 1]; +} + +- (NSUInteger)textureCount { + return 1 + _additionalTextures.count; +} + +- (NSRect)frame { + return _frame; +} + +- (NSRect)quadAtIndex:(NSUInteger)index { + if (_bitmap != nil) { + return _frame; + } + size_t full = (size_t)MAX(1.0, ceil(_frame.size.width * _windowPixelScale)); + size_t tileLeft = _windowLeft + index * VIVA_LABEL_TILE_WIDTH; + size_t tileRight = tileLeft + MIN(_windowRight - tileLeft, VIVA_LABEL_TILE_WIDTH); + CGFloat left = (CGFloat)tileLeft / _windowPixelScale; + CGFloat right = tileRight >= full ? _frame.size.width : (CGFloat)tileRight / _windowPixelScale; + return NSMakeRect(_frame.origin.x + left, _frame.origin.y, right - left, _frame.size.height); +} + +- (NSRect)textureFrameAtIndex:(NSUInteger)index { + if (_bitmap != nil) return _frame; + size_t full = (size_t)MAX(1.0, ceil(_frame.size.width * _windowPixelScale)); + size_t tileLeft = _windowLeft + index * VIVA_LABEL_TILE_WIDTH; + size_t tileRight = tileLeft + MIN(_windowRight - tileLeft, VIVA_LABEL_TILE_WIDTH); + size_t textureLeft = tileLeft > 0 ? tileLeft - 1 : 0; + size_t textureRight = MIN(tileRight + 1, full); + CGFloat left = (CGFloat)textureLeft / _windowPixelScale; + CGFloat right = textureRight >= full ? _frame.size.width : (CGFloat)textureRight / _windowPixelScale; + return NSMakeRect(_frame.origin.x + left, _frame.origin.y, right - left, _frame.size.height); +} + +@end + +// Keep native windows and offscreen frames on the same retained-texture path. +// viewport is the size of the window or frame the labels are drawn in, logical pixels. +int viva_update_label_layers( + NSArray *previous, + const viva_text_label *labels, + NSUInteger count, + id device, + CGFloat scale, + NSSize viewport, + NSMutableArray **updated +) { + NSMutableArray *replacement = + [[NSMutableArray alloc] initWithCapacity:count]; + NSUInteger oldCount = previous.count; + uint64_t *oldHashes = malloc(MAX(oldCount, 1) * sizeof(uint64_t)); + uint64_t *newHashes = malloc(MAX(count, 1) * sizeof(uint64_t)); + int64_t *source = malloc(MAX(count, 1) * sizeof(int64_t)); + if (oldHashes == NULL || newHashes == NULL || source == NULL) { + free(oldHashes); + free(newHashes); + free(source); + [replacement release]; + return 3; + } + for (NSUInteger index = 0; index < oldCount; index++) { + oldHashes[index] = [previous[index] contentHash]; + } + for (NSUInteger index = 0; index < count; index++) { + newHashes[index] = viva_label_content_hash(labels[index]); + } + int status = viva_plan_label_reuse(oldHashes, oldCount, newHashes, count, source); + free(oldHashes); + free(newHashes); + if (status != 0) { + free(source); + [replacement release]; + return status; + } + for (NSUInteger index = 0; index < count; index++) { + VivaTextLayer *existing = nil; + if (source[index] >= 0 && [previous[(NSUInteger)source[index]] matchesConfig:labels[index]]) { + existing = previous[(NSUInteger)source[index]]; + } + if (existing != nil) { + [existing updateFrame:NSMakeRect( + labels[index].x, labels[index].y, + labels[index].width, labels[index].height)]; + [existing updateClipFromConfig:labels[index]]; + [existing updateQuadFromConfig:labels[index]]; + // An image drawn at a new size may need a texture of another resolution, and a + // line held in part another part of it. + BOOL rebuilt = (labels[index].flags & VIVA_LABEL_BITMAP) != 0 + ? [existing rebuildWithDevice:device scale:scale viewport:viewport] + : [existing refreshWindowWithDevice:device scale:scale viewport:viewport]; + if (!rebuilt) { + free(source); + [replacement release]; + return 3; + } + [replacement addObject:existing]; + continue; + } + VivaTextLayer *layer = [[VivaTextLayer alloc] initWithConfig:labels[index]]; + if (layer == nil || ![layer rebuildWithDevice:device scale:scale viewport:viewport]) { + int failure = layer == nil ? 2 : 3; + free(source); + [layer release]; + [replacement release]; + return failure; + } + [layer markContentRebuild]; + [replacement addObject:layer]; + [layer release]; + } + free(source); + *updated = replacement; + return 0; +} + +// viva_label_box_quad writes the four corners of an axis-aligned box in the +// order the text vertex shader expects them: top-left, top-right, bottom-left, +// bottom-right. +void viva_label_box_quad(float *quad, float x, float y, float width, float height) { + quad[0] = x; + quad[1] = y; + quad[2] = x + width; + quad[3] = y; + quad[4] = x; + quad[5] = y + height; + quad[6] = x + width; + quad[7] = y + height; +} + +// viva_label_plain_tint writes the colour that leaves a label's pixels as they +// are: opaque white at every corner. +void viva_label_plain_tint(float *tint) { + for (int index = 0; index < 16; index++) { + tint[index] = 1; + } +} + +// viva_label_tile_mesh maps one texture tile's part of the label's triangles. A +// label wider than a texture holds arrives in several tiles, each a horizontal +// slice of the same picture; clipping the original triangles preserves their +// affine texture coordinates and tints across tile boundaries. +size_t viva_label_tile_mesh( + const float *quad, + const float *tint, + NSRect frame, + NSRect tile, + NSRect texture, + viva_label_vertex *vertices +) { + CGFloat width = frame.size.width > 0 ? frame.size.width : 1; + float left = (float)((tile.origin.x - frame.origin.x) / width); + float right = (float)((tile.origin.x + tile.size.width - frame.origin.x) / width); + left = fminf(fmaxf(left, 0), 1); + right = fminf(fmaxf(right, 0), 1); + float textureLeft = (float)((texture.origin.x - frame.origin.x) / width); + float textureRight = (float)((texture.origin.x + texture.size.width - frame.origin.x) / width); + return viva_label_tile_vertices(quad, tint, left, right, textureLeft, textureRight, vertices); +} + +// viva_text_label_uniform mirrors TextLabelUniform in scene.metal: where a +// label's box starts, its size, and the radius its picture's corners are cut by. +typedef struct { + float originX, originY; + float sizeX, sizeY; + float radius; + float padding; +} viva_text_label_uniform; + +// viva_encode_input draws the native editor's texture. +void viva_encode_input( + id encoder, + id textPipeline, + id inputTexture, + NSRect inputFrame, + NSSize viewport +) { + float viewportSize[2] = {(float)viewport.width, (float)viewport.height}; + float quad[8]; + viva_label_box_quad(quad, + (float)inputFrame.origin.x, (float)inputFrame.origin.y, + (float)inputFrame.size.width, (float)inputFrame.size.height); + float tint[16]; + viva_label_plain_tint(tint); + viva_label_vertex vertices[6]; + viva_label_vertices(quad, tint, vertices); + [encoder setRenderPipelineState:textPipeline]; + [encoder setVertexBytes:vertices length:sizeof(vertices) atIndex:2]; + viva_text_label_uniform labelUniform = {0, 0, 0, 0, 0, 0}; + [encoder setVertexBytes:&labelUniform length:sizeof(labelUniform) atIndex:3]; + [encoder setVertexBytes:&viewportSize length:sizeof(viewportSize) atIndex:1]; + [encoder setFragmentTexture:inputTexture atIndex:0]; + [encoder drawPrimitives:MTLPrimitiveTypeTriangle vertexStart:0 vertexCount:6]; + viva_gpu_draw_call_count++; +} + +// viva_encode_scene draws one frame: the rectangle and text-label batches in +// composite order, with the native editor's texture drawn after every batch of +// its own layer, so a higher layer (a popup over the field) covers it. The window and the +// headless renderer share it, so a screenshot is the pixels the window shows. +void viva_encode_scene( + id encoder, + id rectanglePipeline, + id textPipeline, + id rectangleBuffer, + const viva_composite_command *commands, + NSUInteger commandCount, + NSArray *labels, + id inputTexture, + NSRect inputFrame, + uint16_t inputLayer, + NSSize viewport, + NSUInteger targetWidth, + NSUInteger targetHeight +) { + float viewportSize[2] = {(float)viewport.width, (float)viewport.height}; + BOOL inputDrawn = inputTexture == nil; + // A label that a canvas clip cuts is drawn through a scissor, so the part + // outside the clip is never painted. The scale maps logical pixels to the + // target's. + CGFloat targetScale = viewport.width > 0 ? (CGFloat)targetWidth / viewport.width : 1.0; + float sceneViewport[4] = {(float)viewport.width, (float)viewport.height, (float)(1.0 / targetScale), 0}; + MTLScissorRect fullTarget = {0, 0, targetWidth, targetHeight}; + for (NSUInteger index = 0; index < commandCount; index++) { + viva_composite_command command = commands[index]; + if (!inputDrawn && command.layer > inputLayer) { + viva_encode_input(encoder, textPipeline, inputTexture, inputFrame, viewport); + inputDrawn = YES; + } + if (command.kind == VIVA_COMPOSITE_RECTANGLES) { + // A clipped batch is drawn through a scissor. An edge between two + // pixel boundaries moves to the nearer one, as render.ScissorOf does. + if (command.clipped != 0) { + CGFloat leftEdge = floor(command.clip_x * targetScale + 0.5); + CGFloat topEdge = floor(command.clip_y * targetScale + 0.5); + CGFloat rightEdge = floor((command.clip_x + command.clip_width) * targetScale + 0.5); + CGFloat bottomEdge = floor((command.clip_y + command.clip_height) * targetScale + 0.5); + NSInteger left = (NSInteger)MIN(MAX(leftEdge, 0), (CGFloat)targetWidth); + NSInteger top = (NSInteger)MIN(MAX(topEdge, 0), (CGFloat)targetHeight); + NSInteger right = (NSInteger)MIN(MAX(rightEdge, 0), (CGFloat)targetWidth); + NSInteger bottom = (NSInteger)MIN(MAX(bottomEdge, 0), (CGFloat)targetHeight); + if (right <= left || bottom <= top) { + continue; + } + MTLScissorRect scissor = {(NSUInteger)left, (NSUInteger)top, (NSUInteger)(right - left), (NSUInteger)(bottom - top)}; + [encoder setScissorRect:scissor]; + } + [encoder setRenderPipelineState:rectanglePipeline]; + [encoder setVertexBuffer:rectangleBuffer offset:0 atIndex:0]; + [encoder setVertexBytes:&sceneViewport length:sizeof(sceneViewport) atIndex:1]; + [encoder drawPrimitives:MTLPrimitiveTypeTriangle + vertexStart:0 + vertexCount:6 + instanceCount:command.count + baseInstance:command.first]; + viva_gpu_draw_call_count++; + viva_rectangle_instance_count += command.count; + if (command.clipped != 0) { + [encoder setScissorRect:fullTarget]; + } + continue; + } + + VivaTextLayer *layer = [labels objectAtIndex:command.first]; + BOOL scissored = NO; + if ([layer clipped]) { + NSRect clip = [layer clip]; + NSInteger left = MAX((NSInteger)floor(clip.origin.x * targetScale), 0); + NSInteger top = MAX((NSInteger)floor(clip.origin.y * targetScale), 0); + NSInteger right = MIN((NSInteger)ceil((clip.origin.x + clip.size.width) * targetScale), (NSInteger)targetWidth); + NSInteger bottom = MIN((NSInteger)ceil((clip.origin.y + clip.size.height) * targetScale), (NSInteger)targetHeight); + if (right <= left || bottom <= top) { + continue; + } + MTLScissorRect scissor = {(NSUInteger)left, (NSUInteger)top, (NSUInteger)(right - left), (NSUInteger)(bottom - top)}; + [encoder setScissorRect:scissor]; + scissored = YES; + } + [encoder setRenderPipelineState:textPipeline]; + [encoder setVertexBytes:&viewportSize length:sizeof(viewportSize) atIndex:1]; + NSRect layerFrame = [layer frame]; + viva_text_label_uniform labelUniform = { + (float)layerFrame.origin.x, (float)layerFrame.origin.y, + (float)layerFrame.size.width, (float)layerFrame.size.height, + [layer imageRadius], 0, + }; + [encoder setVertexBytes:&labelUniform length:sizeof(labelUniform) atIndex:3]; + for (NSUInteger tile = 0; tile < [layer textureCount]; tile++) { + viva_label_vertex vertices[18]; + size_t count = viva_label_tile_mesh([layer quad], [layer tint], [layer frame], + [layer quadAtIndex:tile], [layer textureFrameAtIndex:tile], vertices); + if (count == 0) continue; + [encoder setVertexBytes:vertices length:count * sizeof(viva_label_vertex) atIndex:2]; + [encoder setFragmentTexture:[layer textureAtIndex:tile] atIndex:0]; + [encoder drawPrimitives:MTLPrimitiveTypeTriangle vertexStart:0 vertexCount:count]; + viva_gpu_draw_call_count++; + } + if (scissored) { + [encoder setScissorRect:fullTarget]; + } + } + if (!inputDrawn) { + viva_encode_input(encoder, textPipeline, inputTexture, inputFrame, viewport); + } +} + diff --git a/internal/platform/darwin/core_text.m b/internal/platform/darwin/core_text.m new file mode 100644 index 000000000..7860b0c06 --- /dev/null +++ b/internal/platform/darwin/core_text.m @@ -0,0 +1,1284 @@ +#import "core.h" +#include "label_geometry.h" + +NSRange viva_clamp_range(NSRange range, NSUInteger length) { + if (range.location == NSNotFound) { + return NSMakeRange(length, 0); + } + NSUInteger start = MIN(range.location, length); + NSUInteger remaining = length - start; + return NSMakeRange(start, MIN(range.length, remaining)); +} + +// A line of proportional text is shaped once by CoreText, in the system font with its font +// fallback, and everything that needs a position asks that line: the width +// layout uses, the glyphs a label draws, the caret, the selection and the character a click +// lands on. The engine in Go (text_engine.go) caches the lines; vivaShapedLine is how the +// drawing here reaches the same cache. +extern viva_text_line *vivaShapedLine(const unsigned char *utf8, size_t length, double size, double weight); +extern viva_text_line *vivaShapedLineStyle(const unsigned char *utf8, size_t length, double size, double weight, int italic); + +// viva_interface_family is the family viva_text_set_family last named, "" for the +// system font. A plain C buffer, not an NSString: nothing here manages memory for +// the interface font, and the name is read under the shaping the engine serializes. +static char viva_interface_family[256] = ""; + +// viva_system_font is the proportional font that measurement, labels and the editor all +// use (a retained CTFont). It is an NSFont, which is a CTFont already. With a family +// named, its face of that family at the weight stands in for the system font; a family +// the system does not have falls back to the system font, as AppKit does for a name. +CTFontRef viva_system_font(CGFloat size, CGFloat weight) { + if (viva_interface_family[0] != '\0') { + NSString *family = [NSString stringWithUTF8String:viva_interface_family]; + if (family != nil) { + // The weight is the system font's own continuous scale (NSFontWeight), so a + // family's regular, medium, semibold and bold faces are told apart as they are + // in the system font; the nearest face the family has stands in for one it + // lacks. NSFontManager's weight is a 0-15 table that cannot say medium. + NSFontDescriptor *descriptor = [NSFontDescriptor fontDescriptorWithFontAttributes:@{ + NSFontFamilyAttribute: family, + NSFontTraitsAttribute: @{NSFontWeightTrait: @(weight)}, + }]; + NSFont *named = [NSFont fontWithDescriptor:descriptor size:size]; + if (named != nil) { + return (CTFontRef)CFRetain(named); + } + } + } + NSFont *font = [NSFont systemFontOfSize:size weight:weight]; + return font != nil ? (CTFontRef)CFRetain(font) : NULL; +} + +CTFontRef viva_system_font_style(CGFloat size, CGFloat weight, BOOL italic) { + CTFontRef base = viva_system_font(size, weight); + if (!italic || base == NULL) { + return base; + } + // The family's own italic face when it has one. When it has none the base font is + // kept and the glyphs are slanted as they are drawn (viva_draw_text_line), the same + // slant the fallback fonts of a line get. + CTFontRef face = CTFontCreateCopyWithSymbolicTraits(base, size, NULL, kCTFontItalicTrait, kCTFontItalicTrait); + if (face == NULL) { + return base; + } + CFRelease(base); + return face; +} + +void viva_text_set_family(const char *family) { + if (family == NULL) { + viva_interface_family[0] = '\0'; + return; + } + strncpy(viva_interface_family, family, sizeof(viva_interface_family) - 1); + viva_interface_family[sizeof(viva_interface_family) - 1] = '\0'; +} + +viva_text_line *viva_text_line_create_style(const unsigned char *utf8, size_t length, double font_size, double font_weight, int italic) { + @autoreleasepool { + static const unsigned char empty[1] = {0}; + CFStringRef string = CFStringCreateWithBytes( + kCFAllocatorDefault, utf8 != NULL ? utf8 : empty, utf8 != NULL ? (CFIndex)length : 0, kCFStringEncodingUTF8, false); + if (string == NULL) { + return NULL; + } + CTFontRef font = viva_system_font_style(font_size, font_weight, italic != 0); + if (font == NULL) { + CFRelease(string); + return NULL; + } + // The color comes from the context when the line is drawn, so one line serves every color. + const void *keys[] = {kCTFontAttributeName, kCTForegroundColorFromContextAttributeName}; + const void *values[] = {font, kCFBooleanTrue}; + CFDictionaryRef attributes = CFDictionaryCreate( + kCFAllocatorDefault, keys, values, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); + CFAttributedStringRef attributed = CFAttributedStringCreate(kCFAllocatorDefault, string, attributes); + CTLineRef line = CTLineCreateWithAttributedString(attributed); + CFRelease(attributed); + CFRelease(attributes); + viva_text_line *shaped = line != NULL ? calloc(1, sizeof(viva_text_line)) : NULL; + if (shaped == NULL) { + if (line != NULL) { + CFRelease(line); + } + CFRelease(font); + CFRelease(string); + return NULL; + } + CGFloat ascent = 0, descent = 0, leading = 0; + shaped->width = CTLineGetTypographicBounds(line, &ascent, &descent, &leading); + if (ascent + descent <= 0) { + // A line with no glyphs reports zero for both, which would give an empty + // field's caret zero height: the font's own metrics stand in. + ascent = CTFontGetAscent(font); + descent = CTFontGetDescent(font); + } + shaped->ascent = ascent; + shaped->descent = descent; + shaped->line = (void *)line; + shaped->string = (void *)string; + shaped->references = 1; + shaped->italic = italic != 0; + CFRelease(font); + return shaped; + } +} + +viva_text_line *viva_text_line_create(const unsigned char *utf8, size_t length, double font_size, double font_weight) { + return viva_text_line_create_style(utf8, length, font_size, font_weight, 0); +} + +void viva_text_line_retain(viva_text_line *line) { + if (line != NULL) { + __atomic_fetch_add(&line->references, 1, __ATOMIC_RELAXED); + } +} + +void viva_text_line_release(viva_text_line *line) { + if (line != NULL && __atomic_fetch_sub(&line->references, 1, __ATOMIC_ACQ_REL) == 1) { + CFRelease((CTLineRef)line->line); + CFRelease((CFStringRef)line->string); + free(line); + } +} + +// viva_cluster_start moves offset back to the start of the character cluster it falls in. +CFIndex viva_cluster_start(CFStringRef string, size_t offset) { + CFIndex length = CFStringGetLength(string); + if (offset >= (size_t)length) { + return length; + } + return CFStringGetRangeOfComposedCharactersAtIndex(string, (CFIndex)offset).location; +} + +double viva_text_line_caret(const viva_text_line *line, size_t offset) { + CGFloat secondary = 0; + return CTLineGetOffsetForStringIndex((CTLineRef)line->line, viva_cluster_start((CFStringRef)line->string, offset), &secondary); +} + +size_t viva_text_line_index_at(const viva_text_line *line, double x) { + CFStringRef string = (CFStringRef)line->string; + CTLineRef ct = (CTLineRef)line->line; + CFIndex length = CFStringGetLength(string); + if (length == 0) { + return 0; + } + CFIndex index = CTLineGetStringIndexForPosition(ct, CGPointMake(x, 0)); + if (index == kCFNotFound) { + return x <= 0 ? 0 : (size_t)length; + } + index = MIN(index, length); + if (index < length) { + CFRange cluster = CFStringGetRangeOfComposedCharactersAtIndex(string, index); + if (cluster.location != index) { + CGFloat secondary = 0; + CGFloat start = CTLineGetOffsetForStringIndex(ct, cluster.location, &secondary); + CGFloat end = CTLineGetOffsetForStringIndex(ct, cluster.location + cluster.length, &secondary); + index = fabs(x - start) <= fabs(x - end) ? cluster.location : cluster.location + cluster.length; + } + } + return (size_t)index; +} + +// The most extents viva_text_line_selection tells apart before it folds the rest into the +// last: a selection crossing a change of direction more often than this is not text. +#define VIVA_SELECTION_PIECES 32 + +size_t viva_text_line_selection(const viva_text_line *line, size_t start, size_t end, double *spans, size_t capacity) { + CFStringRef string = (CFStringRef)line->string; + CTLineRef ct = (CTLineRef)line->line; + CFIndex from = viva_cluster_start(string, start); + CFIndex to = viva_cluster_start(string, end); + if (from > to) { + CFIndex swap = from; + from = to; + to = swap; + } + if (capacity == 0) { + return 0; + } + double left[VIVA_SELECTION_PIECES], right[VIVA_SELECTION_PIECES]; + size_t count = 0; + CGFloat secondary = 0; + // A cluster stands between its leading edge (the secondary offset of its first unit, where + // a boundary between two directions has two) and the trailing edge of its last, which is + // the primary offset of the unit after it. + for (CFIndex at = from; at < to;) { + CFRange cluster = CFStringGetRangeOfComposedCharactersAtIndex(string, at); + CFIndex next = MIN(cluster.location + cluster.length, to); + CGFloat leading = 0; + CTLineGetOffsetForStringIndex(ct, at, &leading); + CGFloat trailing = CTLineGetOffsetForStringIndex(ct, next, &secondary); + double lo = MIN(leading, trailing), hi = MAX(leading, trailing); + if (count > 0 && lo <= right[count - 1] + 0.01 && hi >= left[count - 1] - 0.01) { + left[count - 1] = MIN(left[count - 1], lo); + right[count - 1] = MAX(right[count - 1], hi); + } else if (count < VIVA_SELECTION_PIECES) { + left[count] = lo; + right[count++] = hi; + } else { + left[count - 1] = MIN(left[count - 1], lo); + right[count - 1] = MAX(right[count - 1], hi); + } + at = next; + } + if (count == 0) { + // An empty selection is the caret. + left[0] = right[0] = CTLineGetOffsetForStringIndex(ct, from, &secondary); + count = 1; + } + // Pieces of the selection that the reordering put side by side are one extent. + for (size_t i = 1; i < count; i++) { + for (size_t j = i; j > 0 && left[j] < left[j - 1]; j--) { + double l = left[j], r = right[j]; + left[j] = left[j - 1]; + right[j] = right[j - 1]; + left[j - 1] = l; + right[j - 1] = r; + } + } + size_t written = 0; + for (size_t i = 0; i < count; i++) { + if (written > 0 && left[i] <= spans[2 * (written - 1)] + spans[2 * (written - 1) + 1] + 0.01) { + double merged = MAX(spans[2 * (written - 1)] + spans[2 * (written - 1) + 1], right[i]); + spans[2 * (written - 1) + 1] = merged - spans[2 * (written - 1)]; + } else if (written < capacity) { + spans[2 * written] = left[i]; + spans[2 * written + 1] = right[i] - left[i]; + written++; + } + } + return written; +} + +// viva_shared_text_line is the engine's line for shown in the system font, retained for the +// caller to release with viva_text_line_release. +viva_text_line *viva_shared_text_line(NSString *shown, CGFloat fontSize, CGFloat weight) { + NSData *bytes = [shown dataUsingEncoding:NSUTF8StringEncoding]; + return vivaShapedLine(bytes != nil ? (const unsigned char *)bytes.bytes : NULL, bytes != nil ? bytes.length : 0, fontSize, weight); +} + +viva_text_line *viva_shared_text_line_style(NSString *shown, CGFloat fontSize, CGFloat weight, BOOL italic) { + NSData *bytes = [shown dataUsingEncoding:NSUTF8StringEncoding]; + return vivaShapedLineStyle(bytes != nil ? (const unsigned char *)bytes.bytes : NULL, bytes != nil ? bytes.length : 0, fontSize, weight, italic ? 1 : 0); +} + +// viva_draw_text_line draws the shaped line in one call, its origin at x on baseline, in +// color (the line carries none, so the same line serves every color). +// VIVA_SYNTHETIC_ITALIC_SLANT is the shear of a glyph drawn in italics from a font that has +// no italic face: about eleven degrees, as the tilt of the system font's own italic. +#define VIVA_SYNTHETIC_ITALIC_SLANT 0.2 + +// viva_run_needs_slant says whether a run of an italic line must be slanted: its font has no +// italic face, as a CJK fallback font has none. A font of color glyphs (emoji) is left upright. +BOOL viva_run_needs_slant(CTRunRef run) { + CFDictionaryRef attributes = CTRunGetAttributes(run); + CTFontRef font = attributes != NULL ? (CTFontRef)CFDictionaryGetValue(attributes, kCTFontAttributeName) : NULL; + if (font == NULL) { + return NO; + } + CTFontSymbolicTraits traits = CTFontGetSymbolicTraits(font); + return (traits & (kCTFontItalicTrait | kCTFontColorGlyphsTrait)) == 0; +} + +void viva_draw_text_line(CGContextRef context, const viva_text_line *line, CGColorRef color, CGFloat x, CGFloat baseline) { + CGContextSaveGState(context); + CGContextSetFillColorWithColor(context, color); + if (!line->italic) { + CGContextSetTextPosition(context, x, baseline); + CTLineDraw((CTLineRef)line->line, context); + } else { + // Run by run: the runs whose font has no italic face are drawn under a shear about + // the baseline. The glyph positions of a run are relative to the line's origin, so + // the shear leaves them where the line put them and only tilts the glyphs. + CFArrayRef runs = CTLineGetGlyphRuns((CTLineRef)line->line); + for (CFIndex index = 0, count = CFArrayGetCount(runs); index < count; index++) { + CTRunRef run = (CTRunRef)CFArrayGetValueAtIndex(runs, index); + CGFloat slant = viva_run_needs_slant(run) ? VIVA_SYNTHETIC_ITALIC_SLANT : 0; + CGContextSetTextMatrix(context, CGAffineTransformMake(1, 0, slant, 1, x, baseline)); + CTRunDraw(run, context, CFRangeMake(0, 0)); + } + // The text matrix is not part of the saved state, and other labels set only a position. + CGContextSetTextMatrix(context, CGAffineTransformIdentity); + } + CGContextRestoreGState(context); +} + +// The geometry of the text a native editor shows: the shaped line of proportional text, or +// a terminal's preedit, which is laid on the terminal's cells and not on the advances of +// its font: the text, and the width of one cell. + +void viva_editor_line_free(viva_editor_line line) { + viva_text_line_release(line.shaped); + [line.grid release]; +} + +// viva_editor_line_made says whether the line could be made. +BOOL viva_editor_line_made(viva_editor_line line) { + return line.shaped != NULL || line.grid != nil; +} + +// viva_terminal_step reads the character of shown at UTF-16 index `at`: how many units it +// takes, and how many cells (see vivaTerminalCells; a combining mark has none). +NSUInteger viva_terminal_step(NSString *shown, NSUInteger at, int *cells) { + unichar first = [shown characterAtIndex:at]; + uint32_t point = first; + NSUInteger length = 1; + if (CFStringIsSurrogateHighCharacter(first) && at + 1 < shown.length) { + unichar second = [shown characterAtIndex:at + 1]; + if (CFStringIsSurrogateLowCharacter(second)) { + point = CFStringGetLongCharacterForSurrogatePair(first, second); + length = 2; + } + } + *cells = vivaTerminalCells(point); + return length; +} + +// viva_terminal_column is the cell column of the boundary before the UTF-16 unit `index` +// of shown, counted from the first cell of the text. +NSUInteger viva_terminal_column(NSString *shown, NSUInteger index) { + NSUInteger column = 0; + for (NSUInteger at = 0; at < index && at < shown.length;) { + int cells = 0; + NSUInteger length = viva_terminal_step(shown, at, &cells); + if (at + length > index) { + break; + } + column += (NSUInteger)cells; + at += length; + } + return column; +} + +// viva_text_offset is where the editor draws the boundary before the UTF-16 unit `index` +// of shown, from the left of the text. +CGFloat viva_text_offset(viva_editor_line line, NSUInteger index, BOOL terminal) { + if (terminal) { + return (CGFloat)viva_terminal_column(line.grid, index) * line.cell; + } + return viva_text_line_caret(line.shaped, index); +} + +// viva_text_spans is the extents of range in the editor, left to right. +size_t viva_text_spans(viva_editor_line line, NSRange range, BOOL terminal, double *spans, size_t capacity) { + if (terminal) { + CGFloat start = viva_text_offset(line, range.location, terminal); + CGFloat end = viva_text_offset(line, NSMaxRange(range), terminal); + spans[0] = MIN(start, end); + spans[1] = fabs(end - start); + return 1; + } + return viva_text_line_selection(line.shaped, range.location, NSMaxRange(range), spans, capacity); +} + +// viva_text_index_at is the boundary of shown nearest to x, the inverse of viva_text_offset. +NSUInteger viva_text_index_at(viva_editor_line line, NSString *shown, CGFloat x, BOOL terminal) { + if (!terminal) { + return viva_text_line_index_at(line.shaped, x); + } + // The boundary between characters whose cell edge is nearest x; a boundary inside a + // character with its combining marks is none, and of two on one edge the later wins. + NSUInteger position = 0; + CGFloat nearest = fabs(x); + NSUInteger column = 0; + for (NSUInteger at = 0; at < shown.length;) { + int cells = 0; + at += viva_terminal_step(shown, at, &cells); + column += (NSUInteger)cells; + if (at < shown.length && [shown rangeOfComposedCharacterSequenceAtIndex:at].location != at) { + continue; + } + CGFloat distance = fabs(x - (CGFloat)column * line.cell); + if (distance <= nearest) { + nearest = distance; + position = at; + } + } + return position; +} + +// viva_mono_font is the system fixed-pitch font, the one every fixed-pitch label +// and the cell metrics are built from. +// +// A face from 2 up stands for an installed family and the families that draw what it +// lacks; viva_register_mono_family teaches the numbers, in registration order. +#define VIVA_MONO_FAMILY_SLOTS 4098 /* the 2 built-in faces and gfx.MaxMonoFaces */ +static NSString *viva_mono_families[VIVA_MONO_FAMILY_SLOTS]; +static NSArray *viva_mono_fallbacks[VIVA_MONO_FAMILY_SLOTS]; +static BOOL viva_mono_classic[VIVA_MONO_FAMILY_SLOTS]; +NSObject *viva_mono_family_lock(void) { + static NSObject *lock; + static dispatch_once_t once; + dispatch_once(&once, ^{ lock = [[NSObject alloc] init]; }); + return lock; +} + +void viva_register_mono_family(int face, const char *utf8, int classic, const char *fallbacks) { + if (face < 2 || face >= VIVA_MONO_FAMILY_SLOTS) { + return; + } + @synchronized(viva_mono_family_lock()) { + [viva_mono_families[face] release]; + [viva_mono_fallbacks[face] release]; + viva_mono_families[face] = (utf8 != NULL && utf8[0] != '\0') ? [[NSString alloc] initWithUTF8String:utf8] : nil; + viva_mono_classic[face] = classic != 0; + // The fallbacks arrive as one name per line. + NSString *joined = fallbacks != NULL ? [[NSString alloc] initWithUTF8String:fallbacks] : nil; + viva_mono_fallbacks[face] = (joined != nil && joined.length > 0) ? [[joined componentsSeparatedByString:@"\n"] retain] : nil; + [joined release]; + } +} + +// viva_mono_face_traits copies what a face stands for: its primary family (nil for a +// built-in one), whether the built-in primary is the classic face, and its fallback +// families in order. +void viva_mono_face_traits(int face, NSString **family, BOOL *classic, NSArray **fallbacks) { + *family = nil; + *classic = face == 1; + *fallbacks = nil; + if (face < 2 || face >= VIVA_MONO_FAMILY_SLOTS) { + return; + } + @synchronized(viva_mono_family_lock()) { + *family = [[viva_mono_families[face] retain] autorelease]; + *classic = viva_mono_classic[face]; + *fallbacks = [[viva_mono_fallbacks[face] retain] autorelease]; + } +} + +// viva_mono_font_on_a_grid reports whether the font advances every printable ASCII +// character by the same width: the one property a terminal cell grid needs. +// +// The font's own fixed-pitch bit is not enough to ask. Families built for coding +// (Nerd Font patches, ligature builds) often leave it clear while drawing on a grid +// all the same, and the bit alone kept them out of the list. The advances are +// compared with a percent of the cell to spare, because a grid font still rounds a +// glyph by a hair (Roboto Mono for Powerline gives '-' 7.207 where its cell is +// 7.201) while a proportional font's differ by a fraction of the cell. +BOOL viva_mono_font_on_a_grid(NSFont *font) { + if (font.isFixedPitch) { + return YES; + } + enum { first = 0x20, last = 0x7E, count = last - first + 1 }; + UniChar characters[count]; + CGGlyph glyphs[count]; + CGSize advances[count]; + for (CFIndex index = 0; index < count; index++) { + characters[index] = (UniChar)(first + index); + } + CTFontRef ctFont = (CTFontRef)font; + if (!CTFontGetGlyphsForCharacters(ctFont, characters, glyphs, count)) { + return NO; // it cannot draw one of them, so it is no terminal face + } + CTFontGetAdvancesForGlyphs(ctFont, kCTFontOrientationHorizontal, glyphs, advances, count); + CGFloat cell = advances[0].width; + if (cell <= 0.0) { + return NO; + } + for (CFIndex index = 1; index < count; index++) { + if (fabs(advances[index].width - cell) > cell * 0.01) { + return NO; + } + } + return YES; +} + +char *viva_list_font_families(void) { + @autoreleasepool { + NSFontManager *manager = [NSFontManager sharedFontManager]; + NSMutableArray *names = [NSMutableArray array]; + for (NSString *family in [manager availableFontFamilies]) { + if ([family hasPrefix:@"."]) { + continue; + } + [names addObject:family]; + } + [names sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)]; + return strdup([[names componentsJoinedByString:@"\n"] UTF8String]); + } +} + +char *viva_list_mono_families(void) { + @autoreleasepool { + NSFontManager *manager = [NSFontManager sharedFontManager]; + NSMutableArray *names = [NSMutableArray array]; + for (NSString *family in [manager availableFontFamilies]) { + if ([family hasPrefix:@"."]) { + continue; + } + NSFont *font = [manager fontWithFamily:family traits:0 weight:5 size:12]; + if (font != nil && viva_mono_font_on_a_grid(font)) { + [names addObject:family]; + } + } + [names sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)]; + return strdup([[names componentsJoinedByString:@"\n"] UTF8String]); + } +} + +// viva_mono_base_font is the primary font of a face, without its fallbacks. +NSFont *viva_mono_base_font(CGFloat size, CGFloat weight, NSString *family, BOOL classic) { + if (family != nil) { + NSFont *named = [[NSFontManager sharedFontManager] fontWithFamily:family + traits:(weight >= 0.34 ? NSBoldFontMask : 0) + weight:5 + size:size]; + if (named != nil) { + return named; + } + } + if (classic) { + NSFont *classicFont = [NSFont userFixedPitchFontOfSize:size]; + if (classicFont != nil) { + return classicFont; + } + } + NSFont *font = [NSFont monospacedSystemFontOfSize:size weight:weight]; + return font != nil ? font : [NSFont userFixedPitchFontOfSize:size]; +} + +// viva_mono_font_primary is the primary font of a face alone, the one the cell is measured in. +NSFont *viva_mono_font_primary(CGFloat size, CGFloat weight, int face) { + NSString *family = nil; + BOOL classic = NO; + NSArray *fallbacks = nil; + viva_mono_face_traits(face, &family, &classic, &fallbacks); + return viva_mono_base_font(size, weight, family, classic); +} + +// viva_mono_font is the font of a face at a size and weight: its primary font, with the +// families that draw what the primary lacks as the font's cascade list, so CoreText +// tries them in order, before its own choice, for every character the primary has no +// glyph for. A family that is not installed is skipped. The cell is the primary's: the +// fallbacks never take part in the metrics, and every glyph is placed on the grid. +NSFont *viva_mono_font(CGFloat size, CGFloat weight, int face) { + NSString *family = nil; + BOOL classic = NO; + NSArray *fallbacks = nil; + viva_mono_face_traits(face, &family, &classic, &fallbacks); + NSFont *base = viva_mono_base_font(size, weight, family, classic); + if (base == nil || fallbacks.count == 0) { + return base; + } + NSMutableArray *cascade = [NSMutableArray arrayWithCapacity:fallbacks.count]; + for (NSString *name in fallbacks) { + [cascade addObject:[NSFontDescriptor fontDescriptorWithFontAttributes:@{NSFontFamilyAttribute: name}]]; + } + NSFontDescriptor *descriptor = [base.fontDescriptor fontDescriptorByAddingAttributes:@{NSFontCascadeListAttribute: cascade}]; + NSFont *stacked = [NSFont fontWithDescriptor:descriptor size:size]; + return stacked != nil ? stacked : base; +} + +/* ---- fallback to the installed fonts for glyphs no family of the face has --- + * + * CoreText draws .LastResort for a character neither the face's families nor its + * own fallback have: private-use icon code points (Powerline, Nerd Fonts) above + * all. It never looks at the fonts the user installed, while the Linux + * (fontconfig) and the Windows (DirectWrite) text stacks do -- so a terminal + * loses the icons of the very font its user installed, and a prompt made of + * Powerline separators reads as boxes. + * + * A cluster that CoreText would draw with the last-resort glyph is handed to the + * installed family that has it, ranked so that a terminal icon font wins over a + * CJK font that maps the same code point to one of its own characters: fixed + * pitch first, then one that draws no Han, then the one covering the most + * private-use code points, then the family name. The choice is remembered per + * cluster (a terminal draws the same icons again and again) and per family (what + * a family covers cannot change while the process runs), so a family installed + * after a character was first drawn is only picked up by a new process. + */ + +// VIVA_MONO_FALLBACK_CACHE bounds the clusters remembered; past it a cluster is +// looked up again each time instead of growing the table without end. +#define VIVA_MONO_FALLBACK_CACHE 4096 +// VIVA_MONO_CLUSTER_LENGTH bounds a cluster; the longest real ones are emoji +// sequences of a few code points. +#define VIVA_MONO_CLUSTER_LENGTH 64 + + +static NSMutableDictionary *viva_mono_trait_cache; +static NSMutableDictionary *viva_mono_cluster_cache; + +NSObject *viva_mono_fallback_lock(void) { + static NSObject *lock; + static dispatch_once_t once; + dispatch_once(&once, ^{ lock = [[NSObject alloc] init]; }); + return lock; +} + +// viva_mono_family_font resolves an installed family at a size and weight, or nil. +NSFont *viva_mono_family_font(NSString *family, CGFloat size, CGFloat weight) { + return [[NSFontManager sharedFontManager] fontWithFamily:family + traits:(weight >= 0.34 ? NSBoldFontMask : 0) + weight:5 + size:size]; +} + +// viva_mono_replacement_font is viva_mono_family_font for a replacement glyph, remembering +// the families asked for: the font manager lookup is most of what a replacement costs, and +// a terminal draws the same icon clusters line after line at the same size. The font is +// returned retained and autoreleased, so it outlives an eviction. +#define VIVA_MONO_REPLACEMENT_CACHE 8 + +typedef struct { + NSString *family; + CGFloat size; + BOOL bold; + NSFont *font; +} viva_mono_replacement; + +static viva_mono_replacement viva_mono_replacements[VIVA_MONO_REPLACEMENT_CACHE]; +static int viva_mono_replacement_count; +static int viva_mono_replacement_next; + +NSFont *viva_mono_replacement_font(NSString *family, CGFloat size, BOOL bold) { + @synchronized(viva_mono_fallback_lock()) { + for (int index = 0; index < viva_mono_replacement_count; index++) { + viva_mono_replacement *entry = &viva_mono_replacements[index]; + if (entry->size == size && entry->bold == bold && [entry->family isEqualToString:family]) { + return [[entry->font retain] autorelease]; + } + } + } + NSFont *font = viva_mono_family_font(family, size, bold ? 1 : 0); + if (font == nil) { + return nil; + } + @synchronized(viva_mono_fallback_lock()) { + viva_mono_replacement *entry; + if (viva_mono_replacement_count < VIVA_MONO_REPLACEMENT_CACHE) { + entry = &viva_mono_replacements[viva_mono_replacement_count++]; + } else { + entry = &viva_mono_replacements[viva_mono_replacement_next++ % VIVA_MONO_REPLACEMENT_CACHE]; + [entry->family release]; + [entry->font release]; + } + entry->family = [family copy]; + entry->size = size; + entry->bold = bold; + entry->font = [font retain]; + } + return [[font retain] autorelease]; +} + +// viva_mono_font_covers reports whether font draws every code unit of value. +BOOL viva_mono_font_covers(CTFontRef font, NSString *value) { + NSUInteger length = value.length; + if (font == NULL || length == 0 || length > VIVA_MONO_CLUSTER_LENGTH) { + return NO; + } + UniChar characters[VIVA_MONO_CLUSTER_LENGTH]; + CGGlyph glyphs[VIVA_MONO_CLUSTER_LENGTH]; + [value getCharacters:characters range:NSMakeRange(0, length)]; + if (!CTFontGetGlyphsForCharacters(font, characters, glyphs, (CFIndex)length)) { + return NO; + } + for (NSUInteger index = 0; index < length; index++) { + if (glyphs[index] == 0) { + return NO; + } + } + return YES; +} + +// viva_mono_draws_han reports whether a font draws Chinese text at all. A family +// that does is a text face, and the glyph it maps a private-use code point to is +// one of its own characters rather than the icon the line asks for. +BOOL viva_mono_draws_han(CTFontRef font) { + static const UniChar probes[] = {0x4E2D, 0x5B57, 0x8A9E}; /* 中 字 語 */ + CGGlyph glyphs[3] = {0}; + CTFontGetGlyphsForCharacters(font, probes, glyphs, 3); + return glyphs[0] != 0 || glyphs[1] != 0 || glyphs[2] != 0; +} + +// viva_mono_private_use counts the private-use code points a font covers, from +// the plane's bitmap: a Nerd Font covers thousands, a CJK font a handful. +int viva_mono_private_use(CTFontRef font) { + CFCharacterSetRef characters = CTFontCopyCharacterSet(font); + if (characters == NULL) { + return 0; + } + CFDataRef bitmap = CFCharacterSetCreateBitmapRepresentation(kCFAllocatorDefault, characters); + CFRelease(characters); + if (bitmap == NULL) { + return 0; + } + const UInt8 *bytes = CFDataGetBytePtr(bitmap); + CFIndex length = CFDataGetLength(bitmap); + int count = 0; + for (int code = 0xE000; code <= 0xF8FF; code++) { + CFIndex index = code >> 3; + if (index >= length) { + break; + } + if ((bytes[index] & (1 << (code & 7))) != 0) { + count++; + } + } + CFRelease(bitmap); + return count; +} + +// viva_mono_family_traits_of is what ranks a family: whether it draws on a grid (the +// same test that decides which families are offered, so a coding family that leaves +// the fixed-pitch bit clear ranks with the ones that set it), whether it draws Han, +// and how much private-use it covers. Read once per family. +viva_mono_family_traits viva_mono_family_traits_of(NSString *family) { + viva_mono_family_traits traits = {NO, YES, 0}; + @synchronized(viva_mono_fallback_lock()) { + NSValue *known = [viva_mono_trait_cache objectForKey:family]; + if (known != nil) { + [known getValue:&traits size:sizeof(traits)]; + return traits; + } + } + NSFont *font = viva_mono_family_font(family, 12, 0); + if (font != nil) { + traits.onGrid = viva_mono_font_on_a_grid(font); + traits.includesHan = viva_mono_draws_han((CTFontRef)font); + traits.privateUse = viva_mono_private_use((CTFontRef)font); + } + NSValue *value = [NSValue valueWithBytes:&traits objCType:@encode(viva_mono_family_traits)]; + @synchronized(viva_mono_fallback_lock()) { + if (viva_mono_trait_cache == nil) { + viva_mono_trait_cache = [[NSMutableDictionary alloc] init]; + } + [viva_mono_trait_cache setObject:value forKey:family]; + } + return traits; +} + +// viva_mono_family_better reports whether candidate ranks before best for a cluster. +BOOL viva_mono_family_better(viva_mono_family_traits candidate, NSString *family, + viva_mono_family_traits best, NSString *bestFamily) { + if (bestFamily == nil) { + return YES; + } + if (candidate.onGrid != best.onGrid) { + return candidate.onGrid; + } + if (candidate.includesHan != best.includesHan) { + return !candidate.includesHan; + } + if (candidate.privateUse != best.privateUse) { + return candidate.privateUse > best.privateUse; + } + return [family localizedCaseInsensitiveCompare:bestFamily] == NSOrderedAscending; +} + +// viva_mono_find_family is the installed family that draws cluster, or nil. It +// asks the system for the fonts covering the cluster's code points, leaves out +// the ones that do not draw every code point of it, and ranks the rest. +NSString *viva_mono_find_family(NSString *cluster) { + CFCharacterSetRef characters = CFCharacterSetCreateWithCharactersInString(kCFAllocatorDefault, (CFStringRef)cluster); + if (characters == NULL) { + return nil; + } + const void *keys[] = {kCTFontCharacterSetAttribute}; + const void *values[] = {characters}; + CFDictionaryRef query = CFDictionaryCreate(kCFAllocatorDefault, keys, values, 1, + &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); + CFRelease(characters); + if (query == NULL) { + return nil; + } + CTFontDescriptorRef descriptor = CTFontDescriptorCreateWithAttributes(query); + CFRelease(query); + if (descriptor == NULL) { + return nil; + } + CFArrayRef matches = CTFontDescriptorCreateMatchingFontDescriptors(descriptor, NULL); + CFRelease(descriptor); + if (matches == NULL) { + return nil; + } + NSString *best = nil; + viva_mono_family_traits bestTraits = {NO, YES, 0}; + CFIndex count = CFArrayGetCount(matches); + for (CFIndex index = 0; index < count; index++) { + CTFontDescriptorRef match = (CTFontDescriptorRef)CFArrayGetValueAtIndex(matches, index); + NSString *family = (NSString *)CTFontDescriptorCopyAttribute(match, kCTFontFamilyNameAttribute); + if (family == nil || family.length == 0) { + if (family != NULL) { + CFRelease(family); + } + continue; + } + NSFont *font = viva_mono_family_font(family, 12, 0); + if (font == nil || !viva_mono_font_covers((CTFontRef)font, cluster)) { + CFRelease(family); + continue; + } + viva_mono_family_traits traits = viva_mono_family_traits_of(family); + if (viva_mono_family_better(traits, family, bestTraits, best)) { + best = [family autorelease]; + bestTraits = traits; + } else { + CFRelease(family); + } + } + CFRelease(matches); + return best; +} + +// viva_mono_face_fallback is the family the face itself puts behind its primary +// that draws cluster, or nil. CoreText ignores a cascade list for private-use code +// points as well, so the application's own fallbacks -- the ones the settings page +// offers -- have to be tried here, before the ranking. +NSString *viva_mono_face_fallback(NSString *cluster, int face) { + NSString *family = nil; + BOOL classic = NO; + NSArray *fallbacks = nil; + viva_mono_face_traits(face, &family, &classic, &fallbacks); + for (NSString *candidate in fallbacks) { + NSFont *font = viva_mono_family_font(candidate, 12, 0); + if (font != nil && viva_mono_font_covers((CTFontRef)font, cluster)) { + return candidate; + } + } + return nil; +} + +// viva_mono_fallback_family is the installed family that draws a cluster CoreText +// cannot, or nil when no installed family has it. +NSString *viva_mono_fallback_family(NSString *cluster) { + if (cluster.length == 0 || cluster.length > VIVA_MONO_CLUSTER_LENGTH) { + return nil; + } + @synchronized(viva_mono_fallback_lock()) { + id known = [viva_mono_cluster_cache objectForKey:cluster]; + if (known != nil) { + return known == [NSNull null] ? nil : known; + } + } + NSString *family = viva_mono_find_family(cluster); + @synchronized(viva_mono_fallback_lock()) { + if (viva_mono_cluster_cache == nil) { + viva_mono_cluster_cache = [[NSMutableDictionary alloc] init]; + } + if (viva_mono_cluster_cache.count < VIVA_MONO_FALLBACK_CACHE) { + [viva_mono_cluster_cache setObject:(family != nil ? family : (id)[NSNull null]) forKey:cluster]; + } + } + return family; +} + +// viva_mono_font_is_last_resort reports whether font is the face CoreText draws a +// character no installed family has with. The face calls itself LastResort, with a +// leading dot in its family name and without it in its PostScript name. +BOOL viva_mono_is_last_resort_name(CFStringRef name) { + if (name == NULL) { + return NO; + } + return CFStringCompare(name, CFSTR("LastResort"), kCFCompareCaseInsensitive) == kCFCompareEqualTo || + CFStringCompare(name, CFSTR(".LastResort"), kCFCompareCaseInsensitive) == kCFCompareEqualTo; +} + +BOOL viva_mono_font_is_last_resort(CTFontRef font) { + if (font == NULL) { + return NO; + } + CFStringRef postscript = CTFontCopyPostScriptName(font); + CFStringRef family = CTFontCopyFamilyName(font); + BOOL last = viva_mono_is_last_resort_name(postscript) || viva_mono_is_last_resort_name(family); + if (postscript != NULL) { + CFRelease(postscript); + } + if (family != NULL) { + CFRelease(family); + } + return last; +} + +// viva_mono_fallback_line shapes a fixed-pitch line in base (the face's font at the +// weight, and with the slant, the caller already resolved): for the clusters CoreText +// would draw with its last-resort glyph, the installed family that has them, at base's +// size and boldness. A line with nothing to replace is shaped once, as before; one with +// a replacement is shaped again with the fallback fonts in place, so every glyph sits +// where the grid says. The line is +1: the caller releases it. +CTLineRef viva_mono_fallback_line(NSString *value, NSFont *base, int face, CGColorRef color) { + if (base == nil || value.length == 0) { + return NULL; + } + CGFloat size = base.pointSize; + BOOL bold = (base.fontDescriptor.symbolicTraits & NSFontBoldTrait) != 0; + CFIndex length = (CFIndex)value.length; + CFMutableAttributedStringRef attributed = CFAttributedStringCreateMutable(kCFAllocatorDefault, 0); + if (attributed == NULL) { + return NULL; + } + CFAttributedStringReplaceString(attributed, CFRangeMake(0, 0), (CFStringRef)value); + CFAttributedStringSetAttribute(attributed, CFRangeMake(0, length), kCTFontAttributeName, (CTFontRef)base); + if (color != NULL) { + CFAttributedStringSetAttribute(attributed, CFRangeMake(0, length), kCTForegroundColorAttributeName, color); + } + CTLineRef line = CTLineCreateWithAttributedString(attributed); + if (line == NULL) { + CFRelease(attributed); + return NULL; + } + BOOL replaced = NO; + CFArrayRef runs = CTLineGetGlyphRuns(line); + CFIndex runCount = runs != NULL ? CFArrayGetCount(runs) : 0; + for (CFIndex index = 0; index < runCount; index++) { + CTRunRef run = (CTRunRef)CFArrayGetValueAtIndex(runs, index); + CFDictionaryRef runAttributes = CTRunGetAttributes(run); + CTFontRef runFont = runAttributes != NULL ? (CTFontRef)CFDictionaryGetValue(runAttributes, kCTFontAttributeName) : NULL; + if (!viva_mono_font_is_last_resort(runFont)) { + continue; + } + CFRange runRange = CTRunGetStringRange(run); + CFIndex end = runRange.location + runRange.length; + for (CFIndex at = runRange.location; at < end;) { + NSRange cluster = [value rangeOfComposedCharacterSequenceAtIndex:(NSUInteger)at]; + if (cluster.length == 0) { + break; + } + NSString *text = [value substringWithRange:cluster]; + NSString *family = viva_mono_face_fallback(text, face); + if (family == nil) { + family = viva_mono_fallback_family(text); + } + NSFont *fallback = family != nil ? viva_mono_replacement_font(family, size, bold) : nil; + if (fallback != nil) { + CFAttributedStringSetAttribute(attributed, + CFRangeMake((CFIndex)cluster.location, (CFIndex)cluster.length), + kCTFontAttributeName, (CTFontRef)fallback); + replaced = YES; + } + at = (CFIndex)NSMaxRange(cluster); + } + } + if (!replaced) { + CFRelease(attributed); + return line; + } + CFRelease(line); + line = CTLineCreateWithAttributedString(attributed); + CFRelease(attributed); + return line; +} + +// viva_text_system_thickening reports whether the user leaves the system's own font +// smoothing on, the weight AppKit's text starts at: AppleFontSmoothing absent or nonzero +// means on, zero (or a value that is not a number, as AppKit reads it) off. A bitmap +// context does not heed the setting, so the engine asks for it here, once, at its start; +// standardUserDefaults reads the argument domain too, which is how tests pin it. +int viva_text_system_thickening(void) { + @autoreleasepool { + NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; + if ([defaults objectForKey:@"AppleFontSmoothing"] == nil) { + return 1; + } + return [defaults integerForKey:@"AppleFontSmoothing"] != 0; + } +} + +// viva_text_thickening is whether Viva draws its text with a thicker stroke, as AppKit draws +// the system's own text: CoreText's font smoothing, which darkens the stems. Off is the +// font's own outlines, so the glyphs stay the weight the font gives them (measured against +// AppKit text: smoothing draws 16 to 45 percent more ink, the lighter the text the more). +// It starts at the system's own weight (viva_text_system_thickening) and is then the +// weight the application asked for. +static int viva_text_thickening = 0; + +int viva_text_set_thickening(int thickening) { + int previous = viva_text_thickening; + viva_text_thickening = thickening; + return previous != thickening; +} + +// viva_prepare_text_context sets a bitmap context up to draw text the way AppKit draws it. +void viva_prepare_text_context(CGContextRef context, CGFloat scale) { + CGContextScaleCTM(context, scale, scale); + CGContextSetTextMatrix(context, CGAffineTransformIdentity); + CGContextSetShouldSmoothFonts(context, viva_text_thickening != 0); +} + +// viva_draw_terminal_preedit draws a terminal's preedit text the way the terminal draws its +// own line: every character on the cells of the grid, a plain ASCII one at the left of its +// cell and any other centered in the cells it takes (two for a wide one), with its combining +// marks. The native editor and the headless renderer both draw it here, so they can only ever +// look the same, and the text does not move when it is committed to the grid. +void viva_draw_terminal_preedit( + CGContextRef context, NSString *shown, CGFloat fontSize, int monoFace, + NSColor *color, CGFloat cellWidth, CGFloat baseline +) { + // The face's font, with the installed fallback for what no family of it draws. + NSFont *font = viva_mono_font(fontSize, 0, monoFace); + NSUInteger column = 0; + for (NSUInteger at = 0; at < shown.length;) { + int cells = 0; + NSUInteger end = at + viva_terminal_step(shown, at, &cells); + for (int marks = 0; end < shown.length;) { + NSUInteger next = viva_terminal_step(shown, end, &marks); + if (marks != 0) { + break; + } + end += next; + } + NSString *cluster = [shown substringWithRange:NSMakeRange(at, end - at)]; + CTLineRef line = viva_mono_fallback_line(cluster, font, monoFace, color.CGColor); + if (line != NULL) { + CGFloat x = (CGFloat)column * cellWidth; + unichar only = cluster.length == 1 ? [cluster characterAtIndex:0] : 0; + if (cells > 0 && !(only >= 0x20 && only < 0x7F)) { + CGFloat width = CTLineGetTypographicBounds(line, NULL, NULL, NULL); + x += ((CGFloat)cells * cellWidth - width) / 2; + } + CGContextSetTextPosition(context, x, baseline); + CTLineDraw(line, context); + CFRelease(line); + } + column += (NSUInteger)cells; + at = end; + } +} + +// viva_new_editor_line is the geometry of the text the editor shows: one shaped line +// shared with layout for proportional text, the terminal's cells for a terminal. A line +// that was not made could not be shaped. +viva_editor_line viva_new_editor_line(NSString *shown, CGFloat fontSize, CGFloat fontWeight, BOOL terminal, CGFloat cellWidth) { + viva_editor_line line = {NULL, nil, 0}; + if (terminal) { + line.grid = [shown copy]; + line.cell = cellWidth; + } else { + line.shaped = viva_shared_text_line(shown, fontSize, fontWeight); + } + return line; +} + +CGFloat viva_editor_alignment_inset(viva_editor_line line, CGFloat width, int alignment, BOOL terminal) { + if (terminal || line.shaped == NULL || (alignment != 1 && alignment != 2)) { + return 0; + } + CGFloat free = MAX(0, width - line.shaped->width); + return alignment == 1 ? free / 2 : free; +} + +CGFloat viva_editor_visible_caret(CGFloat offset, CGFloat width, int alignment, BOOL terminal) { + if (alignment != 2 || terminal) { + return offset; + } + return MIN(offset, MAX(0, width - 2)); +} + +// viva_baseline is the height of the baseline above the bottom of a label's texture, +// in points. The baseline is the same row every backend uses (platform.LabelBaseline): +// a fixed distance below the middle of the line box, on a whole physical pixel, so +// the font's own ascent and descent do not move the text. +CGFloat viva_baseline(CGFloat height, CGFloat fontSize, CGFloat pixelScale) { + CGFloat rows = MAX(1.0, ceil(height * pixelScale)); + CGFloat fromTop = floor(rows * 0.5 + VIVA_BASELINE_BELOW_CENTER * fontSize * pixelScale + 1e-6); + return (rows - fromTop) / pixelScale; +} + +// viva_fixed_baseline is the height above a texture's bottom of the row a canvas worked out +// for a fixed-pitch line, counted from the texture's top in points +// (platform.TextLabel.Baseline), on a whole physical pixel. +CGFloat viva_fixed_baseline(CGFloat height, CGFloat fromTop, CGFloat pixelScale) { + CGFloat rows = MAX(1.0, ceil(height * pixelScale)); + return (rows - floor(fromTop * pixelScale + 0.5)) / pixelScale; +} + +int viva_text_line_rasterize( + const viva_text_line *line, + double font_size, + double scale, + size_t width, + size_t height, + double red, + double green, + double blue, + double alpha, + unsigned char *pixels +) { + if (line == NULL || pixels == NULL || font_size <= 0 || scale <= 0 || + width < 1 || height < 1 || width > 16384 || height > 16384 || + width > SIZE_MAX / 4 || height > SIZE_MAX / (width * 4)) { + return 1; + } + @autoreleasepool { + memset(pixels, 0, width * height * 4); + CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); + CGContextRef context = CGBitmapContextCreate( + pixels, width, height, 8, width * 4, colorSpace, + kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little + ); + CGColorSpaceRelease(colorSpace); + if (context == NULL) { + return 1; + } + viva_prepare_text_context(context, scale); + CGColorRef color = CGColorCreateSRGB(red, green, blue, alpha); + CGFloat logicalHeight = (CGFloat)height / (CGFloat)scale; + CGFloat baseline = viva_baseline(logicalHeight, font_size, scale); + viva_draw_text_line(context, line, color, 0, baseline); + CGColorRelease(color); + CGContextRelease(context); + return 0; + } +} + +// viva_text_input_texture rasterizes the native editor's current appearance: +// the shown text (bullets for a password), the selection or composition, and +// the caret when it is in its visible phase. It returns a retained texture, or +// nil when the frame cannot be rasterized. +id viva_text_input_texture( + id device, + CGFloat scale, + NSString *shown, + CGFloat fontSize, + CGFloat fontWeight, + NSColor *color, + NSSize frameSize, + NSRange selectedRange, + BOOL hasMarked, + NSRange markedRange, + BOOL caretVisible, + BOOL terminal, + BOOL hideNativeOverlays, + int monoFace, + CGFloat cellWidth, + CGFloat cellBaseline, + int alignment +) { + size_t pixelWidth = (size_t)MAX(1.0, ceil(frameSize.width * scale)); + size_t pixelHeight = (size_t)MAX(1.0, ceil(frameSize.height * scale)); + if (pixelWidth > 16384 || pixelHeight > 16384 || pixelWidth > SIZE_MAX / 4) { + return nil; + } + size_t rowBytes = pixelWidth * 4; + if (pixelHeight > SIZE_MAX / rowBytes) { + return nil; + } + void *pixels = calloc(pixelHeight, rowBytes); + if (pixels == NULL) { + return nil; + } + + CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); + CGContextRef context = CGBitmapContextCreate( + pixels, + pixelWidth, + pixelHeight, + 8, + rowBytes, + colorSpace, + kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little + ); + CGColorSpaceRelease(colorSpace); + if (context == NULL) { + free(pixels); + return nil; + } + + viva_prepare_text_context(context, scale); + viva_editor_line line = viva_new_editor_line(shown, fontSize, fontWeight, terminal, cellWidth); + if (!viva_editor_line_made(line)) { + CGContextRelease(context); + free(pixels); + return nil; + } + CGFloat inset = viva_editor_alignment_inset(line, frameSize.width, alignment, terminal); + + CGFloat ascent = 0; + CGFloat descent = 0; + CGFloat baseline = 0; + if (terminal) { + // Sit on the same row as the terminal's own text, whatever the composed + // characters' fallback fonts measure. The primary font alone stands in for the + // ascent and descent of the caret and selection, the fallbacks never taking part. + CTFontRef gridFont = CTFontCreateWithName((CFStringRef)viva_mono_font_primary(fontSize, 0, monoFace).fontName, fontSize, NULL); + ascent = CTFontGetAscent(gridFont); + descent = CTFontGetDescent(gridFont); + CFRelease(gridFont); + baseline = cellBaseline > 0 + ? viva_fixed_baseline(frameSize.height, cellBaseline, ceil(scale)) + : viva_baseline(frameSize.height, fontSize, ceil(scale)); + } else { + ascent = line.shaped->ascent; + descent = line.shaped->descent; + // The editor's text stands on the row the unfocused label stands on, so + // focusing a field does not move it; only the caret and selection use + // the line's own ascent and descent. + baseline = viva_baseline(frameSize.height, fontSize, ceil(scale)); + } + NSUInteger textLength = shown.length; + NSRange selected = viva_clamp_range(selectedRange, textLength); + // Fully transparent text means an editor that exists only to receive input + // (an OTP field paints its own slots): draw none of it, caret and selection + // included. A translucent color still gets its caret and highlight. + NSColor *textColor = [color colorUsingColorSpace:[NSColorSpace sRGBColorSpace]]; + BOOL invisible = textColor != nil && textColor.alphaComponent <= 0.0; + double spans[2 * VIVA_SELECTION_PIECES]; + if (selected.length > 0 && !terminal && !hideNativeOverlays && !invisible) { + size_t count = viva_text_spans(line, selected, terminal, spans, VIVA_SELECTION_PIECES); + CGContextSetRGBFillColor(context, 0.18, 0.42, 0.90, 0.55); + for (size_t piece = 0; piece < count; piece++) { + CGContextFillRect( + context, + CGRectMake(inset + spans[2 * piece], baseline - descent, MAX(1.0, spans[2 * piece + 1]), ascent + descent) + ); + } + } + + if (terminal) { + viva_draw_terminal_preedit(context, shown, fontSize, monoFace, color, cellWidth, baseline); + } else { + // The text is drawn as the one line the offsets above and below are read from, so + // selection, caret and glyphs agree. + viva_draw_text_line(context, line.shaped, color.CGColor, inset, baseline); + } + + if (invisible) { + // nothing more to draw + } else if (hasMarked) { + NSRange marked = viva_clamp_range(markedRange, textLength); + size_t count = viva_text_spans(line, marked, terminal, spans, VIVA_SELECTION_PIECES); + CGContextSetRGBFillColor(context, 0.55, 0.72, 1.0, 1.0); + for (size_t piece = 0; piece < count; piece++) { + // A terminal's row is only as tall as its text, so below the descenders is the + // edge of the row, not two points further down, where nothing would be drawn. + CGContextFillRect(context, CGRectMake(inset + spans[2 * piece], MAX(baseline - descent - 2.0, 0.0), MAX(1.0, spans[2 * piece + 1]), 1.0)); + } + } else if (selected.length == 0 && caretVisible && !terminal && !hideNativeOverlays) { + CGFloat caret = viva_editor_visible_caret(inset + viva_text_offset(line, selected.location, terminal), frameSize.width, alignment, terminal); + NSColor *caretColor = [color colorUsingColorSpace:[NSColorSpace sRGBColorSpace]]; + CGContextSetRGBFillColor( + context, + caretColor.redComponent, + caretColor.greenComponent, + caretColor.blueComponent, + MAX(caretColor.alphaComponent, 0.9) + ); + CGContextFillRect(context, CGRectMake(caret, baseline - descent, 2.0, ascent + descent)); + } + + MTLTextureDescriptor *descriptor = [MTLTextureDescriptor + texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm + width:pixelWidth + height:pixelHeight + mipmapped:NO]; + descriptor.storageMode = MTLStorageModeShared; + descriptor.usage = MTLTextureUsageShaderRead; + id texture = [device newTextureWithDescriptor:descriptor]; + if (texture != nil) { + [texture replaceRegion:MTLRegionMake2D(0, 0, pixelWidth, pixelHeight) + mipmapLevel:0 + withBytes:pixels + bytesPerRow:rowBytes]; + } + + viva_editor_line_free(line); + CGContextRelease(context); + free(pixels); + if (texture == nil) { + return nil; + } + viva_text_texture_rebuild_count++; + return texture; +} + diff --git a/internal/platform/darwin/native.m b/internal/platform/darwin/native.m index 7272d016b..173329dbd 100644 --- a/internal/platform/darwin/native.m +++ b/internal/platform/darwin/native.m @@ -1,38 +1,17 @@ -#import -#include -#import -#import -#import - -#include -#include -#include -#include - -#include "native.h" +#import "core.h" #include "cursor_owner_darwin.h" #include "label_geometry.h" #include "main_menu_darwin.h" static uint64_t viva_process_start_ticks; -static uint64_t viva_gpu_submission_count; -static uint64_t viva_gpu_draw_call_count; -static uint64_t viva_rectangle_instance_count; -static uint64_t viva_gpu_uploaded_bytes; -static uint64_t viva_gpu_full_rebuild_count; -static uint64_t viva_gpu_partial_update_count; static uint64_t viva_pointer_event_count; static uint64_t viva_text_event_count; -static uint64_t viva_text_texture_rebuild_count; -static uint64_t viva_label_texture_rebuild_count; -static uint64_t viva_label_update_count; static uint64_t viva_resize_event_count; static uint64_t viva_key_event_count; static uint64_t viva_accessibility_update_count; static uint64_t viva_close_request_count; static uint64_t viva_scroll_event_count; static double viva_scroll_last_pixel_y; -static NSUInteger viva_label_initial_count; /* The compiled shader library the application passes as it opens its windows, * kept after the first one compiled its pipelines: a window that makes its @@ -1084,2602 +1063,36 @@ static int viva_modifier_flags(NSEventModifierFlags flags) { return modifiers; } -static NSRange viva_clamp_range(NSRange range, NSUInteger length) { - if (range.location == NSNotFound) { - return NSMakeRange(length, 0); - } - NSUInteger start = MIN(range.location, length); - NSUInteger remaining = length - start; - return NSMakeRange(start, MIN(range.length, remaining)); -} - -// A line of proportional text is shaped once by CoreText, in the system font with its font -// fallback, and everything that needs a position asks that line: the width -// layout uses, the glyphs a label draws, the caret, the selection and the character a click -// lands on. The engine in Go (text_engine.go) caches the lines; vivaShapedLine is how the -// drawing here reaches the same cache. -extern viva_text_line *vivaShapedLine(const unsigned char *utf8, size_t length, double size, double weight); -extern viva_text_line *vivaShapedLineStyle(const unsigned char *utf8, size_t length, double size, double weight, int italic); - -// viva_interface_family is the family viva_text_set_family last named, "" for the -// system font. A plain C buffer, not an NSString: nothing here manages memory for -// the interface font, and the name is read under the shaping the engine serializes. -static char viva_interface_family[256] = ""; - -// viva_system_font is the proportional font that measurement, labels and the editor all -// use (a retained CTFont). It is an NSFont, which is a CTFont already. With a family -// named, its face of that family at the weight stands in for the system font; a family -// the system does not have falls back to the system font, as AppKit does for a name. -static CTFontRef viva_system_font(CGFloat size, CGFloat weight) { - if (viva_interface_family[0] != '\0') { - NSString *family = [NSString stringWithUTF8String:viva_interface_family]; - if (family != nil) { - // The weight is the system font's own continuous scale (NSFontWeight), so a - // family's regular, medium, semibold and bold faces are told apart as they are - // in the system font; the nearest face the family has stands in for one it - // lacks. NSFontManager's weight is a 0-15 table that cannot say medium. - NSFontDescriptor *descriptor = [NSFontDescriptor fontDescriptorWithFontAttributes:@{ - NSFontFamilyAttribute: family, - NSFontTraitsAttribute: @{NSFontWeightTrait: @(weight)}, - }]; - NSFont *named = [NSFont fontWithDescriptor:descriptor size:size]; - if (named != nil) { - return (CTFontRef)CFRetain(named); - } - } - } - NSFont *font = [NSFont systemFontOfSize:size weight:weight]; - return font != nil ? (CTFontRef)CFRetain(font) : NULL; -} - -static CTFontRef viva_system_font_style(CGFloat size, CGFloat weight, BOOL italic) { - CTFontRef base = viva_system_font(size, weight); - if (!italic || base == NULL) { - return base; - } - // The family's own italic face when it has one. When it has none the base font is - // kept and the glyphs are slanted as they are drawn (viva_draw_text_line), the same - // slant the fallback fonts of a line get. - CTFontRef face = CTFontCreateCopyWithSymbolicTraits(base, size, NULL, kCTFontItalicTrait, kCTFontItalicTrait); - if (face == NULL) { - return base; - } - CFRelease(base); - return face; -} - -void viva_text_set_family(const char *family) { - if (family == NULL) { - viva_interface_family[0] = '\0'; - return; - } - strncpy(viva_interface_family, family, sizeof(viva_interface_family) - 1); - viva_interface_family[sizeof(viva_interface_family) - 1] = '\0'; -} - -viva_text_line *viva_text_line_create_style(const unsigned char *utf8, size_t length, double font_size, double font_weight, int italic) { - @autoreleasepool { - static const unsigned char empty[1] = {0}; - CFStringRef string = CFStringCreateWithBytes( - kCFAllocatorDefault, utf8 != NULL ? utf8 : empty, utf8 != NULL ? (CFIndex)length : 0, kCFStringEncodingUTF8, false); - if (string == NULL) { - return NULL; - } - CTFontRef font = viva_system_font_style(font_size, font_weight, italic != 0); - if (font == NULL) { - CFRelease(string); - return NULL; - } - // The color comes from the context when the line is drawn, so one line serves every color. - const void *keys[] = {kCTFontAttributeName, kCTForegroundColorFromContextAttributeName}; - const void *values[] = {font, kCFBooleanTrue}; - CFDictionaryRef attributes = CFDictionaryCreate( - kCFAllocatorDefault, keys, values, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); - CFAttributedStringRef attributed = CFAttributedStringCreate(kCFAllocatorDefault, string, attributes); - CTLineRef line = CTLineCreateWithAttributedString(attributed); - CFRelease(attributed); - CFRelease(attributes); - viva_text_line *shaped = line != NULL ? calloc(1, sizeof(viva_text_line)) : NULL; - if (shaped == NULL) { - if (line != NULL) { - CFRelease(line); - } - CFRelease(font); - CFRelease(string); - return NULL; - } - CGFloat ascent = 0, descent = 0, leading = 0; - shaped->width = CTLineGetTypographicBounds(line, &ascent, &descent, &leading); - if (ascent + descent <= 0) { - // A line with no glyphs reports zero for both, which would give an empty - // field's caret zero height: the font's own metrics stand in. - ascent = CTFontGetAscent(font); - descent = CTFontGetDescent(font); - } - shaped->ascent = ascent; - shaped->descent = descent; - shaped->line = (void *)line; - shaped->string = (void *)string; - shaped->references = 1; - shaped->italic = italic != 0; - CFRelease(font); - return shaped; - } -} - -viva_text_line *viva_text_line_create(const unsigned char *utf8, size_t length, double font_size, double font_weight) { - return viva_text_line_create_style(utf8, length, font_size, font_weight, 0); -} - -void viva_text_line_retain(viva_text_line *line) { - if (line != NULL) { - __atomic_fetch_add(&line->references, 1, __ATOMIC_RELAXED); - } -} - -void viva_text_line_release(viva_text_line *line) { - if (line != NULL && __atomic_fetch_sub(&line->references, 1, __ATOMIC_ACQ_REL) == 1) { - CFRelease((CTLineRef)line->line); - CFRelease((CFStringRef)line->string); - free(line); - } -} - -// viva_cluster_start moves offset back to the start of the character cluster it falls in. -static CFIndex viva_cluster_start(CFStringRef string, size_t offset) { - CFIndex length = CFStringGetLength(string); - if (offset >= (size_t)length) { - return length; - } - return CFStringGetRangeOfComposedCharactersAtIndex(string, (CFIndex)offset).location; -} - -double viva_text_line_caret(const viva_text_line *line, size_t offset) { - CGFloat secondary = 0; - return CTLineGetOffsetForStringIndex((CTLineRef)line->line, viva_cluster_start((CFStringRef)line->string, offset), &secondary); -} - -size_t viva_text_line_index_at(const viva_text_line *line, double x) { - CFStringRef string = (CFStringRef)line->string; - CTLineRef ct = (CTLineRef)line->line; - CFIndex length = CFStringGetLength(string); - if (length == 0) { - return 0; - } - CFIndex index = CTLineGetStringIndexForPosition(ct, CGPointMake(x, 0)); - if (index == kCFNotFound) { - return x <= 0 ? 0 : (size_t)length; - } - index = MIN(index, length); - if (index < length) { - CFRange cluster = CFStringGetRangeOfComposedCharactersAtIndex(string, index); - if (cluster.location != index) { - CGFloat secondary = 0; - CGFloat start = CTLineGetOffsetForStringIndex(ct, cluster.location, &secondary); - CGFloat end = CTLineGetOffsetForStringIndex(ct, cluster.location + cluster.length, &secondary); - index = fabs(x - start) <= fabs(x - end) ? cluster.location : cluster.location + cluster.length; - } - } - return (size_t)index; -} - -// The most extents viva_text_line_selection tells apart before it folds the rest into the -// last: a selection crossing a change of direction more often than this is not text. -#define VIVA_SELECTION_PIECES 32 - -size_t viva_text_line_selection(const viva_text_line *line, size_t start, size_t end, double *spans, size_t capacity) { - CFStringRef string = (CFStringRef)line->string; - CTLineRef ct = (CTLineRef)line->line; - CFIndex from = viva_cluster_start(string, start); - CFIndex to = viva_cluster_start(string, end); - if (from > to) { - CFIndex swap = from; - from = to; - to = swap; - } - if (capacity == 0) { - return 0; - } - double left[VIVA_SELECTION_PIECES], right[VIVA_SELECTION_PIECES]; - size_t count = 0; - CGFloat secondary = 0; - // A cluster stands between its leading edge (the secondary offset of its first unit, where - // a boundary between two directions has two) and the trailing edge of its last, which is - // the primary offset of the unit after it. - for (CFIndex at = from; at < to;) { - CFRange cluster = CFStringGetRangeOfComposedCharactersAtIndex(string, at); - CFIndex next = MIN(cluster.location + cluster.length, to); - CGFloat leading = 0; - CTLineGetOffsetForStringIndex(ct, at, &leading); - CGFloat trailing = CTLineGetOffsetForStringIndex(ct, next, &secondary); - double lo = MIN(leading, trailing), hi = MAX(leading, trailing); - if (count > 0 && lo <= right[count - 1] + 0.01 && hi >= left[count - 1] - 0.01) { - left[count - 1] = MIN(left[count - 1], lo); - right[count - 1] = MAX(right[count - 1], hi); - } else if (count < VIVA_SELECTION_PIECES) { - left[count] = lo; - right[count++] = hi; - } else { - left[count - 1] = MIN(left[count - 1], lo); - right[count - 1] = MAX(right[count - 1], hi); - } - at = next; - } - if (count == 0) { - // An empty selection is the caret. - left[0] = right[0] = CTLineGetOffsetForStringIndex(ct, from, &secondary); - count = 1; - } - // Pieces of the selection that the reordering put side by side are one extent. - for (size_t i = 1; i < count; i++) { - for (size_t j = i; j > 0 && left[j] < left[j - 1]; j--) { - double l = left[j], r = right[j]; - left[j] = left[j - 1]; - right[j] = right[j - 1]; - left[j - 1] = l; - right[j - 1] = r; - } - } - size_t written = 0; - for (size_t i = 0; i < count; i++) { - if (written > 0 && left[i] <= spans[2 * (written - 1)] + spans[2 * (written - 1) + 1] + 0.01) { - double merged = MAX(spans[2 * (written - 1)] + spans[2 * (written - 1) + 1], right[i]); - spans[2 * (written - 1) + 1] = merged - spans[2 * (written - 1)]; - } else if (written < capacity) { - spans[2 * written] = left[i]; - spans[2 * written + 1] = right[i] - left[i]; - written++; - } - } - return written; -} - -// viva_shared_text_line is the engine's line for shown in the system font, retained for the -// caller to release with viva_text_line_release. -static viva_text_line *viva_shared_text_line(NSString *shown, CGFloat fontSize, CGFloat weight) { - NSData *bytes = [shown dataUsingEncoding:NSUTF8StringEncoding]; - return vivaShapedLine(bytes != nil ? (const unsigned char *)bytes.bytes : NULL, bytes != nil ? bytes.length : 0, fontSize, weight); -} - -static viva_text_line *viva_shared_text_line_style(NSString *shown, CGFloat fontSize, CGFloat weight, BOOL italic) { - NSData *bytes = [shown dataUsingEncoding:NSUTF8StringEncoding]; - return vivaShapedLineStyle(bytes != nil ? (const unsigned char *)bytes.bytes : NULL, bytes != nil ? bytes.length : 0, fontSize, weight, italic ? 1 : 0); -} - -// viva_draw_text_line draws the shaped line in one call, its origin at x on baseline, in -// color (the line carries none, so the same line serves every color). -// VIVA_SYNTHETIC_ITALIC_SLANT is the shear of a glyph drawn in italics from a font that has -// no italic face: about eleven degrees, as the tilt of the system font's own italic. -#define VIVA_SYNTHETIC_ITALIC_SLANT 0.2 - -// viva_run_needs_slant says whether a run of an italic line must be slanted: its font has no -// italic face, as a CJK fallback font has none. A font of color glyphs (emoji) is left upright. -static BOOL viva_run_needs_slant(CTRunRef run) { - CFDictionaryRef attributes = CTRunGetAttributes(run); - CTFontRef font = attributes != NULL ? (CTFontRef)CFDictionaryGetValue(attributes, kCTFontAttributeName) : NULL; - if (font == NULL) { - return NO; - } - CTFontSymbolicTraits traits = CTFontGetSymbolicTraits(font); - return (traits & (kCTFontItalicTrait | kCTFontColorGlyphsTrait)) == 0; -} - -static void viva_draw_text_line(CGContextRef context, const viva_text_line *line, CGColorRef color, CGFloat x, CGFloat baseline) { - CGContextSaveGState(context); - CGContextSetFillColorWithColor(context, color); - if (!line->italic) { - CGContextSetTextPosition(context, x, baseline); - CTLineDraw((CTLineRef)line->line, context); - } else { - // Run by run: the runs whose font has no italic face are drawn under a shear about - // the baseline. The glyph positions of a run are relative to the line's origin, so - // the shear leaves them where the line put them and only tilts the glyphs. - CFArrayRef runs = CTLineGetGlyphRuns((CTLineRef)line->line); - for (CFIndex index = 0, count = CFArrayGetCount(runs); index < count; index++) { - CTRunRef run = (CTRunRef)CFArrayGetValueAtIndex(runs, index); - CGFloat slant = viva_run_needs_slant(run) ? VIVA_SYNTHETIC_ITALIC_SLANT : 0; - CGContextSetTextMatrix(context, CGAffineTransformMake(1, 0, slant, 1, x, baseline)); - CTRunDraw(run, context, CFRangeMake(0, 0)); - } - // The text matrix is not part of the saved state, and other labels set only a position. - CGContextSetTextMatrix(context, CGAffineTransformIdentity); - } - CGContextRestoreGState(context); -} - -// The geometry of the text a native editor shows: the shaped line of proportional text, or -// a terminal's preedit, which is laid on the terminal's cells and not on the advances of -// its font: the text, and the width of one cell. -typedef struct { - viva_text_line *shaped; - NSString *grid; - CGFloat cell; -} viva_editor_line; - -static void viva_editor_line_free(viva_editor_line line) { - viva_text_line_release(line.shaped); - [line.grid release]; -} - -// viva_editor_line_made says whether the line could be made. -static BOOL viva_editor_line_made(viva_editor_line line) { - return line.shaped != NULL || line.grid != nil; -} - -// viva_terminal_step reads the character of shown at UTF-16 index `at`: how many units it -// takes, and how many cells (see vivaTerminalCells; a combining mark has none). -static NSUInteger viva_terminal_step(NSString *shown, NSUInteger at, int *cells) { - unichar first = [shown characterAtIndex:at]; - uint32_t point = first; - NSUInteger length = 1; - if (CFStringIsSurrogateHighCharacter(first) && at + 1 < shown.length) { - unichar second = [shown characterAtIndex:at + 1]; - if (CFStringIsSurrogateLowCharacter(second)) { - point = CFStringGetLongCharacterForSurrogatePair(first, second); - length = 2; - } - } - *cells = vivaTerminalCells(point); - return length; -} - -// viva_terminal_column is the cell column of the boundary before the UTF-16 unit `index` -// of shown, counted from the first cell of the text. -static NSUInteger viva_terminal_column(NSString *shown, NSUInteger index) { - NSUInteger column = 0; - for (NSUInteger at = 0; at < index && at < shown.length;) { - int cells = 0; - NSUInteger length = viva_terminal_step(shown, at, &cells); - if (at + length > index) { - break; - } - column += (NSUInteger)cells; - at += length; - } - return column; -} - -// viva_text_offset is where the editor draws the boundary before the UTF-16 unit `index` -// of shown, from the left of the text. -static CGFloat viva_text_offset(viva_editor_line line, NSUInteger index, BOOL terminal) { - if (terminal) { - return (CGFloat)viva_terminal_column(line.grid, index) * line.cell; - } - return viva_text_line_caret(line.shaped, index); -} - -// viva_text_spans is the extents of range in the editor, left to right. -static size_t viva_text_spans(viva_editor_line line, NSRange range, BOOL terminal, double *spans, size_t capacity) { - if (terminal) { - CGFloat start = viva_text_offset(line, range.location, terminal); - CGFloat end = viva_text_offset(line, NSMaxRange(range), terminal); - spans[0] = MIN(start, end); - spans[1] = fabs(end - start); - return 1; - } - return viva_text_line_selection(line.shaped, range.location, NSMaxRange(range), spans, capacity); -} - -// viva_text_index_at is the boundary of shown nearest to x, the inverse of viva_text_offset. -static NSUInteger viva_text_index_at(viva_editor_line line, NSString *shown, CGFloat x, BOOL terminal) { - if (!terminal) { - return viva_text_line_index_at(line.shaped, x); - } - // The boundary between characters whose cell edge is nearest x; a boundary inside a - // character with its combining marks is none, and of two on one edge the later wins. - NSUInteger position = 0; - CGFloat nearest = fabs(x); - NSUInteger column = 0; - for (NSUInteger at = 0; at < shown.length;) { - int cells = 0; - at += viva_terminal_step(shown, at, &cells); - column += (NSUInteger)cells; - if (at < shown.length && [shown rangeOfComposedCharacterSequenceAtIndex:at].location != at) { - continue; - } - CGFloat distance = fabs(x - (CGFloat)column * line.cell); - if (distance <= nearest) { - nearest = distance; - position = at; - } - } - return position; -} - -// viva_mono_font is the system fixed-pitch font, the one every fixed-pitch label -// and the cell metrics are built from. -// -// A face from 2 up stands for an installed family and the families that draw what it -// lacks; viva_register_mono_family teaches the numbers, in registration order. -#define VIVA_MONO_FAMILY_SLOTS 4098 /* the 2 built-in faces and gfx.MaxMonoFaces */ -static NSString *viva_mono_families[VIVA_MONO_FAMILY_SLOTS]; -static NSArray *viva_mono_fallbacks[VIVA_MONO_FAMILY_SLOTS]; -static BOOL viva_mono_classic[VIVA_MONO_FAMILY_SLOTS]; -static NSObject *viva_mono_family_lock(void) { - static NSObject *lock; - static dispatch_once_t once; - dispatch_once(&once, ^{ lock = [[NSObject alloc] init]; }); - return lock; -} - -void viva_register_mono_family(int face, const char *utf8, int classic, const char *fallbacks) { - if (face < 2 || face >= VIVA_MONO_FAMILY_SLOTS) { - return; - } - @synchronized(viva_mono_family_lock()) { - [viva_mono_families[face] release]; - [viva_mono_fallbacks[face] release]; - viva_mono_families[face] = (utf8 != NULL && utf8[0] != '\0') ? [[NSString alloc] initWithUTF8String:utf8] : nil; - viva_mono_classic[face] = classic != 0; - // The fallbacks arrive as one name per line. - NSString *joined = fallbacks != NULL ? [[NSString alloc] initWithUTF8String:fallbacks] : nil; - viva_mono_fallbacks[face] = (joined != nil && joined.length > 0) ? [[joined componentsSeparatedByString:@"\n"] retain] : nil; - [joined release]; - } -} - -// viva_mono_face_traits copies what a face stands for: its primary family (nil for a -// built-in one), whether the built-in primary is the classic face, and its fallback -// families in order. -static void viva_mono_face_traits(int face, NSString **family, BOOL *classic, NSArray **fallbacks) { - *family = nil; - *classic = face == 1; - *fallbacks = nil; - if (face < 2 || face >= VIVA_MONO_FAMILY_SLOTS) { - return; - } - @synchronized(viva_mono_family_lock()) { - *family = [[viva_mono_families[face] retain] autorelease]; - *classic = viva_mono_classic[face]; - *fallbacks = [[viva_mono_fallbacks[face] retain] autorelease]; - } -} - -// viva_mono_font_on_a_grid reports whether the font advances every printable ASCII -// character by the same width: the one property a terminal cell grid needs. -// -// The font's own fixed-pitch bit is not enough to ask. Families built for coding -// (Nerd Font patches, ligature builds) often leave it clear while drawing on a grid -// all the same, and the bit alone kept them out of the list. The advances are -// compared with a percent of the cell to spare, because a grid font still rounds a -// glyph by a hair (Roboto Mono for Powerline gives '-' 7.207 where its cell is -// 7.201) while a proportional font's differ by a fraction of the cell. -static BOOL viva_mono_font_on_a_grid(NSFont *font) { - if (font.isFixedPitch) { - return YES; - } - enum { first = 0x20, last = 0x7E, count = last - first + 1 }; - UniChar characters[count]; - CGGlyph glyphs[count]; - CGSize advances[count]; - for (CFIndex index = 0; index < count; index++) { - characters[index] = (UniChar)(first + index); - } - CTFontRef ctFont = (CTFontRef)font; - if (!CTFontGetGlyphsForCharacters(ctFont, characters, glyphs, count)) { - return NO; // it cannot draw one of them, so it is no terminal face - } - CTFontGetAdvancesForGlyphs(ctFont, kCTFontOrientationHorizontal, glyphs, advances, count); - CGFloat cell = advances[0].width; - if (cell <= 0.0) { - return NO; - } - for (CFIndex index = 1; index < count; index++) { - if (fabs(advances[index].width - cell) > cell * 0.01) { - return NO; - } - } - return YES; -} - -char *viva_list_font_families(void) { - @autoreleasepool { - NSFontManager *manager = [NSFontManager sharedFontManager]; - NSMutableArray *names = [NSMutableArray array]; - for (NSString *family in [manager availableFontFamilies]) { - if ([family hasPrefix:@"."]) { - continue; - } - [names addObject:family]; - } - [names sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)]; - return strdup([[names componentsJoinedByString:@"\n"] UTF8String]); - } -} - -char *viva_list_mono_families(void) { - @autoreleasepool { - NSFontManager *manager = [NSFontManager sharedFontManager]; - NSMutableArray *names = [NSMutableArray array]; - for (NSString *family in [manager availableFontFamilies]) { - if ([family hasPrefix:@"."]) { - continue; - } - NSFont *font = [manager fontWithFamily:family traits:0 weight:5 size:12]; - if (font != nil && viva_mono_font_on_a_grid(font)) { - [names addObject:family]; - } - } - [names sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)]; - return strdup([[names componentsJoinedByString:@"\n"] UTF8String]); - } -} - -// viva_mono_base_font is the primary font of a face, without its fallbacks. -static NSFont *viva_mono_base_font(CGFloat size, CGFloat weight, NSString *family, BOOL classic) { - if (family != nil) { - NSFont *named = [[NSFontManager sharedFontManager] fontWithFamily:family - traits:(weight >= 0.34 ? NSBoldFontMask : 0) - weight:5 - size:size]; - if (named != nil) { - return named; - } - } - if (classic) { - NSFont *classicFont = [NSFont userFixedPitchFontOfSize:size]; - if (classicFont != nil) { - return classicFont; - } - } - NSFont *font = [NSFont monospacedSystemFontOfSize:size weight:weight]; - return font != nil ? font : [NSFont userFixedPitchFontOfSize:size]; -} - -// viva_mono_font_primary is the primary font of a face alone, the one the cell is measured in. -static NSFont *viva_mono_font_primary(CGFloat size, CGFloat weight, int face) { - NSString *family = nil; - BOOL classic = NO; - NSArray *fallbacks = nil; - viva_mono_face_traits(face, &family, &classic, &fallbacks); - return viva_mono_base_font(size, weight, family, classic); -} - -// viva_mono_font is the font of a face at a size and weight: its primary font, with the -// families that draw what the primary lacks as the font's cascade list, so CoreText -// tries them in order, before its own choice, for every character the primary has no -// glyph for. A family that is not installed is skipped. The cell is the primary's: the -// fallbacks never take part in the metrics, and every glyph is placed on the grid. -static NSFont *viva_mono_font(CGFloat size, CGFloat weight, int face) { - NSString *family = nil; - BOOL classic = NO; - NSArray *fallbacks = nil; - viva_mono_face_traits(face, &family, &classic, &fallbacks); - NSFont *base = viva_mono_base_font(size, weight, family, classic); - if (base == nil || fallbacks.count == 0) { - return base; - } - NSMutableArray *cascade = [NSMutableArray arrayWithCapacity:fallbacks.count]; - for (NSString *name in fallbacks) { - [cascade addObject:[NSFontDescriptor fontDescriptorWithFontAttributes:@{NSFontFamilyAttribute: name}]]; - } - NSFontDescriptor *descriptor = [base.fontDescriptor fontDescriptorByAddingAttributes:@{NSFontCascadeListAttribute: cascade}]; - NSFont *stacked = [NSFont fontWithDescriptor:descriptor size:size]; - return stacked != nil ? stacked : base; -} - -/* ---- fallback to the installed fonts for glyphs no family of the face has --- - * - * CoreText draws .LastResort for a character neither the face's families nor its - * own fallback have: private-use icon code points (Powerline, Nerd Fonts) above - * all. It never looks at the fonts the user installed, while the Linux - * (fontconfig) and the Windows (DirectWrite) text stacks do -- so a terminal - * loses the icons of the very font its user installed, and a prompt made of - * Powerline separators reads as boxes. - * - * A cluster that CoreText would draw with the last-resort glyph is handed to the - * installed family that has it, ranked so that a terminal icon font wins over a - * CJK font that maps the same code point to one of its own characters: fixed - * pitch first, then one that draws no Han, then the one covering the most - * private-use code points, then the family name. The choice is remembered per - * cluster (a terminal draws the same icons again and again) and per family (what - * a family covers cannot change while the process runs), so a family installed - * after a character was first drawn is only picked up by a new process. - */ - -// VIVA_MONO_FALLBACK_CACHE bounds the clusters remembered; past it a cluster is -// looked up again each time instead of growing the table without end. -#define VIVA_MONO_FALLBACK_CACHE 4096 -// VIVA_MONO_CLUSTER_LENGTH bounds a cluster; the longest real ones are emoji -// sequences of a few code points. -#define VIVA_MONO_CLUSTER_LENGTH 64 - -typedef struct { - BOOL onGrid; - BOOL includesHan; - int privateUse; -} viva_mono_family_traits; - -static NSMutableDictionary *viva_mono_trait_cache; -static NSMutableDictionary *viva_mono_cluster_cache; - -static NSObject *viva_mono_fallback_lock(void) { - static NSObject *lock; - static dispatch_once_t once; - dispatch_once(&once, ^{ lock = [[NSObject alloc] init]; }); - return lock; -} - -// viva_mono_family_font resolves an installed family at a size and weight, or nil. -static NSFont *viva_mono_family_font(NSString *family, CGFloat size, CGFloat weight) { - return [[NSFontManager sharedFontManager] fontWithFamily:family - traits:(weight >= 0.34 ? NSBoldFontMask : 0) - weight:5 - size:size]; -} - -// viva_mono_replacement_font is viva_mono_family_font for a replacement glyph, remembering -// the families asked for: the font manager lookup is most of what a replacement costs, and -// a terminal draws the same icon clusters line after line at the same size. The font is -// returned retained and autoreleased, so it outlives an eviction. -#define VIVA_MONO_REPLACEMENT_CACHE 8 - -typedef struct { - NSString *family; - CGFloat size; - BOOL bold; - NSFont *font; -} viva_mono_replacement; - -static viva_mono_replacement viva_mono_replacements[VIVA_MONO_REPLACEMENT_CACHE]; -static int viva_mono_replacement_count; -static int viva_mono_replacement_next; - -static NSFont *viva_mono_replacement_font(NSString *family, CGFloat size, BOOL bold) { - @synchronized(viva_mono_fallback_lock()) { - for (int index = 0; index < viva_mono_replacement_count; index++) { - viva_mono_replacement *entry = &viva_mono_replacements[index]; - if (entry->size == size && entry->bold == bold && [entry->family isEqualToString:family]) { - return [[entry->font retain] autorelease]; - } - } - } - NSFont *font = viva_mono_family_font(family, size, bold ? 1 : 0); - if (font == nil) { - return nil; - } - @synchronized(viva_mono_fallback_lock()) { - viva_mono_replacement *entry; - if (viva_mono_replacement_count < VIVA_MONO_REPLACEMENT_CACHE) { - entry = &viva_mono_replacements[viva_mono_replacement_count++]; - } else { - entry = &viva_mono_replacements[viva_mono_replacement_next++ % VIVA_MONO_REPLACEMENT_CACHE]; - [entry->family release]; - [entry->font release]; - } - entry->family = [family copy]; - entry->size = size; - entry->bold = bold; - entry->font = [font retain]; - } - return [[font retain] autorelease]; -} - -// viva_mono_font_covers reports whether font draws every code unit of value. -static BOOL viva_mono_font_covers(CTFontRef font, NSString *value) { - NSUInteger length = value.length; - if (font == NULL || length == 0 || length > VIVA_MONO_CLUSTER_LENGTH) { - return NO; - } - UniChar characters[VIVA_MONO_CLUSTER_LENGTH]; - CGGlyph glyphs[VIVA_MONO_CLUSTER_LENGTH]; - [value getCharacters:characters range:NSMakeRange(0, length)]; - if (!CTFontGetGlyphsForCharacters(font, characters, glyphs, (CFIndex)length)) { - return NO; - } - for (NSUInteger index = 0; index < length; index++) { - if (glyphs[index] == 0) { - return NO; - } - } - return YES; -} - -// viva_mono_draws_han reports whether a font draws Chinese text at all. A family -// that does is a text face, and the glyph it maps a private-use code point to is -// one of its own characters rather than the icon the line asks for. -static BOOL viva_mono_draws_han(CTFontRef font) { - static const UniChar probes[] = {0x4E2D, 0x5B57, 0x8A9E}; /* 中 字 語 */ - CGGlyph glyphs[3] = {0}; - CTFontGetGlyphsForCharacters(font, probes, glyphs, 3); - return glyphs[0] != 0 || glyphs[1] != 0 || glyphs[2] != 0; -} - -// viva_mono_private_use counts the private-use code points a font covers, from -// the plane's bitmap: a Nerd Font covers thousands, a CJK font a handful. -static int viva_mono_private_use(CTFontRef font) { - CFCharacterSetRef characters = CTFontCopyCharacterSet(font); - if (characters == NULL) { - return 0; - } - CFDataRef bitmap = CFCharacterSetCreateBitmapRepresentation(kCFAllocatorDefault, characters); - CFRelease(characters); - if (bitmap == NULL) { - return 0; - } - const UInt8 *bytes = CFDataGetBytePtr(bitmap); - CFIndex length = CFDataGetLength(bitmap); - int count = 0; - for (int code = 0xE000; code <= 0xF8FF; code++) { - CFIndex index = code >> 3; - if (index >= length) { - break; - } - if ((bytes[index] & (1 << (code & 7))) != 0) { - count++; - } - } - CFRelease(bitmap); - return count; -} - -// viva_mono_family_traits_of is what ranks a family: whether it draws on a grid (the -// same test that decides which families are offered, so a coding family that leaves -// the fixed-pitch bit clear ranks with the ones that set it), whether it draws Han, -// and how much private-use it covers. Read once per family. -static viva_mono_family_traits viva_mono_family_traits_of(NSString *family) { - viva_mono_family_traits traits = {NO, YES, 0}; - @synchronized(viva_mono_fallback_lock()) { - NSValue *known = [viva_mono_trait_cache objectForKey:family]; - if (known != nil) { - [known getValue:&traits size:sizeof(traits)]; - return traits; - } - } - NSFont *font = viva_mono_family_font(family, 12, 0); - if (font != nil) { - traits.onGrid = viva_mono_font_on_a_grid(font); - traits.includesHan = viva_mono_draws_han((CTFontRef)font); - traits.privateUse = viva_mono_private_use((CTFontRef)font); - } - NSValue *value = [NSValue valueWithBytes:&traits objCType:@encode(viva_mono_family_traits)]; - @synchronized(viva_mono_fallback_lock()) { - if (viva_mono_trait_cache == nil) { - viva_mono_trait_cache = [[NSMutableDictionary alloc] init]; - } - [viva_mono_trait_cache setObject:value forKey:family]; - } - return traits; -} - -// viva_mono_family_better reports whether candidate ranks before best for a cluster. -static BOOL viva_mono_family_better(viva_mono_family_traits candidate, NSString *family, - viva_mono_family_traits best, NSString *bestFamily) { - if (bestFamily == nil) { - return YES; - } - if (candidate.onGrid != best.onGrid) { - return candidate.onGrid; - } - if (candidate.includesHan != best.includesHan) { - return !candidate.includesHan; - } - if (candidate.privateUse != best.privateUse) { - return candidate.privateUse > best.privateUse; - } - return [family localizedCaseInsensitiveCompare:bestFamily] == NSOrderedAscending; -} - -// viva_mono_find_family is the installed family that draws cluster, or nil. It -// asks the system for the fonts covering the cluster's code points, leaves out -// the ones that do not draw every code point of it, and ranks the rest. -static NSString *viva_mono_find_family(NSString *cluster) { - CFCharacterSetRef characters = CFCharacterSetCreateWithCharactersInString(kCFAllocatorDefault, (CFStringRef)cluster); - if (characters == NULL) { - return nil; - } - const void *keys[] = {kCTFontCharacterSetAttribute}; - const void *values[] = {characters}; - CFDictionaryRef query = CFDictionaryCreate(kCFAllocatorDefault, keys, values, 1, - &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); - CFRelease(characters); - if (query == NULL) { - return nil; - } - CTFontDescriptorRef descriptor = CTFontDescriptorCreateWithAttributes(query); - CFRelease(query); - if (descriptor == NULL) { - return nil; - } - CFArrayRef matches = CTFontDescriptorCreateMatchingFontDescriptors(descriptor, NULL); - CFRelease(descriptor); - if (matches == NULL) { - return nil; - } - NSString *best = nil; - viva_mono_family_traits bestTraits = {NO, YES, 0}; - CFIndex count = CFArrayGetCount(matches); - for (CFIndex index = 0; index < count; index++) { - CTFontDescriptorRef match = (CTFontDescriptorRef)CFArrayGetValueAtIndex(matches, index); - NSString *family = (NSString *)CTFontDescriptorCopyAttribute(match, kCTFontFamilyNameAttribute); - if (family == nil || family.length == 0) { - if (family != NULL) { - CFRelease(family); - } - continue; - } - NSFont *font = viva_mono_family_font(family, 12, 0); - if (font == nil || !viva_mono_font_covers((CTFontRef)font, cluster)) { - CFRelease(family); - continue; - } - viva_mono_family_traits traits = viva_mono_family_traits_of(family); - if (viva_mono_family_better(traits, family, bestTraits, best)) { - best = [family autorelease]; - bestTraits = traits; - } else { - CFRelease(family); - } - } - CFRelease(matches); - return best; -} - -// viva_mono_face_fallback is the family the face itself puts behind its primary -// that draws cluster, or nil. CoreText ignores a cascade list for private-use code -// points as well, so the application's own fallbacks -- the ones the settings page -// offers -- have to be tried here, before the ranking. -static NSString *viva_mono_face_fallback(NSString *cluster, int face) { - NSString *family = nil; - BOOL classic = NO; - NSArray *fallbacks = nil; - viva_mono_face_traits(face, &family, &classic, &fallbacks); - for (NSString *candidate in fallbacks) { - NSFont *font = viva_mono_family_font(candidate, 12, 0); - if (font != nil && viva_mono_font_covers((CTFontRef)font, cluster)) { - return candidate; - } - } - return nil; -} - -// viva_mono_fallback_family is the installed family that draws a cluster CoreText -// cannot, or nil when no installed family has it. -static NSString *viva_mono_fallback_family(NSString *cluster) { - if (cluster.length == 0 || cluster.length > VIVA_MONO_CLUSTER_LENGTH) { - return nil; - } - @synchronized(viva_mono_fallback_lock()) { - id known = [viva_mono_cluster_cache objectForKey:cluster]; - if (known != nil) { - return known == [NSNull null] ? nil : known; - } - } - NSString *family = viva_mono_find_family(cluster); - @synchronized(viva_mono_fallback_lock()) { - if (viva_mono_cluster_cache == nil) { - viva_mono_cluster_cache = [[NSMutableDictionary alloc] init]; - } - if (viva_mono_cluster_cache.count < VIVA_MONO_FALLBACK_CACHE) { - [viva_mono_cluster_cache setObject:(family != nil ? family : (id)[NSNull null]) forKey:cluster]; - } - } - return family; -} - -// viva_mono_font_is_last_resort reports whether font is the face CoreText draws a -// character no installed family has with. The face calls itself LastResort, with a -// leading dot in its family name and without it in its PostScript name. -static BOOL viva_mono_is_last_resort_name(CFStringRef name) { - if (name == NULL) { - return NO; - } - return CFStringCompare(name, CFSTR("LastResort"), kCFCompareCaseInsensitive) == kCFCompareEqualTo || - CFStringCompare(name, CFSTR(".LastResort"), kCFCompareCaseInsensitive) == kCFCompareEqualTo; -} - -static BOOL viva_mono_font_is_last_resort(CTFontRef font) { - if (font == NULL) { - return NO; - } - CFStringRef postscript = CTFontCopyPostScriptName(font); - CFStringRef family = CTFontCopyFamilyName(font); - BOOL last = viva_mono_is_last_resort_name(postscript) || viva_mono_is_last_resort_name(family); - if (postscript != NULL) { - CFRelease(postscript); - } - if (family != NULL) { - CFRelease(family); - } - return last; -} - -// viva_mono_fallback_line shapes a fixed-pitch line in base (the face's font at the -// weight, and with the slant, the caller already resolved): for the clusters CoreText -// would draw with its last-resort glyph, the installed family that has them, at base's -// size and boldness. A line with nothing to replace is shaped once, as before; one with -// a replacement is shaped again with the fallback fonts in place, so every glyph sits -// where the grid says. The line is +1: the caller releases it. -static CTLineRef viva_mono_fallback_line(NSString *value, NSFont *base, int face, CGColorRef color) { - if (base == nil || value.length == 0) { - return NULL; - } - CGFloat size = base.pointSize; - BOOL bold = (base.fontDescriptor.symbolicTraits & NSFontBoldTrait) != 0; - CFIndex length = (CFIndex)value.length; - CFMutableAttributedStringRef attributed = CFAttributedStringCreateMutable(kCFAllocatorDefault, 0); - if (attributed == NULL) { - return NULL; - } - CFAttributedStringReplaceString(attributed, CFRangeMake(0, 0), (CFStringRef)value); - CFAttributedStringSetAttribute(attributed, CFRangeMake(0, length), kCTFontAttributeName, (CTFontRef)base); - if (color != NULL) { - CFAttributedStringSetAttribute(attributed, CFRangeMake(0, length), kCTForegroundColorAttributeName, color); - } - CTLineRef line = CTLineCreateWithAttributedString(attributed); - if (line == NULL) { - CFRelease(attributed); - return NULL; - } - BOOL replaced = NO; - CFArrayRef runs = CTLineGetGlyphRuns(line); - CFIndex runCount = runs != NULL ? CFArrayGetCount(runs) : 0; - for (CFIndex index = 0; index < runCount; index++) { - CTRunRef run = (CTRunRef)CFArrayGetValueAtIndex(runs, index); - CFDictionaryRef runAttributes = CTRunGetAttributes(run); - CTFontRef runFont = runAttributes != NULL ? (CTFontRef)CFDictionaryGetValue(runAttributes, kCTFontAttributeName) : NULL; - if (!viva_mono_font_is_last_resort(runFont)) { - continue; - } - CFRange runRange = CTRunGetStringRange(run); - CFIndex end = runRange.location + runRange.length; - for (CFIndex at = runRange.location; at < end;) { - NSRange cluster = [value rangeOfComposedCharacterSequenceAtIndex:(NSUInteger)at]; - if (cluster.length == 0) { - break; - } - NSString *text = [value substringWithRange:cluster]; - NSString *family = viva_mono_face_fallback(text, face); - if (family == nil) { - family = viva_mono_fallback_family(text); - } - NSFont *fallback = family != nil ? viva_mono_replacement_font(family, size, bold) : nil; - if (fallback != nil) { - CFAttributedStringSetAttribute(attributed, - CFRangeMake((CFIndex)cluster.location, (CFIndex)cluster.length), - kCTFontAttributeName, (CTFontRef)fallback); - replaced = YES; - } - at = (CFIndex)NSMaxRange(cluster); - } - } - if (!replaced) { - CFRelease(attributed); - return line; - } - CFRelease(line); - line = CTLineCreateWithAttributedString(attributed); - CFRelease(attributed); - return line; -} - -// viva_text_system_thickening reports whether the user leaves the system's own font -// smoothing on, the weight AppKit's text starts at: AppleFontSmoothing absent or nonzero -// means on, zero (or a value that is not a number, as AppKit reads it) off. A bitmap -// context does not heed the setting, so the engine asks for it here, once, at its start; -// standardUserDefaults reads the argument domain too, which is how tests pin it. -int viva_text_system_thickening(void) { - @autoreleasepool { - NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; - if ([defaults objectForKey:@"AppleFontSmoothing"] == nil) { - return 1; - } - return [defaults integerForKey:@"AppleFontSmoothing"] != 0; - } -} - -// viva_text_thickening is whether Viva draws its text with a thicker stroke, as AppKit draws -// the system's own text: CoreText's font smoothing, which darkens the stems. Off is the -// font's own outlines, so the glyphs stay the weight the font gives them (measured against -// AppKit text: smoothing draws 16 to 45 percent more ink, the lighter the text the more). -// It starts at the system's own weight (viva_text_system_thickening) and is then the -// weight the application asked for. -static int viva_text_thickening = 0; - -int viva_text_set_thickening(int thickening) { - int previous = viva_text_thickening; - viva_text_thickening = thickening; - return previous != thickening; -} - -// viva_prepare_text_context sets a bitmap context up to draw text the way AppKit draws it. -static void viva_prepare_text_context(CGContextRef context, CGFloat scale) { - CGContextScaleCTM(context, scale, scale); - CGContextSetTextMatrix(context, CGAffineTransformIdentity); - CGContextSetShouldSmoothFonts(context, viva_text_thickening != 0); -} - -// viva_draw_terminal_preedit draws a terminal's preedit text the way the terminal draws its -// own line: every character on the cells of the grid, a plain ASCII one at the left of its -// cell and any other centered in the cells it takes (two for a wide one), with its combining -// marks. The native editor and the headless renderer both draw it here, so they can only ever -// look the same, and the text does not move when it is committed to the grid. -static void viva_draw_terminal_preedit( - CGContextRef context, NSString *shown, CGFloat fontSize, int monoFace, - NSColor *color, CGFloat cellWidth, CGFloat baseline -) { - // The face's font, with the installed fallback for what no family of it draws. - NSFont *font = viva_mono_font(fontSize, 0, monoFace); - NSUInteger column = 0; - for (NSUInteger at = 0; at < shown.length;) { - int cells = 0; - NSUInteger end = at + viva_terminal_step(shown, at, &cells); - for (int marks = 0; end < shown.length;) { - NSUInteger next = viva_terminal_step(shown, end, &marks); - if (marks != 0) { - break; - } - end += next; - } - NSString *cluster = [shown substringWithRange:NSMakeRange(at, end - at)]; - CTLineRef line = viva_mono_fallback_line(cluster, font, monoFace, color.CGColor); - if (line != NULL) { - CGFloat x = (CGFloat)column * cellWidth; - unichar only = cluster.length == 1 ? [cluster characterAtIndex:0] : 0; - if (cells > 0 && !(only >= 0x20 && only < 0x7F)) { - CGFloat width = CTLineGetTypographicBounds(line, NULL, NULL, NULL); - x += ((CGFloat)cells * cellWidth - width) / 2; - } - CGContextSetTextPosition(context, x, baseline); - CTLineDraw(line, context); - CFRelease(line); - } - column += (NSUInteger)cells; - at = end; - } -} - -// viva_new_editor_line is the geometry of the text the editor shows: one shaped line -// shared with layout for proportional text, the terminal's cells for a terminal. A line -// that was not made could not be shaped. -static viva_editor_line viva_new_editor_line(NSString *shown, CGFloat fontSize, CGFloat fontWeight, BOOL terminal, CGFloat cellWidth) { - viva_editor_line line = {NULL, nil, 0}; - if (terminal) { - line.grid = [shown copy]; - line.cell = cellWidth; - } else { - line.shaped = viva_shared_text_line(shown, fontSize, fontWeight); - } - return line; -} - -static CGFloat viva_editor_alignment_inset(viva_editor_line line, CGFloat width, int alignment, BOOL terminal) { - if (terminal || line.shaped == NULL || (alignment != 1 && alignment != 2)) { - return 0; - } - CGFloat free = MAX(0, width - line.shaped->width); - return alignment == 1 ? free / 2 : free; -} - -static CGFloat viva_editor_visible_caret(CGFloat offset, CGFloat width, int alignment, BOOL terminal) { - if (alignment != 2 || terminal) { - return offset; - } - return MIN(offset, MAX(0, width - 2)); -} - -// viva_baseline is the height of the baseline above the bottom of a label's texture, -// in points. The baseline is the same row every backend uses (platform.LabelBaseline): -// a fixed distance below the middle of the line box, on a whole physical pixel, so -// the font's own ascent and descent do not move the text. -static CGFloat viva_baseline(CGFloat height, CGFloat fontSize, CGFloat pixelScale) { - CGFloat rows = MAX(1.0, ceil(height * pixelScale)); - CGFloat fromTop = floor(rows * 0.5 + VIVA_BASELINE_BELOW_CENTER * fontSize * pixelScale + 1e-6); - return (rows - fromTop) / pixelScale; -} - -// viva_fixed_baseline is the height above a texture's bottom of the row a canvas worked out -// for a fixed-pitch line, counted from the texture's top in points -// (platform.TextLabel.Baseline), on a whole physical pixel. -static CGFloat viva_fixed_baseline(CGFloat height, CGFloat fromTop, CGFloat pixelScale) { - CGFloat rows = MAX(1.0, ceil(height * pixelScale)); - return (rows - floor(fromTop * pixelScale + 0.5)) / pixelScale; -} - -int viva_text_line_rasterize( - const viva_text_line *line, - double font_size, - double scale, - size_t width, - size_t height, - double red, - double green, - double blue, - double alpha, - unsigned char *pixels -) { - if (line == NULL || pixels == NULL || font_size <= 0 || scale <= 0 || - width < 1 || height < 1 || width > 16384 || height > 16384 || - width > SIZE_MAX / 4 || height > SIZE_MAX / (width * 4)) { - return 1; - } - @autoreleasepool { - memset(pixels, 0, width * height * 4); - CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); - CGContextRef context = CGBitmapContextCreate( - pixels, width, height, 8, width * 4, colorSpace, - kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little - ); - CGColorSpaceRelease(colorSpace); - if (context == NULL) { - return 1; - } - viva_prepare_text_context(context, scale); - CGColorRef color = CGColorCreateSRGB(red, green, blue, alpha); - CGFloat logicalHeight = (CGFloat)height / (CGFloat)scale; - CGFloat baseline = viva_baseline(logicalHeight, font_size, scale); - viva_draw_text_line(context, line, color, 0, baseline); - CGColorRelease(color); - CGContextRelease(context); - return 0; - } -} - -// viva_text_input_texture rasterizes the native editor's current appearance: -// the shown text (bullets for a password), the selection or composition, and -// the caret when it is in its visible phase. It returns a retained texture, or -// nil when the frame cannot be rasterized. -static id viva_text_input_texture( - id device, - CGFloat scale, - NSString *shown, - CGFloat fontSize, - CGFloat fontWeight, - NSColor *color, - NSSize frameSize, - NSRange selectedRange, - BOOL hasMarked, - NSRange markedRange, - BOOL caretVisible, - BOOL terminal, - BOOL hideNativeOverlays, - int monoFace, - CGFloat cellWidth, - CGFloat cellBaseline, - int alignment -) { - size_t pixelWidth = (size_t)MAX(1.0, ceil(frameSize.width * scale)); - size_t pixelHeight = (size_t)MAX(1.0, ceil(frameSize.height * scale)); - if (pixelWidth > 16384 || pixelHeight > 16384 || pixelWidth > SIZE_MAX / 4) { - return nil; - } - size_t rowBytes = pixelWidth * 4; - if (pixelHeight > SIZE_MAX / rowBytes) { - return nil; - } - void *pixels = calloc(pixelHeight, rowBytes); - if (pixels == NULL) { - return nil; - } - - CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); - CGContextRef context = CGBitmapContextCreate( - pixels, - pixelWidth, - pixelHeight, - 8, - rowBytes, - colorSpace, - kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little - ); - CGColorSpaceRelease(colorSpace); - if (context == NULL) { - free(pixels); - return nil; - } - - viva_prepare_text_context(context, scale); - viva_editor_line line = viva_new_editor_line(shown, fontSize, fontWeight, terminal, cellWidth); - if (!viva_editor_line_made(line)) { - CGContextRelease(context); - free(pixels); - return nil; - } - CGFloat inset = viva_editor_alignment_inset(line, frameSize.width, alignment, terminal); - - CGFloat ascent = 0; - CGFloat descent = 0; - CGFloat baseline = 0; - if (terminal) { - // Sit on the same row as the terminal's own text, whatever the composed - // characters' fallback fonts measure. The primary font alone stands in for the - // ascent and descent of the caret and selection, the fallbacks never taking part. - CTFontRef gridFont = CTFontCreateWithName((CFStringRef)viva_mono_font_primary(fontSize, 0, monoFace).fontName, fontSize, NULL); - ascent = CTFontGetAscent(gridFont); - descent = CTFontGetDescent(gridFont); - CFRelease(gridFont); - baseline = cellBaseline > 0 - ? viva_fixed_baseline(frameSize.height, cellBaseline, ceil(scale)) - : viva_baseline(frameSize.height, fontSize, ceil(scale)); - } else { - ascent = line.shaped->ascent; - descent = line.shaped->descent; - // The editor's text stands on the row the unfocused label stands on, so - // focusing a field does not move it; only the caret and selection use - // the line's own ascent and descent. - baseline = viva_baseline(frameSize.height, fontSize, ceil(scale)); - } - NSUInteger textLength = shown.length; - NSRange selected = viva_clamp_range(selectedRange, textLength); - // Fully transparent text means an editor that exists only to receive input - // (an OTP field paints its own slots): draw none of it, caret and selection - // included. A translucent color still gets its caret and highlight. - NSColor *textColor = [color colorUsingColorSpace:[NSColorSpace sRGBColorSpace]]; - BOOL invisible = textColor != nil && textColor.alphaComponent <= 0.0; - double spans[2 * VIVA_SELECTION_PIECES]; - if (selected.length > 0 && !terminal && !hideNativeOverlays && !invisible) { - size_t count = viva_text_spans(line, selected, terminal, spans, VIVA_SELECTION_PIECES); - CGContextSetRGBFillColor(context, 0.18, 0.42, 0.90, 0.55); - for (size_t piece = 0; piece < count; piece++) { - CGContextFillRect( - context, - CGRectMake(inset + spans[2 * piece], baseline - descent, MAX(1.0, spans[2 * piece + 1]), ascent + descent) - ); - } - } - - if (terminal) { - viva_draw_terminal_preedit(context, shown, fontSize, monoFace, color, cellWidth, baseline); - } else { - // The text is drawn as the one line the offsets above and below are read from, so - // selection, caret and glyphs agree. - viva_draw_text_line(context, line.shaped, color.CGColor, inset, baseline); - } - - if (invisible) { - // nothing more to draw - } else if (hasMarked) { - NSRange marked = viva_clamp_range(markedRange, textLength); - size_t count = viva_text_spans(line, marked, terminal, spans, VIVA_SELECTION_PIECES); - CGContextSetRGBFillColor(context, 0.55, 0.72, 1.0, 1.0); - for (size_t piece = 0; piece < count; piece++) { - // A terminal's row is only as tall as its text, so below the descenders is the - // edge of the row, not two points further down, where nothing would be drawn. - CGContextFillRect(context, CGRectMake(inset + spans[2 * piece], MAX(baseline - descent - 2.0, 0.0), MAX(1.0, spans[2 * piece + 1]), 1.0)); - } - } else if (selected.length == 0 && caretVisible && !terminal && !hideNativeOverlays) { - CGFloat caret = viva_editor_visible_caret(inset + viva_text_offset(line, selected.location, terminal), frameSize.width, alignment, terminal); - NSColor *caretColor = [color colorUsingColorSpace:[NSColorSpace sRGBColorSpace]]; - CGContextSetRGBFillColor( - context, - caretColor.redComponent, - caretColor.greenComponent, - caretColor.blueComponent, - MAX(caretColor.alphaComponent, 0.9) - ); - CGContextFillRect(context, CGRectMake(caret, baseline - descent, 2.0, ascent + descent)); - } - - MTLTextureDescriptor *descriptor = [MTLTextureDescriptor - texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm - width:pixelWidth - height:pixelHeight - mipmapped:NO]; - descriptor.storageMode = MTLStorageModeShared; - descriptor.usage = MTLTextureUsageShaderRead; - id texture = [device newTextureWithDescriptor:descriptor]; - if (texture != nil) { - [texture replaceRegion:MTLRegionMake2D(0, 0, pixelWidth, pixelHeight) - mipmapLevel:0 - withBytes:pixels - bytesPerRow:rowBytes]; - } - - viva_editor_line_free(line); - CGContextRelease(context); - free(pixels); - if (texture == nil) { - return nil; - } - viva_text_texture_rebuild_count++; - return texture; -} - -// viva_test_pasteboard replaces the general pasteboard in native tests, which -// must not read or overwrite the user's clipboard. -static NSPasteboard *viva_test_pasteboard; - -static NSPasteboard *viva_pasteboard(void) { - if (viva_test_pasteboard != nil) { - return viva_test_pasteboard; - } - // VIVA_TEST_PASTEBOARD=1 keeps a manual run's copy and paste on a private - // pasteboard, like the other VIVA_TEST_* switches. - const char *value = getenv("VIVA_TEST_PASTEBOARD"); - if (value != NULL && value[0] == '1' && value[1] == '\0') { - return [NSPasteboard pasteboardWithName:@"viva.test.pasteboard"]; - } - return [NSPasteboard generalPasteboard]; -} - -// viva_single_line_paste prepares clipboard text for a single-line field: line -// breaks cannot live in one line, and leading or trailing ones (copied whole -// lines, shell output) must not turn into stray spaces. -static NSString *viva_single_line_paste(NSString *value) { - // CRLF is two characters of the newline set, so splitting leaves an empty - // piece between them; empty pieces are dropped rather than joined as spaces. - NSMutableArray *lines = [NSMutableArray array]; - for (NSString *line in [value componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]]) { - if (line.length > 0) { - [lines addObject:line]; - } - } - return [lines componentsJoinedByString:@" "]; -} - -// viva_fragment_blends_premultiplied says how a fragment function's output must -// be blended. Rectangles output a straight color and blend with SourceAlpha. -// Text returns texels CoreGraphics already multiplied by coverage, so it blends -// with One; SourceAlpha would multiply by alpha twice and thin every glyph edge -// by roughly a fifth. -int viva_fragment_blends_premultiplied(const char *fragmentName) { - return fragmentName != NULL && strcmp(fragmentName, "viva_text_fragment") == 0; -} - -static id viva_create_pipeline( - id device, - id library, - NSString *vertexName, - NSString *fragmentName, - NSError **error -) { - BOOL premultipliedSource = viva_fragment_blends_premultiplied(fragmentName.UTF8String) != 0; - id vertex = [library newFunctionWithName:vertexName]; - id fragment = [library newFunctionWithName:fragmentName]; - if (vertex == nil || fragment == nil) { - [fragment release]; - [vertex release]; - return nil; - } - MTLRenderPipelineDescriptor *descriptor = - [[[MTLRenderPipelineDescriptor alloc] init] autorelease]; - descriptor.vertexFunction = vertex; - descriptor.fragmentFunction = fragment; - descriptor.colorAttachments[0].pixelFormat = MTLPixelFormatBGRA8Unorm; - descriptor.colorAttachments[0].blendingEnabled = YES; - descriptor.colorAttachments[0].rgbBlendOperation = MTLBlendOperationAdd; - descriptor.colorAttachments[0].alphaBlendOperation = MTLBlendOperationAdd; - descriptor.colorAttachments[0].sourceRGBBlendFactor = - premultipliedSource ? MTLBlendFactorOne : MTLBlendFactorSourceAlpha; - descriptor.colorAttachments[0].destinationRGBBlendFactor = MTLBlendFactorOneMinusSourceAlpha; - descriptor.colorAttachments[0].sourceAlphaBlendFactor = MTLBlendFactorOne; - descriptor.colorAttachments[0].destinationAlphaBlendFactor = MTLBlendFactorOneMinusSourceAlpha; - id pipeline = [device - newRenderPipelineStateWithDescriptor:descriptor - error:error]; - [fragment release]; - [vertex release]; - return pipeline; -} - -static uint64_t viva_hash_bytes(uint64_t hash, const void *data, size_t length) { - const unsigned char *bytes = (const unsigned char *)data; - for (size_t index = 0; index < length; index++) { - hash = (hash ^ bytes[index]) * 1099511628211ULL; - } - return hash; -} - -// viva_plan_label_reuse decides which old label texture each new label can take -// over. source[i] is the index of the old label new label i reuses, or -1 when -// it needs a texture of its own. A label first looks at its own index (the -// common case: nothing moved), then at any unused old label with the same -// hash anywhere (a list or terminal that scrolled). Each old label is used at -// most once. Equal hashes only propose a match; the caller confirms it. -int viva_plan_label_reuse( - const uint64_t *old_hashes, - size_t old_count, - const uint64_t *new_hashes, - size_t new_count, - int64_t *source -) { - if ((new_count > 0 && source == NULL) || (old_count > 0 && old_hashes == NULL) || (new_count > 0 && new_hashes == NULL)) { - return 1; - } - size_t table_size = 16; - while (table_size < old_count * 2) { - table_size <<= 1; - } - int64_t *heads = malloc(table_size * sizeof(int64_t)); - int64_t *next = malloc(MAX(old_count, 1) * sizeof(int64_t)); - unsigned char *taken = calloc(MAX(old_count, 1), 1); - if (heads == NULL || next == NULL || taken == NULL) { - free(heads); - free(next); - free(taken); - return 2; - } - for (size_t slot = 0; slot < table_size; slot++) { - heads[slot] = -1; - } - for (size_t old = 0; old < old_count; old++) { - size_t slot = (size_t)(old_hashes[old] & (table_size - 1)); - next[old] = heads[slot]; - heads[slot] = (int64_t)old; - } - for (size_t index = 0; index < new_count; index++) { - source[index] = -1; - if (index < old_count && !taken[index] && old_hashes[index] == new_hashes[index]) { - source[index] = (int64_t)index; - taken[index] = 1; - } - } - for (size_t index = 0; index < new_count; index++) { - if (source[index] >= 0) { - continue; - } - size_t slot = (size_t)(new_hashes[index] & (table_size - 1)); - for (int64_t old = heads[slot]; old >= 0; old = next[old]) { - if (!taken[old] && old_hashes[old] == new_hashes[index]) { - source[index] = old; - taken[old] = 1; - break; - } - } - } - free(heads); - free(next); - free(taken); - return 0; -} - -// viva_quantized_origin is a label's sub-pixel origin to a sixteenth of a logical pixel, -// finer than Core Graphics places a glyph (a fifth of a device pixel at best), so labels -// that differ by less share a texture. -static float viva_quantized_origin(float value) { - return roundf(value * 16.0f) / 16.0f; -} - -// viva_label_content_hash identifies what a label looks like: its text, runs, -// font and color. Position and layer are not part of it. Labels with equal -// hashes are candidates for sharing one texture; matchesConfig confirms. -static uint64_t viva_label_content_hash(viva_text_label config) { - uint64_t hash = 14695981039346656037ULL; - hash = viva_hash_bytes(hash, config.utf8, config.utf8_length); - // Bitmap textures retain their source dimensions. Resizing their draw quad - // must find the same texture when Go omits an unchanged pixel payload. - BOOL bitmap = (config.flags & VIVA_LABEL_BITMAP) != 0; - float values[] = {bitmap ? 0 : config.width, bitmap ? 0 : config.height, config.font_size, config.font_weight, - config.red, config.green, config.blue, config.alpha, config.cell_width, - viva_quantized_origin(config.origin_x), viva_quantized_origin(config.origin_y), config.baseline}; - hash = viva_hash_bytes(hash, values, sizeof(values)); - uint32_t contentFlags = config.flags & ~VIVA_LABEL_CLIPPED; - hash = viva_hash_bytes(hash, &contentFlags, sizeof(contentFlags)); - hash = viva_hash_bytes(hash, &config.mono_face, sizeof(config.mono_face)); - hash = viva_hash_bytes(hash, &config.font_generation, sizeof(config.font_generation)); - if (config.runs != NULL) { - hash = viva_hash_bytes(hash, config.runs, config.run_count * sizeof(viva_text_run)); - } - uint64_t bitmapIdentity[] = { - config.bitmap_id, - config.bitmap_version, - config.bitmap_width, - config.bitmap_height, - config.bitmap_stride, - }; - hash = viva_hash_bytes(hash, bitmapIdentity, sizeof(bitmapIdentity)); - if (config.bitmap != NULL && config.bitmap_id == 0) { - hash = viva_hash_bytes(hash, config.bitmap, config.bitmap_length); - } - return hash; -} - -@interface VivaTextLayer : NSObject { - NSString *_value; - NSRect _frame; - NSRect _clip; // where the label may paint, when _clipped - BOOL _clipped; - CGFloat _fontSize; - CGFloat _fontWeight; - BOOL _italic; - CGFloat _red; - CGFloat _green; - CGFloat _blue; - CGFloat _alpha; - CGFloat _lastScale; - size_t _textureWidth; - size_t _textureHeight; - CGFloat _originX; // where the text starts within the frame, logical pixels - CGFloat _originY; - uint64_t _hash; - uint32_t _fontGeneration; // the interface font generation the picture was made in - BOOL _mono; - int _monoFace; - CGFloat _cellWidth; - CGFloat _baseline; - NSData *_utf8; // the text as bytes, to slice into runs; only for run labels - viva_text_run *_runs; // owned copy; NULL for an ordinary label - size_t _runCount; - NSData *_bitmap; - uint32_t _bitmapWidth; - uint32_t _bitmapHeight; - uint32_t _bitmapStride; - uint64_t _bitmapID; - uint32_t _bitmapVersion; - float _imageRadius; - id _texture; - NSMutableArray> *_additionalTextures; - // A text label wider than a texture holds is rasterized in part: its textures hold the - // device pixels _windowLeft to _windowRight of it, on the _windowPixelScale grid and - // counted from the frame's left edge. Unset, the texture holds the whole label. - BOOL _windowed; - size_t _windowLeft; - size_t _windowRight; - CGFloat _windowPixelScale; - BOOL _hasQuad; - // The shape the label's picture is drawn into this frame, and the colour - // multiplied into each of its corners (viva_text_label.quad, .tint). An - // ordinary label holds the corners of its box and opaque white. - float _quad[8]; - float _tint[16]; -} -- (instancetype)initWithConfig:(viva_text_label)config; -- (BOOL)matchesConfig:(viva_text_label)config; -- (uint64_t)contentHash; -- (BOOL)contentMatchesSizeAgnostic:(viva_text_label)config; -- (void)updateFrame:(NSRect)frame; -- (void)updateClipFromConfig:(viva_text_label)config; -- (void)updateQuadFromConfig:(viva_text_label)config; -- (const float *)quad; -- (const float *)tint; -- (float)imageRadius; -- (NSRect)frame; -- (BOOL)clipped; -- (NSRect)clip; -- (BOOL)forceTextureRebuildWithDevice:(id)device scale:(CGFloat)scale viewport:(NSSize)viewport; -- (void)markContentRebuild; -- (BOOL)rebuildWithDevice:(id)device scale:(CGFloat)scale viewport:(NSSize)viewport; -- (BOOL)refreshWindowWithDevice:(id)device scale:(CGFloat)scale viewport:(NSSize)viewport; -- (void)drawLineInContext:(CGContextRef)context pixelScale:(CGFloat)pixelScale; -- (void)drawRunsInContext:(CGContextRef)context pixelScale:(CGFloat)pixelScale; -- (id)textureAtIndex:(NSUInteger)index; -- (NSUInteger)textureCount; -- (NSRect)quadAtIndex:(NSUInteger)index; -- (NSRect)textureFrameAtIndex:(NSUInteger)index; -- (CGFloat)rasterWidthScale:(CGFloat)scale; -@end - -static NSData *viva_downsample_bitmap(NSData *source, uint32_t sourceWidth, uint32_t sourceHeight, uint32_t sourceStride, size_t width, size_t height) { - if (source == nil || width == 0 || height == 0 || width > sourceWidth || height > sourceHeight || sourceStride < sourceWidth * 4) { - return nil; - } - if (sourceHeight - 1 > SIZE_MAX / sourceStride || source.length < (size_t)(sourceHeight - 1) * sourceStride + (size_t)sourceWidth * 4 || width > SIZE_MAX / 4 || height > SIZE_MAX / (width * 4)) { - return nil; - } - size_t rowBytes = width * 4; - NSMutableData *pixels = [[NSMutableData alloc] initWithLength:height * rowBytes]; - if (pixels == nil) { - return nil; - } - CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); - CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, source.bytes, source.length, NULL); - CGImageRef image = provider == NULL ? NULL : CGImageCreate( - sourceWidth, sourceHeight, 8, 32, sourceStride, colorSpace, - kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little, - provider, NULL, true, kCGRenderingIntentDefault); - CGContextRef context = image == NULL ? NULL : CGBitmapContextCreate( - pixels.mutableBytes, width, height, 8, rowBytes, colorSpace, - kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little); - if (context != NULL) { - CGContextSetInterpolationQuality(context, kCGInterpolationHigh); - CGContextDrawImage(context, CGRectMake(0, 0, width, height), image); - } - if (context != NULL) { - CGContextRelease(context); - } - if (image != NULL) { - CGImageRelease(image); - } - if (provider != NULL) { - CGDataProviderRelease(provider); - } - CGColorSpaceRelease(colorSpace); - if (context == NULL) { - [pixels release]; - return nil; - } - return pixels; -} - -// viva_bitmap_texture_extent is the size of the texture an image label is drawn from: the -// stored image, averaged down to the device pixels the label covers when it is drawn smaller -// than it is stored. internal/platform.BitmapTextureExtent computes the same size. -static void viva_bitmap_texture_extent(NSRect frame, CGFloat scale, size_t sourceWidth, size_t sourceHeight, size_t *width, size_t *height) { - CGFloat pixelScale = MAX(scale, 1.0); - size_t shownWidth = (size_t)MAX(1.0, floor((frame.origin.x + frame.size.width) * pixelScale + 0.5) - floor(frame.origin.x * pixelScale + 0.5)); - size_t shownHeight = (size_t)MAX(1.0, floor((frame.origin.y + frame.size.height) * pixelScale + 0.5) - floor(frame.origin.y * pixelScale + 0.5)); - *width = sourceWidth; - *height = sourceHeight; - if (shownWidth <= sourceWidth && shownHeight <= sourceHeight && (shownWidth < sourceWidth || shownHeight < sourceHeight)) { - *width = shownWidth; - *height = shownHeight; - } -} - -// viva_bitmap_extent_stale reports whether a texture of one dimension no longer suits an image -// that needs another: smaller than needed would blur it, and more than twice as large would -// alias it. Between those the texture stays, so an animated size does not rebuild every frame. -// internal/platform.BitmapTextureStale applies the same rule. -static BOOL viva_bitmap_extent_stale(size_t have, size_t need) { - return need > have || have >= 2 * need; -} - -// VIVA_LABEL_TEXTURE_LIMIT is the widest and tallest texture a label is rasterized into, in -// pixels: the 2D texture limit of every Metal device Viva runs on. -#define VIVA_LABEL_TEXTURE_LIMIT 16384 -#define VIVA_LABEL_TILE_WIDTH (VIVA_LABEL_TEXTURE_LIMIT - 2) - -// viva_label_visible_span clips the destination triangles to the clip and viewport, -// then maps their visible UV range to source pixels, at most full. -// NO when none of the label can be seen. -static BOOL viva_label_visible_span(const float *quad, const float *tint, BOOL clipped, NSRect clip, NSSize viewport, - size_t full, size_t *left, size_t *right) { - NSRect visible = NSMakeRect(0, 0, viewport.width, viewport.height); - if (clipped) { - visible = NSIntersectionRect(visible, clip); - } - if (NSIsEmptyRect(visible)) { - return NO; - } - float sourceLeft, sourceRight; - if (!viva_label_source_span(quad, tint, NSMinX(visible), NSMinY(visible), NSMaxX(visible), NSMaxY(visible), &sourceLeft, &sourceRight)) { - return NO; - } - CGFloat from = floor((double)sourceLeft * full); - CGFloat to = ceil((double)sourceRight * full); - *left = (size_t)MIN(MAX(from, 0), (CGFloat)full); - *right = (size_t)MIN(MAX(to, 0), (CGFloat)full); - return *right > *left; -} - -// viva_label_window chooses the device pixels of a label full pixels wide that a texture of -// at most limit pixels holds. The visible span left to right is kept with as much margin on -// both sides as the span itself, so a scroll of up to a viewport keeps the texture; at an -// end of the label the margin goes to the other side. A span wider than limit is split -// across textures, without a margin. A label none of which is visible keeps its start. -static void viva_label_window(size_t full, size_t limit, BOOL visible, size_t left, size_t right, - size_t *windowLeft, size_t *windowRight) { - size_t width = MIN(full, limit); - if (!visible) { - *windowLeft = 0; - *windowRight = width; - return; - } - size_t span = right - left; - if (span >= width) { - *windowLeft = left; - *windowRight = right; - return; - } - size_t margin = MIN(span, (width - span) / 2); - width = span + 2 * margin; - size_t low = left > margin ? left - margin : 0; - if (low + width > full) { - low = full - width; - } - *windowLeft = low; - *windowRight = low + width; -} - -@implementation VivaTextLayer - -- (instancetype)initWithConfig:(viva_text_label)config { - self = [super init]; - if (self != nil) { - // Bitmap labels carry no UTF-8 buffer. Give them an explicit empty - // string so image-only labels can still own a Metal texture. - if (config.utf8_length == 0) { - _value = [@"" retain]; - } else if (config.utf8 == NULL) { - [self release]; - return nil; - } else { - _value = [[NSString alloc] initWithBytes:config.utf8 - length:config.utf8_length - encoding:NSUTF8StringEncoding]; - } - if (_value == nil) { - [self release]; - return nil; - } - _frame = NSMakeRect(config.x, config.y, config.width, config.height); - [self updateClipFromConfig:config]; - [self updateQuadFromConfig:config]; - _fontSize = config.font_size; - _fontWeight = config.font_weight; - _italic = (config.flags & VIVA_LABEL_ITALIC) != 0; - _red = config.red; - _green = config.green; - _blue = config.blue; - _alpha = config.alpha; - _lastScale = 0; - _originX = viva_quantized_origin(config.origin_x); - _originY = viva_quantized_origin(config.origin_y); - _hash = viva_label_content_hash(config); - _fontGeneration = config.font_generation; - _mono = (config.flags & VIVA_LABEL_MONO) != 0; - _monoFace = config.mono_face; - _cellWidth = config.cell_width; - _baseline = config.baseline; - if (config.run_count > 0 && config.runs != NULL) { - _runs = malloc(config.run_count * sizeof(viva_text_run)); - if (_runs == NULL) { - [self release]; - return nil; - } - memcpy(_runs, config.runs, config.run_count * sizeof(viva_text_run)); - _runCount = config.run_count; - _utf8 = [[NSData alloc] initWithBytes:config.utf8 length:config.utf8_length]; - } - if ((config.flags & VIVA_LABEL_BITMAP) != 0) { - // An image the Go side did not send has nothing to draw from: fail the update - // rather than keep a layer that renders blank. - if (config.bitmap == NULL) { - [self release]; - return nil; - } - _bitmap = [[NSData alloc] initWithBytes:config.bitmap length:config.bitmap_length]; - _bitmapWidth = config.bitmap_width; - _bitmapHeight = config.bitmap_height; - _bitmapStride = config.bitmap_stride; - _bitmapID = config.bitmap_id; - _bitmapVersion = config.bitmap_version; - } - } - return self; -} - -- (void)dealloc { - [_texture release]; - [_additionalTextures release]; - [_value release]; - [_utf8 release]; - [_bitmap release]; - free(_runs); - [super dealloc]; -} - -- (uint64_t)contentHash { - return _hash; -} - -- (BOOL)matchesConfig:(viva_text_label)config { - if (![self contentMatchesSizeAgnostic:config]) { - return NO; - } - if (_bitmap != nil) { - return YES; - } - return _frame.size.width == config.width && _frame.size.height == config.height; -} - -- (BOOL)contentMatchesSizeAgnostic:(viva_text_label)config { - // Content identity: font, color, and text. Position never matters (the - // quad supplies it each draw); size matters only for texel alignment, - // which live resize may temporarily relax. - if (_fontSize != config.font_size || _fontWeight != config.font_weight || _fontGeneration != config.font_generation) { - return NO; - } - if (_italic != ((config.flags & VIVA_LABEL_ITALIC) != 0)) { - return NO; - } - if (_originX != viva_quantized_origin(config.origin_x) || _originY != viva_quantized_origin(config.origin_y)) { - return NO; - } - if (_red != config.red || _green != config.green || - _blue != config.blue || _alpha != config.alpha) { - return NO; - } - if (_mono != ((config.flags & VIVA_LABEL_MONO) != 0) || - _monoFace != config.mono_face || _cellWidth != config.cell_width || _baseline != config.baseline || - _runCount != (config.runs == NULL ? 0 : config.run_count) || - (_runCount > 0 && memcmp(_runs, config.runs, _runCount * sizeof(viva_text_run)) != 0)) { - return NO; - } - BOOL bitmap = (config.flags & VIVA_LABEL_BITMAP) != 0; - if ((_bitmap != nil) != bitmap) { - return NO; - } - if (bitmap) { - if (_bitmapWidth != config.bitmap_width || _bitmapHeight != config.bitmap_height || - _bitmapStride != config.bitmap_stride || _bitmapID != config.bitmap_id || - _bitmapVersion != config.bitmap_version || _bitmap.length != config.bitmap_length) { - return NO; - } - if (config.bitmap_upload != 0 && (config.bitmap == NULL || memcmp(_bitmap.bytes, config.bitmap, config.bitmap_length) != 0)) { - return NO; - } - } - size_t valueLength = [_value lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; - if (config.utf8_length != valueLength) { - return NO; - } - if (config.utf8_length == 0) { - return YES; - } - if (config.utf8 == NULL) { - return NO; - } - return memcmp(config.utf8, [_value UTF8String], config.utf8_length) == 0; -} - -- (void)updateClipFromConfig:(viva_text_label)config { - _clipped = (config.flags & VIVA_LABEL_CLIPPED) != 0; - _clip = _clipped ? NSMakeRect(config.clip_x, config.clip_y, config.clip_width, config.clip_height) : NSZeroRect; -} - -- (void)updateQuadFromConfig:(viva_text_label)config { - // The quad is where the label lands, not what it looks like: it changes - // every frame of an animation while the texture stays the same one. - BOOL hasQuad = NO; - for (int index = 0; index < 8; index++) { - _quad[index] = config.quad[index]; - hasQuad = hasQuad || config.quad[index] != 0; - } - for (int index = 0; index < 16; index++) { - _tint[index] = config.tint[index]; - } - _hasQuad = hasQuad; - _imageRadius = hasQuad ? 0 : config.image_radius; - if (hasQuad) { - return; - } - // An ordinary label keeps its box as the quad and opaque white as its tint, - // so the renderer has no case to special-case per frame. - _quad[0] = config.x; - _quad[1] = config.y; - _quad[2] = config.x + config.width; - _quad[3] = config.y; - _quad[4] = config.x; - _quad[5] = config.y + config.height; - _quad[6] = config.x + config.width; - _quad[7] = config.y + config.height; - for (int index = 0; index < 16; index++) { - _tint[index] = 1; - } - if (config.image_fade > 0) { - // Fade is draw-time: it scales the premultiplied tint, so the picture's - // texture is untouched. - float alpha = 1 - config.image_fade; - for (int index = 0; index < 16; index++) { - _tint[index] *= alpha; - } - } -} - -- (const float *)quad { - return _quad; -} - -- (const float *)tint { - return _tint; -} - -- (float)imageRadius { - return _imageRadius; -} - -- (BOOL)clipped { - return _clipped; -} - -- (NSRect)clip { - return _clip; -} - -- (void)updateFrame:(NSRect)frame { - _frame = frame; -} - -- (BOOL)forceTextureRebuildWithDevice:(id)device scale:(CGFloat)scale viewport:(NSSize)viewport { - _lastScale = 0; - return [self rebuildWithDevice:device scale:scale viewport:viewport]; -} - -- (void)markContentRebuild { - viva_label_texture_rebuild_count++; -} - -// refreshWindowWithDevice rasterizes a label held in part again when the part of it that -// can be seen in viewport is no longer all in its texture: it moved, or its clip or the -// viewport did. Any other label is left as it is. -- (BOOL)refreshWindowWithDevice:(id)device scale:(CGFloat)scale viewport:(NSSize)viewport { - CGFloat widthScale = [self rasterWidthScale:scale]; - if (_texture == nil || _lastScale != scale || - viva_bitmap_extent_stale((size_t)ceil(_frame.size.width * _windowPixelScale), (size_t)ceil(_frame.size.width * widthScale))) { - _lastScale = 0; - BOOL rebuilt = [self rebuildWithDevice:device scale:scale viewport:viewport]; - if (rebuilt) [self markContentRebuild]; - return rebuilt; - } - if (!_windowed) { - return YES; - } - size_t full = (size_t)MAX(1.0, ceil(_frame.size.width * _windowPixelScale)); - size_t left = 0, right = 0; - if (!viva_label_visible_span(_quad, _tint, _clipped, _clip, viewport, full, &left, &right) || - (left >= _windowLeft && right <= _windowRight)) { - return YES; - } - _lastScale = 0; - if (![self rebuildWithDevice:device scale:scale viewport:viewport]) { - return NO; - } - [self markContentRebuild]; - return YES; -} - -- (CGFloat)rasterWidthScale:(CGFloat)scale { - CGFloat pixelScale = ceil(scale); - if (!_hasQuad || _frame.size.width <= 0) { - return pixelScale; - } - CGFloat top = hypot((double)_quad[2] - _quad[0], (double)_quad[3] - _quad[1]); - CGFloat bottom = hypot((double)_quad[6] - _quad[4], (double)_quad[7] - _quad[5]); - return MIN(pixelScale, MAX(1, ceil(MAX(top, bottom) * pixelScale)) / _frame.size.width); -} - -- (BOOL)rebuildWithDevice:(id)device scale:(CGFloat)scale viewport:(NSSize)viewport { - size_t wantWidth = 0, wantHeight = 0; - if (_bitmap != nil) { - viva_bitmap_texture_extent(_frame, scale, _bitmapWidth, _bitmapHeight, &wantWidth, &wantHeight); - } - if (_texture != nil && (_bitmap != nil - ? !viva_bitmap_extent_stale(_textureWidth, wantWidth) && !viva_bitmap_extent_stale(_textureHeight, wantHeight) - : _lastScale == scale)) { - return YES; - } - if (_bitmap != nil) { - if (_bitmapWidth == 0 || _bitmapHeight == 0 || - _bitmapStride < (size_t)_bitmapWidth * 4 || _bitmapHeight - 1 > SIZE_MAX / _bitmapStride || - _bitmap.length < (size_t)(_bitmapHeight - 1) * _bitmapStride + (size_t)_bitmapWidth * 4) { - return NO; - } - size_t uploadWidth = _bitmapWidth, uploadHeight = _bitmapHeight; - NSData *uploadData = _bitmap; - uint32_t uploadStride = _bitmapStride; - if (wantWidth != _bitmapWidth || wantHeight != _bitmapHeight) { - NSData *reduced = viva_downsample_bitmap(_bitmap, _bitmapWidth, _bitmapHeight, _bitmapStride, wantWidth, wantHeight); - if (reduced == nil) { - return NO; - } - uploadData = reduced; - uploadWidth = wantWidth; - uploadHeight = wantHeight; - uploadStride = (uint32_t)(wantWidth * 4); - } - MTLTextureDescriptor *descriptor = [MTLTextureDescriptor - texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm - width:uploadWidth - height:uploadHeight - mipmapped:NO]; - descriptor.storageMode = MTLStorageModeShared; - descriptor.usage = MTLTextureUsageShaderRead; - id texture = [device newTextureWithDescriptor:descriptor]; - if (texture != nil) { - [texture replaceRegion:MTLRegionMake2D(0, 0, uploadWidth, uploadHeight) - mipmapLevel:0 - withBytes:uploadData.bytes - bytesPerRow:uploadStride]; - } - if (uploadData != _bitmap) { - [uploadData release]; - } - if (texture == nil) { - return NO; - } - [_texture release]; - _texture = texture; - _textureWidth = uploadWidth; - _textureHeight = uploadHeight; - _lastScale = scale; - return YES; - } - // Rasterize on the integer physical-pixel grid: a fractional frame origin - // must not bleed anti-aliasing across texel boundaries. - CGFloat pixelScale = ceil(scale); - CGFloat widthScale = [self rasterWidthScale:scale]; - size_t fullWidth = (size_t)MAX(1.0, ceil(_frame.size.width * widthScale)); - size_t pixelHeight = (size_t)MAX(1.0, ceil(_frame.size.height * pixelScale)); - if (pixelHeight > VIVA_LABEL_TEXTURE_LIMIT) { - return NO; - } - // A line wider than a texture holds (a long line laid out at its full width and - // scrolled) is rasterized only around the part of it that can be seen. - BOOL windowed = fullWidth > VIVA_LABEL_TEXTURE_LIMIT; - size_t windowLeft = 0, windowRight = fullWidth; - if (windowed) { - size_t left = 0, right = 0; - BOOL visible = viva_label_visible_span(_quad, _tint, _clipped, _clip, viewport, fullWidth, &left, &right); - viva_label_window(fullWidth, VIVA_LABEL_TEXTURE_LIMIT, visible, left, right, &windowLeft, &windowRight); - } - id texture = nil; - NSMutableArray> *additionalTextures = nil; - for (size_t tileLeft = windowLeft; tileLeft < windowRight;) { - size_t tileRight = tileLeft + MIN(windowRight - tileLeft, VIVA_LABEL_TILE_WIDTH); - size_t textureLeft = tileLeft > 0 ? tileLeft - 1 : 0; - size_t textureRight = MIN(tileRight + 1, fullWidth); - size_t pixelWidth = textureRight - textureLeft; - size_t rowBytes = pixelWidth * 4; - if (pixelHeight > SIZE_MAX / rowBytes) { - [texture release]; - [additionalTextures release]; - return NO; - } - void *pixels = calloc(pixelHeight, rowBytes); - if (pixels == NULL) { - [texture release]; - [additionalTextures release]; - return NO; - } - CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); - CGContextRef context = CGBitmapContextCreate( - pixels, pixelWidth, pixelHeight, 8, rowBytes, colorSpace, - kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little - ); - CGColorSpaceRelease(colorSpace); - if (context == NULL) { - free(pixels); - [texture release]; - [additionalTextures release]; - return NO; - } - viva_prepare_text_context(context, pixelScale); - CGContextScaleCTM(context, widthScale / pixelScale, 1); - if (textureLeft > 0) { - CGContextTranslateCTM(context, -(CGFloat)textureLeft / widthScale, 0); - } - if (_runCount > 0) { - [self drawRunsInContext:context pixelScale:pixelScale]; - } else { - [self drawLineInContext:context pixelScale:pixelScale]; - } - MTLTextureDescriptor *descriptor = [MTLTextureDescriptor - texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm - width:pixelWidth - height:pixelHeight - mipmapped:NO]; - descriptor.storageMode = MTLStorageModeShared; - descriptor.usage = MTLTextureUsageShaderRead; - id nextTexture = [device newTextureWithDescriptor:descriptor]; - if (nextTexture != nil) { - [nextTexture replaceRegion:MTLRegionMake2D(0, 0, pixelWidth, pixelHeight) - mipmapLevel:0 withBytes:pixels bytesPerRow:rowBytes]; - } - CGContextRelease(context); - free(pixels); - if (nextTexture == nil) { - [texture release]; - [additionalTextures release]; - return NO; - } - if (texture == nil) { - texture = nextTexture; - } else { - if (additionalTextures == nil) { - additionalTextures = [[NSMutableArray alloc] init]; - if (additionalTextures == nil) { - [nextTexture release]; - [texture release]; - return NO; - } - } - [additionalTextures addObject:nextTexture]; - [nextTexture release]; - } - tileLeft = tileRight; - } - [_texture release]; - _texture = texture; - [_additionalTextures release]; - _additionalTextures = additionalTextures; - _lastScale = scale; - _windowed = windowed; - _windowLeft = windowLeft; - _windowRight = windowRight; - _windowPixelScale = widthScale; - return YES; -} - -// drawLineInContext draws an ordinary label: one line in one font and color, -// vertically centered. -- (void)drawLineInContext:(CGContextRef)context pixelScale:(CGFloat)pixelScale { - CGColorRef foreground = CGColorCreateSRGB(_red, _green, _blue, _alpha); - CGFloat baseline = _baseline > 0 - ? viva_fixed_baseline(_frame.size.height, _baseline, pixelScale) - : viva_baseline(_frame.size.height, _fontSize, pixelScale); - // Text laid out at a fraction of a pixel below the frame: Core Graphics puts a baseline - // on the next device row down (it floors in its y-up space, so AppKit does), and a - // glyph at a fraction of a pixel across (it quantizes the position, in drawing the line). - baseline -= ceil(_originY * pixelScale - 1e-4) / pixelScale; - if (_mono) { - // A fixed-pitch label is not proportional text: it keeps its own advances. - // The line carries the face's font (the NSFont itself: looking it up again by - // name fails for the monospaced system font at a weight, whose name is private - // to that instance, and CoreText answers with Times New Roman) and, for the - // clusters no family of it draws, the installed fallback. - CTLineRef line = viva_mono_fallback_line(_value, viva_mono_font(_fontSize, _fontWeight, _monoFace), _monoFace, foreground); - if (line != NULL) { - CGContextSetTextPosition(context, _originX, baseline); - CTLineDraw(line, context); - CFRelease(line); - } - } else { - viva_text_line *shaped = viva_shared_text_line_style(_value, _fontSize, _fontWeight, _italic); - if (shaped != NULL) { - viva_draw_text_line(context, shaped, foreground, _originX, baseline); - viva_text_line_release(shaped); - } - } - CFRelease(foreground); -} - -// drawRunsInContext draws a fixed-pitch grid line. Every run is shaped on its -// own and placed at its cell, so colors, wide characters and glyphs that come -// from fallback fonts cannot push later text off its column. All runs share -// one baseline taken from the base font. -- (void)drawRunsInContext:(CGContextRef)context pixelScale:(CGFloat)pixelScale { - NSFont *baseFont = viva_mono_font(_fontSize, _fontWeight, _monoFace); - CGFloat baseline = _baseline > 0 - ? viva_fixed_baseline(_frame.size.height, _baseline, pixelScale) - : viva_baseline(_frame.size.height, _fontSize, pixelScale); - CGFloat hairline = 1.0 / pixelScale; - const unsigned char *bytes = (const unsigned char *)_utf8.bytes; - size_t length = _utf8.length; - size_t offset = 0; - - // Fonts differ only by weight and slant; a line rarely has more than a few. - enum { kFontCache = 4, kMaxGlyphRun = 256 }; - CTFontRef cachedFont[kFontCache] = {NULL}; - float cachedWeight[kFontCache] = {0}; - BOOL cachedItalic[kFontCache] = {NO}; - int cacheCount = 0; - - for (size_t index = 0; index < _runCount; index++) { - const viva_text_run *run = &_runs[index]; - if (run->bytes > length - offset) { - break; - } - const unsigned char *start = bytes + offset; - size_t count = run->bytes; - offset += count; - BOOL italic = (run->flags & VIVA_RUN_ITALIC) != 0; - CTFontRef font = NULL; - for (int slot = 0; slot < cacheCount; slot++) { - if (cachedWeight[slot] == run->weight && cachedItalic[slot] == italic) { - font = cachedFont[slot]; - break; - } - } - if (font == NULL) { - NSFont *native = viva_mono_font(_fontSize, run->weight, _monoFace); - font = (CTFontRef)CFRetain(native); - if (italic) { - CGAffineTransform slant = CGAffineTransformMake(1, 0, 0.2126, 1, 0, 0); - CTFontRef slanted = CTFontCreateCopyWithAttributes(font, _fontSize, &slant, NULL); - if (slanted != NULL) { - CFRelease(font); - font = slanted; - } - } - if (cacheCount < kFontCache) { - cachedFont[cacheCount] = font; - cachedWeight[cacheCount] = run->weight; - cachedItalic[cacheCount] = italic; - cacheCount++; - } - } - CGColorRef foreground = CGColorCreateSRGB(run->red, run->green, run->blue, run->alpha); - CGFloat cellLeft = (CGFloat)run->column * _cellWidth; - CGFloat span = (CGFloat)run->cells * _cellWidth; - BOOL ascii = YES; - for (size_t at = 0; ascii && at < count; at++) { - ascii = start[at] >= 0x20 && start[at] < 0x7F; - } - if ((run->flags & VIVA_RUN_LIGATURES) != 0 && count > 0) { - // A ligature run is shaped as one line and scaled to its cells, so - // the font's substitutions survive and the run still ends where - // the grid says it does. - NSString *shown = [[NSString alloc] initWithBytes:start - length:count - encoding:NSUTF8StringEncoding]; - if (shown != nil) { - CTLineRef line = viva_mono_fallback_line(shown, (NSFont *)font, _monoFace, foreground); - if (line != NULL) { - CGFloat width = CTLineGetTypographicBounds(line, NULL, NULL, NULL); - if (width > 0 && span > 0) { - CGContextSaveGState(context); - CGContextTranslateCTM(context, cellLeft, baseline); - CGContextScaleCTM(context, span / width, 1); - CGContextSetTextPosition(context, 0, 0); - CTLineDraw(line, context); - CGContextRestoreGState(context); - } - CFRelease(line); - } - [shown release]; - } - } else if (ascii) { - // Plain ASCII needs no shaping in a fixed-pitch font: map the - // characters to glyphs and put glyph i exactly on cell i. The run - // is drawn in pieces of kMaxGlyphRun, every glyph still on its - // own cell. - UniChar characters[kMaxGlyphRun]; - CGGlyph glyphs[kMaxGlyphRun]; - CGPoint positions[kMaxGlyphRun]; - CGContextSetFillColorWithColor(context, foreground); - // Glyph positions are relative to the text position. - CGContextSetTextPosition(context, 0, 0); - for (size_t first = 0; first < count; first += kMaxGlyphRun) { - size_t piece = count - first; - if (piece > kMaxGlyphRun) { - piece = kMaxGlyphRun; - } - for (size_t at = 0; at < piece; at++) { - characters[at] = start[first + at]; - positions[at] = CGPointMake(cellLeft + (CGFloat)(first + at) * _cellWidth, baseline); - } - CTFontGetGlyphsForCharacters(font, characters, glyphs, (CFIndex)piece); - CTFontDrawGlyphs(font, glyphs, positions, (CFIndex)piece, context); - } - } else { - NSString *shown = [[NSString alloc] initWithBytes:start - length:count - encoding:NSUTF8StringEncoding]; - if (shown == nil) { - CFRelease(foreground); - continue; - } - CTLineRef line = viva_mono_fallback_line(shown, (NSFont *)font, _monoFace, foreground); - if (line == NULL) { - [shown release]; - CFRelease(foreground); - continue; - } - CGFloat x = cellLeft; - if (run->cells > 0) { - CFRange cluster = CFStringGetRangeOfComposedCharactersAtIndex((CFStringRef)shown, 0); - if (cluster.length == (CFIndex)shown.length) { - // A lone character takes the middle of its cells, so wide - // characters and symbols from other fonts sit evenly. - CGFloat width = CTLineGetTypographicBounds(line, NULL, NULL, NULL); - x = cellLeft + (span - width) / 2; - } - } - CGContextSetTextPosition(context, x, baseline); - CTLineDraw(line, context); - CFRelease(line); - [shown release]; - } - - if ((run->flags & (VIVA_RUN_UNDERLINE | VIVA_RUN_STRIKE)) != 0 && span > 0) { - CGContextSetFillColorWithColor(context, foreground); - CGFloat thickness = MAX(hairline, CTFontGetUnderlineThickness(font)); - thickness = ceil(thickness * pixelScale) / pixelScale; - if ((run->flags & VIVA_RUN_UNDERLINE) != 0) { - CGFloat y = baseline + CTFontGetUnderlinePosition(font) - thickness / 2; - y = floor(y * pixelScale) / pixelScale; - CGContextFillRect(context, CGRectMake(cellLeft, y, span, thickness)); - } - if ((run->flags & VIVA_RUN_STRIKE) != 0) { - CGFloat y = baseline + CTFontGetXHeight(font) * 0.5 - thickness / 2; - y = floor(y * pixelScale) / pixelScale; - CGContextFillRect(context, CGRectMake(cellLeft, y, span, thickness)); - } - } - - CFRelease(foreground); - } - for (int slot = 0; slot < cacheCount; slot++) { - CFRelease(cachedFont[slot]); - } -} - -- (id)textureAtIndex:(NSUInteger)index { - return index == 0 ? _texture : [_additionalTextures objectAtIndex:index - 1]; -} - -- (NSUInteger)textureCount { - return 1 + _additionalTextures.count; -} - -- (NSRect)frame { - return _frame; -} - -- (NSRect)quadAtIndex:(NSUInteger)index { - if (_bitmap != nil) { - return _frame; - } - size_t full = (size_t)MAX(1.0, ceil(_frame.size.width * _windowPixelScale)); - size_t tileLeft = _windowLeft + index * VIVA_LABEL_TILE_WIDTH; - size_t tileRight = tileLeft + MIN(_windowRight - tileLeft, VIVA_LABEL_TILE_WIDTH); - CGFloat left = (CGFloat)tileLeft / _windowPixelScale; - CGFloat right = tileRight >= full ? _frame.size.width : (CGFloat)tileRight / _windowPixelScale; - return NSMakeRect(_frame.origin.x + left, _frame.origin.y, right - left, _frame.size.height); -} - -- (NSRect)textureFrameAtIndex:(NSUInteger)index { - if (_bitmap != nil) return _frame; - size_t full = (size_t)MAX(1.0, ceil(_frame.size.width * _windowPixelScale)); - size_t tileLeft = _windowLeft + index * VIVA_LABEL_TILE_WIDTH; - size_t tileRight = tileLeft + MIN(_windowRight - tileLeft, VIVA_LABEL_TILE_WIDTH); - size_t textureLeft = tileLeft > 0 ? tileLeft - 1 : 0; - size_t textureRight = MIN(tileRight + 1, full); - CGFloat left = (CGFloat)textureLeft / _windowPixelScale; - CGFloat right = textureRight >= full ? _frame.size.width : (CGFloat)textureRight / _windowPixelScale; - return NSMakeRect(_frame.origin.x + left, _frame.origin.y, right - left, _frame.size.height); -} - -@end +// viva_test_pasteboard replaces the general pasteboard in native tests, which +// must not read or overwrite the user's clipboard. +static NSPasteboard *viva_test_pasteboard; -// Keep native windows and offscreen frames on the same retained-texture path. -// viewport is the size of the window or frame the labels are drawn in, logical pixels. -static int viva_update_label_layers( - NSArray *previous, - const viva_text_label *labels, - NSUInteger count, - id device, - CGFloat scale, - NSSize viewport, - NSMutableArray **updated -) { - NSMutableArray *replacement = - [[NSMutableArray alloc] initWithCapacity:count]; - NSUInteger oldCount = previous.count; - uint64_t *oldHashes = malloc(MAX(oldCount, 1) * sizeof(uint64_t)); - uint64_t *newHashes = malloc(MAX(count, 1) * sizeof(uint64_t)); - int64_t *source = malloc(MAX(count, 1) * sizeof(int64_t)); - if (oldHashes == NULL || newHashes == NULL || source == NULL) { - free(oldHashes); - free(newHashes); - free(source); - [replacement release]; - return 3; - } - for (NSUInteger index = 0; index < oldCount; index++) { - oldHashes[index] = [previous[index] contentHash]; - } - for (NSUInteger index = 0; index < count; index++) { - newHashes[index] = viva_label_content_hash(labels[index]); - } - int status = viva_plan_label_reuse(oldHashes, oldCount, newHashes, count, source); - free(oldHashes); - free(newHashes); - if (status != 0) { - free(source); - [replacement release]; - return status; +static NSPasteboard *viva_pasteboard(void) { + if (viva_test_pasteboard != nil) { + return viva_test_pasteboard; } - for (NSUInteger index = 0; index < count; index++) { - VivaTextLayer *existing = nil; - if (source[index] >= 0 && [previous[(NSUInteger)source[index]] matchesConfig:labels[index]]) { - existing = previous[(NSUInteger)source[index]]; - } - if (existing != nil) { - [existing updateFrame:NSMakeRect( - labels[index].x, labels[index].y, - labels[index].width, labels[index].height)]; - [existing updateClipFromConfig:labels[index]]; - [existing updateQuadFromConfig:labels[index]]; - // An image drawn at a new size may need a texture of another resolution, and a - // line held in part another part of it. - BOOL rebuilt = (labels[index].flags & VIVA_LABEL_BITMAP) != 0 - ? [existing rebuildWithDevice:device scale:scale viewport:viewport] - : [existing refreshWindowWithDevice:device scale:scale viewport:viewport]; - if (!rebuilt) { - free(source); - [replacement release]; - return 3; - } - [replacement addObject:existing]; - continue; - } - VivaTextLayer *layer = [[VivaTextLayer alloc] initWithConfig:labels[index]]; - if (layer == nil || ![layer rebuildWithDevice:device scale:scale viewport:viewport]) { - int failure = layer == nil ? 2 : 3; - free(source); - [layer release]; - [replacement release]; - return failure; - } - [layer markContentRebuild]; - [replacement addObject:layer]; - [layer release]; + // VIVA_TEST_PASTEBOARD=1 keeps a manual run's copy and paste on a private + // pasteboard, like the other VIVA_TEST_* switches. + const char *value = getenv("VIVA_TEST_PASTEBOARD"); + if (value != NULL && value[0] == '1' && value[1] == '\0') { + return [NSPasteboard pasteboardWithName:@"viva.test.pasteboard"]; } - free(source); - *updated = replacement; - return 0; + return [NSPasteboard generalPasteboard]; } -// viva_label_box_quad writes the four corners of an axis-aligned box in the -// order the text vertex shader expects them: top-left, top-right, bottom-left, -// bottom-right. -static void viva_label_box_quad(float *quad, float x, float y, float width, float height) { - quad[0] = x; - quad[1] = y; - quad[2] = x + width; - quad[3] = y; - quad[4] = x; - quad[5] = y + height; - quad[6] = x + width; - quad[7] = y + height; -} - -// viva_label_plain_tint writes the colour that leaves a label's pixels as they -// are: opaque white at every corner. -static void viva_label_plain_tint(float *tint) { - for (int index = 0; index < 16; index++) { - tint[index] = 1; - } -} - -// viva_label_tile_mesh maps one texture tile's part of the label's triangles. A -// label wider than a texture holds arrives in several tiles, each a horizontal -// slice of the same picture; clipping the original triangles preserves their -// affine texture coordinates and tints across tile boundaries. -static size_t viva_label_tile_mesh( - const float *quad, - const float *tint, - NSRect frame, - NSRect tile, - NSRect texture, - viva_label_vertex *vertices -) { - CGFloat width = frame.size.width > 0 ? frame.size.width : 1; - float left = (float)((tile.origin.x - frame.origin.x) / width); - float right = (float)((tile.origin.x + tile.size.width - frame.origin.x) / width); - left = fminf(fmaxf(left, 0), 1); - right = fminf(fmaxf(right, 0), 1); - float textureLeft = (float)((texture.origin.x - frame.origin.x) / width); - float textureRight = (float)((texture.origin.x + texture.size.width - frame.origin.x) / width); - return viva_label_tile_vertices(quad, tint, left, right, textureLeft, textureRight, vertices); -} - -// viva_text_label_uniform mirrors TextLabelUniform in scene.metal: where a -// label's box starts, its size, and the radius its picture's corners are cut by. -typedef struct { - float originX, originY; - float sizeX, sizeY; - float radius; - float padding; -} viva_text_label_uniform; - -// viva_encode_input draws the native editor's texture. -static void viva_encode_input( - id encoder, - id textPipeline, - id inputTexture, - NSRect inputFrame, - NSSize viewport -) { - float viewportSize[2] = {(float)viewport.width, (float)viewport.height}; - float quad[8]; - viva_label_box_quad(quad, - (float)inputFrame.origin.x, (float)inputFrame.origin.y, - (float)inputFrame.size.width, (float)inputFrame.size.height); - float tint[16]; - viva_label_plain_tint(tint); - viva_label_vertex vertices[6]; - viva_label_vertices(quad, tint, vertices); - [encoder setRenderPipelineState:textPipeline]; - [encoder setVertexBytes:vertices length:sizeof(vertices) atIndex:2]; - viva_text_label_uniform labelUniform = {0, 0, 0, 0, 0, 0}; - [encoder setVertexBytes:&labelUniform length:sizeof(labelUniform) atIndex:3]; - [encoder setVertexBytes:&viewportSize length:sizeof(viewportSize) atIndex:1]; - [encoder setFragmentTexture:inputTexture atIndex:0]; - [encoder drawPrimitives:MTLPrimitiveTypeTriangle vertexStart:0 vertexCount:6]; - viva_gpu_draw_call_count++; -} - -// viva_encode_scene draws one frame: the rectangle and text-label batches in -// composite order, with the native editor's texture drawn after every batch of -// its own layer, so a higher layer (a popup over the field) covers it. The window and the -// headless renderer share it, so a screenshot is the pixels the window shows. -static void viva_encode_scene( - id encoder, - id rectanglePipeline, - id textPipeline, - id rectangleBuffer, - const viva_composite_command *commands, - NSUInteger commandCount, - NSArray *labels, - id inputTexture, - NSRect inputFrame, - uint16_t inputLayer, - NSSize viewport, - NSUInteger targetWidth, - NSUInteger targetHeight -) { - float viewportSize[2] = {(float)viewport.width, (float)viewport.height}; - BOOL inputDrawn = inputTexture == nil; - // A label that a canvas clip cuts is drawn through a scissor, so the part - // outside the clip is never painted. The scale maps logical pixels to the - // target's. - CGFloat targetScale = viewport.width > 0 ? (CGFloat)targetWidth / viewport.width : 1.0; - float sceneViewport[4] = {(float)viewport.width, (float)viewport.height, (float)(1.0 / targetScale), 0}; - MTLScissorRect fullTarget = {0, 0, targetWidth, targetHeight}; - for (NSUInteger index = 0; index < commandCount; index++) { - viva_composite_command command = commands[index]; - if (!inputDrawn && command.layer > inputLayer) { - viva_encode_input(encoder, textPipeline, inputTexture, inputFrame, viewport); - inputDrawn = YES; - } - if (command.kind == VIVA_COMPOSITE_RECTANGLES) { - // A clipped batch is drawn through a scissor. An edge between two - // pixel boundaries moves to the nearer one, as render.ScissorOf does. - if (command.clipped != 0) { - CGFloat leftEdge = floor(command.clip_x * targetScale + 0.5); - CGFloat topEdge = floor(command.clip_y * targetScale + 0.5); - CGFloat rightEdge = floor((command.clip_x + command.clip_width) * targetScale + 0.5); - CGFloat bottomEdge = floor((command.clip_y + command.clip_height) * targetScale + 0.5); - NSInteger left = (NSInteger)MIN(MAX(leftEdge, 0), (CGFloat)targetWidth); - NSInteger top = (NSInteger)MIN(MAX(topEdge, 0), (CGFloat)targetHeight); - NSInteger right = (NSInteger)MIN(MAX(rightEdge, 0), (CGFloat)targetWidth); - NSInteger bottom = (NSInteger)MIN(MAX(bottomEdge, 0), (CGFloat)targetHeight); - if (right <= left || bottom <= top) { - continue; - } - MTLScissorRect scissor = {(NSUInteger)left, (NSUInteger)top, (NSUInteger)(right - left), (NSUInteger)(bottom - top)}; - [encoder setScissorRect:scissor]; - } - [encoder setRenderPipelineState:rectanglePipeline]; - [encoder setVertexBuffer:rectangleBuffer offset:0 atIndex:0]; - [encoder setVertexBytes:&sceneViewport length:sizeof(sceneViewport) atIndex:1]; - [encoder drawPrimitives:MTLPrimitiveTypeTriangle - vertexStart:0 - vertexCount:6 - instanceCount:command.count - baseInstance:command.first]; - viva_gpu_draw_call_count++; - viva_rectangle_instance_count += command.count; - if (command.clipped != 0) { - [encoder setScissorRect:fullTarget]; - } - continue; - } - - VivaTextLayer *layer = [labels objectAtIndex:command.first]; - BOOL scissored = NO; - if ([layer clipped]) { - NSRect clip = [layer clip]; - NSInteger left = MAX((NSInteger)floor(clip.origin.x * targetScale), 0); - NSInteger top = MAX((NSInteger)floor(clip.origin.y * targetScale), 0); - NSInteger right = MIN((NSInteger)ceil((clip.origin.x + clip.size.width) * targetScale), (NSInteger)targetWidth); - NSInteger bottom = MIN((NSInteger)ceil((clip.origin.y + clip.size.height) * targetScale), (NSInteger)targetHeight); - if (right <= left || bottom <= top) { - continue; - } - MTLScissorRect scissor = {(NSUInteger)left, (NSUInteger)top, (NSUInteger)(right - left), (NSUInteger)(bottom - top)}; - [encoder setScissorRect:scissor]; - scissored = YES; - } - [encoder setRenderPipelineState:textPipeline]; - [encoder setVertexBytes:&viewportSize length:sizeof(viewportSize) atIndex:1]; - NSRect layerFrame = [layer frame]; - viva_text_label_uniform labelUniform = { - (float)layerFrame.origin.x, (float)layerFrame.origin.y, - (float)layerFrame.size.width, (float)layerFrame.size.height, - [layer imageRadius], 0, - }; - [encoder setVertexBytes:&labelUniform length:sizeof(labelUniform) atIndex:3]; - for (NSUInteger tile = 0; tile < [layer textureCount]; tile++) { - viva_label_vertex vertices[18]; - size_t count = viva_label_tile_mesh([layer quad], [layer tint], [layer frame], - [layer quadAtIndex:tile], [layer textureFrameAtIndex:tile], vertices); - if (count == 0) continue; - [encoder setVertexBytes:vertices length:count * sizeof(viva_label_vertex) atIndex:2]; - [encoder setFragmentTexture:[layer textureAtIndex:tile] atIndex:0]; - [encoder drawPrimitives:MTLPrimitiveTypeTriangle vertexStart:0 vertexCount:count]; - viva_gpu_draw_call_count++; - } - if (scissored) { - [encoder setScissorRect:fullTarget]; +// viva_single_line_paste prepares clipboard text for a single-line field: line +// breaks cannot live in one line, and leading or trailing ones (copied whole +// lines, shell output) must not turn into stray spaces. +static NSString *viva_single_line_paste(NSString *value) { + // CRLF is two characters of the newline set, so splitting leaves an empty + // piece between them; empty pieces are dropped rather than joined as spaces. + NSMutableArray *lines = [NSMutableArray array]; + for (NSString *line in [value componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]]) { + if (line.length > 0) { + [lines addObject:line]; } } - if (!inputDrawn) { - viva_encode_input(encoder, textPipeline, inputTexture, inputFrame, viewport); - } + return [lines componentsJoinedByString:@" "]; } @interface VivaAccessibleElement : NSAccessibilityElement { diff --git a/internal/platform/darwin/testdata/dock_reopen.m b/internal/platform/darwin/testdata/dock_reopen.m index ca1efffc0..d173896c2 100644 --- a/internal/platform/darwin/testdata/dock_reopen.m +++ b/internal/platform/darwin/testdata/dock_reopen.m @@ -1,3 +1,5 @@ +#include "../core_text.m" +#include "../core_render.m" #include "../native.m" #include "../main_menu_darwin.m" #include diff --git a/internal/platform/darwin/testdata/file_drop.m b/internal/platform/darwin/testdata/file_drop.m index a5fd45781..5837a8cf8 100644 --- a/internal/platform/darwin/testdata/file_drop.m +++ b/internal/platform/darwin/testdata/file_drop.m @@ -1,3 +1,5 @@ +#include "../core_text.m" +#include "../core_render.m" #include "../native.m" #include "../main_menu_darwin.m" #include diff --git a/internal/platform/darwin/testdata/live_resize.m b/internal/platform/darwin/testdata/live_resize.m index 4ff6bd95e..2be17ebea 100644 --- a/internal/platform/darwin/testdata/live_resize.m +++ b/internal/platform/darwin/testdata/live_resize.m @@ -1,3 +1,5 @@ +#include "../core_text.m" +#include "../core_render.m" #include "../native.m" #include "../main_menu_darwin.m" #include diff --git a/internal/platform/darwin/testdata/modifier_taps.m b/internal/platform/darwin/testdata/modifier_taps.m index 4746f4c9b..07a2074a3 100644 --- a/internal/platform/darwin/testdata/modifier_taps.m +++ b/internal/platform/darwin/testdata/modifier_taps.m @@ -1,3 +1,5 @@ +#include "../core_text.m" +#include "../core_render.m" #include "../native.m" #include "../main_menu_darwin.m" #include diff --git a/internal/platform/darwin/testdata/text_selection.m b/internal/platform/darwin/testdata/text_selection.m index 8a558eada..bf2d9f348 100644 --- a/internal/platform/darwin/testdata/text_selection.m +++ b/internal/platform/darwin/testdata/text_selection.m @@ -1,3 +1,5 @@ +#include "../core_text.m" +#include "../core_render.m" #include "../native.m" #include "../main_menu_darwin.m" #include diff --git a/internal/platform/darwin/testdata/traffic_lights.m b/internal/platform/darwin/testdata/traffic_lights.m index e3c22c283..04a4b6d75 100644 --- a/internal/platform/darwin/testdata/traffic_lights.m +++ b/internal/platform/darwin/testdata/traffic_lights.m @@ -1,3 +1,5 @@ +#include "../core_text.m" +#include "../core_render.m" #include "../native.m" #include "../main_menu_darwin.m" #include diff --git a/internal/platform/darwin/testdata/window_close.m b/internal/platform/darwin/testdata/window_close.m index 3dcfeb4a2..efda95605 100644 --- a/internal/platform/darwin/testdata/window_close.m +++ b/internal/platform/darwin/testdata/window_close.m @@ -1,3 +1,5 @@ +#include "../core_text.m" +#include "../core_render.m" #include "../native.m" #include "../main_menu_darwin.m" #include diff --git a/internal/platform/darwin/testdata/window_notification.m b/internal/platform/darwin/testdata/window_notification.m index d1d5e6a2e..10a22c1ae 100644 --- a/internal/platform/darwin/testdata/window_notification.m +++ b/internal/platform/darwin/testdata/window_notification.m @@ -1,3 +1,5 @@ +#include "../core_text.m" +#include "../core_render.m" #include "../native.m" #include "../main_menu_darwin.m" #include "window_test_callbacks.h" diff --git a/internal/platform/darwin/testdata/window_size.m b/internal/platform/darwin/testdata/window_size.m index a7998ca54..7fab1de82 100644 --- a/internal/platform/darwin/testdata/window_size.m +++ b/internal/platform/darwin/testdata/window_size.m @@ -1,3 +1,5 @@ +#include "../core_text.m" +#include "../core_render.m" #include "../native.m" #include "../main_menu_darwin.m" #include From 3f592fa7ad844b1ce2ba23649527cc7c96f6f4eb Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 22 Nov 2026 19:57:49 +0800 Subject: [PATCH 22/64] refactor(darwin): draw a window's scene through a surface-independent renderer VivaMetalView held, next to its events, text input and accessibility, the whole of what it draws: the rectangle buffer and its clips, the label layers, the composite plan, the pipelines and the command queue, and the code that updates, encodes, presents and recovers them. Nothing but an NSView could reach it. That part is now VivaRenderer in core_render.m, over a CAMetalLayer it is given: building a scene, updating its rectangles and labels, rendering into a drawable, drawing the labels' textures again and making the Metal resources again after the device is lost. The view creates one and forwards to it; the composite planning and the remembered shader library moved with it. The text and rendering core (core_text.m, core_render.m, core.h) no longer uses AppKit classes: geometry is CoreGraphics, fonts and colors go through VivaFont and VivaColor and the few calls that differ (the font manager, color conversion) through small shims, so the same files compile against the iOS SDK. A shared-mode buffer is no longer told it was modified on iOS, where that call does not exist. Behavior is unchanged: the darwin tests pass as before, and the native test programs still build. hello for macOS grows by 848 bytes (4,447,282 to 4,448,130). ADR 0095 W1, step 2. --- internal/platform/darwin/core.h | 162 ++++-- internal/platform/darwin/core_render.m | 698 +++++++++++++++++++++++-- internal/platform/darwin/core_text.m | 162 ++++-- internal/platform/darwin/native.m | 611 ++-------------------- 4 files changed, 938 insertions(+), 695 deletions(-) diff --git a/internal/platform/darwin/core.h b/internal/platform/darwin/core.h index 0a07c2a1f..4c64b47d1 100644 --- a/internal/platform/darwin/core.h +++ b/internal/platform/darwin/core.h @@ -6,7 +6,12 @@ #ifndef VIVA_INTERNAL_PLATFORM_DARWIN_CORE_H #define VIVA_INTERNAL_PLATFORM_DARWIN_CORE_H +#include +#if TARGET_OS_OSX #import +#else +#import +#endif #include #import #import @@ -17,6 +22,26 @@ #include #include +#if TARGET_OS_OSX +typedef NSFont VivaFont; +typedef NSFontDescriptor VivaFontDescriptor; +typedef NSColor VivaColor; +#define VivaFontFamilyAttribute NSFontFamilyAttribute +#define VivaFontTraitsAttribute NSFontTraitsAttribute +#define VivaFontWeightTrait NSFontWeightTrait +#define VivaFontCascadeListAttribute NSFontCascadeListAttribute +#define VivaFontBoldTrait NSFontBoldTrait +#else +typedef UIFont VivaFont; +typedef UIFontDescriptor VivaFontDescriptor; +typedef UIColor VivaColor; +#define VivaFontFamilyAttribute UIFontDescriptorFamilyAttribute +#define VivaFontTraitsAttribute UIFontDescriptorTraitsAttribute +#define VivaFontWeightTrait UIFontWeightTrait +#define VivaFontCascadeListAttribute UIFontDescriptorCascadeListAttribute +#define VivaFontBoldTrait UIFontDescriptorTraitBold +#endif + #include "native.h" #include "label_geometry.h" @@ -34,8 +59,8 @@ typedef struct { @interface VivaTextLayer : NSObject { NSString *_value; - NSRect _frame; - NSRect _clip; // where the label may paint, when _clipped + CGRect _frame; + CGRect _clip; // where the label may paint, when _clipped BOOL _clipped; CGFloat _fontSize; CGFloat _fontWeight; @@ -85,29 +110,106 @@ typedef struct { - (BOOL)matchesConfig:(viva_text_label)config; - (uint64_t)contentHash; - (BOOL)contentMatchesSizeAgnostic:(viva_text_label)config; -- (void)updateFrame:(NSRect)frame; +- (void)updateFrame:(CGRect)frame; - (void)updateClipFromConfig:(viva_text_label)config; - (void)updateQuadFromConfig:(viva_text_label)config; - (const float *)quad; - (const float *)tint; - (float)imageRadius; -- (NSRect)frame; +- (CGRect)frame; - (BOOL)clipped; -- (NSRect)clip; -- (BOOL)forceTextureRebuildWithDevice:(id)device scale:(CGFloat)scale viewport:(NSSize)viewport; +- (CGRect)clip; +- (BOOL)forceTextureRebuildWithDevice:(id)device scale:(CGFloat)scale viewport:(CGSize)viewport; - (void)markContentRebuild; -- (BOOL)rebuildWithDevice:(id)device scale:(CGFloat)scale viewport:(NSSize)viewport; -- (BOOL)refreshWindowWithDevice:(id)device scale:(CGFloat)scale viewport:(NSSize)viewport; +- (BOOL)rebuildWithDevice:(id)device scale:(CGFloat)scale viewport:(CGSize)viewport; +- (BOOL)refreshWindowWithDevice:(id)device scale:(CGFloat)scale viewport:(CGSize)viewport; - (void)drawLineInContext:(CGContextRef)context pixelScale:(CGFloat)pixelScale; - (void)drawRunsInContext:(CGContextRef)context pixelScale:(CGFloat)pixelScale; - (id)textureAtIndex:(NSUInteger)index; - (NSUInteger)textureCount; -- (NSRect)quadAtIndex:(NSUInteger)index; -- (NSRect)textureFrameAtIndex:(NSUInteger)index; +- (CGRect)quadAtIndex:(NSUInteger)index; +- (CGRect)textureFrameAtIndex:(NSUInteger)index; - (CGFloat)rasterWidthScale:(CGFloat)scale; @end +// VivaRenderer draws the scene of one surface into a CAMetalLayer: the rectangle +// instances, the label layers and the native editor's texture, in the order the +// composite plan gives. The surface owns its layer and its events; the renderer +// owns what is drawn into it, so the AppKit view, the UIKit view and the +// offscreen target share one implementation of it. +@interface VivaRenderer : NSObject { + CAMetalLayer *_layer; + id _commandQueue; + id _rectanglePipeline; + id _textPipeline; + id _rectangleBuffer; + NSUInteger _rectangleCount; + // Capacity is the slots the buffers hold; count is the instances the scene + // owns. An append past the capacity grows it by doubling; rebuilds + // re-tighten it to the exact count. + NSUInteger _rectangleCapacity; + viva_clip *_rectangleClips; + NSMutableArray *_textLabels; + uint16_t *_textLabelLayers; + uint32_t *_textLabelShapesBefore; + NSUInteger _textLabelCount; + viva_composite_command *_compositeCommands; + NSUInteger _compositeCommandCount; + MTLClearColor _clearColor; +} +@property(nonatomic, readonly) CAMetalLayer *layer; +@property(nonatomic, readonly) NSMutableArray *textLabels; +@property(nonatomic, readonly) NSUInteger rectangleCount; +@property(nonatomic) MTLClearColor clearColor; +@property(nonatomic, readonly) id textPipeline; + +// initWithLayer takes the Metal objects the scene was first built on, and the +// scene itself; viewport is the layer's size in points, which labels are laid out +// in. It returns nil when a label or the composite plan cannot be made. +- (instancetype)initWithLayer:(CAMetalLayer *)layer + commandQueue:(id)commandQueue + rectanglePipeline:(id)rectanglePipeline + rectangleBuffer:(id)rectangleBuffer + rectangleCount:(NSUInteger)rectangleCount + rectangleClips:(const viva_clip *)rectangleClips + textPipeline:(id)textPipeline + textLabels:(const viva_text_label *)textLabels + textLabelCount:(NSUInteger)textLabelCount + clearColor:(MTLClearColor)clearColor + viewport:(CGSize)viewport; +- (BOOL)rebuildTextLabelsWithViewport:(CGSize)viewport; +// forceRebuildTextLabelsWithViewport draws every label's texture again, as the +// surface's size and scale call for after a live resize. +- (void)forceRebuildTextLabelsWithViewport:(CGSize)viewport; +- (int)updateRectangles:(const viva_rectangle *)rectangles + clips:(const viva_clip *)clips + totalCount:(NSUInteger)totalCount + first:(NSUInteger)first + count:(NSUInteger)count + rebuild:(BOOL)rebuild; +- (int)updateLabels:(const viva_text_label *)labels + count:(NSUInteger)count + viewport:(CGSize)viewport; +// renderToDrawable encodes the scene, the editor's texture over it, and presents the +// drawable. The command buffer is returned so the surface can wait for it to be +// scheduled. +- (id)renderToDrawable:(id)drawable + viewport:(CGSize)viewport + inputTexture:(id)inputTexture + inputFrame:(CGRect)inputFrame + inputLayer:(uint16_t)inputLayer; +// recoverWithViewport makes the Metal resources again after the device stopped +// serving them, on the system's default device. The scene must be sent again as a +// rebuild. NO when the device, its queue or the pipelines cannot be made. +- (BOOL)recoverWithViewport:(CGSize)viewport; +@end + extern int vivaTerminalCells(uint32_t character); +extern void *viva_shader_library_bytes; +extern size_t viva_shader_library_length; +int viva_remember_shader_library(const unsigned char *bytes, size_t length); + +BOOL viva_color_srgb(VivaColor *color, CGFloat rgba[4]); extern uint64_t viva_gpu_submission_count; @@ -139,13 +241,13 @@ size_t viva_text_spans(viva_editor_line line, NSRange range, BOOL terminal, doub NSUInteger viva_text_index_at(viva_editor_line line, NSString *shown, CGFloat x, BOOL terminal); NSObject *viva_mono_family_lock(void); void viva_mono_face_traits(int face, NSString **family, BOOL *classic, NSArray **fallbacks); -BOOL viva_mono_font_on_a_grid(NSFont *font); -NSFont *viva_mono_base_font(CGFloat size, CGFloat weight, NSString *family, BOOL classic); -NSFont *viva_mono_font_primary(CGFloat size, CGFloat weight, int face); -NSFont *viva_mono_font(CGFloat size, CGFloat weight, int face); +BOOL viva_mono_font_on_a_grid(VivaFont *font); +VivaFont *viva_mono_base_font(CGFloat size, CGFloat weight, NSString *family, BOOL classic); +VivaFont *viva_mono_font_primary(CGFloat size, CGFloat weight, int face); +VivaFont *viva_mono_font(CGFloat size, CGFloat weight, int face); NSObject *viva_mono_fallback_lock(void); -NSFont *viva_mono_family_font(NSString *family, CGFloat size, CGFloat weight); -NSFont *viva_mono_replacement_font(NSString *family, CGFloat size, BOOL bold); +VivaFont *viva_mono_family_font(NSString *family, CGFloat size, CGFloat weight); +VivaFont *viva_mono_replacement_font(NSString *family, CGFloat size, BOOL bold); BOOL viva_mono_font_covers(CTFontRef font, NSString *value); BOOL viva_mono_draws_han(CTFontRef font); int viva_mono_private_use(CTFontRef font); @@ -157,11 +259,11 @@ NSString *viva_mono_face_fallback(NSString *cluster, int face); NSString *viva_mono_fallback_family(NSString *cluster); BOOL viva_mono_is_last_resort_name(CFStringRef name); BOOL viva_mono_font_is_last_resort(CTFontRef font); -CTLineRef viva_mono_fallback_line(NSString *value, NSFont *base, int face, CGColorRef color); +CTLineRef viva_mono_fallback_line(NSString *value, VivaFont *base, int face, CGColorRef color); void viva_prepare_text_context(CGContextRef context, CGFloat scale); void viva_draw_terminal_preedit( CGContextRef context, NSString *shown, CGFloat fontSize, int monoFace, - NSColor *color, CGFloat cellWidth, CGFloat baseline + VivaColor *color, CGFloat cellWidth, CGFloat baseline ); viva_editor_line viva_new_editor_line(NSString *shown, CGFloat fontSize, CGFloat fontWeight, BOOL terminal, CGFloat cellWidth); CGFloat viva_editor_alignment_inset(viva_editor_line line, CGFloat width, int alignment, BOOL terminal); @@ -174,8 +276,8 @@ id viva_text_input_texture( NSString *shown, CGFloat fontSize, CGFloat fontWeight, - NSColor *color, - NSSize frameSize, + VivaColor *color, + CGSize frameSize, NSRange selectedRange, BOOL hasMarked, NSRange markedRange, @@ -198,9 +300,9 @@ uint64_t viva_hash_bytes(uint64_t hash, const void *data, size_t length); float viva_quantized_origin(float value); uint64_t viva_label_content_hash(viva_text_label config); NSData *viva_downsample_bitmap(NSData *source, uint32_t sourceWidth, uint32_t sourceHeight, uint32_t sourceStride, size_t width, size_t height); -void viva_bitmap_texture_extent(NSRect frame, CGFloat scale, size_t sourceWidth, size_t sourceHeight, size_t *width, size_t *height); +void viva_bitmap_texture_extent(CGRect frame, CGFloat scale, size_t sourceWidth, size_t sourceHeight, size_t *width, size_t *height); BOOL viva_bitmap_extent_stale(size_t have, size_t need); -BOOL viva_label_visible_span(const float *quad, const float *tint, BOOL clipped, NSRect clip, NSSize viewport, +BOOL viva_label_visible_span(const float *quad, const float *tint, BOOL clipped, CGRect clip, CGSize viewport, size_t full, size_t *left, size_t *right); void viva_label_window(size_t full, size_t limit, BOOL visible, size_t left, size_t right, size_t *windowLeft, size_t *windowRight); @@ -210,7 +312,7 @@ int viva_update_label_layers( NSUInteger count, id device, CGFloat scale, - NSSize viewport, + CGSize viewport, NSMutableArray **updated ); void viva_label_box_quad(float *quad, float x, float y, float width, float height); @@ -218,17 +320,17 @@ void viva_label_plain_tint(float *tint); size_t viva_label_tile_mesh( const float *quad, const float *tint, - NSRect frame, - NSRect tile, - NSRect texture, + CGRect frame, + CGRect tile, + CGRect texture, viva_label_vertex *vertices ); void viva_encode_input( id encoder, id textPipeline, id inputTexture, - NSRect inputFrame, - NSSize viewport + CGRect inputFrame, + CGSize viewport ); void viva_encode_scene( id encoder, @@ -239,9 +341,9 @@ void viva_encode_scene( NSUInteger commandCount, NSArray *labels, id inputTexture, - NSRect inputFrame, + CGRect inputFrame, uint16_t inputLayer, - NSSize viewport, + CGSize viewport, NSUInteger targetWidth, NSUInteger targetHeight ); diff --git a/internal/platform/darwin/core_render.m b/internal/platform/darwin/core_render.m index 7481f3d36..71474ee07 100644 --- a/internal/platform/darwin/core_render.m +++ b/internal/platform/darwin/core_render.m @@ -1,6 +1,186 @@ #import "core.h" #include "label_geometry.h" +/* The compiled shader library the application passes as it opens its windows, + * kept after the first one compiled its pipelines: a window that makes its + * Metal resources again builds a library from these bytes on the device it is + * given, which need not be the device the first library was compiled for. */ +void *viva_shader_library_bytes = NULL; +size_t viva_shader_library_length = 0; + +int viva_remember_shader_library(const unsigned char *bytes, size_t length) { + if (bytes == NULL || length == 0) { + return 0; + } + if (viva_shader_library_bytes != NULL && viva_shader_library_length == length && + memcmp(viva_shader_library_bytes, bytes, length) == 0) { + return 1; + } + void *copy = malloc(length); + if (copy == NULL) { + return 0; + } + memcpy(copy, bytes, length); + free(viva_shader_library_bytes); + viva_shader_library_bytes = copy; + viva_shader_library_length = length; + return 1; +} + +uint16_t viva_rectangle_layer(viva_rectangle rectangle) { + if (rectangle.reserved0 <= 0) { + return 0; + } + if (rectangle.reserved0 >= UINT16_MAX) { + return UINT16_MAX; + } + return (uint16_t)rectangle.reserved0; +} + +static int viva_compare_composite_commands(const void *left, const void *right) { + const viva_composite_command *a = left; + const viva_composite_command *b = right; + if (a->layer != b->layer) { + return a->layer < b->layer ? -1 : 1; + } + if (a->sequence != b->sequence) { + return a->sequence < b->sequence ? -1 : 1; + } + if (a->kind != b->kind) { + return a->kind < b->kind ? -1 : 1; + } + if (a->first != b->first) { + return a->first < b->first ? -1 : 1; + } + return 0; +} + +// viva_same_batch reports whether two instances can share one draw: the same +// layer and the same clip. An instance no clip cuts ignores its stale clip fields. +static int viva_same_batch( + const viva_rectangle *rectangles, + const viva_clip *clips, + size_t left, + size_t right +) { + if (viva_rectangle_layer(rectangles[left]) != viva_rectangle_layer(rectangles[right])) { + return 0; + } + int left_clipped = clips != NULL && clips[left].clipped != 0; + int right_clipped = clips != NULL && clips[right].clipped != 0; + if (left_clipped != right_clipped) { + return 0; + } + if (!left_clipped) { + return 1; + } + return clips[left].x == clips[right].x && clips[left].y == clips[right].y && + clips[left].width == clips[right].width && + clips[left].height == clips[right].height; +} + +/* viva_rectangle_capacity answers the instance slots the renderer's rectangle + * buffers need to hold count instances, given the slots they already hold. A + * buffer that has room keeps it, so an append landing in the headroom of an + * earlier growth costs nothing; a buffer that must grow doubles, so a scene + * that appends one instance at a time allocates a logarithmic number of times + * and the buffers stay within twice the instances that exist. */ +size_t viva_rectangle_capacity(size_t capacity, size_t count) { + if (capacity >= count) { + return capacity; + } + size_t next = capacity > 0 ? capacity : 64; + while (next < count) { + if (next > SIZE_MAX / 2) { + return count; + } + next *= 2; + } + return next; +} + +int viva_plan_composite( + const viva_rectangle *rectangles, + const viva_clip *clips, + size_t rectangle_count, + const uint16_t *text_layers, + const uint32_t *text_shapes_before, + size_t text_count, + viva_composite_command *commands, + size_t command_capacity, + size_t *command_count +) { + if (command_count == NULL || + (rectangle_count > 0 && (rectangles == NULL || clips == NULL)) || + (text_count > 0 && (text_layers == NULL || text_shapes_before == NULL)) || + rectangle_count > UINT32_MAX || text_count > UINT32_MAX) { + return 1; + } + + // At most one command per shape and one per label: a shape batch can be cut + // at every label boundary. + if (rectangle_count > SIZE_MAX - text_count) { + return 2; + } + size_t required = rectangle_count + text_count; + if (required > command_capacity || (required > 0 && commands == NULL)) { + return 2; + } + + // Shapes and labels arrive in paint order. A label that says k shapes were + // painted before it belongs after instance k-1 and before instance k, so + // the plan walks both lists by that boundary, cutting a shape batch when a + // label falls inside it. + size_t command_index = 0; + size_t rectangle_index = 0; + size_t text_index = 0; + while (rectangle_index < rectangle_count || text_index < text_count) { + if (text_index < text_count && + (text_shapes_before[text_index] <= rectangle_index || rectangle_index >= rectangle_count)) { + uint32_t sequence = (uint32_t)command_index; + commands[command_index++] = (viva_composite_command){ + .layer = text_layers[text_index], + .kind = VIVA_COMPOSITE_TEXT, + .first = (uint32_t)text_index, + .count = 1, + .sequence = sequence, + }; + text_index++; + continue; + } + size_t first = rectangle_index; + size_t end = first + 1; + while (end < rectangle_count && + viva_same_batch(rectangles, clips, first, end) && + (text_index >= text_count || end < text_shapes_before[text_index])) { + end++; + } + uint16_t layer = viva_rectangle_layer(rectangles[first]); + uint32_t sequence = (uint32_t)command_index; + viva_composite_command command = { + .layer = layer, + .kind = VIVA_COMPOSITE_RECTANGLES, + .first = (uint32_t)first, + .count = (uint32_t)(end - first), + .sequence = sequence, + }; + if (clips[first].clipped != 0) { + command.clipped = 1; + command.clip_x = clips[first].x; + command.clip_y = clips[first].y; + command.clip_width = clips[first].width; + command.clip_height = clips[first].height; + } + commands[command_index++] = command; + rectangle_index = end; + } + qsort(commands, command_index, sizeof(viva_composite_command), + viva_compare_composite_commands); + *command_count = command_index; + return 0; +} + + uint64_t viva_gpu_submission_count; uint64_t viva_gpu_draw_call_count; uint64_t viva_rectangle_instance_count; @@ -215,7 +395,7 @@ uint64_t viva_label_content_hash(viva_text_label config) { // viva_bitmap_texture_extent is the size of the texture an image label is drawn from: the // stored image, averaged down to the device pixels the label covers when it is drawn smaller // than it is stored. internal/platform.BitmapTextureExtent computes the same size. -void viva_bitmap_texture_extent(NSRect frame, CGFloat scale, size_t sourceWidth, size_t sourceHeight, size_t *width, size_t *height) { +void viva_bitmap_texture_extent(CGRect frame, CGFloat scale, size_t sourceWidth, size_t sourceHeight, size_t *width, size_t *height) { CGFloat pixelScale = MAX(scale, 1.0); size_t shownWidth = (size_t)MAX(1.0, floor((frame.origin.x + frame.size.width) * pixelScale + 0.5) - floor(frame.origin.x * pixelScale + 0.5)); size_t shownHeight = (size_t)MAX(1.0, floor((frame.origin.y + frame.size.height) * pixelScale + 0.5) - floor(frame.origin.y * pixelScale + 0.5)); @@ -243,17 +423,17 @@ BOOL viva_bitmap_extent_stale(size_t have, size_t need) { // viva_label_visible_span clips the destination triangles to the clip and viewport, // then maps their visible UV range to source pixels, at most full. // NO when none of the label can be seen. -BOOL viva_label_visible_span(const float *quad, const float *tint, BOOL clipped, NSRect clip, NSSize viewport, +BOOL viva_label_visible_span(const float *quad, const float *tint, BOOL clipped, CGRect clip, CGSize viewport, size_t full, size_t *left, size_t *right) { - NSRect visible = NSMakeRect(0, 0, viewport.width, viewport.height); + CGRect visible = CGRectMake(0, 0, viewport.width, viewport.height); if (clipped) { - visible = NSIntersectionRect(visible, clip); + visible = CGRectIntersection(visible, clip); } - if (NSIsEmptyRect(visible)) { + if (CGRectIsEmpty(visible)) { return NO; } float sourceLeft, sourceRight; - if (!viva_label_source_span(quad, tint, NSMinX(visible), NSMinY(visible), NSMaxX(visible), NSMaxY(visible), &sourceLeft, &sourceRight)) { + if (!viva_label_source_span(quad, tint, CGRectGetMinX(visible), CGRectGetMinY(visible), CGRectGetMaxX(visible), CGRectGetMaxY(visible), &sourceLeft, &sourceRight)) { return NO; } CGFloat from = floor((double)sourceLeft * full); @@ -313,7 +493,7 @@ - (instancetype)initWithConfig:(viva_text_label)config { [self release]; return nil; } - _frame = NSMakeRect(config.x, config.y, config.width, config.height); + _frame = CGRectMake(config.x, config.y, config.width, config.height); [self updateClipFromConfig:config]; [self updateQuadFromConfig:config]; _fontSize = config.font_size; @@ -436,7 +616,7 @@ - (BOOL)contentMatchesSizeAgnostic:(viva_text_label)config { - (void)updateClipFromConfig:(viva_text_label)config { _clipped = (config.flags & VIVA_LABEL_CLIPPED) != 0; - _clip = _clipped ? NSMakeRect(config.clip_x, config.clip_y, config.clip_width, config.clip_height) : NSZeroRect; + _clip = _clipped ? CGRectMake(config.clip_x, config.clip_y, config.clip_width, config.clip_height) : CGRectZero; } - (void)updateQuadFromConfig:(viva_text_label)config { @@ -494,15 +674,15 @@ - (BOOL)clipped { return _clipped; } -- (NSRect)clip { +- (CGRect)clip { return _clip; } -- (void)updateFrame:(NSRect)frame { +- (void)updateFrame:(CGRect)frame { _frame = frame; } -- (BOOL)forceTextureRebuildWithDevice:(id)device scale:(CGFloat)scale viewport:(NSSize)viewport { +- (BOOL)forceTextureRebuildWithDevice:(id)device scale:(CGFloat)scale viewport:(CGSize)viewport { _lastScale = 0; return [self rebuildWithDevice:device scale:scale viewport:viewport]; } @@ -514,7 +694,7 @@ - (void)markContentRebuild { // refreshWindowWithDevice rasterizes a label held in part again when the part of it that // can be seen in viewport is no longer all in its texture: it moved, or its clip or the // viewport did. Any other label is left as it is. -- (BOOL)refreshWindowWithDevice:(id)device scale:(CGFloat)scale viewport:(NSSize)viewport { +- (BOOL)refreshWindowWithDevice:(id)device scale:(CGFloat)scale viewport:(CGSize)viewport { CGFloat widthScale = [self rasterWidthScale:scale]; if (_texture == nil || _lastScale != scale || viva_bitmap_extent_stale((size_t)ceil(_frame.size.width * _windowPixelScale), (size_t)ceil(_frame.size.width * widthScale))) { @@ -550,7 +730,7 @@ - (CGFloat)rasterWidthScale:(CGFloat)scale { return MIN(pixelScale, MAX(1, ceil(MAX(top, bottom) * pixelScale)) / _frame.size.width); } -- (BOOL)rebuildWithDevice:(id)device scale:(CGFloat)scale viewport:(NSSize)viewport { +- (BOOL)rebuildWithDevice:(id)device scale:(CGFloat)scale viewport:(CGSize)viewport { size_t wantWidth = 0, wantHeight = 0; if (_bitmap != nil) { viva_bitmap_texture_extent(_frame, scale, _bitmapWidth, _bitmapHeight, &wantWidth, &wantHeight); @@ -725,7 +905,7 @@ - (void)drawLineInContext:(CGContextRef)context pixelScale:(CGFloat)pixelScale { baseline -= ceil(_originY * pixelScale - 1e-4) / pixelScale; if (_mono) { // A fixed-pitch label is not proportional text: it keeps its own advances. - // The line carries the face's font (the NSFont itself: looking it up again by + // The line carries the face's font (the VivaFont itself: looking it up again by // name fails for the monospaced system font at a weight, whose name is private // to that instance, and CoreText answers with Times New Roman) and, for the // clusters no family of it draws, the installed fallback. @@ -750,7 +930,7 @@ - (void)drawLineInContext:(CGContextRef)context pixelScale:(CGFloat)pixelScale { // from fallback fonts cannot push later text off its column. All runs share // one baseline taken from the base font. - (void)drawRunsInContext:(CGContextRef)context pixelScale:(CGFloat)pixelScale { - NSFont *baseFont = viva_mono_font(_fontSize, _fontWeight, _monoFace); + VivaFont *baseFont = viva_mono_font(_fontSize, _fontWeight, _monoFace); CGFloat baseline = _baseline > 0 ? viva_fixed_baseline(_frame.size.height, _baseline, pixelScale) : viva_baseline(_frame.size.height, _fontSize, pixelScale); @@ -783,7 +963,7 @@ - (void)drawRunsInContext:(CGContextRef)context pixelScale:(CGFloat)pixelScale { } } if (font == NULL) { - NSFont *native = viva_mono_font(_fontSize, run->weight, _monoFace); + VivaFont *native = viva_mono_font(_fontSize, run->weight, _monoFace); font = (CTFontRef)CFRetain(native); if (italic) { CGAffineTransform slant = CGAffineTransformMake(1, 0, 0.2126, 1, 0, 0); @@ -815,7 +995,7 @@ - (void)drawRunsInContext:(CGContextRef)context pixelScale:(CGFloat)pixelScale { length:count encoding:NSUTF8StringEncoding]; if (shown != nil) { - CTLineRef line = viva_mono_fallback_line(shown, (NSFont *)font, _monoFace, foreground); + CTLineRef line = viva_mono_fallback_line(shown, (VivaFont *)font, _monoFace, foreground); if (line != NULL) { CGFloat width = CTLineGetTypographicBounds(line, NULL, NULL, NULL); if (width > 0 && span > 0) { @@ -861,7 +1041,7 @@ - (void)drawRunsInContext:(CGContextRef)context pixelScale:(CGFloat)pixelScale { CFRelease(foreground); continue; } - CTLineRef line = viva_mono_fallback_line(shown, (NSFont *)font, _monoFace, foreground); + CTLineRef line = viva_mono_fallback_line(shown, (VivaFont *)font, _monoFace, foreground); if (line == NULL) { [shown release]; CFRelease(foreground); @@ -914,11 +1094,11 @@ - (NSUInteger)textureCount { return 1 + _additionalTextures.count; } -- (NSRect)frame { +- (CGRect)frame { return _frame; } -- (NSRect)quadAtIndex:(NSUInteger)index { +- (CGRect)quadAtIndex:(NSUInteger)index { if (_bitmap != nil) { return _frame; } @@ -927,10 +1107,10 @@ - (NSRect)quadAtIndex:(NSUInteger)index { size_t tileRight = tileLeft + MIN(_windowRight - tileLeft, VIVA_LABEL_TILE_WIDTH); CGFloat left = (CGFloat)tileLeft / _windowPixelScale; CGFloat right = tileRight >= full ? _frame.size.width : (CGFloat)tileRight / _windowPixelScale; - return NSMakeRect(_frame.origin.x + left, _frame.origin.y, right - left, _frame.size.height); + return CGRectMake(_frame.origin.x + left, _frame.origin.y, right - left, _frame.size.height); } -- (NSRect)textureFrameAtIndex:(NSUInteger)index { +- (CGRect)textureFrameAtIndex:(NSUInteger)index { if (_bitmap != nil) return _frame; size_t full = (size_t)MAX(1.0, ceil(_frame.size.width * _windowPixelScale)); size_t tileLeft = _windowLeft + index * VIVA_LABEL_TILE_WIDTH; @@ -939,7 +1119,7 @@ - (NSRect)textureFrameAtIndex:(NSUInteger)index { size_t textureRight = MIN(tileRight + 1, full); CGFloat left = (CGFloat)textureLeft / _windowPixelScale; CGFloat right = textureRight >= full ? _frame.size.width : (CGFloat)textureRight / _windowPixelScale; - return NSMakeRect(_frame.origin.x + left, _frame.origin.y, right - left, _frame.size.height); + return CGRectMake(_frame.origin.x + left, _frame.origin.y, right - left, _frame.size.height); } @end @@ -952,7 +1132,7 @@ int viva_update_label_layers( NSUInteger count, id device, CGFloat scale, - NSSize viewport, + CGSize viewport, NSMutableArray **updated ) { NSMutableArray *replacement = @@ -988,7 +1168,7 @@ int viva_update_label_layers( existing = previous[(NSUInteger)source[index]]; } if (existing != nil) { - [existing updateFrame:NSMakeRect( + [existing updateFrame:CGRectMake( labels[index].x, labels[index].y, labels[index].width, labels[index].height)]; [existing updateClipFromConfig:labels[index]]; @@ -1052,9 +1232,9 @@ void viva_label_plain_tint(float *tint) { size_t viva_label_tile_mesh( const float *quad, const float *tint, - NSRect frame, - NSRect tile, - NSRect texture, + CGRect frame, + CGRect tile, + CGRect texture, viva_label_vertex *vertices ) { CGFloat width = frame.size.width > 0 ? frame.size.width : 1; @@ -1081,8 +1261,8 @@ void viva_encode_input( id encoder, id textPipeline, id inputTexture, - NSRect inputFrame, - NSSize viewport + CGRect inputFrame, + CGSize viewport ) { float viewportSize[2] = {(float)viewport.width, (float)viewport.height}; float quad[8]; @@ -1116,9 +1296,9 @@ void viva_encode_scene( NSUInteger commandCount, NSArray *labels, id inputTexture, - NSRect inputFrame, + CGRect inputFrame, uint16_t inputLayer, - NSSize viewport, + CGSize viewport, NSUInteger targetWidth, NSUInteger targetHeight ) { @@ -1173,7 +1353,7 @@ void viva_encode_scene( VivaTextLayer *layer = [labels objectAtIndex:command.first]; BOOL scissored = NO; if ([layer clipped]) { - NSRect clip = [layer clip]; + CGRect clip = [layer clip]; NSInteger left = MAX((NSInteger)floor(clip.origin.x * targetScale), 0); NSInteger top = MAX((NSInteger)floor(clip.origin.y * targetScale), 0); NSInteger right = MIN((NSInteger)ceil((clip.origin.x + clip.size.width) * targetScale), (NSInteger)targetWidth); @@ -1187,7 +1367,7 @@ void viva_encode_scene( } [encoder setRenderPipelineState:textPipeline]; [encoder setVertexBytes:&viewportSize length:sizeof(viewportSize) atIndex:1]; - NSRect layerFrame = [layer frame]; + CGRect layerFrame = [layer frame]; viva_text_label_uniform labelUniform = { (float)layerFrame.origin.x, (float)layerFrame.origin.y, (float)layerFrame.size.width, (float)layerFrame.size.height, @@ -1213,3 +1393,453 @@ void viva_encode_scene( } } + +@interface VivaRenderer (Plan) +- (BOOL)replaceCompositePlanForRectangles:(const viva_rectangle *)rectangles + clips:(const viva_clip *)clips + rectangleCount:(NSUInteger)rectangleCount + textLayers:(const uint16_t *)textLayers + textShapesBefore:(const uint32_t *)textShapesBefore + textCount:(NSUInteger)textCount; +@end + +@implementation VivaRenderer + +@synthesize layer = _layer; +@synthesize textLabels = _textLabels; +@synthesize rectangleCount = _rectangleCount; +@synthesize clearColor = _clearColor; +@synthesize textPipeline = _textPipeline; + +- (instancetype)initWithLayer:(CAMetalLayer *)layer + commandQueue:(id)commandQueue + rectanglePipeline:(id)rectanglePipeline + rectangleBuffer:(id)rectangleBuffer + rectangleCount:(NSUInteger)rectangleCount + rectangleClips:(const viva_clip *)rectangleClips + textPipeline:(id)textPipeline + textLabels:(const viva_text_label *)textLabels + textLabelCount:(NSUInteger)textLabelCount + clearColor:(MTLClearColor)clearColor + viewport:(CGSize)viewport { + self = [super init]; + if (self == nil) { + return nil; + } + _layer = [layer retain]; + _commandQueue = [commandQueue retain]; + _rectanglePipeline = [rectanglePipeline retain]; + _rectangleBuffer = [rectangleBuffer retain]; + _rectangleCount = rectangleCount; + _rectangleCapacity = rectangleCount; + if (rectangleCount > 0) { + _rectangleClips = malloc(rectangleCount * sizeof(viva_clip)); + if (_rectangleClips == NULL) { + [self release]; + return nil; + } + memcpy(_rectangleClips, rectangleClips, rectangleCount * sizeof(viva_clip)); + } + _textPipeline = [textPipeline retain]; + _clearColor = clearColor; + if (textLabelCount > 0) { + _textLabelLayers = malloc(textLabelCount * sizeof(uint16_t)); + _textLabelShapesBefore = malloc(textLabelCount * sizeof(uint32_t)); + if (_textLabelLayers == NULL || _textLabelShapesBefore == NULL) { + [self release]; + return nil; + } + for (NSUInteger index = 0; index < textLabelCount; index++) { + _textLabelLayers[index] = textLabels[index].layer; + _textLabelShapesBefore[index] = textLabels[index].shapes_before; + } + } + _textLabelCount = textLabelCount; + _textLabels = [[NSMutableArray alloc] initWithCapacity:textLabelCount]; + for (NSUInteger index = 0; index < textLabelCount; index++) { + VivaTextLayer *textLayer = [[VivaTextLayer alloc] initWithConfig:textLabels[index]]; + if (textLayer == nil) { + [self release]; + return nil; + } + [_textLabels addObject:textLayer]; + [textLayer release]; + } + if (![self rebuildTextLabelsWithViewport:viewport]) { + [self release]; + return nil; + } + if (![self replaceCompositePlanForRectangles: + rectangleBuffer == nil ? NULL : rectangleBuffer.contents + clips:_rectangleClips + rectangleCount:rectangleCount + textLayers:_textLabelLayers + textShapesBefore:_textLabelShapesBefore + textCount:_textLabelCount]) { + [self release]; + return nil; + } + viva_label_initial_count = textLabelCount; + return self; +} + +- (void)dealloc { + free(_compositeCommands); + free(_rectangleClips); + free(_textLabelLayers); + free(_textLabelShapesBefore); + [_rectangleBuffer release]; + [_rectanglePipeline release]; + [_textLabels release]; + [_textPipeline release]; + [_commandQueue release]; + [_layer release]; + [super dealloc]; +} + +- (BOOL)replaceCompositePlanForRectangles:(const viva_rectangle *)rectangles + clips:(const viva_clip *)clips + rectangleCount:(NSUInteger)rectangleCount + textLayers:(const uint16_t *)textLayers + textShapesBefore:(const uint32_t *)textShapesBefore + textCount:(NSUInteger)textCount { + if (rectangleCount > SIZE_MAX - textCount) { + return NO; + } + NSUInteger capacity = rectangleCount + textCount; + viva_composite_command *replacement = NULL; + if (capacity > 0) { + if (capacity > SIZE_MAX / sizeof(viva_composite_command)) { + return NO; + } + replacement = malloc(capacity * sizeof(viva_composite_command)); + if (replacement == NULL) { + return NO; + } + } + size_t count = 0; + int status = viva_plan_composite( + rectangles, + clips, + rectangleCount, + textLayers, + textShapesBefore, + textCount, + replacement, + capacity, + &count + ); + if (status != 0) { + free(replacement); + return NO; + } + free(_compositeCommands); + _compositeCommands = replacement; + _compositeCommandCount = count; + return YES; +} + +- (BOOL)rebuildTextLabelsWithViewport:(CGSize)viewport { + CGFloat scale = MAX(_layer.contentsScale, 1.0); + for (VivaTextLayer *textLayer in _textLabels) { + if (![textLayer rebuildWithDevice:_layer.device scale:scale viewport:viewport]) { + return NO; + } + } + return YES; +} + +- (void)forceRebuildTextLabelsWithViewport:(CGSize)viewport { + CGFloat scale = MAX(_layer.contentsScale, 1.0); + for (VivaTextLayer *textLayer in _textLabels) { + [textLayer forceTextureRebuildWithDevice:_layer.device scale:scale viewport:viewport]; + } + viva_label_texture_rebuild_count += _textLabels.count; +} + +- (id)renderToDrawable:(id)drawable + viewport:(CGSize)viewport + inputTexture:(id)inputTexture + inputFrame:(CGRect)inputFrame + inputLayer:(uint16_t)inputLayer { + MTLRenderPassDescriptor *pass = [MTLRenderPassDescriptor renderPassDescriptor]; + pass.colorAttachments[0].texture = drawable.texture; + pass.colorAttachments[0].loadAction = MTLLoadActionClear; + pass.colorAttachments[0].storeAction = MTLStoreActionStore; + pass.colorAttachments[0].clearColor = _clearColor; + + id commandBuffer = [_commandQueue commandBuffer]; + id encoder = [commandBuffer renderCommandEncoderWithDescriptor:pass]; + viva_encode_scene(encoder, _rectanglePipeline, _textPipeline, _rectangleBuffer, + _compositeCommands, _compositeCommandCount, _textLabels, + inputTexture, inputFrame, inputLayer, viewport, + drawable.texture.width, drawable.texture.height); + [encoder endEncoding]; + [commandBuffer presentDrawable:drawable]; + [commandBuffer commit]; + viva_gpu_submission_count++; + return commandBuffer; +} + +- (BOOL)recoverWithViewport:(CGSize)viewport { + if (viva_shader_library_bytes == NULL) { + return NO; + } + @autoreleasepool { + id device = MTLCreateSystemDefaultDevice(); + if (device == nil) { + return NO; + } + id queue = [device newCommandQueue]; + if (queue == nil) { + [device release]; + return NO; + } + dispatch_data_t libraryData = dispatch_data_create( + viva_shader_library_bytes, + viva_shader_library_length, + dispatch_get_main_queue(), + DISPATCH_DATA_DESTRUCTOR_DEFAULT + ); + NSError *libraryError = nil; + id library = [device newLibraryWithData:libraryData error:&libraryError]; + dispatch_release(libraryData); + if (library == nil) { + [queue release]; + [device release]; + return NO; + } + // Both pipelines, whatever the window had: the frame that failed asked + // for rectangles, and a label texture of the old device cannot be drawn + // by the new one. + id rectanglePipeline = viva_create_pipeline( + device, library, @"viva_rectangle_vertex", @"viva_rectangle_fragment", NULL); + id textPipeline = viva_create_pipeline( + device, library, @"viva_text_vertex", @"viva_text_fragment", NULL); + [library release]; + if (rectanglePipeline == nil || textPipeline == nil) { + [rectanglePipeline release]; + [textPipeline release]; + [queue release]; + [device release]; + return NO; + } + _layer.device = device; + [_commandQueue release]; + _commandQueue = queue; + [_rectanglePipeline release]; + _rectanglePipeline = rectanglePipeline; + [_textPipeline release]; + _textPipeline = textPipeline; + // The instance buffers belonged to the old device; the application + // sends every instance again, as a rebuild. + [_rectangleBuffer release]; + _rectangleBuffer = nil; + free(_rectangleClips); + _rectangleClips = NULL; + _rectangleCount = 0; + _rectangleCapacity = 0; + free(_compositeCommands); + _compositeCommands = NULL; + _compositeCommandCount = 0; + CGFloat scale = MAX(_layer.contentsScale, 1.0); + for (VivaTextLayer *textLayer in _textLabels) { + if (![textLayer forceTextureRebuildWithDevice:device scale:scale viewport:viewport]) { + [device release]; + return NO; + } + } + viva_label_texture_rebuild_count += _textLabels.count; + [device release]; + return YES; + } +} + +- (int)updateRectangles:(const viva_rectangle *)rectangles + clips:(const viva_clip *)clips + totalCount:(NSUInteger)totalCount + first:(NSUInteger)first + count:(NSUInteger)count + rebuild:(BOOL)rebuild { + if (rebuild) { + id replacement = nil; + viva_clip *replacementClips = NULL; + if (totalCount > 0) { + if (_rectanglePipeline == nil || clips == NULL) { + return 3; + } + replacementClips = malloc(totalCount * sizeof(viva_clip)); + if (replacementClips == NULL) { + return 3; + } + memcpy(replacementClips, clips, totalCount * sizeof(viva_clip)); + replacement = [_layer.device + newBufferWithBytes:rectangles + length:totalCount * sizeof(viva_rectangle) + options:MTLResourceStorageModeShared]; + if (replacement == nil) { + free(replacementClips); + return 3; + } + // The staged instances carry their layer in reserved0, so the + // bytes newBufferWithBytes copies are already complete. + } + if (![self replaceCompositePlanForRectangles: + replacement == nil ? NULL : replacement.contents + clips:replacementClips + rectangleCount:totalCount + textLayers:_textLabelLayers + textShapesBefore:_textLabelShapesBefore + textCount:_textLabelCount]) { + [replacement release]; + free(replacementClips); + return 3; + } + [_rectangleBuffer release]; + free(_rectangleClips); + _rectangleClips = replacementClips; + _rectangleBuffer = replacement; + _rectangleCount = totalCount; + _rectangleCapacity = totalCount; + viva_gpu_uploaded_bytes += totalCount * sizeof(viva_rectangle); + viva_gpu_full_rebuild_count++; + return 0; + } + BOOL shrank = totalCount < _rectangleCount; + if (shrank) { + if (first + count != totalCount) { + return 2; + } + _rectangleCount = totalCount; + } + if (count == 0) { + if (shrank && ![self replaceCompositePlanForRectangles: + _rectangleBuffer == nil ? NULL : _rectangleBuffer.contents + clips:_rectangleClips + rectangleCount:_rectangleCount + textLayers:_textLabelLayers + textShapesBefore:_textLabelShapesBefore + textCount:_textLabelCount]) { + return 3; + } + return 0; + } + if (_rectangleBuffer == nil || _rectangleClips == NULL || clips == NULL || + first > totalCount || count > totalCount - first) { + return 2; + } + BOOL grew = totalCount > _rectangleCount; + BOOL reallocated = NO; + if (grew) { + // The scene appended instances. A stream that appends every frame + // must not allocate, copy and re-flush the whole buffer each time, + // so the buffers carry headroom; a rebuild re-tightens them to the + // exact count. The headroom is only made when the new count no + // longer fits: growing on every append multiplied the capacity by + // a quarter per frame while the scene appended one instance, and + // the request passed what the device hands out within a few dozen + // appends. + if (first > _rectangleCount || first + count != totalCount) { + return 2; + } + NSUInteger capacity = viva_rectangle_capacity(_rectangleCapacity, totalCount); + if (capacity != _rectangleCapacity) { + id replacement = [_layer.device + newBufferWithLength:capacity * sizeof(viva_rectangle) + options:MTLResourceStorageModeShared]; + if (replacement == nil) { + return 3; + } + viva_clip *replacementClips = malloc(capacity * sizeof(viva_clip)); + if (replacementClips == NULL) { + [replacement release]; + return 3; + } + memcpy(replacementClips, _rectangleClips, _rectangleCount * sizeof(viva_clip)); + memcpy(replacement.contents, _rectangleBuffer.contents, _rectangleCount * sizeof(viva_rectangle)); + [_rectangleBuffer release]; + free(_rectangleClips); + _rectangleBuffer = replacement; + _rectangleClips = replacementClips; + _rectangleCapacity = capacity; + reallocated = YES; + } + _rectangleCount = totalCount; + } + memcpy(_rectangleClips + first, clips, count * sizeof(viva_clip)); + memcpy( + (uint8_t *)_rectangleBuffer.contents + first * sizeof(viva_rectangle), + rectangles, + count * sizeof(viva_rectangle) + ); + // The staged instances carry their layer in reserved0, so the memcpy + // above has already written every field this buffer holds. +#if TARGET_OS_OSX + [_rectangleBuffer didModifyRange:NSMakeRange( + reallocated ? 0 : first * sizeof(viva_rectangle), + reallocated ? totalCount * sizeof(viva_rectangle) : count * sizeof(viva_rectangle) + )]; +#endif + if (![self replaceCompositePlanForRectangles:_rectangleBuffer.contents + clips:_rectangleClips + rectangleCount:_rectangleCount + textLayers:_textLabelLayers + textShapesBefore:_textLabelShapesBefore + textCount:_textLabelCount]) { + return 3; + } + viva_gpu_uploaded_bytes += count * sizeof(viva_rectangle); + viva_gpu_partial_update_count++; + return 0; +} + +- (int)updateLabels:(const viva_text_label *)labels + count:(NSUInteger)count + viewport:(CGSize)viewport { + CGFloat scale = MAX(_layer.contentsScale, 1.0); + uint16_t *replacementLayers = NULL; + uint32_t *replacementShapesBefore = NULL; + if (count > 0) { + replacementLayers = malloc(count * sizeof(uint16_t)); + replacementShapesBefore = malloc(count * sizeof(uint32_t)); + if (replacementLayers == NULL || replacementShapesBefore == NULL) { + free(replacementLayers); + free(replacementShapesBefore); + return 3; + } + for (NSUInteger index = 0; index < count; index++) { + replacementLayers[index] = labels[index].layer; + replacementShapesBefore[index] = labels[index].shapes_before; + } + } + NSMutableArray *replacement = nil; + int status = viva_update_label_layers(_textLabels, labels, count, _layer.device, scale, viewport, &replacement); + if (status != 0) { + free(replacementLayers); + free(replacementShapesBefore); + return status; + } + if (![self replaceCompositePlanForRectangles: + _rectangleBuffer == nil ? NULL : _rectangleBuffer.contents + clips:_rectangleClips + rectangleCount:_rectangleCount + textLayers:replacementLayers + textShapesBefore:replacementShapesBefore + textCount:count]) { + [replacement release]; + free(replacementLayers); + free(replacementShapesBefore); + return 3; + } + [_textLabels release]; + _textLabels = replacement; + free(_textLabelLayers); + free(_textLabelShapesBefore); + _textLabelLayers = replacementLayers; + _textLabelShapesBefore = replacementShapesBefore; + _textLabelCount = count; + viva_label_update_count++; + return 0; +} + +@end diff --git a/internal/platform/darwin/core_text.m b/internal/platform/darwin/core_text.m index 7860b0c06..c77b3e76f 100644 --- a/internal/platform/darwin/core_text.m +++ b/internal/platform/darwin/core_text.m @@ -10,6 +10,69 @@ NSRange viva_clamp_range(NSRange range, NSUInteger length) { return NSMakeRange(start, MIN(range.length, remaining)); } +// The few places the platforms' font and color classes differ. Everything else here +// is CoreText and CoreGraphics, which are the same on macOS and iOS. +#if TARGET_OS_OSX +static NSArray *viva_font_family_names(void) { + return [[NSFontManager sharedFontManager] availableFontFamilies]; +} + +// viva_font_in_family is the face of an installed family nearest regular (or bold), or nil. +static VivaFont *viva_font_in_family(NSString *family, CGFloat size, BOOL bold) { + return [[NSFontManager sharedFontManager] fontWithFamily:family + traits:(bold ? NSBoldFontMask : 0) + weight:5 + size:size]; +} + +static VivaFont *viva_font_user_fixed_pitch(CGFloat size) { + return [NSFont userFixedPitchFontOfSize:size]; +} + +BOOL viva_color_srgb(VivaColor *color, CGFloat rgba[4]) { + NSColor *converted = [color colorUsingColorSpace:[NSColorSpace sRGBColorSpace]]; + rgba[0] = converted.redComponent; + rgba[1] = converted.greenComponent; + rgba[2] = converted.blueComponent; + rgba[3] = converted.alphaComponent; + return converted != nil; +} +#else +static NSArray *viva_font_family_names(void) { + return [UIFont familyNames]; +} + +static VivaFont *viva_font_in_family(NSString *family, CGFloat size, BOOL bold) { + // UIFont answers a family it does not have with the system font, so ask first. + if (![[UIFont familyNames] containsObject:family]) { + return nil; + } + UIFontDescriptor *descriptor = [UIFontDescriptor fontDescriptorWithFontAttributes:@{UIFontDescriptorFamilyAttribute: family}]; + if (bold) { + UIFontDescriptor *heavier = [descriptor fontDescriptorWithSymbolicTraits:UIFontDescriptorTraitBold]; + if (heavier != nil) { + descriptor = heavier; + } + } + return [UIFont fontWithDescriptor:descriptor size:size]; +} + +static VivaFont *viva_font_user_fixed_pitch(CGFloat size) { + VivaFont *menlo = [UIFont fontWithName:@"Menlo-Regular" size:size]; + return menlo != nil ? menlo : [UIFont monospacedSystemFontOfSize:size weight:UIFontWeightRegular]; +} + +BOOL viva_color_srgb(VivaColor *color, CGFloat rgba[4]) { + CGFloat red = 0, green = 0, blue = 0, alpha = 0; + BOOL resolved = [color getRed:&red green:&green blue:&blue alpha:&alpha]; + rgba[0] = red; + rgba[1] = green; + rgba[2] = blue; + rgba[3] = alpha; + return resolved; +} +#endif + // A line of proportional text is shaped once by CoreText, in the system font with its font // fallback, and everything that needs a position asks that line: the width // layout uses, the glyphs a label draws, the caret, the selection and the character a click @@ -24,7 +87,7 @@ NSRange viva_clamp_range(NSRange range, NSUInteger length) { static char viva_interface_family[256] = ""; // viva_system_font is the proportional font that measurement, labels and the editor all -// use (a retained CTFont). It is an NSFont, which is a CTFont already. With a family +// use (a retained CTFont). It is an VivaFont, which is a CTFont already. With a family // named, its face of that family at the weight stands in for the system font; a family // the system does not have falls back to the system font, as AppKit does for a name. CTFontRef viva_system_font(CGFloat size, CGFloat weight) { @@ -35,17 +98,17 @@ CTFontRef viva_system_font(CGFloat size, CGFloat weight) { // family's regular, medium, semibold and bold faces are told apart as they are // in the system font; the nearest face the family has stands in for one it // lacks. NSFontManager's weight is a 0-15 table that cannot say medium. - NSFontDescriptor *descriptor = [NSFontDescriptor fontDescriptorWithFontAttributes:@{ - NSFontFamilyAttribute: family, - NSFontTraitsAttribute: @{NSFontWeightTrait: @(weight)}, + VivaFontDescriptor *descriptor = [VivaFontDescriptor fontDescriptorWithFontAttributes:@{ + VivaFontFamilyAttribute: family, + VivaFontTraitsAttribute: @{VivaFontWeightTrait: @(weight)}, }]; - NSFont *named = [NSFont fontWithDescriptor:descriptor size:size]; + VivaFont *named = [VivaFont fontWithDescriptor:descriptor size:size]; if (named != nil) { return (CTFontRef)CFRetain(named); } } } - NSFont *font = [NSFont systemFontOfSize:size weight:weight]; + VivaFont *font = [VivaFont systemFontOfSize:size weight:weight]; return font != nil ? (CTFontRef)CFRetain(font) : NULL; } @@ -456,8 +519,8 @@ void viva_mono_face_traits(int face, NSString **family, BOOL *classic, NSArray *names = [NSMutableArray array]; - for (NSString *family in [manager availableFontFamilies]) { + for (NSString *family in viva_font_family_names()) { if ([family hasPrefix:@"."]) { continue; } @@ -501,13 +563,12 @@ BOOL viva_mono_font_on_a_grid(NSFont *font) { char *viva_list_mono_families(void) { @autoreleasepool { - NSFontManager *manager = [NSFontManager sharedFontManager]; NSMutableArray *names = [NSMutableArray array]; - for (NSString *family in [manager availableFontFamilies]) { + for (NSString *family in viva_font_family_names()) { if ([family hasPrefix:@"."]) { continue; } - NSFont *font = [manager fontWithFamily:family traits:0 weight:5 size:12]; + VivaFont *font = viva_font_in_family(family, 12, NO); if (font != nil && viva_mono_font_on_a_grid(font)) { [names addObject:family]; } @@ -518,28 +579,25 @@ BOOL viva_mono_font_on_a_grid(NSFont *font) { } // viva_mono_base_font is the primary font of a face, without its fallbacks. -NSFont *viva_mono_base_font(CGFloat size, CGFloat weight, NSString *family, BOOL classic) { +VivaFont *viva_mono_base_font(CGFloat size, CGFloat weight, NSString *family, BOOL classic) { if (family != nil) { - NSFont *named = [[NSFontManager sharedFontManager] fontWithFamily:family - traits:(weight >= 0.34 ? NSBoldFontMask : 0) - weight:5 - size:size]; + VivaFont *named = viva_font_in_family(family, size, weight >= 0.34); if (named != nil) { return named; } } if (classic) { - NSFont *classicFont = [NSFont userFixedPitchFontOfSize:size]; + VivaFont *classicFont = viva_font_user_fixed_pitch(size); if (classicFont != nil) { return classicFont; } } - NSFont *font = [NSFont monospacedSystemFontOfSize:size weight:weight]; - return font != nil ? font : [NSFont userFixedPitchFontOfSize:size]; + VivaFont *font = [VivaFont monospacedSystemFontOfSize:size weight:weight]; + return font != nil ? font : viva_font_user_fixed_pitch(size); } // viva_mono_font_primary is the primary font of a face alone, the one the cell is measured in. -NSFont *viva_mono_font_primary(CGFloat size, CGFloat weight, int face) { +VivaFont *viva_mono_font_primary(CGFloat size, CGFloat weight, int face) { NSString *family = nil; BOOL classic = NO; NSArray *fallbacks = nil; @@ -552,21 +610,21 @@ BOOL viva_mono_font_on_a_grid(NSFont *font) { // tries them in order, before its own choice, for every character the primary has no // glyph for. A family that is not installed is skipped. The cell is the primary's: the // fallbacks never take part in the metrics, and every glyph is placed on the grid. -NSFont *viva_mono_font(CGFloat size, CGFloat weight, int face) { +VivaFont *viva_mono_font(CGFloat size, CGFloat weight, int face) { NSString *family = nil; BOOL classic = NO; NSArray *fallbacks = nil; viva_mono_face_traits(face, &family, &classic, &fallbacks); - NSFont *base = viva_mono_base_font(size, weight, family, classic); + VivaFont *base = viva_mono_base_font(size, weight, family, classic); if (base == nil || fallbacks.count == 0) { return base; } - NSMutableArray *cascade = [NSMutableArray arrayWithCapacity:fallbacks.count]; + NSMutableArray *cascade = [NSMutableArray arrayWithCapacity:fallbacks.count]; for (NSString *name in fallbacks) { - [cascade addObject:[NSFontDescriptor fontDescriptorWithFontAttributes:@{NSFontFamilyAttribute: name}]]; + [cascade addObject:[VivaFontDescriptor fontDescriptorWithFontAttributes:@{VivaFontFamilyAttribute: name}]]; } - NSFontDescriptor *descriptor = [base.fontDescriptor fontDescriptorByAddingAttributes:@{NSFontCascadeListAttribute: cascade}]; - NSFont *stacked = [NSFont fontWithDescriptor:descriptor size:size]; + VivaFontDescriptor *descriptor = [base.fontDescriptor fontDescriptorByAddingAttributes:@{VivaFontCascadeListAttribute: cascade}]; + VivaFont *stacked = [VivaFont fontWithDescriptor:descriptor size:size]; return stacked != nil ? stacked : base; } @@ -608,11 +666,8 @@ BOOL viva_mono_font_on_a_grid(NSFont *font) { } // viva_mono_family_font resolves an installed family at a size and weight, or nil. -NSFont *viva_mono_family_font(NSString *family, CGFloat size, CGFloat weight) { - return [[NSFontManager sharedFontManager] fontWithFamily:family - traits:(weight >= 0.34 ? NSBoldFontMask : 0) - weight:5 - size:size]; +VivaFont *viva_mono_family_font(NSString *family, CGFloat size, CGFloat weight) { + return viva_font_in_family(family, size, weight >= 0.34); } // viva_mono_replacement_font is viva_mono_family_font for a replacement glyph, remembering @@ -625,14 +680,14 @@ BOOL viva_mono_font_on_a_grid(NSFont *font) { NSString *family; CGFloat size; BOOL bold; - NSFont *font; + VivaFont *font; } viva_mono_replacement; static viva_mono_replacement viva_mono_replacements[VIVA_MONO_REPLACEMENT_CACHE]; static int viva_mono_replacement_count; static int viva_mono_replacement_next; -NSFont *viva_mono_replacement_font(NSString *family, CGFloat size, BOOL bold) { +VivaFont *viva_mono_replacement_font(NSString *family, CGFloat size, BOOL bold) { @synchronized(viva_mono_fallback_lock()) { for (int index = 0; index < viva_mono_replacement_count; index++) { viva_mono_replacement *entry = &viva_mono_replacements[index]; @@ -641,7 +696,7 @@ BOOL viva_mono_font_on_a_grid(NSFont *font) { } } } - NSFont *font = viva_mono_family_font(family, size, bold ? 1 : 0); + VivaFont *font = viva_mono_family_font(family, size, bold ? 1 : 0); if (font == nil) { return nil; } @@ -733,7 +788,7 @@ viva_mono_family_traits viva_mono_family_traits_of(NSString *family) { return traits; } } - NSFont *font = viva_mono_family_font(family, 12, 0); + VivaFont *font = viva_mono_family_font(family, 12, 0); if (font != nil) { traits.onGrid = viva_mono_font_on_a_grid(font); traits.includesHan = viva_mono_draws_han((CTFontRef)font); @@ -805,7 +860,7 @@ BOOL viva_mono_family_better(viva_mono_family_traits candidate, NSString *family } continue; } - NSFont *font = viva_mono_family_font(family, 12, 0); + VivaFont *font = viva_mono_family_font(family, 12, 0); if (font == nil || !viva_mono_font_covers((CTFontRef)font, cluster)) { CFRelease(family); continue; @@ -832,7 +887,7 @@ BOOL viva_mono_family_better(viva_mono_family_traits candidate, NSString *family NSArray *fallbacks = nil; viva_mono_face_traits(face, &family, &classic, &fallbacks); for (NSString *candidate in fallbacks) { - NSFont *font = viva_mono_family_font(candidate, 12, 0); + VivaFont *font = viva_mono_family_font(candidate, 12, 0); if (font != nil && viva_mono_font_covers((CTFontRef)font, cluster)) { return candidate; } @@ -897,12 +952,12 @@ BOOL viva_mono_font_is_last_resort(CTFontRef font) { // size and boldness. A line with nothing to replace is shaped once, as before; one with // a replacement is shaped again with the fallback fonts in place, so every glyph sits // where the grid says. The line is +1: the caller releases it. -CTLineRef viva_mono_fallback_line(NSString *value, NSFont *base, int face, CGColorRef color) { +CTLineRef viva_mono_fallback_line(NSString *value, VivaFont *base, int face, CGColorRef color) { if (base == nil || value.length == 0) { return NULL; } CGFloat size = base.pointSize; - BOOL bold = (base.fontDescriptor.symbolicTraits & NSFontBoldTrait) != 0; + BOOL bold = (base.fontDescriptor.symbolicTraits & VivaFontBoldTrait) != 0; CFIndex length = (CFIndex)value.length; CFMutableAttributedStringRef attributed = CFAttributedStringCreateMutable(kCFAllocatorDefault, 0); if (attributed == NULL) { @@ -940,7 +995,7 @@ CTLineRef viva_mono_fallback_line(NSString *value, NSFont *base, int face, CGCol if (family == nil) { family = viva_mono_fallback_family(text); } - NSFont *fallback = family != nil ? viva_mono_replacement_font(family, size, bold) : nil; + VivaFont *fallback = family != nil ? viva_mono_replacement_font(family, size, bold) : nil; if (fallback != nil) { CFAttributedStringSetAttribute(attributed, CFRangeMake((CFIndex)cluster.location, (CFIndex)cluster.length), @@ -1003,10 +1058,10 @@ void viva_prepare_text_context(CGContextRef context, CGFloat scale) { // look the same, and the text does not move when it is committed to the grid. void viva_draw_terminal_preedit( CGContextRef context, NSString *shown, CGFloat fontSize, int monoFace, - NSColor *color, CGFloat cellWidth, CGFloat baseline + VivaColor *color, CGFloat cellWidth, CGFloat baseline ) { // The face's font, with the installed fallback for what no family of it draws. - NSFont *font = viva_mono_font(fontSize, 0, monoFace); + VivaFont *font = viva_mono_font(fontSize, 0, monoFace); NSUInteger column = 0; for (NSUInteger at = 0; at < shown.length;) { int cells = 0; @@ -1132,8 +1187,8 @@ int viva_text_line_rasterize( NSString *shown, CGFloat fontSize, CGFloat fontWeight, - NSColor *color, - NSSize frameSize, + VivaColor *color, + CGSize frameSize, NSRange selectedRange, BOOL hasMarked, NSRange markedRange, @@ -1211,8 +1266,8 @@ int viva_text_line_rasterize( // Fully transparent text means an editor that exists only to receive input // (an OTP field paints its own slots): draw none of it, caret and selection // included. A translucent color still gets its caret and highlight. - NSColor *textColor = [color colorUsingColorSpace:[NSColorSpace sRGBColorSpace]]; - BOOL invisible = textColor != nil && textColor.alphaComponent <= 0.0; + CGFloat textRGBA[4]; + BOOL invisible = viva_color_srgb(color, textRGBA) && textRGBA[3] <= 0.0; double spans[2 * VIVA_SELECTION_PIECES]; if (selected.length > 0 && !terminal && !hideNativeOverlays && !invisible) { size_t count = viva_text_spans(line, selected, terminal, spans, VIVA_SELECTION_PIECES); @@ -1246,14 +1301,9 @@ int viva_text_line_rasterize( } } else if (selected.length == 0 && caretVisible && !terminal && !hideNativeOverlays) { CGFloat caret = viva_editor_visible_caret(inset + viva_text_offset(line, selected.location, terminal), frameSize.width, alignment, terminal); - NSColor *caretColor = [color colorUsingColorSpace:[NSColorSpace sRGBColorSpace]]; - CGContextSetRGBFillColor( - context, - caretColor.redComponent, - caretColor.greenComponent, - caretColor.blueComponent, - MAX(caretColor.alphaComponent, 0.9) - ); + CGFloat caretRGBA[4]; + viva_color_srgb(color, caretRGBA); // a color with no sRGB form gives zeros, as nil did + CGContextSetRGBFillColor(context, caretRGBA[0], caretRGBA[1], caretRGBA[2], MAX(caretRGBA[3], 0.9)); CGContextFillRect(context, CGRectMake(caret, baseline - descent, 2.0, ascent + descent)); } diff --git a/internal/platform/darwin/native.m b/internal/platform/darwin/native.m index 173329dbd..364f49c05 100644 --- a/internal/platform/darwin/native.m +++ b/internal/platform/darwin/native.m @@ -13,31 +13,6 @@ static uint64_t viva_scroll_event_count; static double viva_scroll_last_pixel_y; -/* The compiled shader library the application passes as it opens its windows, - * kept after the first one compiled its pipelines: a window that makes its - * Metal resources again builds a library from these bytes on the device it is - * given, which need not be the device the first library was compiled for. */ -static void *viva_shader_library_bytes = NULL; -static size_t viva_shader_library_length = 0; - -static int viva_remember_shader_library(const unsigned char *bytes, size_t length) { - if (bytes == NULL || length == 0) { - return 0; - } - if (viva_shader_library_bytes != NULL && viva_shader_library_length == length && - memcmp(viva_shader_library_bytes, bytes, length) == 0) { - return 1; - } - void *copy = malloc(length); - if (copy == NULL) { - return 0; - } - memcpy(copy, bytes, length); - free(viva_shader_library_bytes); - viva_shader_library_bytes = copy; - viva_shader_library_length = length; - return 1; -} /* Window chrome modes. */ enum { @@ -185,158 +160,6 @@ static void viva_place_traffic_lights(NSWindow *window, CGFloat stripHeight, CGF VIVA_STATUS_REMOVE_EVENT = 0x4754, }; -static uint16_t viva_rectangle_layer(viva_rectangle rectangle) { - if (rectangle.reserved0 <= 0) { - return 0; - } - if (rectangle.reserved0 >= UINT16_MAX) { - return UINT16_MAX; - } - return (uint16_t)rectangle.reserved0; -} - -static int viva_compare_composite_commands(const void *left, const void *right) { - const viva_composite_command *a = left; - const viva_composite_command *b = right; - if (a->layer != b->layer) { - return a->layer < b->layer ? -1 : 1; - } - if (a->sequence != b->sequence) { - return a->sequence < b->sequence ? -1 : 1; - } - if (a->kind != b->kind) { - return a->kind < b->kind ? -1 : 1; - } - if (a->first != b->first) { - return a->first < b->first ? -1 : 1; - } - return 0; -} - -// viva_same_batch reports whether two instances can share one draw: the same -// layer and the same clip. An instance no clip cuts ignores its stale clip fields. -static int viva_same_batch( - const viva_rectangle *rectangles, - const viva_clip *clips, - size_t left, - size_t right -) { - if (viva_rectangle_layer(rectangles[left]) != viva_rectangle_layer(rectangles[right])) { - return 0; - } - int left_clipped = clips != NULL && clips[left].clipped != 0; - int right_clipped = clips != NULL && clips[right].clipped != 0; - if (left_clipped != right_clipped) { - return 0; - } - if (!left_clipped) { - return 1; - } - return clips[left].x == clips[right].x && clips[left].y == clips[right].y && - clips[left].width == clips[right].width && - clips[left].height == clips[right].height; -} - -/* viva_rectangle_capacity answers the instance slots the renderer's rectangle - * buffers need to hold count instances, given the slots they already hold. A - * buffer that has room keeps it, so an append landing in the headroom of an - * earlier growth costs nothing; a buffer that must grow doubles, so a scene - * that appends one instance at a time allocates a logarithmic number of times - * and the buffers stay within twice the instances that exist. */ -size_t viva_rectangle_capacity(size_t capacity, size_t count) { - if (capacity >= count) { - return capacity; - } - size_t next = capacity > 0 ? capacity : 64; - while (next < count) { - if (next > SIZE_MAX / 2) { - return count; - } - next *= 2; - } - return next; -} - -int viva_plan_composite( - const viva_rectangle *rectangles, - const viva_clip *clips, - size_t rectangle_count, - const uint16_t *text_layers, - const uint32_t *text_shapes_before, - size_t text_count, - viva_composite_command *commands, - size_t command_capacity, - size_t *command_count -) { - if (command_count == NULL || - (rectangle_count > 0 && (rectangles == NULL || clips == NULL)) || - (text_count > 0 && (text_layers == NULL || text_shapes_before == NULL)) || - rectangle_count > UINT32_MAX || text_count > UINT32_MAX) { - return 1; - } - - // At most one command per shape and one per label: a shape batch can be cut - // at every label boundary. - if (rectangle_count > SIZE_MAX - text_count) { - return 2; - } - size_t required = rectangle_count + text_count; - if (required > command_capacity || (required > 0 && commands == NULL)) { - return 2; - } - - // Shapes and labels arrive in paint order. A label that says k shapes were - // painted before it belongs after instance k-1 and before instance k, so - // the plan walks both lists by that boundary, cutting a shape batch when a - // label falls inside it. - size_t command_index = 0; - size_t rectangle_index = 0; - size_t text_index = 0; - while (rectangle_index < rectangle_count || text_index < text_count) { - if (text_index < text_count && - (text_shapes_before[text_index] <= rectangle_index || rectangle_index >= rectangle_count)) { - uint32_t sequence = (uint32_t)command_index; - commands[command_index++] = (viva_composite_command){ - .layer = text_layers[text_index], - .kind = VIVA_COMPOSITE_TEXT, - .first = (uint32_t)text_index, - .count = 1, - .sequence = sequence, - }; - text_index++; - continue; - } - size_t first = rectangle_index; - size_t end = first + 1; - while (end < rectangle_count && - viva_same_batch(rectangles, clips, first, end) && - (text_index >= text_count || end < text_shapes_before[text_index])) { - end++; - } - uint16_t layer = viva_rectangle_layer(rectangles[first]); - uint32_t sequence = (uint32_t)command_index; - viva_composite_command command = { - .layer = layer, - .kind = VIVA_COMPOSITE_RECTANGLES, - .first = (uint32_t)first, - .count = (uint32_t)(end - first), - .sequence = sequence, - }; - if (clips[first].clipped != 0) { - command.clipped = 1; - command.clip_x = clips[first].x; - command.clip_y = clips[first].y; - command.clip_width = clips[first].width; - command.clip_height = clips[first].height; - } - commands[command_index++] = command; - rectangle_index = end; - } - qsort(commands, command_index, sizeof(viva_composite_command), - viva_compare_composite_commands); - *command_count = command_index; - return 0; -} /* Key identities mirror input.Key values. */ enum { @@ -1307,22 +1130,9 @@ - (void)setAccessibilitySelectedTextRange:(NSRange)range { @interface VivaMetalView : NSView { CAMetalLayer *_metalLayer; - id _commandQueue; - id _rectanglePipeline; - id _rectangleBuffer; - NSUInteger _rectangleCount; - // Capacity is the slots the buffers hold; count is the instances the scene - // owns. An append past the capacity grows it by doubling; rebuilds - // re-tighten it to the exact count. - NSUInteger _rectangleCapacity; - viva_clip *_rectangleClips; - id _textPipeline; - NSMutableArray *_textLabels; - uint16_t *_textLabelLayers; - uint32_t *_textLabelShapesBefore; - NSUInteger _textLabelCount; - viva_composite_command *_compositeCommands; - NSUInteger _compositeCommandCount; + // What the surface draws: the rectangles, the label layers, the pipelines and + // the queue they go through (VivaRenderer, shared with the other surfaces). + VivaRenderer *_renderer; id _textTexture; NSString *_text; NSRect _textFrame; @@ -1381,8 +1191,7 @@ @interface VivaMetalView : NSView { BOOL _titlebarDragPending; NSPoint _titlebarDragOrigin; uintptr_t _callbackHandle; - MTLClearColor _clearColor; - NSMutableArray *_accessibilityElements; + NSMutableArray *_accessibilityElements; NSSize _lastReportedSize; BOOL _liveResizeRelaxed; BOOL _reportedSize; @@ -1427,12 +1236,6 @@ - (int)updateRectangles:(const viva_rectangle *)rectangles render:(BOOL)render; - (int)updateLabels:(const viva_text_label *)labels count:(NSUInteger)count; -- (BOOL)replaceCompositePlanForRectangles:(const viva_rectangle *)rectangles - clips:(const viva_clip *)clips - rectangleCount:(NSUInteger)rectangleCount - textLayers:(const uint16_t *)textLayers - textShapesBefore:(const uint32_t *)textShapesBefore - textCount:(NSUInteger)textCount; - (int)updateAccessibility:(const viva_accessibility_node *)nodes count:(NSUInteger)count; - (int)updateText:(const unsigned char *)utf8 @@ -1545,20 +1348,6 @@ - (instancetype)initWithFrame:(NSRect)frame clearColor:(MTLClearColor)clearColor { self = [super initWithFrame:frame]; if (self != nil) { - _commandQueue = [commandQueue retain]; - _rectanglePipeline = [rectanglePipeline retain]; - _rectangleBuffer = [rectangleBuffer retain]; - _rectangleCount = rectangleCount; - _rectangleCapacity = rectangleCount; - if (rectangleCount > 0) { - _rectangleClips = malloc(rectangleCount * sizeof(viva_clip)); - if (_rectangleClips == NULL) { - [self release]; - return nil; - } - memcpy(_rectangleClips, rectangleClips, rectangleCount * sizeof(viva_clip)); - } - _textPipeline = [textPipeline retain]; _textInputEnabled = textInput.enabled != 0; _textInputMultiline = textInput.multiline != 0; _textPlaced = textInput.placed != 0; @@ -1613,7 +1402,6 @@ - (instancetype)initWithFrame:(NSRect)frame _text = [@"" retain]; } _callbackHandle = callbackHandle; - _clearColor = clearColor; _lastReportedSize = frame.size; _reportedSize = YES; _profileEnabled = viva_profile_enabled(); @@ -1648,44 +1436,21 @@ - (instancetype)initWithFrame:(NSRect)frame userInfo:nil]; [self addTrackingArea:tracking]; [tracking release]; - if (textLabelCount > 0) { - _textLabelLayers = malloc(textLabelCount * sizeof(uint16_t)); - _textLabelShapesBefore = malloc(textLabelCount * sizeof(uint32_t)); - if (_textLabelLayers == NULL || _textLabelShapesBefore == NULL) { - [self release]; - return nil; - } - for (NSUInteger index = 0; index < textLabelCount; index++) { - _textLabelLayers[index] = textLabels[index].layer; - _textLabelShapesBefore[index] = textLabels[index].shapes_before; - } - } - _textLabelCount = textLabelCount; - _textLabels = [[NSMutableArray alloc] initWithCapacity:textLabelCount]; - for (NSUInteger index = 0; index < textLabelCount; index++) { - VivaTextLayer *layer = [[VivaTextLayer alloc] initWithConfig:textLabels[index]]; - if (layer == nil) { - [self release]; - return nil; - } - [_textLabels addObject:layer]; - [layer release]; - } - if (![self rebuildTextLabels]) { - [self release]; - return nil; - } - if (![self replaceCompositePlanForRectangles: - rectangleBuffer == nil ? NULL : rectangleBuffer.contents - clips:_rectangleClips - rectangleCount:rectangleCount - textLayers:_textLabelLayers - textShapesBefore:_textLabelShapesBefore - textCount:_textLabelCount]) { + _renderer = [[VivaRenderer alloc] initWithLayer:_metalLayer + commandQueue:commandQueue + rectanglePipeline:rectanglePipeline + rectangleBuffer:rectangleBuffer + rectangleCount:rectangleCount + rectangleClips:rectangleClips + textPipeline:textPipeline + textLabels:textLabels + textLabelCount:textLabelCount + clearColor:clearColor + viewport:self.bounds.size]; + if (_renderer == nil) { [self release]; return nil; } - viva_label_initial_count = textLabelCount; _accessibilityElements = [[NSMutableArray alloc] init]; for (NSUInteger index = 0; index < accessibilityCount; index++) { VivaAccessibleElement *element = @@ -1715,65 +1480,16 @@ - (void)dealloc { _textInputEnabled = NO; [self syncSecureEventInput]; [self stopCaretBlink]; - free(_compositeCommands); - free(_rectangleClips); - free(_textLabelLayers); - free(_textLabelShapesBefore); [_cursor release]; - [_rectangleBuffer release]; - [_rectanglePipeline release]; [_textTexture release]; - [_textLabels release]; [_accessibilityElements release]; - [_textPipeline release]; [_text release]; [_textColor release]; - [_commandQueue release]; + [_renderer release]; [_metalLayer release]; [super dealloc]; } -- (BOOL)replaceCompositePlanForRectangles:(const viva_rectangle *)rectangles - clips:(const viva_clip *)clips - rectangleCount:(NSUInteger)rectangleCount - textLayers:(const uint16_t *)textLayers - textShapesBefore:(const uint32_t *)textShapesBefore - textCount:(NSUInteger)textCount { - if (rectangleCount > SIZE_MAX - textCount) { - return NO; - } - NSUInteger capacity = rectangleCount + textCount; - viva_composite_command *replacement = NULL; - if (capacity > 0) { - if (capacity > SIZE_MAX / sizeof(viva_composite_command)) { - return NO; - } - replacement = malloc(capacity * sizeof(viva_composite_command)); - if (replacement == NULL) { - return NO; - } - } - size_t count = 0; - int status = viva_plan_composite( - rectangles, - clips, - rectangleCount, - textLayers, - textShapesBefore, - textCount, - replacement, - capacity, - &count - ); - if (status != 0) { - free(replacement); - return NO; - } - free(_compositeCommands); - _compositeCommands = replacement; - _compositeCommandCount = count; - return YES; -} - (BOOL)isOpaque { return _windowMode != VIVA_WINDOW_PANEL && _windowMode != VIVA_WINDOW_PREVIEW && _windowMode != VIVA_WINDOW_NOTIFICATION; @@ -2438,11 +2154,7 @@ - (void)endLiveResizeRelaxation { return; } _liveResizeRelaxed = NO; - CGFloat scale = MAX(_metalLayer.contentsScale, 1.0); - for (VivaTextLayer *layer in _textLabels) { - [layer forceTextureRebuildWithDevice:_metalLayer.device scale:scale viewport:self.bounds.size]; - } - viva_label_texture_rebuild_count += _textLabels.count; + [_renderer forceRebuildTextLabelsWithViewport:self.bounds.size]; // setNeedsDisplay is not honored without drawRect; render explicitly so // the refreshed textures actually reach the screen. [self render]; @@ -2464,13 +2176,7 @@ - (void)viewDidChangeBackingProperties { } - (BOOL)rebuildTextLabels { - CGFloat scale = MAX(_metalLayer.contentsScale, 1.0); - for (VivaTextLayer *layer in _textLabels) { - if (![layer rebuildWithDevice:_metalLayer.device scale:scale viewport:self.bounds.size]) { - return NO; - } - } - return YES; + return [_renderer rebuildTextLabelsWithViewport:self.bounds.size]; } - (void)updateDrawableSize { @@ -2548,7 +2254,7 @@ - (viva_editor_line)newTextLine { } - (BOOL)rebuildTextTexture { - if (!_textInputEnabled || _textPipeline == nil) { + if (!_textInputEnabled || _renderer.textPipeline == nil) { return !_textInputEnabled; } id texture = viva_text_input_texture( @@ -2688,23 +2394,11 @@ - (void)renderWaitingForSchedule:(BOOL)wait { }]; } - MTLRenderPassDescriptor *pass = [MTLRenderPassDescriptor renderPassDescriptor]; - pass.colorAttachments[0].texture = drawable.texture; - pass.colorAttachments[0].loadAction = MTLLoadActionClear; - pass.colorAttachments[0].storeAction = MTLStoreActionStore; - pass.colorAttachments[0].clearColor = _clearColor; - - id commandBuffer = [_commandQueue commandBuffer]; - id encoder = - [commandBuffer renderCommandEncoderWithDescriptor:pass]; - viva_encode_scene(encoder, _rectanglePipeline, _textPipeline, _rectangleBuffer, - _compositeCommands, _compositeCommandCount, _textLabels, - _textTexture, _textFrame, _textLayer, self.bounds.size, - drawable.texture.width, drawable.texture.height); - [encoder endEncoding]; - [commandBuffer presentDrawable:drawable]; - [commandBuffer commit]; - viva_gpu_submission_count++; + id commandBuffer = [_renderer renderToDrawable:drawable + viewport:self.bounds.size + inputTexture:_textTexture + inputFrame:_textFrame + inputLayer:_textLayer]; if (probe) { viva_probe_committed(); } @@ -2738,76 +2432,11 @@ - (void)renderWaitingForSchedule:(BOOL)wait { * Returns NO when the device, its queue or the pipelines cannot be made, which * is when the window cannot go on. */ - (BOOL)recoverResources { - if (viva_shader_library_bytes == NULL) { - return NO; - } @autoreleasepool { - id device = MTLCreateSystemDefaultDevice(); - if (device == nil) { - return NO; - } - id queue = [device newCommandQueue]; - if (queue == nil) { - [device release]; - return NO; - } - dispatch_data_t libraryData = dispatch_data_create( - viva_shader_library_bytes, - viva_shader_library_length, - dispatch_get_main_queue(), - DISPATCH_DATA_DESTRUCTOR_DEFAULT - ); - NSError *libraryError = nil; - id library = [device newLibraryWithData:libraryData error:&libraryError]; - dispatch_release(libraryData); - if (library == nil) { - [queue release]; - [device release]; - return NO; - } - // Both pipelines, whatever the window had: the frame that failed asked - // for rectangles, and a label texture of the old device cannot be drawn - // by the new one. - id rectanglePipeline = viva_create_pipeline( - device, library, @"viva_rectangle_vertex", @"viva_rectangle_fragment", NULL); - id textPipeline = viva_create_pipeline( - device, library, @"viva_text_vertex", @"viva_text_fragment", NULL); - [library release]; - if (rectanglePipeline == nil || textPipeline == nil) { - [rectanglePipeline release]; - [textPipeline release]; - [queue release]; - [device release]; - return NO; - } - _metalLayer.device = device; [self updateDrawableSize]; - [_commandQueue release]; - _commandQueue = queue; - [_rectanglePipeline release]; - _rectanglePipeline = rectanglePipeline; - [_textPipeline release]; - _textPipeline = textPipeline; - // The instance buffers belonged to the old device; the application - // sends every instance again, as a rebuild. - [_rectangleBuffer release]; - _rectangleBuffer = nil; - free(_rectangleClips); - _rectangleClips = NULL; - _rectangleCount = 0; - _rectangleCapacity = 0; - free(_compositeCommands); - _compositeCommands = NULL; - _compositeCommandCount = 0; - CGFloat scale = MAX(_metalLayer.contentsScale, 1.0); - for (VivaTextLayer *layer in _textLabels) { - if (![layer forceTextureRebuildWithDevice:device scale:scale viewport:self.bounds.size]) { - [device release]; - return NO; - } + if (![_renderer recoverWithViewport:self.bounds.size]) { + return NO; } - viva_label_texture_rebuild_count += _textLabels.count; - [device release]; if (_textInputEnabled && ![self rebuildTextTexture]) { return NO; } @@ -2822,189 +2451,21 @@ - (int)updateRectangles:(const viva_rectangle *)rectangles count:(NSUInteger)count rebuild:(BOOL)rebuild render:(BOOL)render { - if (rebuild) { - id replacement = nil; - viva_clip *replacementClips = NULL; - if (totalCount > 0) { - if (_rectanglePipeline == nil || clips == NULL) { - return 3; - } - replacementClips = malloc(totalCount * sizeof(viva_clip)); - if (replacementClips == NULL) { - return 3; - } - memcpy(replacementClips, clips, totalCount * sizeof(viva_clip)); - replacement = [_metalLayer.device - newBufferWithBytes:rectangles - length:totalCount * sizeof(viva_rectangle) - options:MTLResourceStorageModeShared]; - if (replacement == nil) { - free(replacementClips); - return 3; - } - // The staged instances carry their layer in reserved0, so the - // bytes newBufferWithBytes copies are already complete. - } - if (![self replaceCompositePlanForRectangles: - replacement == nil ? NULL : replacement.contents - clips:replacementClips - rectangleCount:totalCount - textLayers:_textLabelLayers - textShapesBefore:_textLabelShapesBefore - textCount:_textLabelCount]) { - [replacement release]; - free(replacementClips); - return 3; - } - [_rectangleBuffer release]; - free(_rectangleClips); - _rectangleClips = replacementClips; - _rectangleBuffer = replacement; - _rectangleCount = totalCount; - _rectangleCapacity = totalCount; - viva_gpu_uploaded_bytes += totalCount * sizeof(viva_rectangle); - viva_gpu_full_rebuild_count++; - } else { - BOOL shrank = totalCount < _rectangleCount; - if (shrank) { - if (first + count != totalCount) { - return 2; - } - _rectangleCount = totalCount; - } - if (count == 0) { - if (shrank && ![self replaceCompositePlanForRectangles: - _rectangleBuffer == nil ? NULL : _rectangleBuffer.contents - clips:_rectangleClips - rectangleCount:_rectangleCount - textLayers:_textLabelLayers - textShapesBefore:_textLabelShapesBefore - textCount:_textLabelCount]) { - return 3; - } - if (render) { - [self render]; - } - return 0; - } - if (_rectangleBuffer == nil || _rectangleClips == NULL || clips == NULL || - first > totalCount || count > totalCount - first) { - return 2; - } - BOOL grew = totalCount > _rectangleCount; - BOOL reallocated = NO; - if (grew) { - // The scene appended instances. A stream that appends every frame - // must not allocate, copy and re-flush the whole buffer each time, - // so the buffers carry headroom; a rebuild re-tightens them to the - // exact count. The headroom is only made when the new count no - // longer fits: growing on every append multiplied the capacity by - // a quarter per frame while the scene appended one instance, and - // the request passed what the device hands out within a few dozen - // appends. - if (first > _rectangleCount || first + count != totalCount) { - return 2; - } - NSUInteger capacity = viva_rectangle_capacity(_rectangleCapacity, totalCount); - if (capacity != _rectangleCapacity) { - id replacement = [_metalLayer.device - newBufferWithLength:capacity * sizeof(viva_rectangle) - options:MTLResourceStorageModeShared]; - if (replacement == nil) { - return 3; - } - viva_clip *replacementClips = malloc(capacity * sizeof(viva_clip)); - if (replacementClips == NULL) { - [replacement release]; - return 3; - } - memcpy(replacementClips, _rectangleClips, _rectangleCount * sizeof(viva_clip)); - memcpy(replacement.contents, _rectangleBuffer.contents, _rectangleCount * sizeof(viva_rectangle)); - [_rectangleBuffer release]; - free(_rectangleClips); - _rectangleBuffer = replacement; - _rectangleClips = replacementClips; - _rectangleCapacity = capacity; - reallocated = YES; - } - _rectangleCount = totalCount; - } - memcpy(_rectangleClips + first, clips, count * sizeof(viva_clip)); - memcpy( - (uint8_t *)_rectangleBuffer.contents + first * sizeof(viva_rectangle), - rectangles, - count * sizeof(viva_rectangle) - ); - // The staged instances carry their layer in reserved0, so the memcpy - // above has already written every field this buffer holds. - [_rectangleBuffer didModifyRange:NSMakeRange( - reallocated ? 0 : first * sizeof(viva_rectangle), - reallocated ? totalCount * sizeof(viva_rectangle) : count * sizeof(viva_rectangle) - )]; - if (![self replaceCompositePlanForRectangles:_rectangleBuffer.contents - clips:_rectangleClips - rectangleCount:_rectangleCount - textLayers:_textLabelLayers - textShapesBefore:_textLabelShapesBefore - textCount:_textLabelCount]) { - return 3; - } - viva_gpu_uploaded_bytes += count * sizeof(viva_rectangle); - viva_gpu_partial_update_count++; - } - - if (render) { + int status = [_renderer updateRectangles:rectangles + clips:clips + totalCount:totalCount + first:first + count:count + rebuild:rebuild]; + if (status == 0 && render) { [self render]; } - return 0; + return status; } - (int)updateLabels:(const viva_text_label *)labels count:(NSUInteger)count { - CGFloat scale = MAX(_metalLayer.contentsScale, 1.0); - uint16_t *replacementLayers = NULL; - uint32_t *replacementShapesBefore = NULL; - if (count > 0) { - replacementLayers = malloc(count * sizeof(uint16_t)); - replacementShapesBefore = malloc(count * sizeof(uint32_t)); - if (replacementLayers == NULL || replacementShapesBefore == NULL) { - free(replacementLayers); - free(replacementShapesBefore); - return 3; - } - for (NSUInteger index = 0; index < count; index++) { - replacementLayers[index] = labels[index].layer; - replacementShapesBefore[index] = labels[index].shapes_before; - } - } - NSMutableArray *replacement = nil; - int status = viva_update_label_layers(_textLabels, labels, count, _metalLayer.device, scale, self.bounds.size, &replacement); - if (status != 0) { - free(replacementLayers); - free(replacementShapesBefore); - return status; - } - if (![self replaceCompositePlanForRectangles: - _rectangleBuffer == nil ? NULL : _rectangleBuffer.contents - clips:_rectangleClips - rectangleCount:_rectangleCount - textLayers:replacementLayers - textShapesBefore:replacementShapesBefore - textCount:count]) { - [replacement release]; - free(replacementLayers); - free(replacementShapesBefore); - return 3; - } - [_textLabels release]; - _textLabels = replacement; - free(_textLabelLayers); - free(_textLabelShapesBefore); - _textLabelLayers = replacementLayers; - _textLabelShapesBefore = replacementShapesBefore; - _textLabelCount = count; - viva_label_update_count++; - return 0; + return [_renderer updateLabels:labels count:count viewport:self.bounds.size]; } - (int)updateAccessibility:(const viva_accessibility_node *)nodes From 386b6a632205ee931f671f75247fed1c8cf45203 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 22 Nov 2026 20:24:32 +0800 Subject: [PATCH 23/64] feat(ios): run an application in a UIKit window drawn by the Metal renderer The iOS backend shares internal/platform/darwin with macOS, split by build tag: the Go side that encodes frames, shapes text and routes callbacks is the same, and cgo types cannot cross packages. ios_host.m answers the same C interface as the AppKit host with one full-screen UIView over a CAMetalLayer, touches forwarded as touch pointers, and a single window (a second one is refused). The Go program runs as the executable: UIApplicationMain starts it and the application's start runs from didFinishLaunching. Shader libraries are built for macOS, iOS devices and the iOS simulator and chosen at run time. The macOS shader library is unchanged. Not yet: safe area, keyboard, accessibility, lifecycle, device runs. --- app/backend_ios.go | 13 + app/ios_unsupported.go | 6 - internal/platform/darwin/callback.go | 31 +- internal/platform/darwin/core.h | 8 + internal/platform/darwin/core_render.m | 124 +++++ internal/platform/darwin/core_text.m | 110 ++++ .../platform/darwin/font_register_darwin.go | 2 +- internal/platform/darwin/ios_callback.go | 37 ++ internal/platform/darwin/ios_hooks.go | 46 ++ internal/platform/darwin/ios_host.h | 19 + internal/platform/darwin/ios_host.m | 522 ++++++++++++++++++ internal/platform/darwin/ios_run.go | 52 ++ internal/platform/darwin/mono_family.go | 2 +- internal/platform/darwin/native.m | 218 +------- internal/platform/darwin/open_file_darwin.go | 2 +- internal/platform/darwin/open_url_darwin.go | 2 +- internal/platform/darwin/platform.go | 35 +- internal/platform/darwin/post_darwin.go | 2 +- internal/platform/darwin/post_darwin.h | 2 +- internal/platform/darwin/post_darwin.m | 2 +- .../platform/darwin/quit_request_darwin.go | 2 +- internal/platform/darwin/reopen_darwin.go | 2 +- internal/platform/darwin/run_macos.go | 40 ++ internal/platform/darwin/shader_ios.go | 28 + .../darwin/shaders/scene_ios.metallib | Bin 0 -> 23222 bytes .../shaders/scene_ios_simulator.metallib | Bin 0 -> 23318 bytes internal/platform/darwin/text.go | 2 +- internal/platform/darwin/text_engine.go | 2 +- tools/generate_darwin_shaders.sh | 22 + 29 files changed, 1064 insertions(+), 269 deletions(-) create mode 100644 app/backend_ios.go create mode 100644 internal/platform/darwin/ios_callback.go create mode 100644 internal/platform/darwin/ios_hooks.go create mode 100644 internal/platform/darwin/ios_host.h create mode 100644 internal/platform/darwin/ios_host.m create mode 100644 internal/platform/darwin/ios_run.go create mode 100644 internal/platform/darwin/run_macos.go create mode 100644 internal/platform/darwin/shader_ios.go create mode 100644 internal/platform/darwin/shaders/scene_ios.metallib create mode 100644 internal/platform/darwin/shaders/scene_ios_simulator.metallib diff --git a/app/backend_ios.go b/app/backend_ios.go new file mode 100644 index 000000000..968839fbe --- /dev/null +++ b/app/backend_ios.go @@ -0,0 +1,13 @@ +//go:build ios + +package app + +import ( + "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/internal/platform/darwin" +) + +func runNative(config platform.Config) error { return darwin.Run(config) } +func runNativeApplication(start platform.ApplicationStart) error { + return darwin.RunApplication(start) +} diff --git a/app/ios_unsupported.go b/app/ios_unsupported.go index 4f981e037..26c7ad12c 100644 --- a/app/ios_unsupported.go +++ b/app/ios_unsupported.go @@ -7,7 +7,6 @@ import ( "os" "github.com/vivaui/viva/gfx" - "github.com/vivaui/viva/internal/platform" ) // Until the iOS backend provides them (ADR 0095), the platform's native hooks @@ -15,11 +14,6 @@ import ( // give, such as the clipboard, the cursor, dialogs and notifications, is added // here one by one, and each moves out of this file as it lands. -func runNative(platform.Config) error { return fmt.Errorf("%w: the iOS backend", ErrUnsupported) } -func runNativeApplication(platform.ApplicationStart) error { - return fmt.Errorf("%w: the iOS backend", ErrUnsupported) -} - func currentPlatform() Platform { return PlatformUnknown } func nativeReduceMotion() bool { return false } diff --git a/internal/platform/darwin/callback.go b/internal/platform/darwin/callback.go index 3fa07fa43..54802a9ba 100644 --- a/internal/platform/darwin/callback.go +++ b/internal/platform/darwin/callback.go @@ -1,4 +1,4 @@ -//go:build darwin && !ios +//go:build darwin package darwin @@ -79,18 +79,10 @@ func vivaPointerEvent( screenY C.double, ) { state, ok := runStateFor(handle) - if !ok || state.closed || state.pointerHandler == nil { + if !ok { return } - defer func() { - if recovered := recover(); recovered != nil { - platform.ReportFault("darwin: AppKit callback", recovered) - state.err = fmt.Errorf("darwin: pointer handler panicked: %v", recovered) - C.viva_view_close(view) - } - }() - - frame, err := state.pointerHandler(PointerEvent{ + deliverPointer(state, view, PointerEvent{ Kind: PointerEventKind(kind), Button: gfx.PointerButton(button), Modifiers: input.Modifiers(modifiers), @@ -100,6 +92,23 @@ func vivaPointerEvent( ScreenY: float32(screenY), ClickCount: int(clickCount), }) +} + +// deliverPointer gives the application a pointer event, and shows the frame it +// answers with. A handler that panics or fails ends the window. +func deliverPointer(state *runState, view unsafe.Pointer, event PointerEvent) { + if state.closed || state.pointerHandler == nil { + return + } + defer func() { + if recovered := recover(); recovered != nil { + platform.ReportFault("darwin: native callback", recovered) + state.err = fmt.Errorf("darwin: pointer handler panicked: %v", recovered) + C.viva_view_close(view) + } + }() + + frame, err := state.pointerHandler(event) if err == nil { err = presentFrame(state, view, frame, false) } diff --git a/internal/platform/darwin/core.h b/internal/platform/darwin/core.h index 4c64b47d1..9b0f4b3d2 100644 --- a/internal/platform/darwin/core.h +++ b/internal/platform/darwin/core.h @@ -205,6 +205,14 @@ typedef struct { @end extern int vivaTerminalCells(uint32_t character); +int viva_make_scene_resources( + const viva_window_config *config, + id *device, + id *queue, + id *rectangle_pipeline, + id *text_pipeline, + id *rectangle_buffer +); extern void *viva_shader_library_bytes; extern size_t viva_shader_library_length; int viva_remember_shader_library(const unsigned char *bytes, size_t length); diff --git a/internal/platform/darwin/core_render.m b/internal/platform/darwin/core_render.m index 71474ee07..026224d05 100644 --- a/internal/platform/darwin/core_render.m +++ b/internal/platform/darwin/core_render.m @@ -1394,6 +1394,130 @@ void viva_encode_scene( } +// viva_make_scene_resources makes the Metal objects a window's first scene is +// drawn with: the device, its queue, the two pipelines the window's events and +// content call for, and the rectangle buffer. Every object it returns is +// retained for the caller. It answers 0, or the status the window reports when +// the object it names cannot be made (1 device, 2 queue, 3 library, 4 rectangle +// pipeline, 5 buffer, 6 text pipeline), with everything made so far released. +int viva_make_scene_resources( + const viva_window_config *config_in, + id *device_out, + id *queue_out, + id *rectangle_pipeline_out, + id *text_pipeline_out, + id *rectangle_buffer_out +) { + const viva_window_config config = *config_in; + *device_out = nil; + *queue_out = nil; + *rectangle_pipeline_out = nil; + *text_pipeline_out = nil; + *rectangle_buffer_out = nil; + id device = MTLCreateSystemDefaultDevice(); + if (device == nil) { + return 1; + } + + id commandQueue = [device newCommandQueue]; + if (commandQueue == nil) { + [device release]; + return 2; + } + + id rectanglePipeline = nil; + id textPipeline = nil; + id rectangleBuffer = nil; + if (config.shader_library != NULL && config.shader_library_length > 0) { + viva_remember_shader_library(config.shader_library, config.shader_library_length); + _Static_assert(sizeof(viva_rectangle) == 80, "rectangle ABI must be 80 bytes"); + _Static_assert(sizeof(viva_text_label) == 272, "text label ABI must be 272 bytes"); + _Static_assert(sizeof(viva_text_run) == 36, "text run ABI must be 36 bytes"); + _Static_assert(sizeof(viva_composite_command) == 36, "composite command ABI must be 36 bytes"); + dispatch_data_t libraryData = dispatch_data_create( + config.shader_library, + config.shader_library_length, + dispatch_get_main_queue(), + DISPATCH_DATA_DESTRUCTOR_DEFAULT + ); + NSError *libraryError = nil; + id library = [device newLibraryWithData:libraryData + error:&libraryError]; + dispatch_release(libraryData); + if (library == nil) { + fprintf(stderr, "viva: Metal library error: %s\n", + libraryError.localizedDescription.UTF8String); + [commandQueue release]; + [device release]; + return 3; + } + + NSError *pipelineError = nil; + if (config.rectangle_count > 0 || config.pointer_events_enabled || + config.resize_events_enabled || config.redraw_events_enabled) { + rectanglePipeline = viva_create_pipeline( + device, + library, + @"viva_rectangle_vertex", + @"viva_rectangle_fragment", + &pipelineError + ); + if (rectanglePipeline == nil) { + fprintf(stderr, "viva: rectangle pipeline error: %s\n", + pipelineError.localizedDescription.UTF8String); + [library release]; + [commandQueue release]; + [device release]; + return 4; + } + } + if (config.text_input.enabled || config.dynamic_text_input || config.text_label_count > 0 || + config.resize_events_enabled || config.redraw_events_enabled) { + pipelineError = nil; + textPipeline = viva_create_pipeline( + device, + library, + @"viva_text_vertex", + @"viva_text_fragment", + &pipelineError + ); + if (textPipeline == nil) { + fprintf(stderr, "viva: text pipeline error: %s\n", + pipelineError.localizedDescription.UTF8String); + [rectanglePipeline release]; + [library release]; + [commandQueue release]; + [device release]; + return 6; + } + } + [library release]; + + if (config.rectangle_count > 0) { + rectangleBuffer = [device + newBufferWithBytes:config.rectangles + length:config.rectangle_count * sizeof(viva_rectangle) + options:MTLResourceStorageModeShared]; + if (rectangleBuffer == nil) { + [textPipeline release]; + [rectanglePipeline release]; + [commandQueue release]; + [device release]; + return 5; + } + viva_gpu_uploaded_bytes += + config.rectangle_count * sizeof(viva_rectangle); + viva_gpu_full_rebuild_count++; + } + } + *device_out = device; + *queue_out = commandQueue; + *rectangle_pipeline_out = rectanglePipeline; + *text_pipeline_out = textPipeline; + *rectangle_buffer_out = rectangleBuffer; + return 0; +} + @interface VivaRenderer (Plan) - (BOOL)replaceCompositePlanForRectangles:(const viva_rectangle *)rectangles clips:(const viva_clip *)clips diff --git a/internal/platform/darwin/core_text.m b/internal/platform/darwin/core_text.m index c77b3e76f..01c1aa3e7 100644 --- a/internal/platform/darwin/core_text.m +++ b/internal/platform/darwin/core_text.m @@ -1332,3 +1332,113 @@ int viva_text_line_rasterize( return texture; } +int viva_measure_text( + const unsigned char *utf8, + size_t utf8_length, + double font_size, + double font_weight, + viva_text_metrics *metrics +) { + if (metrics == NULL || font_size <= 0 || (utf8 == NULL && utf8_length > 0)) { + return 1; + } + @autoreleasepool { + CFStringRef string = CFStringCreateWithBytes( + kCFAllocatorDefault, + utf8, + utf8_length, + kCFStringEncodingUTF8, + false + ); + if (string == NULL) { + return 2; + } + + // The font a label of this weight is drawn in (drawLineInContext). + VivaFont *nativeFont = [VivaFont systemFontOfSize:font_size weight:font_weight]; + CTFontRef font = (CTFontRef)CFRetain(nativeFont); + if (font == NULL) { + CFRelease(string); + return 3; + } + + const void *keys[] = {kCTFontAttributeName}; + const void *values[] = {font}; + CFDictionaryRef attributes = CFDictionaryCreate( + kCFAllocatorDefault, + keys, + values, + 1, + &kCFTypeDictionaryKeyCallBacks, + &kCFTypeDictionaryValueCallBacks + ); + CFAttributedStringRef attributed = CFAttributedStringCreate( + kCFAllocatorDefault, + string, + attributes + ); + CTLineRef line = CTLineCreateWithAttributedString(attributed); + + CGFloat ascent = 0; + CGFloat descent = 0; + CGFloat leading = 0; + double width = CTLineGetTypographicBounds(line, &ascent, &descent, &leading); + metrics->width = width; + metrics->height = ascent + descent + leading; + metrics->ascent = ascent; + metrics->descent = descent; + metrics->leading = leading; + + CFRelease(line); + CFRelease(attributed); + CFRelease(attributes); + CFRelease(font); + CFRelease(string); + return 0; + } +} + +int viva_measure_mono(double font_size, int mono_face, double *advance, double *ascent, double *descent, double *leading, double *rule, double *heavy) { + if (advance == NULL || ascent == NULL || descent == NULL || leading == NULL || rule == NULL || heavy == NULL || font_size <= 0) { + return 1; + } + @autoreleasepool { + // The cell is the primary font's, whatever the face's fallbacks hold. + VivaFont *native = viva_mono_font_primary(font_size, 0, mono_face); + if (native == nil) { + return 2; + } + CTFontRef font = CTFontCreateWithName((CFStringRef)native.fontName, font_size, NULL); + if (font == NULL) { + return 3; + } + UniChar glyphCharacter = 'M'; + CGGlyph glyph = 0; + CTFontGetGlyphsForCharacters(font, &glyphCharacter, &glyph, 1); + CGSize advances; + CTFontGetAdvancesForGlyphs(font, kCTFontOrientationHorizontal, &glyph, &advances, 1); + *advance = advances.width; + *ascent = CTFontGetAscent(font); + *descent = CTFontGetDescent(font); + *leading = CTFontGetLeading(font); + // The weight of the face's own box drawing lines: the ink width of a light and a + // heavy stem, which the face may draw at a different weight than its underline. + // The lookup answers false when either is missing, and still fills the other, so + // each glyph is checked on its own. + *rule = 0; + *heavy = 0; + UniChar boxCharacters[2] = {0x2502, 0x2503}; /* │ ┃ */ + CGGlyph boxGlyphs[2] = {0, 0}; + CTFontGetGlyphsForCharacters(font, boxCharacters, boxGlyphs, 2); + CGRect bounds[2] = {CGRectZero, CGRectZero}; + CTFontGetBoundingRectsForGlyphs(font, kCTFontOrientationHorizontal, boxGlyphs, bounds, 2); + if (boxGlyphs[0] != 0) { + *rule = bounds[0].size.width; + } + if (boxGlyphs[1] != 0) { + *heavy = bounds[1].size.width; + } + CFRelease(font); + return *advance > 0 ? 0 : 4; + } +} diff --git a/internal/platform/darwin/font_register_darwin.go b/internal/platform/darwin/font_register_darwin.go index b4636c02f..3d0af5cda 100644 --- a/internal/platform/darwin/font_register_darwin.go +++ b/internal/platform/darwin/font_register_darwin.go @@ -1,4 +1,4 @@ -//go:build darwin && !ios +//go:build darwin package darwin diff --git a/internal/platform/darwin/ios_callback.go b/internal/platform/darwin/ios_callback.go new file mode 100644 index 000000000..19c4dc726 --- /dev/null +++ b/internal/platform/darwin/ios_callback.go @@ -0,0 +1,37 @@ +//go:build ios + +package darwin + +/* +#include "native.h" +*/ +import "C" + +import ( + "unsafe" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/platform" +) + +// vivaTouchEvent is a finger of the window's view: kind is a PointerEventKind, +// id tells the fingers touching at once apart, and the coordinates are logical +// pixels in the view and on the screen. +// +//export vivaTouchEvent +func vivaTouchEvent(handle C.uintptr_t, view unsafe.Pointer, kind C.int, id C.int, x, y, screenX, screenY C.double) { + state, ok := runStateFor(handle) + if !ok { + return + } + deliverPointer(state, view, PointerEvent{ + Kind: platform.PointerEventKind(kind), + Button: gfx.PointerButtonPrimary, + X: float32(x), + Y: float32(y), + ScreenX: float32(screenX), + ScreenY: float32(screenY), + Device: gfx.PointerTouch, + PointerID: int32(id), + }) +} diff --git a/internal/platform/darwin/ios_hooks.go b/internal/platform/darwin/ios_hooks.go new file mode 100644 index 000000000..262a7c9d9 --- /dev/null +++ b/internal/platform/darwin/ios_hooks.go @@ -0,0 +1,46 @@ +//go:build ios + +package darwin + +import ( + "errors" + "unsafe" + + "github.com/vivaui/viva/internal/platform" +) + +// What a macOS window or application has that an iOS one does not, or has not +// yet (ADR 0095): each is a plain stand-in here, and moves out of this file as +// the iOS backend gets its own. + +// webState is the pages of one window; iOS hosts none yet, so a window never +// makes one (newWebState answers nil) and these are never called. +type webState struct { + token unsafe.Pointer +} + +func newWebState(*runState, *platform.WebHost, []platform.NativeView) *webState { return nil } +func (*webState) frame(platform.Frame) {} +func (*webState) layout(bool) {} +func (*webState) closeAll() {} + +// AddStatusItem: iOS has no status area. +func (application *nativeApplication) AddStatusItem(platform.StatusItemConfig) (platform.StatusItem, error) { + return nil, errors.New("darwin: iOS has no status item") +} + +// setApplicationIcon: an iOS application's icon is its bundle's. +func setApplicationIcon(platform.WindowIcon) {} + +// Quit does nothing: an iOS application does not end itself; the system does. +func (application *nativeApplication) Quit() {} + +// SetDockBadge and SetProgress: there is no Dock; an icon badge needs a permission +// this backend does not ask for yet. +func (application *nativeApplication) SetDockBadge(string) {} +func (application *nativeApplication) SetProgress(float32) {} + +// SetMenuBar: iOS has no menu bar. +func (application *nativeApplication) SetMenuBar([]platform.MenuBarMenu) error { + return errors.New("darwin: iOS has no menu bar") +} diff --git a/internal/platform/darwin/ios_host.h b/internal/platform/darwin/ios_host.h new file mode 100644 index 000000000..ec8d99b14 --- /dev/null +++ b/internal/platform/darwin/ios_host.h @@ -0,0 +1,19 @@ +//go:build ios + +#ifndef VIVA_IOS_HOST_H +#define VIVA_IOS_HOST_H + +/* Runs UIApplicationMain with Viva's application delegate. The Go side starts + * the application from vivaIOSLaunched, once UIKit has launched it, and this + * returns only if UIKit gives up. */ +int viva_ios_main(void); + +/* Ends the process, as an application that cannot go on must: iOS has no way to + * quit gracefully. */ +void viva_ios_terminate(int status); + +/* Nonzero when the program runs in the iOS simulator, which takes another build + * of the Metal library than a device. */ +int viva_ios_is_simulator(void); + +#endif diff --git a/internal/platform/darwin/ios_host.m b/internal/platform/darwin/ios_host.m new file mode 100644 index 000000000..8bfc3c13c --- /dev/null +++ b/internal/platform/darwin/ios_host.m @@ -0,0 +1,522 @@ +//go:build ios + +// The iOS host: UIKit's application, window and view around the shared renderer. +// It answers the same C interface (native.h) the AppKit host does, so the Go side +// that runs a window is the same code; what a phone has no use for answers that +// the system does not offer it. Everything runs on the main thread, where UIKit +// calls it and where the Go callbacks are made. + +#import "core.h" +#import +#include "ios_host.h" + +/* The callbacks into Go. */ +extern void vivaIOSLaunched(void); +extern void vivaViewResized(uintptr_t callbackHandle, void *view, double width, double height); +extern void vivaRedrawRequested(uintptr_t callbackHandle, void *view); +extern void vivaWindowClosed(uintptr_t callbackHandle); +extern void vivaTouchEvent(uintptr_t callbackHandle, void *view, int kind, int identifier, + double x, double y, double screenX, double screenY); + +/* The pointer kinds, as platform.PointerEventKind numbers them. */ +enum { + VIVA_IOS_POINTER_DOWN = 1, + VIVA_IOS_POINTER_MOVE = 2, + VIVA_IOS_POINTER_UP = 3, + VIVA_IOS_POINTER_CANCEL = 5, +}; + +/* What viva_application_open_window reports when it cannot make the window. */ +enum { + VIVA_IOS_STATUS_NO_APPLICATION = 8, + VIVA_IOS_STATUS_ONE_WINDOW = 9, + VIVA_IOS_STATUS_NO_VIEW = 7, +}; + +static int viva_application_status = 0; + +@interface VivaIOSView : UIView { + VivaRenderer *_renderer; + uintptr_t _callbackHandle; + BOOL _resizeEventsEnabled; + BOOL _closed; + CGSize _lastReportedSize; + BOOL _reportedSize; +} +@property(nonatomic, readonly) uintptr_t callbackHandle; +@property(nonatomic, readonly) BOOL closed; +- (instancetype)initWithFrame:(CGRect)frame + device:(id)device + commandQueue:(id)commandQueue + rectanglePipeline:(id)rectanglePipeline + rectangleBuffer:(id)rectangleBuffer + textPipeline:(id)textPipeline + config:(const viva_window_config *)config; +- (void)render; +- (void)renderWaitingForSchedule:(BOOL)wait; +- (BOOL)recoverResources; +- (int)updateRectangles:(const viva_rectangle *)rectangles + clips:(const viva_clip *)clips + totalCount:(NSUInteger)totalCount + first:(NSUInteger)first + count:(NSUInteger)count + rebuild:(BOOL)rebuild + render:(BOOL)render; +- (int)updateLabels:(const viva_text_label *)labels count:(NSUInteger)count; +- (void)closeWindow; +@end + +@implementation VivaIOSView + +@synthesize callbackHandle = _callbackHandle; +@synthesize closed = _closed; + ++ (Class)layerClass { + return [CAMetalLayer class]; +} + +- (instancetype)initWithFrame:(CGRect)frame + device:(id)device + commandQueue:(id)commandQueue + rectanglePipeline:(id)rectanglePipeline + rectangleBuffer:(id)rectangleBuffer + textPipeline:(id)textPipeline + config:(const viva_window_config *)config { + self = [super initWithFrame:frame]; + if (self == nil) { + return nil; + } + _callbackHandle = config->callback_handle; + _resizeEventsEnabled = config->resize_events_enabled != 0; + // Fingers are separate pointers: a second one ends what the first was doing. + self.multipleTouchEnabled = YES; + self.opaque = config->clear_alpha >= 1.0; + + CAMetalLayer *layer = (CAMetalLayer *)self.layer; + layer.device = device; + layer.pixelFormat = MTLPixelFormatBGRA8Unorm; + layer.framebufferOnly = YES; + layer.opaque = config->clear_alpha >= 1.0; + layer.maximumDrawableCount = 2; + layer.allowsNextDrawableTimeout = YES; + [self updateDrawableSize]; + + _renderer = [[VivaRenderer alloc] + initWithLayer:layer + commandQueue:commandQueue + rectanglePipeline:rectanglePipeline + rectangleBuffer:rectangleBuffer + rectangleCount:config->rectangle_count + rectangleClips:config->rectangle_clips + textPipeline:textPipeline + textLabels:config->text_labels + textLabelCount:config->text_label_count + clearColor:MTLClearColorMake(config->clear_red, config->clear_green, config->clear_blue, config->clear_alpha) + viewport:self.bounds.size]; + if (_renderer == nil) { + [self release]; + return nil; + } + return self; +} + +- (void)dealloc { + [_renderer release]; + [super dealloc]; +} + +// updateDrawableSize makes the layer as many pixels as the view has points times +// the screen's scale, so the picture is not stretched. +- (void)updateDrawableSize { + CGFloat scale = self.window.screen.scale ?: UIScreen.mainScreen.scale; + CAMetalLayer *layer = (CAMetalLayer *)self.layer; + CGSize size = self.bounds.size; + layer.contentsScale = scale; + layer.drawableSize = CGSizeMake(size.width * scale, size.height * scale); +} + +// layoutSubviews runs when the view gets its size, the first time and on every +// rotation: the application is told, and answers with the scene at that size. +- (void)layoutSubviews { + [super layoutSubviews]; + if (_closed) { + return; + } + [self updateDrawableSize]; + CGSize size = self.bounds.size; + if (_resizeEventsEnabled && (!_reportedSize || !CGSizeEqualToSize(size, _lastReportedSize))) { + _reportedSize = YES; + _lastReportedSize = size; + vivaViewResized(_callbackHandle, self, size.width, size.height); + } +} + +- (void)render { + [self renderWaitingForSchedule:NO]; +} + +- (void)renderWaitingForSchedule:(BOOL)wait { + if (_closed) { + return; + } + @autoreleasepool { + CAMetalLayer *layer = (CAMetalLayer *)self.layer; + if (layer.drawableSize.width < 1 || layer.drawableSize.height < 1) { + return; + } + id drawable = [layer nextDrawable]; + if (drawable == nil) { + return; + } + id commandBuffer = [_renderer renderToDrawable:drawable + viewport:self.bounds.size + inputTexture:nil + inputFrame:CGRectZero + inputLayer:0]; + if (wait) { + [commandBuffer waitUntilScheduled]; + } + } +} + +- (BOOL)recoverResources { + @autoreleasepool { + [self updateDrawableSize]; + return [_renderer recoverWithViewport:self.bounds.size]; + } +} + +- (int)updateRectangles:(const viva_rectangle *)rectangles + clips:(const viva_clip *)clips + totalCount:(NSUInteger)totalCount + first:(NSUInteger)first + count:(NSUInteger)count + rebuild:(BOOL)rebuild + render:(BOOL)render { + int status = [_renderer updateRectangles:rectangles + clips:clips + totalCount:totalCount + first:first + count:count + rebuild:rebuild]; + if (status == 0 && render) { + [self render]; + } + return status; +} + +- (int)updateLabels:(const viva_text_label *)labels count:(NSUInteger)count { + return [_renderer updateLabels:labels count:count viewport:self.bounds.size]; +} + +// closeWindow ends the window for the application: iOS windows are not closed +// by the user, so this is the application's own doing, after a failure. +- (void)closeWindow { + if (_closed) { + return; + } + _closed = YES; + vivaWindowClosed(_callbackHandle); +} + +#pragma mark Touches + +// emitTouches reports each finger of a phase. A finger is its UITouch for as long +// as it touches, so the object's address names it. +- (void)emitTouches:(NSSet *)touches kind:(int)kind { + if (_closed) { + return; + } + for (UITouch *touch in touches) { + CGPoint point = [touch locationInView:self]; + CGPoint onScreen = [touch locationInView:nil]; + int identifier = (int)(((uintptr_t)touch >> 4) & 0x7fffffff); + vivaTouchEvent(_callbackHandle, self, kind, identifier, point.x, point.y, onScreen.x, onScreen.y); + } +} + +- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { + [self emitTouches:touches kind:VIVA_IOS_POINTER_DOWN]; +} + +- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { + [self emitTouches:touches kind:VIVA_IOS_POINTER_MOVE]; +} + +- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { + [self emitTouches:touches kind:VIVA_IOS_POINTER_UP]; +} + +- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event { + [self emitTouches:touches kind:VIVA_IOS_POINTER_CANCEL]; +} + +@end + +@interface VivaIOSViewController : UIViewController +@end + +@implementation VivaIOSViewController + +- (UIInterfaceOrientationMask)supportedInterfaceOrientations { + return UIInterfaceOrientationMaskAll; +} + +@end + +@interface VivaIOSAppDelegate : UIResponder +@end + +@implementation VivaIOSAppDelegate + +- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { + vivaIOSLaunched(); + return YES; +} + +@end + +/* The one window an iPhone application shows (see viva_application_open_window). */ +static UIWindow *viva_ios_window; +static VivaIOSView *viva_ios_view; + +int viva_ios_main(void) { + @autoreleasepool { + char *argv[] = {"viva", NULL}; + return UIApplicationMain(1, argv, nil, NSStringFromClass([VivaIOSAppDelegate class])); + } +} + +void viva_ios_terminate(int status) { + exit(status); +} + +int viva_ios_is_simulator(void) { +#if TARGET_OS_SIMULATOR + return 1; +#else + return 0; +#endif +} + +int viva_application_last_status(void) { + return viva_application_status; +} + +/* viva_application_open_window makes the application's window: one that fills the + * screen, as a phone's does. A second one is refused, since there is no screen to + * put it on; how an application shows a second surface there is a decision the + * framework has yet to make (ADR 0095). It must be called from the launch + * callback, on the main thread. */ +void *viva_application_open_window(viva_window_config config) { + @autoreleasepool { + if (viva_ios_view != nil) { + viva_application_status = VIVA_IOS_STATUS_ONE_WINDOW; + return NULL; + } + id device = nil; + id commandQueue = nil; + id rectanglePipeline = nil; + id textPipeline = nil; + id rectangleBuffer = nil; + int status = viva_make_scene_resources( + &config, &device, &commandQueue, &rectanglePipeline, &textPipeline, &rectangleBuffer); + if (status != 0) { + viva_application_status = status; + return NULL; + } + CGRect screen = UIScreen.mainScreen.bounds; + VivaIOSView *view = [[VivaIOSView alloc] initWithFrame:screen + device:device + commandQueue:commandQueue + rectanglePipeline:rectanglePipeline + rectangleBuffer:rectangleBuffer + textPipeline:textPipeline + config:&config]; + [rectangleBuffer release]; + [textPipeline release]; + [rectanglePipeline release]; + [commandQueue release]; + [device release]; + if (view == nil) { + viva_application_status = VIVA_IOS_STATUS_NO_VIEW; + return NULL; + } + VivaIOSViewController *controller = [[VivaIOSViewController alloc] init]; + controller.view = view; + UIWindow *window = [[UIWindow alloc] initWithFrame:screen]; + window.rootViewController = controller; + [window makeKeyAndVisible]; + [controller release]; + viva_ios_window = window; + viva_ios_view = view; + return view; + } +} + +/* viva_request_redraw asks, from any thread, for the application to paint again. */ +void viva_request_redraw(uintptr_t callback_handle) { + dispatch_async(dispatch_get_main_queue(), ^{ + VivaIOSView *view = viva_ios_view; + if (view != nil && !view.closed && view.callbackHandle == callback_handle) { + vivaRedrawRequested(callback_handle, view); + } + }); +} + +/* The window always fills the screen: where it is and how big, in the points of + * the screen, and that it is full screen, are not the application's to change. */ +int viva_application_window_frame(void *window, double *out) { + VivaIOSView *view = (VivaIOSView *)window; + if (view == nil || view != viva_ios_view) { + return 0; + } + CGRect bounds = view.window.bounds; + out[0] = 0; + out[1] = 0; + out[2] = bounds.size.width; + out[3] = bounds.size.height; + return 1; +} + +void viva_application_move_window(void *window, double x, double y) {} +void viva_application_set_window_size(void *window, double width, double height) {} +int viva_application_set_fullscreen(void *window, int fullscreen) { return 0; } +int viva_application_fullscreen(void *window) { return 1; } +int viva_application_set_always_on_top(void *window, int enabled) { return 0; } +void viva_application_hide_window(void *window) {} +void viva_application_show_window(void *window) {} + +int viva_application_set_title(void *window, const char *title) { + VivaIOSView *view = (VivaIOSView *)window; + NSString *text = title != NULL ? [NSString stringWithUTF8String:title] : nil; + view.window.windowScene.title = text; + return 0; +} + +void viva_application_close_all(void) { + [viva_ios_view closeWindow]; +} + +void viva_application_close_window(void *window) { + [(VivaIOSView *)window closeWindow]; +} + +int viva_view_update_rectangles( + void *view, + const viva_rectangle *rectangles, + const viva_clip *clips, + size_t total_count, + size_t first, + size_t count, + int rebuild, + int render +) { + if (view == NULL) { + return 1; + } + @autoreleasepool { + return [(VivaIOSView *)view updateRectangles:rectangles + clips:clips + totalCount:total_count + first:first + count:count + rebuild:rebuild != 0 + render:render != 0]; + } +} + +int viva_view_update_labels(void *view, const viva_text_label *labels, size_t count) { + if (view == NULL) { + return 1; + } + @autoreleasepool { + return [(VivaIOSView *)view updateLabels:labels count:count]; + } +} + +int viva_view_recover(void *view) { + if (view == NULL) { + return 1; + } + return [(VivaIOSView *)view recoverResources] ? 0 : 1; +} + +void viva_view_render(void *view) { + [(VivaIOSView *)view render]; +} + +void viva_view_render_sync(void *view) { + [(VivaIOSView *)view renderWaitingForSchedule:YES]; +} + +void viva_view_close(void *view) { + [(VivaIOSView *)view closeWindow]; +} + +void viva_view_close_confirmed(void *view) { + [(VivaIOSView *)view closeWindow]; +} + +/* What an iOS view does not take yet (ADR 0095): the system keyboard, the + * accessibility tree and the web views come with their own work packages. They + * accept what the application sends and show nothing of it. */ +int viva_view_update_accessibility(void *view, const viva_accessibility_node *nodes, size_t count) { + return 0; +} + +int viva_view_update_text( + void *view, + const unsigned char *utf8, + size_t utf8_length, + size_t selected_start, + size_t selected_length, + size_t marked_start, + size_t marked_length, + int has_marked_text, + int tentative_composition, + int ends_composition, + int render +) { + return 0; +} + +int viva_view_update_text_input(void *view, viva_text_input_config text_input) { + return 0; +} + +int viva_view_update_text_input_keeping_composition(void *view, viva_text_input_config text_input) { + return 0; +} + +int viva_view_move_text_input(void *view, float x, float y, float width, float height) { + return 0; +} + +void viva_web_ready_later(uintptr_t callback_handle) {} + +/* The AppKit text input's key routing is a Mac keyboard's: an iOS one comes + * through UIKit's own text input, so nothing here asks for raw keys. */ +int viva_text_input_row_key_is_raw(int placed, int composing, int key, int command) { return 0; } +int viva_text_input_navigation_key_is_raw(int navigation_keys, int composing, int key) { return 0; } +int viva_text_input_should_interpret_key(int enabled, int multiline, int composing, int key) { return 0; } +int viva_text_input_caret_should_blink( + int enabled, + size_t selected_length, + int composing, + int terminal, + int hide_native_overlays +) { + return 0; +} +int viva_terminal_key_routes_raw( + int composing, + int named_key, + int control, + int command, + int alt, + int alt_sends_escape +) { + return 0; +} +int viva_terminal_key_code(unsigned short character) { return 0; } diff --git a/internal/platform/darwin/ios_run.go b/internal/platform/darwin/ios_run.go new file mode 100644 index 000000000..459b95236 --- /dev/null +++ b/internal/platform/darwin/ios_run.go @@ -0,0 +1,52 @@ +//go:build ios + +package darwin + +/* +#include "native.h" +#include "ios_host.h" +*/ +import "C" + +import ( + "fmt" + "os" + "runtime" + + "github.com/vivaui/viva/internal/platform" +) + +// iosLaunch is what the application started with. UIKit owns the process from +// UIApplicationMain on, and has the application launched before anything of ours +// may make a window, so start runs from the launch callback, not before. +var iosLaunch struct { + start platform.ApplicationStart +} + +// Run enters the UIKit event loop with one window. +func Run(config Config) error { + return RunApplication(func(application platform.Application) error { + _, err := application.OpenWindow(config) + return err + }) +} + +// RunApplication enters the UIKit event loop; start opens the windows once the +// application has launched. It returns only if UIKit fails to start: an iOS +// application is ended by the system. +func RunApplication(start platform.ApplicationStart) error { + runtime.LockOSThread() + iosLaunch.start = start + return nativeStatusError(C.viva_ios_main()) +} + +// vivaIOSLaunched runs on the main thread, in application:didFinishLaunching. +// +//export vivaIOSLaunched +func vivaIOSLaunched() { + if err := iosLaunch.start(&nativeApplication{}); err != nil { + // There is no caller to return to: UIKit runs the process. + fmt.Fprintf(os.Stderr, "viva: %v\n", err) + C.viva_ios_terminate(1) + } +} diff --git a/internal/platform/darwin/mono_family.go b/internal/platform/darwin/mono_family.go index 3c56e52c2..9fb858e4a 100644 --- a/internal/platform/darwin/mono_family.go +++ b/internal/platform/darwin/mono_family.go @@ -1,4 +1,4 @@ -//go:build darwin && !ios +//go:build darwin package darwin diff --git a/internal/platform/darwin/native.m b/internal/platform/darwin/native.m index 364f49c05..61bb88eb9 100644 --- a/internal/platform/darwin/native.m +++ b/internal/platform/darwin/native.m @@ -1,3 +1,5 @@ +//go:build !ios + #import "core.h" #include "cursor_owner_darwin.h" #include "label_geometry.h" @@ -4315,107 +4317,16 @@ int viva_application_last_status(void) { viva_application_status = 8; return NULL; } - id device = MTLCreateSystemDefaultDevice(); - if (device == nil) { - viva_application_status = 1; - return NULL; - } - - id commandQueue = [device newCommandQueue]; - if (commandQueue == nil) { - [device release]; - viva_application_status = 2; - return NULL; - } - + id device = nil; + id commandQueue = nil; id rectanglePipeline = nil; id textPipeline = nil; id rectangleBuffer = nil; - if (config.shader_library != NULL && config.shader_library_length > 0) { - viva_remember_shader_library(config.shader_library, config.shader_library_length); - _Static_assert(sizeof(viva_rectangle) == 80, "rectangle ABI must be 80 bytes"); - _Static_assert(sizeof(viva_text_label) == 272, "text label ABI must be 272 bytes"); - _Static_assert(sizeof(viva_text_run) == 36, "text run ABI must be 36 bytes"); - _Static_assert(sizeof(viva_composite_command) == 36, "composite command ABI must be 36 bytes"); - dispatch_data_t libraryData = dispatch_data_create( - config.shader_library, - config.shader_library_length, - dispatch_get_main_queue(), - DISPATCH_DATA_DESTRUCTOR_DEFAULT - ); - NSError *libraryError = nil; - id library = [device newLibraryWithData:libraryData - error:&libraryError]; - dispatch_release(libraryData); - if (library == nil) { - fprintf(stderr, "viva: Metal library error: %s\n", - libraryError.localizedDescription.UTF8String); - [commandQueue release]; - [device release]; - viva_application_status = 3; - return NULL; - } - - NSError *pipelineError = nil; - if (config.rectangle_count > 0 || config.pointer_events_enabled || - config.resize_events_enabled || config.redraw_events_enabled) { - rectanglePipeline = viva_create_pipeline( - device, - library, - @"viva_rectangle_vertex", - @"viva_rectangle_fragment", - &pipelineError - ); - if (rectanglePipeline == nil) { - fprintf(stderr, "viva: rectangle pipeline error: %s\n", - pipelineError.localizedDescription.UTF8String); - [library release]; - [commandQueue release]; - [device release]; - viva_application_status = 4; - return NULL; - } - } - if (config.text_input.enabled || config.dynamic_text_input || config.text_label_count > 0 || - config.resize_events_enabled || config.redraw_events_enabled) { - pipelineError = nil; - textPipeline = viva_create_pipeline( - device, - library, - @"viva_text_vertex", - @"viva_text_fragment", - &pipelineError - ); - if (textPipeline == nil) { - fprintf(stderr, "viva: text pipeline error: %s\n", - pipelineError.localizedDescription.UTF8String); - [rectanglePipeline release]; - [library release]; - [commandQueue release]; - [device release]; - viva_application_status = 6; - return NULL; - } - } - [library release]; - - if (config.rectangle_count > 0) { - rectangleBuffer = [device - newBufferWithBytes:config.rectangles - length:config.rectangle_count * sizeof(viva_rectangle) - options:MTLResourceStorageModeShared]; - if (rectangleBuffer == nil) { - [textPipeline release]; - [rectanglePipeline release]; - [commandQueue release]; - [device release]; - viva_application_status = 5; - return NULL; - } - viva_gpu_uploaded_bytes += - config.rectangle_count * sizeof(viva_rectangle); - viva_gpu_full_rebuild_count++; - } + int resourceStatus = viva_make_scene_resources( + &config, &device, &commandQueue, &rectanglePipeline, &textPipeline, &rectangleBuffer); + if (resourceStatus != 0) { + viva_application_status = resourceStatus; + return NULL; } VivaAppDelegate *delegate = [[VivaAppDelegate alloc] initWithConfig:config @@ -4962,117 +4873,6 @@ int viva_view_move_text_input(void *view, float x, float y, float width, float h } } -int viva_measure_text( - const unsigned char *utf8, - size_t utf8_length, - double font_size, - double font_weight, - viva_text_metrics *metrics -) { - if (metrics == NULL || font_size <= 0 || (utf8 == NULL && utf8_length > 0)) { - return 1; - } - @autoreleasepool { - CFStringRef string = CFStringCreateWithBytes( - kCFAllocatorDefault, - utf8, - utf8_length, - kCFStringEncodingUTF8, - false - ); - if (string == NULL) { - return 2; - } - - // The font a label of this weight is drawn in (drawLineInContext). - NSFont *nativeFont = [NSFont systemFontOfSize:font_size weight:font_weight]; - CTFontRef font = (CTFontRef)CFRetain(nativeFont); - if (font == NULL) { - CFRelease(string); - return 3; - } - - const void *keys[] = {kCTFontAttributeName}; - const void *values[] = {font}; - CFDictionaryRef attributes = CFDictionaryCreate( - kCFAllocatorDefault, - keys, - values, - 1, - &kCFTypeDictionaryKeyCallBacks, - &kCFTypeDictionaryValueCallBacks - ); - CFAttributedStringRef attributed = CFAttributedStringCreate( - kCFAllocatorDefault, - string, - attributes - ); - CTLineRef line = CTLineCreateWithAttributedString(attributed); - - CGFloat ascent = 0; - CGFloat descent = 0; - CGFloat leading = 0; - double width = CTLineGetTypographicBounds(line, &ascent, &descent, &leading); - metrics->width = width; - metrics->height = ascent + descent + leading; - metrics->ascent = ascent; - metrics->descent = descent; - metrics->leading = leading; - - CFRelease(line); - CFRelease(attributed); - CFRelease(attributes); - CFRelease(font); - CFRelease(string); - return 0; - } -} - -int viva_measure_mono(double font_size, int mono_face, double *advance, double *ascent, double *descent, double *leading, double *rule, double *heavy) { - if (advance == NULL || ascent == NULL || descent == NULL || leading == NULL || rule == NULL || heavy == NULL || font_size <= 0) { - return 1; - } - @autoreleasepool { - // The cell is the primary font's, whatever the face's fallbacks hold. - NSFont *native = viva_mono_font_primary(font_size, 0, mono_face); - if (native == nil) { - return 2; - } - CTFontRef font = CTFontCreateWithName((CFStringRef)native.fontName, font_size, NULL); - if (font == NULL) { - return 3; - } - UniChar glyphCharacter = 'M'; - CGGlyph glyph = 0; - CTFontGetGlyphsForCharacters(font, &glyphCharacter, &glyph, 1); - CGSize advances; - CTFontGetAdvancesForGlyphs(font, kCTFontOrientationHorizontal, &glyph, &advances, 1); - *advance = advances.width; - *ascent = CTFontGetAscent(font); - *descent = CTFontGetDescent(font); - *leading = CTFontGetLeading(font); - // The weight of the face's own box drawing lines: the ink width of a light and a - // heavy stem, which the face may draw at a different weight than its underline. - // The lookup answers false when either is missing, and still fills the other, so - // each glyph is checked on its own. - *rule = 0; - *heavy = 0; - UniChar boxCharacters[2] = {0x2502, 0x2503}; /* │ ┃ */ - CGGlyph boxGlyphs[2] = {0, 0}; - CTFontGetGlyphsForCharacters(font, boxCharacters, boxGlyphs, 2); - CGRect bounds[2] = {CGRectZero, CGRectZero}; - CTFontGetBoundingRectsForGlyphs(font, kCTFontOrientationHorizontal, boxGlyphs, bounds, 2); - if (boxGlyphs[0] != 0) { - *rule = bounds[0].size.width; - } - if (boxGlyphs[1] != 0) { - *heavy = bounds[1].size.width; - } - CFRelease(font); - return *advance > 0 ? 0 : 4; - } -} - #ifdef VIVA_OFFSCREEN /* defined by offscreen.go, which builds only with -tags vivahead */ /* ---- Fonts a headless run carries along -------------------------------- diff --git a/internal/platform/darwin/open_file_darwin.go b/internal/platform/darwin/open_file_darwin.go index e4a29efb2..2bde6dd2b 100644 --- a/internal/platform/darwin/open_file_darwin.go +++ b/internal/platform/darwin/open_file_darwin.go @@ -1,4 +1,4 @@ -//go:build darwin && !ios +//go:build darwin package darwin diff --git a/internal/platform/darwin/open_url_darwin.go b/internal/platform/darwin/open_url_darwin.go index 79b3dbb89..052eb6ac5 100644 --- a/internal/platform/darwin/open_url_darwin.go +++ b/internal/platform/darwin/open_url_darwin.go @@ -1,4 +1,4 @@ -//go:build darwin && !ios +//go:build darwin package darwin diff --git a/internal/platform/darwin/platform.go b/internal/platform/darwin/platform.go index e1d19e72c..1a1dc623b 100644 --- a/internal/platform/darwin/platform.go +++ b/internal/platform/darwin/platform.go @@ -1,10 +1,11 @@ -//go:build darwin && !ios +//go:build darwin // Package darwin implements the native macOS application and Metal backend. package darwin /* -#cgo LDFLAGS: -framework Cocoa -framework CoreGraphics -framework CoreText -framework Metal -framework QuartzCore +#cgo darwin,!ios LDFLAGS: -framework Cocoa -framework CoreGraphics -framework CoreText -framework Metal -framework QuartzCore +#cgo ios LDFLAGS: -framework Foundation -framework UIKit -framework CoreGraphics -framework CoreText -framework Metal -framework QuartzCore #include #include "native.h" #include "web_darwin.h" @@ -310,36 +311,6 @@ func onlyMoved(previous, next TextInput) bool { return sameTextInputPresentation(previous, next) } -// Run enters the Cocoa event loop with one window. -func Run(config Config) error { - return RunApplication(func(application platform.Application) error { - _, err := application.OpenWindow(config) - return err - }) -} - -// RunApplication enters one Cocoa event loop for every window opened by start. -func RunApplication(start platform.ApplicationStart) error { - if status := C.viva_application_begin(); status != 0 { - return nativeStatusError(status) - } - application := &nativeApplication{} - defer application.SetQuitRequestHandler(nil) - defer application.SetReopenHandler(nil) - if err := start(application); err != nil { - C.viva_application_close_all() - if application.windows > 0 { - _ = C.viva_application_run() - } - return err - } - status := C.viva_application_run() - if application.firstErr != nil { - return application.firstErr - } - return nativeStatusError(status) -} - // SupportsDragPreview marks an adapter whose windows can be a drag preview. func (application *nativeApplication) SupportsDragPreview() {} diff --git a/internal/platform/darwin/post_darwin.go b/internal/platform/darwin/post_darwin.go index 86221a13b..550f0ebc4 100644 --- a/internal/platform/darwin/post_darwin.go +++ b/internal/platform/darwin/post_darwin.go @@ -1,4 +1,4 @@ -//go:build darwin && !ios +// Portable: macOS and iOS package darwin diff --git a/internal/platform/darwin/post_darwin.h b/internal/platform/darwin/post_darwin.h index 50532c706..d62e2b07f 100644 --- a/internal/platform/darwin/post_darwin.h +++ b/internal/platform/darwin/post_darwin.h @@ -1,4 +1,4 @@ -//go:build !ios +// Portable: macOS and iOS #ifndef VIVA_POST_DARWIN_H #define VIVA_POST_DARWIN_H diff --git a/internal/platform/darwin/post_darwin.m b/internal/platform/darwin/post_darwin.m index 7b373fb44..554515a48 100644 --- a/internal/platform/darwin/post_darwin.m +++ b/internal/platform/darwin/post_darwin.m @@ -1,4 +1,4 @@ -//go:build !ios +// Portable: macOS and iOS #import diff --git a/internal/platform/darwin/quit_request_darwin.go b/internal/platform/darwin/quit_request_darwin.go index 95f900427..eb5d913d0 100644 --- a/internal/platform/darwin/quit_request_darwin.go +++ b/internal/platform/darwin/quit_request_darwin.go @@ -1,4 +1,4 @@ -//go:build darwin && !ios +//go:build darwin package darwin diff --git a/internal/platform/darwin/reopen_darwin.go b/internal/platform/darwin/reopen_darwin.go index 8c5d4a490..4b8c843d2 100644 --- a/internal/platform/darwin/reopen_darwin.go +++ b/internal/platform/darwin/reopen_darwin.go @@ -1,4 +1,4 @@ -//go:build darwin && !ios +//go:build darwin package darwin diff --git a/internal/platform/darwin/run_macos.go b/internal/platform/darwin/run_macos.go new file mode 100644 index 000000000..57d1fa1d8 --- /dev/null +++ b/internal/platform/darwin/run_macos.go @@ -0,0 +1,40 @@ +//go:build darwin && !ios + +package darwin + +/* +#include "native.h" +*/ +import "C" + +import "github.com/vivaui/viva/internal/platform" + +// Run enters the Cocoa event loop with one window. +func Run(config Config) error { + return RunApplication(func(application platform.Application) error { + _, err := application.OpenWindow(config) + return err + }) +} + +// RunApplication enters one Cocoa event loop for every window opened by start. +func RunApplication(start platform.ApplicationStart) error { + if status := C.viva_application_begin(); status != 0 { + return nativeStatusError(status) + } + application := &nativeApplication{} + defer application.SetQuitRequestHandler(nil) + defer application.SetReopenHandler(nil) + if err := start(application); err != nil { + C.viva_application_close_all() + if application.windows > 0 { + _ = C.viva_application_run() + } + return err + } + status := C.viva_application_run() + if application.firstErr != nil { + return application.firstErr + } + return nativeStatusError(status) +} diff --git a/internal/platform/darwin/shader_ios.go b/internal/platform/darwin/shader_ios.go new file mode 100644 index 000000000..29ae48abe --- /dev/null +++ b/internal/platform/darwin/shader_ios.go @@ -0,0 +1,28 @@ +//go:build ios + +package darwin + +/* +#include "ios_host.h" +*/ +import "C" + +import _ "embed" + +// A Metal library records the platform it was built for, and the simulator's is +// not the device's, so both are shipped and the one the build runs on is chosen. +// tools/generate_darwin_shaders.sh makes them. +var ( + //go:embed shaders/scene_ios.metallib + sceneShaderLibraryDevice []byte + //go:embed shaders/scene_ios_simulator.metallib + sceneShaderLibrarySimulator []byte +) + +// sceneShaderLibrary is the library of the platform the program runs on. +var sceneShaderLibrary = func() []byte { + if C.viva_ios_is_simulator() != 0 { + return sceneShaderLibrarySimulator + } + return sceneShaderLibraryDevice +}() diff --git a/internal/platform/darwin/shaders/scene_ios.metallib b/internal/platform/darwin/shaders/scene_ios.metallib new file mode 100644 index 0000000000000000000000000000000000000000..4d92d40523accaabaacd268c93693cdef1814db8 GIT binary patch literal 23222 zcmeHv3s@6Z+W+K2GC)WMK@F0?go{N5I$T7kSSJK1w%7(m7keWCg3xk_5D@K!T!5gW z##Sl4>^4-}rLOJL>RQ|Fc5|W1XH%EDwo6^tf>M|Evt6{-rCmPxzh}a5>t*-5{P)}M zd7OvId(L~#ob#S@X3m`R{(j8r{M-x<#>IpfW+pHUJ9;ntz)|28*g~#1&@v&(3H?j6 z;>RcABR}zG;Dgu!=iSQHS@W>^@_KDyjjq_Bt=d?jE3DVm7<3I-{swgx2g7odYja2} z^sc`t4*uFvWS|9`N(R%<9^`dp78--!Y(Mha^C!9SWvesS-iu?J1>WNC$+a0_7Ldr4K(8rKyWxAS$k)7L`sSBU9d7LI)P^5k@AK>2oqsCb zy(;?l4wcV!pPq|eD;%h&;P6_3dm|VtSsTA=#ZJhHtdP#`kkT6M#!6k4VWLYo-Y%gO zA%D47_0XRSzx6xZIk4se<;i>S*2AwxT&+7i9x$%G*K17Qj4qk53}Yp^#B1GmjcJ`Q zCTLohe7_x8`RZ({kK6d*GkH({=Htg3!6`IF?osygR|$y3v?n-CqG%sHB#ghK$SBR?W<24a(L*E#r{dDP{1S^= zb8Nw+D!cVXEF>|5ze;QijO^Gt1nmQT0y6S4){NDPaGG7}?OeaVt$eo*9rCiuD7 z)M*QzliSwj-_(;!bUQ^3ipvp2;tm-{S`dx%IRu|06+ih>>zsv+(M`T(ZOuezId_4H z&La3qs#VRm;3lmtkR$wPbL5i)Pbu&8}d#0!23+)S?z;Va3C zU8FRdI1*77x(RN$s{-yCO%Bi0BO_X)w1fh032f5(X{5@6mcUjh0mJfOsH`AE9Z{pG z|2Snln!7kcHoyrR8kCQ826#Hd&S_<59kPMWfU^qOFh`DUwOO~u2#sY{gWj5=vDTzo z^%`qRx3xwp+}a@AQf7H1M_6MQ8nDYovC%0%-x<);8FtzvA6CfEX~QrV(s-0%u1@*M z&VYeI`Dv$oxKlRN8F11hKixT5zTUdIj8|*3>dUM(WxR$4s7?s=LisfstD(%A0vWsp z;KEvLSQ++tr_5V86zI{0eV@%tnVWIp<_>ELC2T0O)Z@afw9ptf)ERb?L!KLypVfq& z9+aKyl=XH7Tm!2H<(I%(PS{zy++_;usz@1rlH=eRyO2G43N^FVXiX`z>QV1`TVxD) zmcsni0fRR2)jq)mwd9gU{3$7^91#DdPcY~Ze@2ME!YW1t+ydj`99|i2HQ1~vgmo(= ztVMmrLw4fA`W&miL#VMR$Iu{SM>u39DdH5QNKc@+#K>2N;zKAXq|ee(T)iMv^r<(> zjlovIJpzvo7SuvZ7m6~qx%e($?i0BT`r!x_P&iS@cF>1KbT|7DIz|ODk`= zo|g)L{rb>P`vfC)VLdI}su3EPK&4H*$u4YwzdpfdM&VZG4=FXmt%R`NE`$I?Ye^xr z18yYN!Y!n5D=Dml%*-!jt5Ku2O#MPOHM(l+v|m&jCaj@R;d&DFk2eYfjH-ar zP!9yUZ0nly9pQm4e)92*vAKb(dzNN$7xOVAi~$WNW>l=vrO}hGBTTgCBhqZd&`gZx zSxg#nMH$86P!MEZSybjj%`IH62I9TraG{%gCa2j1euwnCFgdhp2lFFWhPiK;LL@qGYn`JT*5dcq%#Nkn$kYJ zg@e)akUbJO6T>>BA%VHJHs6JJ9OtVRY`63MI%Ow+j`{e#K;Nn5+eLm|4nN9H^U6Xv zF*fevZm!6#k5w*)YhQzgz6df2H_CbjWu?KK6|Jh&CU;wgQMjc+Slh8lbP1DuL5Qyz z#Yv)!Fqcz)s#8`<`7qfmp&s6fUe$^=-U?4c8_YA0;KD8N$iRf7=hZh@^`te#6DYoH z6Ax07DoS#3L_DGvClNjJ^9otNLhjOrl~UW5zinCGr%F4*OMlyv-o#t(840e}2p=gE zE<-bzaGBAnhuKUctd9}akNQBdn~l~&+`36>t?96C=`h89IU@dYK>W2se3{}E^`a?J z=3#ze20p2f^_b)*wStdqsSdl?o5rUiYm~>6m%>8Q$`4x9CKX_>*}mQ^?Od<&VQF0}NKkN3??c zW=pEay}Vns0y<>Ol|H0e-U?B7+q-_yQtM{02PWPaVNHkW{)>e8vP1l-TKp9i={&83 z_s;zOLHT(wASYybw`Ii~2NqaE{&-w` zStI#kKrli|KBXiuLta;ls|fK$N(|Aj1_YlCh=Z#q0% zYcua6*XwF(%d4w47nf;k3Tw-^>a^uG@s-+!!V+D5d9kjrsIIgWvas6X>Z)2;f*WS* z4P`YtZOO)(>N@>*l3=A=SEHLO0%a`RTvKk)6{1D-^rTvCrM?1cQ|dvGl{$mAf`pYm zGLTG4q!N?jQxYjMhDj*Z#Z9Uftwvdqjm6cK`tk~0e2K2Ax~8(Wu%x_JTU5a`icKoj z)*1>cwT7}nUDbEeYP6L)Z<7m4b%x^UdGyt_RimxhSZLUy*A-Sl{?dwSts$9J zBhB=z-knNeb)7+9XV|E#($#1Ux{{cs#nlznHJSCvg{6y_;8apVQbl#Kwn9BoUuJzG z7N=T{EmXz1kPF(JdOr<6pYRZ+~%TQ=$LdIl5#>@oOWP)lc zAx&T2psQF5m6tA>3{E8{Btiwu&TX}}_Th&X)s|Uwi8rt+6DiA?+YRo+ z@)9=aP4Es9%7Xd?jZ0y9Rf(pq_(64?z`H;TD`WIxdmzsHFd=X@5q%`l~xy3 z*Hx9&)*7}{=xWQfCAtLWH<7uP9bxvFm>hC#Mft`m=22P0Zbw&5Sjn2m-0Ks!5xTy< zT(?Xq2eH&7f2Pl=z zLyagGb+|-LHGVH?{F3} zuS=3X`PchDSY}BuIcu}DlqF#s$YPLtobD_g$fupPg1`kH`(^H}*UYz$aZ{TtscpP8 zkESDILHb7GWv8em{1D0$>ajh|UDUyi5+0!aUc%PBjDFuYEw-5#(S~ln0~$ZI+(TYb zh8{C58g+&`OyND8+xj_6&T$r{HxQpXMW+`XF@@R8p`)how>h#AlicQlKVH@&6i+Mu zvrYUt|#+AW?d#H<3@iB0U^n2dmZzt{O)?P zHsq0qEq4_!`P){@{<|KjeKu5g%;)~z=C!WVL-$`kIW&B7B-{5RW(D*ztU;pT9`X09 ziGg>!aBG3S1KuZYc#Ed>xy_ek$2$XHQ4dQGcD-WDrLQf8tL8QBiZ+t?g+|OwwvIb-M*){; zi^kmrToQ!fl}L==hP4Gk7PFnohD>;4F&`qNv@P)5#YcC1EagDt#`_a_KJiBVgFTo> zIpz!>GKJeH9>t~FQTdHfIwOmHp@>l-Qe}F;MC=MIXfr`Z+|g^xo0oGt(*3Sh(2n*i z)sMYFQS!JHD4 z_`TXB)Mr6Wx@XDQbA0V*3-KMxlm+k1b**^Yy`2;OB`0jX=o`J{O1DC94Nxr~wxm}` zuWQ4HwC+gBR}RTnlw^!Xfv+K;L4i>2qy5B?TaX=g$rOG`8#Zb}fzKhJRYlCWBviDe zL-;tXAqT7hmUItqC9H!3i>TxSRFG1jQu*DIyu3(5khox1%-hQDceOTNnlyzpH(^Ip ziCVqDEy%PHj(JwI_>`vKh|l5nU(lR!hKNE5QwDaQOuU@3Xn7GDT(g5$BP^vVXudz^ zep&2mI}~E`N;?_zYw0CTj*p-D^&OpJzx9mb%K?&6C?s=!0*YchOD?*DUqX(aAl(;U zaZ0&GeuqV-rRP4p+-g!9Nondao6xyXD4MGt468dqaMwvoT6<}6O8_208dr;DON_2= zP9Vwe{H4HCYU~T6t5Kxw zZcb>@&W$B{8b!{s<^;ZKK7>DMCE==FaFuIi%vSZ@K+Aqy**zjT7#6JS8HmXsV#h46 z3$sEJQnwR)|8e70C7wNzoqUWmyZc@-&NUoUlr>Y*gc!)e`!WoaKh+W9!L#(A5}J(j zv0J2W3?#*uIZ1$~VrbbIy5I)^ECn>&Gvuxbi2X{Laxo z8k@$YW@273ZeCpgQ;;;n6a@F#1_=K)P&v9=D$T;p&5b#a2g03qi*odYo)_=%k>)Nt zlSz6KbMK~$1NSC0VXii)eIFYrZ{A@En~{Y*Y05{;FFe>S^4iy#+rlEx{XJh>K0-U0D`^kEgXf zkMque&Jht`f%kr5PQ%7Gn9J>%c413?urkA1+HN}dkdwOyA5Umaon>|#5wM*o`r^pvDJ9bC)}T5jdx{djP3OGy|PS!H~Q1&u|G>M zM-1;&whY8)xVIL?x;|;5$Kre)jqUaYT{wUHx`jKojT%j#wVYG$uI-}x19=uqN$KgK zl*fzO$xs!&Dak%7MJ-CXY23F4!o6^E9ZCws@3n~5JM z&Sj*FQl=@_WKKPHa}`__cO<-|*Z-rwooOu}62s78nw{sn75Mm$-O)!=4+tLT2je}q zbHsR>;A8wcBzFW{?Z$3(d}7WRi^~DAa7-AIp<32gY*QxZxYJ90UstxA83_0~b-bWx zhoy3F4sD`iiGV9_*iq+J*dz7LcW#XTsZ(&9U|pAEm>XGPSM@!0ry>3WQ1PF7xod}^ z+axxXEWVs5udws5=lx3KJ5bVxFPB|a6=SxeNRd= z=*W~l>*#%??YBNxI5&!M;f^+iG_EM)@z&q^aKE|lasJ@S6YB8n-JS%#xvfn>B_>Wx z;Xk|9`-mr{*NS;k_yyD-i5ypjiVip&V9G*@gg+8x$17A0`QZSi85D(2C~4%935WAO z@yi3&{ozDoe~tRxm9qaZj=J03i|Gr)!k+M>vVy=lcdR6Dbbs3CwOk8%iyX4|V`djULHi`50ijXlyzco&kgYr<@AWv}0rcvH$$$c%?@$1_6 zy2ByQqBTP!!UL#obZjEMe)&W(5z&O5V)n*JuLA?MAm{M*j=~az@!fw6(ihHLIMMo~ z08VruiQ0qq)9APW=UgV_m4BTGv*{>`^0UYEyvV_cMR~8A2N_Trl1PuoVi*EZ0^wvO zqlf(I6M9y%`qiKhfRmN1{@#iFtYq~MPvmDMt8V~3!Y5eC>UT`&S;^{u271&+R^cI=y(7MQi6oB_$%t-?_CsCRMc0-SCqqUyS!2tud6DF*Hh)G zXbZ+{)Jwq^5nr0b?8z8K?WP(7t0<{9#MdWIPc79J)v~FTm$q{LJ4u&9J% zI=*CwMKS89AH$cv1mEaCgf9hq@udTk_|ls1;7fZVrr}GAy!cWW*pwKN!{AF#MgYF_ zWW)r%v>ouJ1Gz*_66VJFR2zwXgh$|Lzg7TH zzJthkF(%l;opQ=gnq+6`aIot9kKj#!m+1i;0mD*ffjd}H*swx&Tq}nLg3}dHu;Zq% z^Uy}<3a8ii8vqpn4h54=D>xVdZ>oi6eiypx@Al<(V;>UY&j1@D#b0a0m(&O_0+(_n zcq|#mwL?%XHTra!lN~Jxv?=3l>Jruh>I8j-a4`#@cm~|M1xsn*b7JYa2RMmMs@r;1 zp{=SF9TsqkrXMkZgESO8+Xqys9v*`Wq4_$fm6jqO{!J_hAwvHQEJzJl(8|C+T>D98 za^N2bUn3xKXduvpjYXy4!Oif>?d75gpQ62moC1;uBuL+<$KZ0K{NDHcF5}f!Ev?3qCw)G5c4%q?N-fWbjx~6<% zc@@f*t1Z%1tg9+71q`hMg=Yd7C7oziNB9NJkHl9en`t}}?|~Q*iDxF5X(_}&kPu5W z(=iZBGI6uiuCnt$&2#-_5ljC)iTO)MKJybtu6F?aC>T^z!MJ{bX>N~=a`UPPU z|KCIw*=0_+hmLv7A$*ilb$bXZiT}Q+`73%)vLzw!p1B*6q`&`~4g|nLchB5%h+NMP z1i+$h_x#6_q`$=cUnBhw)BZ`)M=`-Y(##^t?G|ov2n2`x0J1*N30+$Ma;CcJ0vyG~J4+<-a$vP)zM zKf}E>I22=H3cxFV1gRL{F6r>8?(li6Ul7xqqcO)96(4@Mw)~OEUlcE?O(^zX{%oiZ zr&&!j=aJ28sOGh)%{$+J_5J9bhdev0_F{9Zd;xrTZON0*0_qSNozuJ@ArAenbEiIc zojUmrKo6HrpFfxFn?LvxpczlS_D0IFI_ zCqVmh1}6x^ksAT~U8JC0x8c8r6QD_If=l|nU_iq6YLmWKo4Ba(-u$%*DYGBrApVJ` z$<*KRou>8pFeYBoVxWQ5k}ou~ zZUJ;itFnnho9fiofb6sm%kmC)+A()arwsNjDg4j7l{wbBe&Uc@ppc)@x(9v*m#6k3 zPM+Mu2|uNE+a#lU20J=&tY4=wZ|COKhdej9pSC?9=puN286m2e`0e}<6`mLxapet~ zZ1g8b!c_$a6Zq~#=bT1={?#{@fZtMZlCY$;(EZm#(i3T(A3tF+KK@t>m1;?|)3(Q2 z5^{LU?U?OjftXVo%8l))#N)L`6?DtTEdwMd_VN)Gj;xu4+^cV^(Z48A#k#OC1htjQo_NeqcFE<;U)w z!H?Y=jdPV4Ux^7KwqsZcV!UQ-C-DP&f$>^&lEk@b%}^lOg)8aPh)^5j2_#GQnGVLg zF5zY^U%AA5G;kSVJG5H+>fWET6?srtw#^_)^gaxvHpv2rnCz48jl;y`c>r~PISP}jE-B*SinJQ&uJ^9~V0GwfF63;_b_`A)5onPn%+zv3Rk zI3y$?Zxu#mZr!$u!=)j}%*dM7sCjevd?Un3IFSMI@xIdyIQ>uoFkqR&PzKe35eG0} znZi)KCFdK&fJN~M1MV!TnPz~kpHv6G4W;|@8GrpOzs&dWUAK2ebuHl7t8a2#Z*pA! z^*OFf;W3=$lR0Y?UGksilgZrUjG1G}`DpC~%@xlJoU4sq;JoRN`A_*{Y5;T7)f57l zwGmjf)13)3$*t2#t;N8D0wOD9uBtB714CC2RLJsrhGdC+5wl6K?05+KhvLEJ%x`8UH0mf*GSq=Uc3s6NXl0;R+ z+u(1J;hQKoDRj#`R4*q1{4F(VaKl(+QUg-o0dAOHPLbE&5_*mk2L6^UfHO_=w^)P? zBXkn~7ZlGd+>^Y5SogloVX9lz&&&H*v@NvYnWhz?@4jyvGJUwJ|8U-U(JEQN^Gz!> zbhA^`D=#Rb1i#DP1HrHY9ST0}6t&6t^pUJN$E_*AF zyXM%0x5LZcv`kqI?ebsvFJJPv*I7>r)%+~-q#QqgcHngX$#>2V41*u#Qg+DQ zoVjZTI}kH8>CNuLM^TyP`_LHvU-y|5!D=Lkzmb4t2eYzCK0_)4f=SLg;DY(A<(KTE zLl{P9@-D0`8sl&xF~*fLvJ7aOi?%-L^inf-23~vYy$ffhoQK~@dvND;VyD?Db?$tl z_&r8>;kS(cCCAM1iNunyC=UiSP{b5-=cg38)!`Jiz z`PJ3>_{zFkgTAJEBO;0iHEq97aV;aY0ylui!v7tIe`rhLsLzA_#ARj;mK3O==mXTb zkvBO~Pohytv?cTqgxz04ozTCp3>PKx`$Gz-R+jr_z3A7V zpX9!sS~9HEG#CXJR-Wkd*-!Nn4V9WqROB7>=!sS(u;rxsql721!$h=6WejO8^*5Mb zBUPjiR^an)433&(`17O#D`if;xv@RvpmgS&u#{B0GPV`5D7(0v3VjZ51J(?zPPGr0x~+tMGab&Li?2+TD*e-gmox85f|6u=sUN}Ig zNy5L^2#hYn?&LupsJ-2z}r+BtqFXkjNxr|lGcPKbJzrLGfo2pIpw?s zj{=jeR4Hro1!kv0V;yYO$bjFdE7+?^%^OS~T*O4Q8D^kxfck?sdwA}RxH*0Js4nj|W{_6A5t%AiEhr8$J zE=3%WLGc|x2DQE9c*wO7x=1nV>(50jzY>?39;?J1EZfuFze6*@Va1B*URoElsh z+hrYjgA5!`;Me8&``=KE#i;%(N5^_^}yda7A_Cz{m-%`%zym9th3?p)0BOX;nu z0P|q0Jq`_K_gg@Qb&WZ0aFbo1tcgf=HL~p7Z+6n`6&gpelqDG2uHt81Eyl@S7hS_I zN&6!7z-A=lMqK7hATmxBqTEfw5Hl2C>P%!uv;)iJ^pRL!F)b?7>&_a%?}+@-g=b>kHhV^Ql=F^JUx$%2lBjh>Edj7j;rllBK$f3y}3J~NwWg6Vs~lrv&HQW(Q)GP#T6})+^=8;Xjh1O$?pGf1Y7|w=k7nLCI0+L z7N}kyHL!CKA1{yqzd58wBQhs6-G~YFr}^+?wFZI5`D!t1vu}_>nm~K$*;|`hcWc@; zBCuE~>b*rI%IX+-!;uNSIKi3@eA2;P2)x!a`;B{)Et(bA+{}~dC4kG4ef!yBEqPB) zbya_qR7F;lh&t&#EI~Z;?xx8{Yul4p=Aj0-xjAF+Uz7lQmTZjNgLviM2VS(oHx>)L zvTPiOXSMT=o)VGsju=Mtj~y!nY5=g-^^0O-7)(#B2&YY2~82XlaIr?K=Y*O>&&v(UhoCSJQPLk zLcDhM{n2*=C3QK=bEk`t90=6!!r!Rj%c29`S;=w?!|3{gVBzvNevrm&6p$~c&2KJ;w#0{NG1vW0(N5Y`= zHmUc)ZJRq>!VVYbDQ6R+C&P^9?H;${DQq=cwzSsQ%-(^#2h0iljP=I}zcrJMIF~gw zCDr?m_V~q&#Sv(7OhvqY)wcQf0%%dg^89(7Pm%Yu0i!xI8lSwed4+K2J+NtR5ckUS z#l!os^=S6D--0zK&^zyWe!*jNt}P-?8h_bKT8vVLr+QyY3jVnEy%B-)){2k|sc#&dl2G7X@31eE1hJO~9mfc`8TUPWBuC-eD z&srcuuw>Zpl4&=Wml(>XsIL zsv~go&l2G~FdxV`MNQhbav0WbA-7|r;)TWqk(eNGv33{P5s6u}e9jU-T|v*j2h7Gj zDFAu(Q!Zmbq{u~aO{+O=U?zimJqGe7?)5MGotN*&z2G$q2g1D$aY)XGg8jJBrz=I; zg2mFmQl{O2v_|YKhOn-K0fMV2FN2&#{yhw=Wk0o$-`hl@`RnF4T>crn-D^fd!71s@ z*%L@dHfdkg8>I2+OzO8ud8MPn93Kd~c{7l)%S7}HVCvh>Ez^K0X~fGt!5j`Md;%H!eA~+$E)DSs z1Nifw74R`Ij|3fN>=Bq;AHwXqfkXt6SvVH=^FMw2*YWZBwvm;_?uZyuMvV39BHCn* zv8|DEVk|}WDleRMlVg07WBf18F^-4(eHNZ|#wgnQT|6uGv@|_CKX82>e7Pm|39}s5 zCO5y+@}K!m%Rd9pLKs(FRb8!)`OXNt_@0e!{UA4a7S#2xK~+ZNF!&e`vhBN{RPlb9 zXCg~tNjhV4Ea_F>KJC(pPxutVKgSt#FrP=&p-CQLSH^@$T%KY!E{()HlFY^xk+?M3 zY|Mffh}95VYBsKe7zkh$_b-Kyi6+6nio$meRiStl*2NiU;cbc(Et4{?`x zF)9yrPPw?pB{Bo6_{G1APXRcE@Tmd+FZPl zfm6~S0H<;~gL7wtQw6DufZnT%KNPU*mE12M-WA{WYDLvv8f|O;&tq1|PY}dcF+5+? zAbuOR7kgkS#ijd2m@X0<+PM@nQ6Etvo~f2t=e9Wu_ym3e$9$*2EB(bU`fHNmdmGn#D{se93F^lNz6;WcviQ)|MhDF5T1SImql8gEPco8g+RS2b; z55G>=QO^(<06{BTFu|Xs8B#-}z{-5pU`H5k^4SZY8jxk9PYuLAN(r3$O#Px83GWfO z>1k8cjTV7&^mhsQnIQlXt(Ue*rA)@;$Egl=({Ft_lb2?`Kxo)fC5!mZR+AQe8{v*3 zKloP02Lkx6K`3BD-dYZkd^YQQi}^Z@Pw1VxfF4Ov{I%W; zqad3n76ce`5YmoAdPy9~A;b z!JjdJ{29nch5RQ!#F6!fG!48%(QyV&5-4>HqarT6DwK$U7$njS5~rm)CQEFm8`yELeEN8kM_;TN5x8353E$iR#vk5 zpHApm$?Cg79||WcSv{zja#)G!@vIkEQ^U*c$j6FpYW?yRP qec=7aYu0Hq-9I$r-?RT29wo1}?3d#T6HDS5AJRYS_Ceji9RClAC=`VN literal 0 HcmV?d00001 diff --git a/internal/platform/darwin/shaders/scene_ios_simulator.metallib b/internal/platform/darwin/shaders/scene_ios_simulator.metallib new file mode 100644 index 0000000000000000000000000000000000000000..7add350bce6f8aa8e8fa4967631e1e295c0da310 GIT binary patch literal 23318 zcmeHv3tSUdzW?MwGC)Wsf*K?V6CM^7=I}LjtZz~<~`AQWP6d}Wcad&T3%TH-5cL}mS65#vpjp{Jve5Z{iZuZypu6S2BhNTz2cz=CU@wFIxCUF6%6VoXD9|lXBA{Z7L_jY}R|qg{ zH~_C!$?(b+w)j>au#=)&@PVdQ7a2f?Sq!jH*=G6d7DTKi-$6kquK(=vKDS=^gb&b z&RIL{VKegE+k>q=`9!x%;H20rK{W1^vLr>ZIG06mSrXyS7usgbZH~1DRW#>9%>6*Hedf!6RhejA1dmp@`>#6u6mQ9nMvf zRoh5OE^#2LB4QofaF=-O6`DMbsYgn*#b^ly-YT|ggESIlQLDHOO2DuJxKuWf5zd%V z)PJlB4$Yn)B^_YNhX!RMogv;%`Dv~6lv6s;8FES?9cIa}jdt6{IKHvMX3*QxG`6~Q zn_go}>$cTN_#2z}8!9Xh_q28`Fh*>3QoPPHE&P z2BoJvrM;aYm%*w**?F**B|qhmxlQsumV>{c%T|Zs>ziz85XSjUM$`}W*B5o(BzJ42 zpFjhZ@-rs+F|BlXPzG&;uJF2~$CPqZkuvfa%gHfzA$#-`YG%FBmR4cYqu%qk$Qbez zg$1ia2JOO2eY~@3(Rq#Vb5c}2ApCP5Z_p|Hf)IX#RgLi2MaKDgoC@4#u-noI+eV6C zkNS#(?8Nzvc{Y6qUt>{@p^J0UEJ_I0IPx7HzaA!dPqSH#yOi$HZmnxc8ltxrXPbo?xnpUz#WB>yuY}1IQS0vit zv#JjA5PUdRYeefvWc=i@k9UROZy@;_Nqz%l_8lQxof@@e@(9_~=&X%Xj;J(@Uq_?D z^(5*ae-y4assc(wJs@`5SG5#6BgJlR>XEFmnd0R=3$xktxtI|y2@N}DRIJct&=YSb zOt9k<(rm=gz>J1nOcHfb8N*^x5cIvlsO$$?TG?z3#CtlcAsD8P3h>`$inDZxCj)<@(xM3IN#nLIQRA=T-BV-4sKAV^w_VkfS~8-JG5Mf zAgIe3L^)_qMK~+Y&Ys`R7C7|r%K32aYtYK)L8jnFY0sdvJdCxZO_gr-v}YOl8=Cm_ z9qR<=G0|6q@Ul^uBFK`vU9t~4rR7wBFPkO8%URN^TGGy0;%#b&G3Ozi54W%$1|L1A zvB{<H3hQ0#i6tr)khli2DyY#TaE@n4S!za9{N z>l9v~I3>Mkc$9j5M;MKdDWp9n*)c8e6T2#-SC!G>J09|+?^311gSX3bD^xmWUVM_X zxZ5K*T4~c4+3NHbLj`(34HBEdVGI9YrRZx+bV)57vJ21AqCrx40a`)E$xgfEZl(N$ zLVDUHKRtj3z%NfB|{oi@PmL4p<_rp7eHAhS!sM$d%FSfi`A(^A4MLt&)|Xaj>x%0uH|n&Nb&1v5rs6VPV`ZtXxTK-H9I`Ol z(%PDOn2sB+*BdJ8blS4Db+rxp8JFueQ{Z3 zy|$#v*C-~bTw8A_uGShVigh(Nq}6Gwb^az7m+K6rQ}gI+>njal393e0x3<`@L9Z*W zf&ArFwOT_eqehykS^cY);@Sp-zQM3oSEH-b8gylG3rlOOYU{EaQ;W;z`GS*4Nhwve zrP?a>czxN8$&klaN%FLW$um;Xh4be_p~-}_I&E2HL;d*a{>Wr%s-dn@=|2sHrYB@g zBxFrbP)#JLCKEFBl});;l~8&4youmsa#Au>;9JEl*VaGyz`Taa8pBi#>b&uesx0#d zmSrPlrSEow`>?W%3HlTK7YSuSeS)q_ab-=Jt_f+-9fqW~tPJkE`r>-Mw$yhE)Env= zN)7%iS6NeDTTE#^nxZRh5NpMm7?nNs?$Yb%Tgqv-_ivOElF!WoT*Kb zth{pHjx{~CJ zZyjT&TP^ABoD8p~BWq6PTH-~Qpfz$o$`j$WKf#{Y!H(hYqk~?+R=tRh$4&F?=6STC zJ7}LKNG9Wlx5 zZuoI>9-=r};h*fnFDZ{P=<{yjOg?7gNsq2$es7te$njqhOo;aA-eSr6d_N;Q&S;+J z;4bK9ZyRZ?Hk#YHbBCkS(texv_`yZ5-*zy0cFMu-H{L2BR#yc4yeXilEnrPY%gX-# z3#aZo(R=LlaBg75;GXW(jM=|Ue(S9Ri{30S-;+K+e)$J23Er>vCtlcp;r&`}QN4;h}jN->$X@UiJxu8 z%w*d&7w#-#6Ya6Mr-)60;Jp%!aoe$WF=R12s9eZ|Hd@B3F-( z=lRSZ4G!~SUgel8a>x{Er#KXw+Jnk(hSGhqG!Tjyv?<7+NHL-rcz&P0B;M4UX?2=(VL1?Em%MnW+|00VkE%0psi1+FRj(<>f?UU zbv5t0YzZ)?#3lcrHU;%rs8#nA8Go9q{bDY@Ws$Pzotf?>hdrBFkzcdqs|DZbMHjmj zdRvHU@vtScN^(UTIi&SOi@tG+zM({8GzxqR0SyX7upjOxhCIAn`FT_1d98fZgaThe zK&y(Hc1na`LkIs+m_rWOLM)kH&Qh2Mi%Y1~eN?EDr&0yolDfD=Ly$OcTijt~_j_79 zCqt4(nyuKubfR9*^YF6mgmae7Ec`&zZ^UP?`_F1ly21q!geeQVS1MdgS+txe4X)Y3 zspFSZRWvu4b)Pi;wJi#vd8vbp`>o`>CNCh!{Q8zoVbE%y;_Cs@r%;Gy{2Uaec#ceP zJGYD+JxY4czT%RwOM>1Im=>P?_(GdWX(T1-hwOaUT)tqYdQjeQlwhxtl(qHJ!qyNx ziZm`4N*5U2-7GQ5?f&=92LsfSGUEptl&B!F(lglD?SjowT$eN0<}m-l81%66xYGSu zd(7BZMt8G7+uf36)y|A3dYT2Uik2jFt^xr_U-?Nnmw)R9A~@X?fr_)12d}LBAvOOQ{f7 zD%;heqjzZz4GQjH3(CW1#CGqW)zi$Jws})+dK7_Q>xfnJZcFV?zmFq+Y>@Y`Brv(7 zrq}iuo~UuM*Bebi1D%PIl0DidI@a)B$Y7e>{nRLDv1Gh2ocb&g`%9anUBUfc!@8~Q znv|2yotM;0SS^_yV(YawSAmr*8s+n5{c3<8&AVM})(l1#6}4q)vazd=&$zP+Mzjt* zj_7S;tw0%V4YT-S?~MG}39tRTNm>!*pvm>zGQ z)x|#=Wp|AJ!DziEF%z>&ar5#b7=k2Orck)g)TblD86~mo(i*od+ zo|EVdkmN5qnN50=^Y5Zd#k-QMSbY1fpA7I?qwO8Un1|OvH1FI*j{Pdysu|fHWXrNe zu>TFStlfX;&zQ^>^11|Os{92OLxiH?z zzZj{KkswW6SZL&)C1jn(xfb8rvEecyW;e zZw{u-V}Fudh#KCiY#m6<@@y=LcYkK3#}Wda&3hbkx^V91Rdcs&8a0}}Xg#goUf)Ic zi#ZldN$KgKv`0(!kP#|+%W26re1&Rc`WTP)SP@@NwsPlQ~2(}6m-$`P$^xnphOGcMk3yj5M!VRm$tL)G{A9frh@ zK*fFh#jY)eZj;bdHvdAhtjfW`o((Eb>_AB$zgThpxp2s>c_v7Z7#J~36h0Saxzl}w zV23Ma1|E}S(a~vrw$Xb@`?~=bSyxMO{+4!yB%vhh(YAL3*x%jzD0gt_QFUbQc5f2b z+}^IBl9R`W@Lyi;eaM^EYs0*0+#>1^M4r1!MTfi*V#+~^q(2Z9N2*j#*&88BGboB5 zQ_{#E6AAmh!WRc@dn1YF{yO!0OQrv59QEw+%%{%|^Lru>N{hrZZeL1X?f$$kXh-_@ ztc$h;OE~wh-8$N$i99HHkhtL4F>4g+eNOQRfUf!`fUlSJd}sp1bM>J){Syb zi0*B@f?v_T-yI2g=B*eS;qOCrqir4O_t7T{i6|@fk#B8`^g1w53vvc$*C~nd5p!GWzA94}qPLjQ*bS{ETGu502+&B%^NvJ;Ev&$>_I?>lw-D ze+hcjMn*FFmq0fgc1ALK7w9CgGt#Gr_M+{6Cr+u- z*PT#ZSu?59R#icyG6_`=t`4*kO>9W4Oi4~GN2N};6&xXujI5n-M8J7zsR>%-zDTI7 ztxrlzq!Ouw`pW8tDy^Zm4t2_uZ7TkB04B<)?|uq@x(LqF{}TQb=EtA*P2f)}Zor>* zL`}h;=K1j_IoOsQmFL5sc18jIv@>cPf7%TA)4qHnF9q}9T&kVKKEb1K)_L4H5LLN3 zPJ8Lzvrqma>dCg?kSwdxnsw;TC!_A@7~6B`g&BC;d)0RLCP^yJ;)#V?LP^|_)TZ2Y zlBR>~07pr(ajTL`OISV}$pZC9JUWge839L%`yaxQ1~3UiW@zb`;GZ+e0p2<9$7-C? zA%*l*r}PviKLg+rz$}2PIFJ|i)HI-m0-(m$7-vf}+Scds*E?)=0Fr>`6_5#pknjO$ zf>b><4G1E^6)OF4@JA0WVH*G}Hy}2C3<{QYAGl=4Owv|;Xs1z<;{@LP@Wycz*Y;AXA{FQ(6#?c~);i~(KdRA(y!bt*XPy7={gNaRz|xwytay6nK31|-bz840qD{4=!vc=d%mXHHnnr-Pd!H)Z%kkkxXxs>Gqa_Gr zxQP}0ldvK+U`0#CzrXzR>{RjZi9jO&cj&tKUXL+pc-S-W*6d}o(EAE-m#`_gOH_`U z-J%wLzS77JC?KDw*s%03q=s@aKw-MJ#^#}=^-a9xCf@Qdjkhd^8~r-GVuXdGlx)z;Plh5+D;AHVPeDmNrf zViu_e04e+c4GK*rEcBr;{!)Cw$)vvvh(VLg3D5%}B2$5n{}Ft{hs2<2CculIKr;#f zj9cxa*daRr`@0^+sI9A9TUmp$AnLgDEEM_DHt)e*iybEEO)sb(6F z#(N+}MB~{>W?BL<5G2Hs&2${ZlFi*%G|o*i)2S(fI>PG`aAbG`<WpLQkeb47NUD^@7-Fn3!7OJ2;jtP3wAyQ zs6<3;UdvvDNc6i;fAFRIgJbUiG;#jKnbWy}g@Z2u+VS{nZ>AkeJ^1>s7p1=qpvPMU zt*bOGtJ7lv_;~Nt{B5raYIhmYTJirnhOr&m5Xx2hFpMAw58YvO`k)1z=Yt?@hp2C$$Y1co-q1>ZSkm(FK?QzbEsuB0tc2?4nV<4_i8Vs9&csZ)O)XhCe;Hm$u)}>moQo zS>dX<#Le7r6`mXsb@5G_Yz`(zB2`5%C2>8;t{Kh2+)HmR0KX>h7-7k1rTedhXC~8} zAa2rp{MsX}RJtX@LE9f`P0Hgec3}2Tc|uls1UtT?8c)<7RM4%TwhoY>*xO5z2-kw8 zIQX|Z^|o^|qN%@*$jOxc+2{oSR@~5F6Q3(T7}lF4!k1KKyyTE=+elx~zHbWnN`I15 zBDzHI9rKvl^8E-GZ2CiLpEzOiSOG54B3)nB+kxgfda`c zTuGlm1l%~Um@M0EdMVL;9ye>b$_3_w;zfj=trFtgyAVm20~ZwWV>iNS6Ml^%4jtuY z$q}oQ6$up6FI_T#a&IJvwl%_f-se`R2X0aY=b<>n2wD$o=|eUHaQmOYKwggx!zsr*qm zi|zASpa(tFtjQwt@zy|2fh5#iYBt7%ve9DqrVrzv_AxE6cWY7(O^oWI1pkZ>7Z$Z)zxhT>0`q}9t>;Edxr?8eQa3d z909`WnNF?IH}H;^f6+69u}DZl&Mb_|-neNQi%mn&H%M#RVrI?Ya*YrtVMhieCI(J5 z;KTz(z?k(FhBB!3jW~fZ>njY!Tl2m{j9C;PH{g!4x+wodWVJWUi?#)&r|o5A?~(MjtT~ z`6sR?&NBZh177EkGG|d~Q;PZ*Akrd>$^q>AClhM17zC!l2Bguv5k*g0mqfgG+&*Ob zcv=4&1!n}yq(#qKmuTn~m!MZxR6_AS%-sP&d65nUpKuA}`!AlJTg*59GmUDs+y6)*oKIkD+4*XST z%^tb_1!vHHXV4*IF#O&b2#!-kn*!f%Lr#+CzuLNg+biDp+7m8R)r46^-#bNDv9K&< zSngn$k1Cq_dh(*T3)m|Tje9`+j88|{HpKYU2G=isIe77czrN0RSE!b!kay+CnNtHN z`j5SHW?&e6E9Y~=?_$kdG1!6Fq$zK8zi|+iX}%X-!~g4kloFVZgmTvsXx>3Wds0u5 z%8)RUwF>xS0V}y>yXkNr3p8~b)*cJ2i)hT}UKv>gRL^-Ece?y^&aL9hkGy~Ol!W!* zI~l*&I+YA+c1c`Y-zbNsm0pD#z>5+5jx#u-wRkk( z7yZNq-y|$WtfAY3<-r1!``vUe-y+l*BCL0xbJ3V@|O$iJ;iT)tr zP3|xe?GmYv=$8I(SWq)nq7PHxv#t(~n&Y^$Bm+yOF0Q$`T@nUaSZ@Zq;w|9<d3WzTyT|~T9APfb1TLuAKPo>e8#8patT+dF@ zmSi={$GM&f8X(mvXU%yS*l*=ZX?q~BK@}R?V4Fq?oJd{KE=_tCX>%?;Lg3B7UGpkO zwtvy8k+rTd>l|5cY|U1;M(;5cjg_XG3;0Kuz7TO*i@y-TZjzLTcg&?S?12(V4PJ<7 zmrqAYk|+TXLgR1wS|KVA^a62{q6tCw(}!%C9kER>&8z@Yp?MDu{J^-N{FvM*=mqoc zZju1no+~mQ75ZVXKX7D zLQjDH(zCH`y!jZ5z2jGIMFJ2=@hw0gwZGtez&#hbNHH21%tp+>GPju?tHzxSL)6p1 zMKjKP<$SjVi#w@n&^F zvrOjQm5h~xTjw*JRC=Q-#5~yMNI(~}`)wf5y2qSX*{SZ&Rz#(`n;Ay$cUx)Z42`o? z!jKZ}m+({WR^vpk3ohg5C4EtPU_g=yBW`mxkRK-tQEn&U68mVu)XC_MSSOe@_}J_R z_b7fh;w;*`(EVABd*NjE%I%YNo}N8U#g55# z=Eroz4nUpSl@ZlU_b=OV3)7i&VNY;7@HU@~9Y)vao0bO-DQ~^Rfyd!zw^F7hKvq42 zT@!Qs6zkGlc#dlwY$EgDzL?;{&U$Nml2x+=F=@AH@l&OHoPs07g>y?I$$B+T987cJ$!ZG)FZ88S z#^%6Kg(QjgQ@S@=+qP@=Xar!fQqX&gK#^%Vl4$bC%dXYMxr9C$^@PC4u({oeV29O(b}{V%iiAvH#ckS_&E_U zZpr589f*tWf8Yg60^>39#YNX}cvd@a?{oEOfX@q{=6=(6LCWqnp`+=M;lg=U6M?upy25ty2GCRwBMCmx4Y zV)KOQtIX2Zo(lwLJrqT4LtJ?EeX(}|jdd}@ji*auyT#G$OK(P^hs57^p03@_M`I8Z zIa3?@O(uB%;TZ^=OBN;uy-B5l;GWuVP>lw-DYeA2AON?an4}%WzW*N!ow~y-?$>^U0{S4R{ z$>_AOb_pJMB^@NZloNH7H28wt4UE6WTOlXThf48WkB%EA2`4Ba2#;3CrQ zbXsm{75o)=dZ~B(ua} zWs)`%$+c{Y!r8Gpf@|6nMQ|7D2;BV3WcaSkM^aXaRr_|HkL6p;?pUjMu6a&0#uLxi zZX-LQF^iVVS`efw>e+q2*|;MOAhCYRZ48MPxGA=2IjbG@9m2&P0eKS_`yD5(Uy-o;r z%>4qxNO*e3fvZB^DmK>$aT0a_u9k_O3z!C6&8I`AA!qlu&6v1y2p8^E3Y6pxFs#tks`@J#McVX$38Vu)079VeOn?ITN#-BEF-tT@}Hd9=wKXI~*<#aT)mHGa73CNKFWFZo}Zmz)SU{B?NONuyxn zjd)l32}x#dp?Gxxd<`c4F|!QjDmTCV^7nlE<$nY3LKs*>O+&rT_w5p9a(+Gf^`m^| z>!7fI4SF+TF2VTH zW@Az`E=w~T7e?b9DQ4r6Xk3zNHs(MK#Bzu&G#ghz3JW_$i0EnHm03L$ypsF~c$L=~mVZ5XRg^vtD8ahK{UO_4$^ZJnZHeu# zR@LmH(X#jdJf?;G2%%h+j~k2{#BIlRVfQbj*mS=D(?w%LTNh#`>Jv)9G1U{RJa$(R zm%xwWSl}eMr9byoe_bkkqXZ+8IKFR_;LY$wl95GhdQUY*e}_|QGilNH7H%&Ig70s9#Di}oL;!Z=uVp{UWwO3MpR3aZgk7D54=gRw zND-R!(P6g?KKEb%bV-8Zuk~gbdAZ!7+6Ms+no-5M5&W- zRvaS0t|R^aDc^s;S>H|L)gr(Y{2c?x-+_Es$iMPqyxL$$)4)3vZ6{$zJ}l%*L4KTX zU`HF1j>0HE+L%0yM2j5c!-|D8Ckc-~SsPC%?7K*XW9q%MyJ) KroY=Q^#1_NgF6QR literal 0 HcmV?d00001 diff --git a/internal/platform/darwin/text.go b/internal/platform/darwin/text.go index 814e913cb..da642d066 100644 --- a/internal/platform/darwin/text.go +++ b/internal/platform/darwin/text.go @@ -1,4 +1,4 @@ -//go:build darwin && !ios +//go:build darwin package darwin diff --git a/internal/platform/darwin/text_engine.go b/internal/platform/darwin/text_engine.go index 346f59d22..c18a7294a 100644 --- a/internal/platform/darwin/text_engine.go +++ b/internal/platform/darwin/text_engine.go @@ -1,4 +1,4 @@ -//go:build darwin && !ios +//go:build darwin package darwin diff --git a/tools/generate_darwin_shaders.sh b/tools/generate_darwin_shaders.sh index b97d88cd3..dde64d275 100755 --- a/tools/generate_darwin_shaders.sh +++ b/tools/generate_darwin_shaders.sh @@ -24,3 +24,25 @@ xcrun --sdk macosx metallib \ -o "$shader_dir/scene.metallib" unlink "$air" + +# iOS has two: a Metal library records the platform it was built for, and the +# simulator's is not the device's (shader_ios.go picks the one it runs on). +minimum_ios=16.0 + +xcrun --sdk iphoneos metal \ + -mios-version-min="$minimum_ios" \ + -c "$shader_dir/scene.metal" \ + -o "$air" +xcrun --sdk iphoneos metallib \ + "$air" \ + -o "$shader_dir/scene_ios.metallib" +unlink "$air" + +xcrun --sdk iphonesimulator metal \ + -mios-simulator-version-min="$minimum_ios" \ + -c "$shader_dir/scene.metal" \ + -o "$air" +xcrun --sdk iphonesimulator metallib \ + "$air" \ + -o "$shader_dir/scene_ios_simulator.metallib" +unlink "$air" From 9b8a4ae2323788cfcfcb2e72b0f4666167f0ff76 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 22 Nov 2026 20:31:27 +0800 Subject: [PATCH 24/64] docs(guides): sync the windows guide with its example --- website/content/guides/en/windows.md | 2 +- website/content/guides/zh/windows.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/website/content/guides/en/windows.md b/website/content/guides/en/windows.md index 543183198..e56047b53 100644 --- a/website/content/guides/en/windows.md +++ b/website/content/guides/en/windows.md @@ -102,7 +102,7 @@ type notes struct { func (state *notes) page(c ui.C) { // The bar is as tall as the title bar and leaves room for the window buttons // on whichever side the platform puts them. - leading, trailing := app.TitlebarInsets() + leading, trailing := c.TitlebarInsets() ui.Column(c).Fill().Children(func() { ui.Row(c).Height(28).PadRight(trailing).PadLeft(leading).Items(ui.Center).MovesWindow().Children(func() { ui.Text(c, "Notes").Muted() diff --git a/website/content/guides/zh/windows.md b/website/content/guides/zh/windows.md index 1a24c8f91..eb2b53f0c 100644 --- a/website/content/guides/zh/windows.md +++ b/website/content/guides/zh/windows.md @@ -68,7 +68,7 @@ type notes struct { func (state *notes) page(c ui.C) { // The bar is as tall as the title bar and leaves room for the window buttons // on whichever side the platform puts them. - leading, trailing := app.TitlebarInsets() + leading, trailing := c.TitlebarInsets() ui.Column(c).Fill().Children(func() { ui.Row(c).Height(28).PadRight(trailing).PadLeft(leading).Items(ui.Center).MovesWindow().Children(func() { ui.Text(c, "Notes").Muted() From d87693b573bdf891c3fba53a76a58042513d0a11 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 22 Nov 2026 20:46:56 +0800 Subject: [PATCH 25/64] feat(cmd/viva): build for the iOS simulator and run there with viva run build --target ios-sim|ios writes an .app: the program built with cgo against the Xcode SDK of the target, and an Info.plist from viva.toml. run builds one for the simulator, boots a device when none is, installs and starts it; the device comes from --device, else a booted iPhone, else the newest installed. Signing for devices and the Xcode export are still to do. --- cmd/viva/build.go | 61 +++++- cmd/viva/help.go | 15 +- cmd/viva/ios.go | 316 ++++++++++++++++++++++++++++++ cmd/viva/ios_test.go | 163 +++++++++++++++ tools/appbundle/ios_plist.go | 75 +++++++ tools/appbundle/ios_plist_test.go | 41 ++++ 6 files changed, 663 insertions(+), 8 deletions(-) create mode 100644 cmd/viva/ios.go create mode 100644 cmd/viva/ios_test.go create mode 100644 tools/appbundle/ios_plist.go create mode 100644 tools/appbundle/ios_plist_test.go diff --git a/cmd/viva/build.go b/cmd/viva/build.go index 9de3b919f..7642ca12a 100644 --- a/cmd/viva/build.go +++ b/cmd/viva/build.go @@ -18,7 +18,7 @@ import ( const mebibyte = 1 << 20 var ( - buildTargets = []string{"darwin", "windows", "linux", "web"} + buildTargets = []string{"darwin", "windows", "linux", "web", "ios-sim", "ios"} buildArches = []string{"arm64", "amd64"} ) @@ -36,16 +36,30 @@ type buildPlan struct { debug bool // cgo explicitly opts Linux and Windows applications into native dependencies. cgo bool + // toolchain is Xcode's compiler and SDK, found when an iOS build starts. + toolchain iosToolchain } // goTarget is the GOOS/GOARCH pair for a target. func (plan buildPlan) goTarget() (goos, goarch string) { - if plan.target == "web" { + switch plan.target { + case "web": return "js", "wasm" + case "ios-sim", "ios": + return "ios", plan.arch } return plan.target, plan.arch } +// programPath is the executable a build writes: the output itself, or for iOS +// the file inside the .app. +func (plan buildPlan) programPath() string { + if plan.isIOS() { + return filepath.Join(plan.out, plan.executable) + } + return plan.out +} + // ldflags are the linker flags: stripped unless debug, a fixed build ID so the // same sources give the same bytes, and on Windows the GUI subsystem for // release builds (a debug build keeps the console so output is visible). @@ -92,6 +106,8 @@ func (plan buildPlan) environment(base []string) []string { } environment = append(environment, name+"="+value) } + case "ios-sim", "ios": + return plan.iosEnvironment(environment, base) case "linux", "windows": // These targets reach the system through purego and the standard // library's own system calls, not through cgo. Go turns cgo on by @@ -121,8 +137,19 @@ func lastEnvironment(environment []string, name string) string { return value } -// run builds into output. +// run builds into output; for an iOS target, the .app at plan.out. func (plan buildPlan) run(output string, errorOutput io.Writer) error { + if plan.isIOS() { + return plan.runIOS(errorOutput) + } + if err := plan.build(output, errorOutput); err != nil { + return err + } + return plan.addWindowsResources(output, errorOutput) +} + +// build runs go build into the output file. +func (plan buildPlan) build(output string, errorOutput io.Writer) error { if err := os.MkdirAll(filepath.Dir(output), 0o755); err != nil { return err } @@ -139,7 +166,7 @@ func (plan buildPlan) run(output string, errorOutput io.Writer) error { } return fmt.Errorf("go build failed: %w", err) } - return plan.addWindowsResources(output, errorOutput) + return nil } // buildFlags holds the flags build and package share. @@ -156,7 +183,7 @@ type buildFlags struct { func (shared *buildFlags) register(flags *flag.FlagSet, defaultTarget string) { flags.StringVar(&shared.dir, "C", ".", "directory holding viva.toml and the Go module") flags.StringVar(&shared.dir, "dir", ".", "same as -C") - flags.StringVar(&shared.target, "target", defaultTarget, "darwin, windows, linux or web") + flags.StringVar(&shared.target, "target", defaultTarget, "darwin, windows, linux, web, ios-sim (the simulator) or ios (devices)") flags.StringVar(&shared.arch, "arch", runtime.GOARCH, "arm64 or amd64 (not used by web)") flags.StringVar(&shared.tags, "tags", "", "comma-separated build tags, added to [build] tags") flags.BoolVar(&shared.debug, "debug", false, "keep symbols and debug information (not the release size)") @@ -168,6 +195,11 @@ func newPlan(shared buildFlags, packageArgument string) (buildPlan, error) { if !contains(buildTargets, shared.target) { return buildPlan{}, fmt.Errorf("unknown target %q; use one of: %s", shared.target, strings.Join(buildTargets, ", ")) } + if shared.target == "ios-sim" || shared.target == "ios" { + if err := checkIOS(shared); err != nil { + return buildPlan{}, err + } + } if shared.target != "web" && !contains(buildArches, shared.arch) { return buildPlan{}, fmt.Errorf("unknown architecture %q; use one of: %s", shared.arch, strings.Join(buildArches, ", ")) } @@ -249,6 +281,20 @@ func (plan *buildPlan) outputPath(requested string) error { return err } plan.out = filepath.Join(plan.manifest.Path(plan.manifest.Build.Out), "web") + case plan.isIOS(): + name += "-" + plan.target + ".app" + if requested != "" { + absolute, err := filepath.Abs(requested) + if err != nil { + return err + } + if info, statErr := os.Stat(absolute); statErr == nil && info.IsDir() && filepath.Ext(absolute) != ".app" { + absolute = filepath.Join(absolute, name) + } + plan.out = absolute + } else { + plan.out = filepath.Join(plan.manifest.Path(plan.manifest.Build.Out), name) + } default: if plan.target != runtime.GOOS || plan.arch != runtime.GOARCH { name += "-" + plan.target + "-" + plan.arch @@ -311,7 +357,7 @@ func runBuild(arguments []string, output, errorOutput io.Writer) error { if err := plan.run(plan.out, errorOutput); err != nil { return err } - info, err := os.Stat(plan.out) + info, err := os.Stat(plan.programPath()) if err != nil { return err } @@ -333,6 +379,9 @@ func displayPath(path string) string { func printBuildDetails(output io.Writer, plan buildPlan, size int64) { goos, goarch := plan.goTarget() target := goos + "/" + goarch + if plan.isIOS() { + target += " (iOS " + iosMinSystem + " or later)" + } if plan.target == "darwin" { target += " (macOS " + plan.manifest.Mac.MinSystem + " or later)" } diff --git a/cmd/viva/help.go b/cmd/viva/help.go index 0aef5441e..e97c53cd0 100644 --- a/cmd/viva/help.go +++ b/cmd/viva/help.go @@ -23,17 +23,28 @@ type command struct { func commands() []command { return []command{ {name: "build", usage: "build [flags] [package]", - summary: "Build a release program for macOS, Windows, Linux or the browser.", + summary: "Build a release program for macOS, Windows, Linux, iOS or the browser.", detail: "Builds with -trimpath and a stripped, reproducible link, and reports the size. Settings come from\n" + "viva.toml when there is one; the package argument overrides [app] package (or [web] package for\n" + "--target web, which also writes the loader and an index.html). macOS builds are compiled for\n" + "[mac] min_system, not for the macOS of the machine building them, and reach Cocoa through cgo;\n" + "Linux and Windows builds disable cgo by default. Use --cgo for application-owned native libraries;\n" + "provide the target C compiler and link flags, and check the resulting system dependencies.\n" + - "Windows release builds use the GUI subsystem; with --debug they keep the console.", + "Windows release builds use the GUI subsystem; with --debug they keep the console. --target ios-sim writes\n" + + "an .app for the iOS simulator (macOS with Xcode; the Metal and UIKit bridge is built with cgo against\n" + + "the SDK); viva run builds, installs and starts it.", run: func(arguments []string, output, errorOutput io.Writer) error { return runBuild(arguments, output, errorOutput) }}, + {name: "run", usage: "run [flags] [package]", + summary: "Build the application and start it in the iOS simulator.", + detail: "Builds an .app for the simulator (--target ios-sim, the only target run takes), boots a simulator if none\n" + + "is running, installs the app and starts it. --device names the simulator or gives its identifier; without\n" + + "it, an iPhone already booted is used, else the newest iPhone the machine has. The Simulator window is\n" + + "shown unless -open=false. It needs macOS with Xcode. For the desktop, use viva dev.", + run: func(arguments []string, output, errorOutput io.Writer) error { + return runRun(arguments, output, errorOutput) + }}, {name: "sign", usage: "sign --target windows --program FILE", summary: "Sign a Windows program that was built elsewhere, in place.", detail: "Uses the same Windows signing options as package: a custom command with {file} " + diff --git a/cmd/viva/ios.go b/cmd/viva/ios.go new file mode 100644 index 000000000..3890131a1 --- /dev/null +++ b/cmd/viva/ios.go @@ -0,0 +1,316 @@ +package main + +import ( + "bytes" + "encoding/json" + "errors" + "flag" + "fmt" + "io" + "os" + "os/exec" + "path/filepath" + "runtime" + "sort" + "strconv" + "strings" + + "github.com/vivaui/viva/tools/appbundle" + "github.com/vivaui/viva/tools/manifest" +) + +// iosMinSystem is the oldest iOS an application is built for. +const iosMinSystem = "16.0" + +// isIOS reports whether the plan builds an iOS application bundle, for the +// simulator or for devices. +func (plan buildPlan) isIOS() bool { return plan.target == "ios-sim" || plan.target == "ios" } + +// iosToolchain is where Xcode keeps what cgo needs to build for an iOS SDK. +type iosToolchain struct { + clang, sdk string +} + +// xcrun runs Xcode's tool locator and returns its trimmed output; tests replace it. +var xcrun = func(arguments ...string) (string, error) { + command := exec.Command("xcrun", arguments...) + var stderr bytes.Buffer + command.Stderr = &stderr + output, err := command.Output() + if err != nil { + return "", fmt.Errorf("xcrun %s: %w: %s", strings.Join(arguments, " "), err, strings.TrimSpace(stderr.String())) + } + return strings.TrimSpace(string(output)), nil +} + +// iosSDK is the Xcode SDK a target is built against. +func iosSDK(target string) string { + if target == "ios-sim" { + return "iphonesimulator" + } + return "iphoneos" +} + +// findIOSToolchain asks Xcode for the SDK and the C compiler of the target. +func findIOSToolchain(target string) (iosToolchain, error) { + sdk := iosSDK(target) + root, err := xcrun("--sdk", sdk, "--show-sdk-path") + if err != nil { + return iosToolchain{}, fmt.Errorf("the %s SDK was not found; install Xcode and run 'xcode-select -s /Applications/Xcode.app': %w", sdk, err) + } + clang, err := xcrun("--sdk", sdk, "-f", "clang") + if err != nil { + return iosToolchain{}, err + } + return iosToolchain{clang: clang, sdk: root}, nil +} + +// triple is the clang target of an iOS build. +func (plan buildPlan) iosTriple() string { + arch := plan.arch + if arch == "amd64" { + arch = "x86_64" + } + triple := arch + "-apple-ios" + iosMinSystem + if plan.target == "ios-sim" { + triple += "-simulator" + } + return triple +} + +// iosEnvironment is what go build needs for iOS: cgo, with Xcode's compiler +// pointed at the SDK and the deployment target. The Metal and UIKit bridge is +// Objective-C, so there is no building it without them. +func (plan buildPlan) iosEnvironment(environment, base []string) []string { + flags := "-isysroot " + plan.toolchain.sdk + " -target " + plan.iosTriple() + environment = append(environment, "CGO_ENABLED=1", "CC="+plan.toolchain.clang+" "+flags) + for _, name := range []string{"CGO_CFLAGS", "CGO_LDFLAGS"} { + value := flags + if existing := lastEnvironment(base, name); existing != "" { + value = existing + " " + flags + } + environment = append(environment, name+"="+value) + } + return environment +} + +// checkIOS reports what a machine or flag combination cannot build. +func checkIOS(shared buildFlags) error { + if runtime.GOOS != "darwin" { + return errors.New("building for iOS needs a macOS host with Xcode: the Metal and UIKit bridge is Objective-C") + } + if shared.target == "ios" && shared.arch != "arm64" { + return fmt.Errorf("iOS devices run arm64; got --arch %s", shared.arch) + } + if shared.cgo { + return errors.New("--cgo is for Linux and Windows; iOS builds always use cgo") + } + return nil +} + +// bundleID is the application's identifier on a device. +func (plan buildPlan) bundleID() string { + if id := plan.manifest.App.ID; id != "" { + return id + } + return "dev.viva." + manifest.Slug(plan.executable) +} + +// runIOS builds the program into the .app and writes the Info.plist beside it. +func (plan buildPlan) runIOS(errorOutput io.Writer) error { + toolchain, err := findIOSToolchain(plan.target) + if err != nil { + return err + } + plan.toolchain = toolchain + if err := os.RemoveAll(plan.out); err != nil { + return err + } + if err := os.MkdirAll(plan.out, 0o755); err != nil { + return err + } + if err := plan.build(plan.programPath(), errorOutput); err != nil { + return err + } + name := plan.manifest.App.Name + if name == "" { + name = plan.executable + } + plist, err := appbundle.IOSInfo{ + Name: name, ID: plan.bundleID(), Version: plan.manifest.App.Version, Executable: plan.executable, + MinSystem: iosMinSystem, Simulator: plan.target == "ios-sim", + }.Plist() + if err != nil { + return err + } + return os.WriteFile(filepath.Join(plan.out, "Info.plist"), plist, 0o644) +} + +// simulator is one device of the iOS simulator. +type simulator struct { + UDID string `json:"udid"` + Name string `json:"name"` + State string `json:"state"` + Runtime string `json:"-"` +} + +// listSimulators reads the available devices out of 'simctl list devices -j'. +func listSimulators(data []byte) ([]simulator, error) { + var listing struct { + Devices map[string][]simulator `json:"devices"` + } + if err := json.Unmarshal(data, &listing); err != nil { + return nil, fmt.Errorf("reading the simulator list: %w", err) + } + var devices []simulator + for runtimeName, list := range listing.Devices { + if !strings.Contains(runtimeName, ".iOS-") { + continue + } + for _, device := range list { + device.Runtime = runtimeName + devices = append(devices, device) + } + } + return devices, nil +} + +// runtimeVersion orders runtime names such as ...SimRuntime.iOS-18-5 by version. +func runtimeVersion(name string) []int { + _, version, _ := strings.Cut(name, ".iOS-") + var numbers []int + for _, part := range strings.Split(version, "-") { + number, _ := strconv.Atoi(part) + numbers = append(numbers, number) + } + return numbers +} + +func versionLess(a, b []int) bool { + for index := 0; index < len(a) && index < len(b); index++ { + if a[index] != b[index] { + return a[index] < b[index] + } + } + return len(a) < len(b) +} + +// chooseSimulator picks the device to run on: the one asked for by name or +// identifier; otherwise an iPhone already booted, or the first iPhone of the +// newest iOS the machine has. +func chooseSimulator(devices []simulator, requested string) (simulator, error) { + if requested != "" { + for _, device := range devices { + if device.UDID == requested || device.Name == requested { + return device, nil + } + } + return simulator{}, fmt.Errorf("no simulator named %q; 'xcrun simctl list devices available' lists them", requested) + } + var phones []simulator + for _, device := range devices { + if strings.HasPrefix(device.Name, "iPhone") { + phones = append(phones, device) + } + } + if len(phones) == 0 { + return simulator{}, errors.New("no iPhone simulator is installed; add one in Xcode's Devices and Simulators window") + } + sort.SliceStable(phones, func(i, j int) bool { + a, b := phones[i], phones[j] + if (a.State == "Booted") != (b.State == "Booted") { + return a.State == "Booted" + } + if a.Runtime != b.Runtime { + return versionLess(runtimeVersion(b.Runtime), runtimeVersion(a.Runtime)) + } + return a.Name < b.Name + }) + return phones[0], nil +} + +// simctl runs the simulator's control tool; tests replace it. +var simctl = func(output io.Writer, arguments ...string) ([]byte, error) { + command := exec.Command("xcrun", append([]string{"simctl"}, arguments...)...) + var stdout, stderr bytes.Buffer + command.Stdout, command.Stderr = &stdout, &stderr + if err := command.Run(); err != nil { + return stdout.Bytes(), fmt.Errorf("simctl %s: %w: %s", strings.Join(arguments, " "), err, strings.TrimSpace(stderr.String())) + } + return stdout.Bytes(), nil +} + +// openSimulatorApp shows the Simulator window; tests replace it. +var openSimulatorApp = func(udid string) error { + return exec.Command("open", "-a", "Simulator", "--args", "-CurrentDeviceUDID", udid).Run() +} + +func runRun(arguments []string, output, errorOutput io.Writer) error { + c, _ := findCommand("run") + flags := flag.NewFlagSet("run", flag.ContinueOnError) + var shared buildFlags + shared.register(flags, "ios-sim") + var device string + open := true + flags.StringVar(&device, "device", "", "simulator name or identifier (default: a booted iPhone, else the newest one installed)") + flags.BoolVar(&open, "open", true, "show the Simulator window") + positional, helped, err := parseFlags(c, flags, arguments, output) + if helped || err != nil { + return err + } + if shared.target != "ios-sim" { + return fmt.Errorf("run starts an application in the iOS simulator (--target ios-sim); got %q. Use viva dev for the desktop", shared.target) + } + if len(positional) > 1 { + return errors.New("run takes at most one package; run 'viva help run'") + } + argument := "" + if len(positional) == 1 { + argument = positional[0] + } + plan, err := newPlan(shared, argument) + if err != nil { + return err + } + if err := plan.outputPath(""); err != nil { + return err + } + if err := plan.run(plan.out, errorOutput); err != nil { + return err + } + listing, err := simctl(errorOutput, "list", "devices", "available", "-j") + if err != nil { + return err + } + devices, err := listSimulators(listing) + if err != nil { + return err + } + chosen, err := chooseSimulator(devices, device) + if err != nil { + return err + } + if chosen.State != "Booted" { + if _, err := simctl(errorOutput, "boot", chosen.UDID); err != nil { + return err + } + } + if open { + if err := openSimulatorApp(chosen.UDID); err != nil { + return fmt.Errorf("showing the Simulator window: %w", err) + } + } + if _, err := simctl(errorOutput, "bootstatus", chosen.UDID, "-b"); err != nil { + return err + } + if _, err := simctl(errorOutput, "install", chosen.UDID, plan.out); err != nil { + return err + } + // Without --terminate-running-process a copy still running from the last + // run would be brought forward instead of started again. + if _, err := simctl(errorOutput, "launch", "--terminate-running-process", chosen.UDID, plan.bundleID()); err != nil { + return err + } + fmt.Fprintf(output, "started %s on %s (%s)\n", plan.bundleID(), chosen.Name, chosen.UDID) + return nil +} diff --git a/cmd/viva/ios_test.go b/cmd/viva/ios_test.go new file mode 100644 index 000000000..786809c5d --- /dev/null +++ b/cmd/viva/ios_test.go @@ -0,0 +1,163 @@ +package main + +import ( + "runtime" + "slices" + "strings" + "testing" +) + +const simulatorListing = `{"devices": { + "com.apple.CoreSimulator.SimRuntime.iOS-9-0": [ + {"udid": "OLD", "name": "iPhone 6", "state": "Shutdown"}], + "com.apple.CoreSimulator.SimRuntime.iOS-18-5": [ + {"udid": "PRO", "name": "iPhone 16 Pro", "state": "Shutdown"}, + {"udid": "PAD", "name": "iPad Pro", "state": "Booted"}, + {"udid": "SIX", "name": "iPhone 16", "state": "Shutdown"}], + "com.apple.CoreSimulator.SimRuntime.watchOS-11-0": [ + {"udid": "WATCH", "name": "Apple Watch", "state": "Booted"}] +}}` + +func simulators(t *testing.T) []simulator { + t.Helper() + devices, err := listSimulators([]byte(simulatorListing)) + if err != nil { + t.Fatal(err) + } + return devices +} + +// The newest iOS wins by version, not by the order of the names: 18-5 is newer +// than 9-0 though "9" sorts after "1". +func TestRunPicksAnIPhoneOfTheNewestRuntime(t *testing.T) { + devices := simulators(t) + chosen, err := chooseSimulator(devices, "") + if err != nil { + t.Fatal(err) + } + if !strings.Contains(chosen.Runtime, "iOS-18-5") || !strings.HasPrefix(chosen.Name, "iPhone") { + t.Fatalf("chose %+v, want an iPhone of iOS 18.5", chosen) + } +} + +// What is already running is used rather than booting a second device, and a +// watch or an iPad is not an iPhone to start on. +func TestRunPrefersABootedIPhone(t *testing.T) { + devices := simulators(t) + for index := range devices { + if devices[index].UDID == "OLD" { + devices[index].State = "Booted" + } + } + chosen, err := chooseSimulator(devices, "") + if err != nil { + t.Fatal(err) + } + if chosen.UDID != "OLD" { + t.Fatalf("chose %+v, want the booted iPhone", chosen) + } +} + +func TestRunTakesADeviceByNameOrIdentifier(t *testing.T) { + devices := simulators(t) + for _, requested := range []string{"SIX", "iPhone 16"} { + chosen, err := chooseSimulator(devices, requested) + if err != nil || chosen.UDID != "SIX" { + t.Fatalf("--device %s chose %+v, %v", requested, chosen, err) + } + } + if _, err := chooseSimulator(devices, "iPhone 99"); err == nil { + t.Fatal("an unknown device was accepted") + } +} + +func TestRunNeedsAnIPhoneSimulator(t *testing.T) { + devices, err := listSimulators([]byte(`{"devices": {"com.apple.CoreSimulator.SimRuntime.iOS-18-5": [{"udid": "PAD", "name": "iPad Pro", "state": "Shutdown"}]}}`)) + if err != nil { + t.Fatal(err) + } + if _, err := chooseSimulator(devices, ""); err == nil { + t.Fatal("no iPhone, and still a device was chosen") + } +} + +func TestIOSBuildChecks(t *testing.T) { + err := checkIOS(buildFlags{target: "ios-sim", arch: "arm64"}) + if runtime.GOOS != "darwin" { + // Only a Mac has Xcode: the check says so before anything else. + if err == nil { + t.Fatal("an iOS build was accepted on a host without Xcode") + } + return + } + if err != nil { + t.Fatalf("a simulator build was refused on a Mac: %v", err) + } + if checkIOS(buildFlags{target: "ios", arch: "amd64"}) == nil { + t.Error("an amd64 device build was accepted; devices run arm64") + } + if checkIOS(buildFlags{target: "ios-sim", arch: "arm64", cgo: true}) == nil { + t.Error("--cgo was accepted for iOS, which always uses cgo") + } +} + +// An iOS build compiles the Objective-C bridge against the SDK of its target: +// the environment must name the SDK, the architecture and, for the simulator +// only, the simulator. +func TestIOSEnvironmentPointsCgoAtTheSDK(t *testing.T) { + for _, test := range []struct { + target, arch, triple string + simulator bool + }{ + {"ios-sim", "arm64", "arm64-apple-ios" + iosMinSystem + "-simulator", true}, + {"ios-sim", "amd64", "x86_64-apple-ios" + iosMinSystem + "-simulator", true}, + {"ios", "arm64", "arm64-apple-ios" + iosMinSystem, false}, + } { + plan := buildPlan{target: test.target, arch: test.arch, toolchain: iosToolchain{clang: "/x/clang", sdk: "/x/SDK.sdk"}} + environment := plan.environment([]string{"CGO_CFLAGS=-O2"}) + for _, want := range []string{"GOOS=ios", "GOARCH=" + test.arch, "CGO_ENABLED=1"} { + if !slices.Contains(environment, want) { + t.Errorf("%s/%s: environment lacks %s", test.target, test.arch, want) + } + } + for _, name := range []string{"CC", "CGO_CFLAGS", "CGO_LDFLAGS"} { + value := lastEnvironment(environment, name) + if !strings.Contains(value, "-isysroot /x/SDK.sdk") || !strings.Contains(value, "-target "+test.triple) { + t.Errorf("%s/%s: %s = %q, want the SDK and target %s", test.target, test.arch, name, value, test.triple) + } + if strings.HasSuffix(test.triple, "-simulator") != test.simulator { + t.Errorf("test table disagrees with itself for %s", test.target) + } + } + if value := lastEnvironment(environment, "CGO_CFLAGS"); !strings.Contains(value, "-O2") { + t.Errorf("%s: the developer's CGO_CFLAGS were dropped: %q", test.target, value) + } + } +} + +// The simulator's app and the device's do not overwrite each other, and both +// are bundles, not files. +func TestIOSOutputsAreSeparateBundles(t *testing.T) { + dir := fixture(t, notesTOML) + var outputs []string + for _, target := range []string{"ios-sim", "ios"} { + plan := buildPlan{manifest: loadPlan(t, dir, buildFlags{target: runtime.GOOS}, "").manifest, target: target, arch: "arm64", executable: "notes"} + if err := plan.outputPath(""); err != nil { + t.Fatal(err) + } + if !strings.HasSuffix(plan.out, ".app") || !strings.HasSuffix(plan.programPath(), "/notes") { + t.Errorf("%s: output %q, program %q", target, plan.out, plan.programPath()) + } + outputs = append(outputs, plan.out) + } + if outputs[0] == outputs[1] { + t.Fatalf("both targets write to %s", outputs[0]) + } +} + +func TestPackagingRefusesIOS(t *testing.T) { + dir := fixture(t, notesTOML) + if err := run([]string{"package", "-C", dir, "--target", "ios-sim"}, new(strings.Builder)); err == nil { + t.Fatal("package accepted an iOS target") + } +} diff --git a/tools/appbundle/ios_plist.go b/tools/appbundle/ios_plist.go new file mode 100644 index 000000000..30b685727 --- /dev/null +++ b/tools/appbundle/ios_plist.go @@ -0,0 +1,75 @@ +package appbundle + +import ( + "bytes" + "encoding/xml" + "fmt" +) + +// IOSInfo is what an iOS application's Info.plist records. An iOS bundle is +// flat: the executable and Info.plist sit side by side in the .app. +type IOSInfo struct { + // Name is the display name (CFBundleName and CFBundleDisplayName). + Name string + // ID is the bundle identifier. + ID string + // Version is both the short version and the build version. + Version string + // Executable is the file name inside the bundle. + Executable string + // MinSystem is MinimumOSVersion. + MinSystem string + // Simulator marks a bundle for the simulator rather than for devices. + Simulator bool +} + +// Plist renders Info.plist as XML, keys in a fixed order so the same IOSInfo +// always gives the same bytes. The application fills the screen, in any +// orientation, on iPhone and iPad. +func (info IOSInfo) Plist() ([]byte, error) { + if info.Name == "" || info.ID == "" || info.Version == "" || info.Executable == "" || info.MinSystem == "" { + return nil, fmt.Errorf("appbundle: name, identifier, version, executable and minimum system are required") + } + platform := "iPhoneOS" + if info.Simulator { + platform = "iPhoneSimulator" + } + var buffer bytes.Buffer + buffer.WriteString(`` + "\n") + buffer.WriteString(`` + "\n") + buffer.WriteString(`` + "\n\n") + text := func(key, value string) { + buffer.WriteString("\t" + key + "\n\t") + xml.EscapeText(&buffer, []byte(value)) + buffer.WriteString("\n") + } + list := func(key string, values ...string) { + buffer.WriteString("\t" + key + "\n\t\n") + for _, value := range values { + buffer.WriteString("\t\t") + xml.EscapeText(&buffer, []byte(value)) + buffer.WriteString("\n") + } + buffer.WriteString("\t\n") + } + text("CFBundleDevelopmentRegion", "en") + text("CFBundleDisplayName", info.Name) + text("CFBundleExecutable", info.Executable) + text("CFBundleIdentifier", info.ID) + text("CFBundleInfoDictionaryVersion", "6.0") + text("CFBundleName", info.Name) + text("CFBundlePackageType", "APPL") + list("CFBundleSupportedPlatforms", platform) + text("CFBundleShortVersionString", info.Version) + text("CFBundleVersion", info.Version) + text("MinimumOSVersion", info.MinSystem) + buffer.WriteString("\tUIDeviceFamily\n\t\n\t\t1\n\t\t2\n\t\n") + buffer.WriteString("\tUILaunchScreen\n\t\n") + list("UISupportedInterfaceOrientations", + "UIInterfaceOrientationPortrait", "UIInterfaceOrientationLandscapeLeft", "UIInterfaceOrientationLandscapeRight") + list("UISupportedInterfaceOrientations~ipad", + "UIInterfaceOrientationPortrait", "UIInterfaceOrientationPortraitUpsideDown", + "UIInterfaceOrientationLandscapeLeft", "UIInterfaceOrientationLandscapeRight") + buffer.WriteString("\n\n") + return buffer.Bytes(), nil +} diff --git a/tools/appbundle/ios_plist_test.go b/tools/appbundle/ios_plist_test.go new file mode 100644 index 000000000..029a1e473 --- /dev/null +++ b/tools/appbundle/ios_plist_test.go @@ -0,0 +1,41 @@ +package appbundle + +import ( + "strings" + "testing" +) + +func TestIOSPlistNamesTheApplicationAndItsPlatform(t *testing.T) { + info := IOSInfo{Name: "Notes & Co", ID: "dev.example.notes", Version: "2.0.1", Executable: "notes", MinSystem: "16.0", Simulator: true} + data, err := info.Plist() + if err != nil { + t.Fatal(err) + } + text := string(data) + for _, want := range []string{"dev.example.notes", "2.0.1", "notes", "16.0", "iPhoneSimulator", "Notes & Co"} { + if !strings.Contains(text, want) { + t.Errorf("Info.plist lacks %q", want) + } + } + info.Simulator = false + data, err = info.Plist() + if err != nil { + t.Fatal(err) + } + if text := string(data); !strings.Contains(text, "iPhoneOS") || strings.Contains(text, "iPhoneSimulator") { + t.Error("a device bundle names the simulator platform") + } +} + +func TestIOSPlistIsReproducibleAndNeedsItsFields(t *testing.T) { + info := IOSInfo{Name: "N", ID: "a.b", Version: "1", Executable: "n", MinSystem: "16.0"} + first, _ := info.Plist() + second, _ := info.Plist() + if string(first) != string(second) { + t.Fatal("the same bundle gave different bytes") + } + info.ID = "" + if _, err := info.Plist(); err == nil { + t.Fatal("a bundle with no identifier was accepted") + } +} From 2d099b2237dc6fb0c2075aefb417b4f318524305 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 22 Nov 2026 20:53:29 +0800 Subject: [PATCH 26/64] build(android): add the environment script for the Android toolchain --- .gitignore | 1 + tools/android/env.sh | 14 ++++++++++++++ 2 files changed, 15 insertions(+) create mode 100644 tools/android/env.sh diff --git a/.gitignore b/.gitignore index 151c58ecf..391c7ffdf 100644 --- a/.gitignore +++ b/.gitignore @@ -27,3 +27,4 @@ # A signing key written by viva update-keygen in the project root. /update.key +tools/android/local.sh diff --git a/tools/android/env.sh b/tools/android/env.sh new file mode 100644 index 000000000..5655ea359 --- /dev/null +++ b/tools/android/env.sh @@ -0,0 +1,14 @@ +#!/bin/sh +# Source this: the Android SDK, NDK and emulator Viva's mobile work uses. +# Paths of this machine go in tools/android/local.sh (git-ignored); the defaults +# are where Homebrew's android-commandlinetools puts them. +here=$(cd "$(dirname "$0")" && pwd) +[ -f "$here/local.sh" ] && . "$here/local.sh" +: "${ANDROID_HOME:=/opt/homebrew/share/android-commandlinetools}" +export ANDROID_HOME ANDROID_SDK_ROOT=$ANDROID_HOME +: "${ANDROID_NDK_HOME:=$(ls -d "$ANDROID_HOME"/ndk/* 2>/dev/null | sort | tail -1)}" +export ANDROID_NDK_HOME +export PATH="$ANDROID_HOME/platform-tools:$ANDROID_HOME/emulator:$ANDROID_HOME/cmdline-tools/latest/bin:$PATH" +# The virtual device viva run --target android-emu starts. +: "${VIVA_ANDROID_AVD:=viva-api35}" +export VIVA_ANDROID_AVD From 6d2fd9b0289c81c6c7bd2e0b106d177bd5ad9c45 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 22 Nov 2026 21:29:53 +0800 Subject: [PATCH 27/64] refactor(platform): move the Vulkan renderer out of the Linux backend The renderer and its device, scene, text and frame code move from internal/platform/linux to internal/platform/vulkan, which knows no window system: a window system gives it a SurfaceSource (the instance extension and the call that makes the surface), and the platform gives it a TextRasterizer that draws label glyphs. Linux supplies the XCB surface and its Pango text services; the driver search for desktop manifests stays with desktop Linux (libvulkan.so.1), and Android will supply an ANativeWindow surface and the system's text drawing with libvulkan.so. Window-system-neutral pieces move to where both renderers reach them: the frame geometry (platform/windowframe), the label and rectangle validation (platform, render) and the font size check. The Linux window keeps its windowRenderer seam and adapts the Vulkan renderer to it. Tests move with what they test. The renderer's recovery and device tests now present to an X window made with a few libxcb calls, or to a headless surface, and use a solid text rasterizer; the window's resize tests use a fake renderer; the ones that need Pango and renderer internals together keep to Linux through small exported counters. Two test fixtures that never set the window's text input are fixed. The Linux hello grows by 12,288 bytes (0.2%): the adapter and the exported renderer API. --- internal/platform/label_pixels.go | 8 + internal/platform/label_validate.go | 80 ++ internal/platform/linux/api_linux_test.go | 1032 +---------------- internal/platform/linux/cpu_lcd_linux_test.go | 2 +- .../platform/linux/cpu_offscreen_linux.go | 12 +- internal/platform/linux/cpu_window_linux.go | 44 +- .../platform/linux/cpu_window_linux_test.go | 60 +- .../linux/cpu_window_live_linux_test.go | 9 +- .../linux/desktop_fonts_linux_test.go | 2 +- internal/platform/linux/display_scale.go | 4 +- .../platform/linux/ink_overflow_linux_test.go | 9 +- internal/platform/linux/input_linux_test.go | 97 +- internal/platform/linux/offscreen_linux.go | 275 +---- .../platform/linux/shared_api_linux_test.go | 9 +- internal/platform/linux/soft_scene_linux.go | 8 +- internal/platform/linux/status_item_linux.go | 6 +- internal/platform/linux/text_engine_linux.go | 2 +- internal/platform/linux/text_input_linux.go | 2 +- internal/platform/linux/text_linux.go | 38 +- .../platform/linux/text_resize_linux_test.go | 270 +---- .../platform/linux/vulkan_window_linux.go | 116 +- .../platform/linux/wide_label_linux_test.go | 53 - .../platform/linux/window_controls_linux.go | 4 +- internal/platform/linux/window_frame.go | 84 -- .../platform/linux/window_frame_linux_test.go | 28 +- internal/platform/linux/window_linux.go | 21 +- .../platform/linux/window_margin_linux.go | 13 +- .../linux/window_renderer_fake_linux_test.go | 96 ++ .../platform/linux/window_renderer_linux.go | 4 +- .../linux/window_resize_bench_linux_test.go | 67 +- .../linux/window_resize_linux_test.go | 80 +- .../platform/linux/window_size_linux_test.go | 6 +- .../linux/window_sync_resize_linux_test.go | 29 +- internal/platform/vulkan/abi_test.go | 85 ++ internal/platform/vulkan/api_vulkan_test.go | 999 ++++++++++++++++ internal/platform/vulkan/driver_android.go | 10 + .../platform/vulkan/driver_desktop_linux.go | 92 ++ internal/platform/vulkan/helpers_test.go | 155 +++ internal/platform/vulkan/input_vulkan_test.go | 103 ++ internal/platform/{linux => vulkan}/layers.go | 12 +- .../platform/{linux => vulkan}/layers_test.go | 2 +- internal/platform/vulkan/offscreen_linux.go | 300 +++++ internal/platform/vulkan/probe_select_test.go | 62 + internal/platform/vulkan/rasterizer.go | 32 + .../{linux => vulkan}/shaders/scene.frag | 0 .../{linux => vulkan}/shaders/scene.frag.spv | Bin .../{linux => vulkan}/shaders/scene.vert | 0 .../{linux => vulkan}/shaders/scene.vert.spv | Bin .../{linux => vulkan}/shaders/text.frag | 0 .../{linux => vulkan}/shaders/text.frag.spv | Bin .../{linux => vulkan}/shaders/text.vert | 0 .../{linux => vulkan}/shaders/text.vert.spv | Bin .../{linux => vulkan}/shaders/text_lcd.frag | 0 .../shaders/text_lcd.frag.spv | Bin .../{linux => vulkan}/shaders_linux.go | 2 +- internal/platform/vulkan/shared_api_test.go | 16 + .../platform/vulkan/text_resize_linux_test.go | 255 ++++ .../vulkan_bench_linux_test.go | 6 +- .../{linux => vulkan}/vulkan_device_linux.go | 18 +- .../vulkan_device_linux_test.go | 28 +- .../{linux => vulkan}/vulkan_frame_linux.go | 46 +- .../vulkan_frame_linux_test.go | 4 +- .../{linux => vulkan}/vulkan_hotpath_linux.go | 4 +- .../vulkan_imagepool_linux.go | 10 +- .../{linux => vulkan}/vulkan_linux.go | 334 +++--- .../platform/{linux => vulkan}/vulkan_loss.go | 4 +- .../{linux => vulkan}/vulkan_loss_test.go | 2 +- .../{linux => vulkan}/vulkan_probe_linux.go | 6 +- .../vulkan_probe_linux_test.go | 6 +- .../vulkan_recovery_linux_test.go | 100 +- .../{linux => vulkan}/vulkan_refresh_linux.go | 8 +- .../{linux => vulkan}/vulkan_scene_linux.go | 30 +- .../{linux => vulkan}/vulkan_staging_linux.go | 16 +- .../vulkan_staging_linux_test.go | 2 +- .../vulkan_swapchain_retire_linux_test.go | 4 +- .../{linux => vulkan}/vulkan_text_linux.go | 133 +-- .../vulkan_text_scissor_test.go | 2 +- .../platform/vulkan/vulkan_window_linux.go | 44 + .../platform/vulkan/wide_label_linux_test.go | 62 + .../vulkan/window_resize_bench_linux_test.go | 140 +++ internal/platform/vulkan/xcb_test.go | 125 ++ internal/platform/windowframe/windowframe.go | 88 ++ .../windowframe_test.go} | 34 +- internal/render/validate.go | 46 + 84 files changed, 3453 insertions(+), 2544 deletions(-) create mode 100644 internal/platform/label_validate.go delete mode 100644 internal/platform/linux/window_frame.go create mode 100644 internal/platform/linux/window_renderer_fake_linux_test.go create mode 100644 internal/platform/vulkan/abi_test.go create mode 100644 internal/platform/vulkan/api_vulkan_test.go create mode 100644 internal/platform/vulkan/driver_android.go create mode 100644 internal/platform/vulkan/driver_desktop_linux.go create mode 100644 internal/platform/vulkan/helpers_test.go create mode 100644 internal/platform/vulkan/input_vulkan_test.go rename internal/platform/{linux => vulkan}/layers.go (92%) rename internal/platform/{linux => vulkan}/layers_test.go (99%) create mode 100644 internal/platform/vulkan/offscreen_linux.go create mode 100644 internal/platform/vulkan/probe_select_test.go create mode 100644 internal/platform/vulkan/rasterizer.go rename internal/platform/{linux => vulkan}/shaders/scene.frag (100%) rename internal/platform/{linux => vulkan}/shaders/scene.frag.spv (100%) rename internal/platform/{linux => vulkan}/shaders/scene.vert (100%) rename internal/platform/{linux => vulkan}/shaders/scene.vert.spv (100%) rename internal/platform/{linux => vulkan}/shaders/text.frag (100%) rename internal/platform/{linux => vulkan}/shaders/text.frag.spv (100%) rename internal/platform/{linux => vulkan}/shaders/text.vert (100%) rename internal/platform/{linux => vulkan}/shaders/text.vert.spv (100%) rename internal/platform/{linux => vulkan}/shaders/text_lcd.frag (100%) rename internal/platform/{linux => vulkan}/shaders/text_lcd.frag.spv (100%) rename internal/platform/{linux => vulkan}/shaders_linux.go (95%) create mode 100644 internal/platform/vulkan/shared_api_test.go create mode 100644 internal/platform/vulkan/text_resize_linux_test.go rename internal/platform/{linux => vulkan}/vulkan_bench_linux_test.go (93%) rename internal/platform/{linux => vulkan}/vulkan_device_linux.go (93%) rename internal/platform/{linux => vulkan}/vulkan_device_linux_test.go (79%) rename internal/platform/{linux => vulkan}/vulkan_frame_linux.go (77%) rename internal/platform/{linux => vulkan}/vulkan_frame_linux_test.go (97%) rename internal/platform/{linux => vulkan}/vulkan_hotpath_linux.go (98%) rename internal/platform/{linux => vulkan}/vulkan_imagepool_linux.go (91%) rename internal/platform/{linux => vulkan}/vulkan_linux.go (85%) rename internal/platform/{linux => vulkan}/vulkan_loss.go (92%) rename internal/platform/{linux => vulkan}/vulkan_loss_test.go (98%) rename internal/platform/{linux => vulkan}/vulkan_probe_linux.go (94%) rename internal/platform/{linux => vulkan}/vulkan_probe_linux_test.go (83%) rename internal/platform/{linux => vulkan}/vulkan_recovery_linux_test.go (63%) rename internal/platform/{linux => vulkan}/vulkan_refresh_linux.go (81%) rename internal/platform/{linux => vulkan}/vulkan_scene_linux.go (94%) rename internal/platform/{linux => vulkan}/vulkan_staging_linux.go (90%) rename internal/platform/{linux => vulkan}/vulkan_staging_linux_test.go (99%) rename internal/platform/{linux => vulkan}/vulkan_swapchain_retire_linux_test.go (99%) rename internal/platform/{linux => vulkan}/vulkan_text_linux.go (90%) rename internal/platform/{linux => vulkan}/vulkan_text_scissor_test.go (99%) create mode 100644 internal/platform/vulkan/vulkan_window_linux.go create mode 100644 internal/platform/vulkan/wide_label_linux_test.go create mode 100644 internal/platform/vulkan/window_resize_bench_linux_test.go create mode 100644 internal/platform/vulkan/xcb_test.go create mode 100644 internal/platform/windowframe/windowframe.go rename internal/platform/{linux/window_frame_test.go => windowframe/windowframe_test.go} (57%) create mode 100644 internal/render/validate.go diff --git a/internal/platform/label_pixels.go b/internal/platform/label_pixels.go index 723ee419a..9875465c8 100644 --- a/internal/platform/label_pixels.go +++ b/internal/platform/label_pixels.go @@ -248,3 +248,11 @@ func BitmapTextureStale(label TextLabel, scale float32, haveWidth, haveHeight in } func extentStale(have, need int) bool { return need > have || have >= 2*need } + +// ValidFontSize reports whether size can be laid out: positive and finite. +func ValidFontSize(size float32) bool { + return size > 0 && !math.IsNaN(float64(size)) && !math.IsInf(float64(size), 0) +} + +// MaxDisplayScale is the largest display scale a window or a scene is drawn at. +const MaxDisplayScale = 8.0 diff --git a/internal/platform/label_validate.go b/internal/platform/label_validate.go new file mode 100644 index 000000000..fc5c44f33 --- /dev/null +++ b/internal/platform/label_validate.go @@ -0,0 +1,80 @@ +package platform + +import ( + "fmt" + "math" + + "github.com/vivaui/viva/gfx" +) + +// The checks and comparisons of text labels that every renderer makes. + +func ValidateTextLabel(index int, label TextLabel) error { + for _, value := range []float32{label.X, label.Y, label.Width, label.Height, label.FontSize, label.Weight, label.CellWidth} { + if !finiteFloat(value) { + return fmt.Errorf("platform: text label %d has a non-finite metric", index) + } + } + if label.Width < 0 || label.Height < 0 || len(label.Bitmap) == 0 && !ValidFontSize(label.FontSize) { + return fmt.Errorf("platform: text label %d has invalid bounds or font size", index) + } + if len(label.Runs) > 0 && label.CellWidth <= 0 { + return fmt.Errorf("platform: text label %d has invalid cell width", index) + } + if len(label.Bitmap) > 0 { + if label.BitmapWidth <= 0 || label.BitmapHeight <= 0 || label.BitmapStride < label.BitmapWidth*4 { + return fmt.Errorf("platform: bitmap label %d has invalid dimensions", index) + } + required := (label.BitmapHeight-1)*label.BitmapStride + label.BitmapWidth*4 + if required < 0 || len(label.Bitmap) < required { + return fmt.Errorf("platform: bitmap label %d has a short payload", index) + } + } + return nil +} + +func SameTextRuns(left, right []gfx.TextRun) bool { + if len(left) != len(right) { + return false + } + for index := range left { + if left[index] != right[index] { + return false + } + } + return true +} + +func SameBitmapBytes(left, right []byte) bool { + if len(left) != len(right) { + return false + } + return len(left) == 0 || &left[0] == &right[0] +} + +func TightBitmap(source []byte, width, height, stride int) []byte { + if stride == width*4 { + return source[:width*height*4] + } + pixels := make([]byte, width*height*4) + for row := 0; row < height; row++ { + copy(pixels[row*width*4:(row+1)*width*4], source[row*stride:row*stride+width*4]) + } + return pixels +} + +func ValidateTextLabels(labels []TextLabel) error { + for index, label := range labels { + if err := ValidateTextLabel(index, label); err != nil { + return err + } + } + return nil +} + +func finiteFloat(value float32) bool { + return !math.IsNaN(float64(value)) && !math.IsInf(float64(value), 0) +} + +// MaxOffscreenSize is the largest side, in device pixels, of an offscreen scene. +const MaxOffscreenSize = 16384 diff --git a/internal/platform/linux/api_linux_test.go b/internal/platform/linux/api_linux_test.go index 966d15127..f826d6973 100644 --- a/internal/platform/linux/api_linux_test.go +++ b/internal/platform/linux/api_linux_test.go @@ -1,19 +1,12 @@ package linux import ( - "bytes" "encoding/binary" - "errors" - "fmt" "math" "os" - "path/filepath" - "slices" - "strings" "testing" "unsafe" - "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/internal/platform" "github.com/vivaui/viva/internal/render" "github.com/vivaui/viva/internal/scene" @@ -28,6 +21,7 @@ func TestNativeStructureABI(t *testing.T) { size uintptr want uintptr }{ + {"VkXcbSurfaceCreateInfoKHR", unsafe.Sizeof(vkXcbSurfaceCreateInfo{}), 40}, {"xcb_screen_t", unsafe.Sizeof(xcbScreen{}), 40}, {"xcb_screen_iterator_t", unsafe.Sizeof(xcbScreenIterator{}), 16}, {"xcb_setup_t", unsafe.Sizeof(xcbSetup{}), 40}, @@ -47,85 +41,11 @@ func TestNativeStructureABI(t *testing.T) { {"xcb_selection_notify_wire", unsafe.Sizeof(xcbSelectionNotifyWire{}), 32}, {"pollfd", unsafe.Sizeof(pollFD{}), 8}, {"xcb_translate_coordinates_reply_t", unsafe.Sizeof(xcbTranslateReply{}), 16}, - {"VkApplicationInfo", unsafe.Sizeof(vkApplicationInfo{}), 48}, - {"VkInstanceCreateInfo", unsafe.Sizeof(vkInstanceCreateInfo{}), 64}, - {"VkXcbSurfaceCreateInfoKHR", unsafe.Sizeof(vkXcbSurfaceCreateInfo{}), 40}, - {"VkQueueFamilyProperties", unsafe.Sizeof(vkQueueFamilyProperties{}), 24}, - {"VkDeviceQueueCreateInfo", unsafe.Sizeof(vkDeviceQueueCreateInfo{}), 40}, - {"VkDeviceCreateInfo", unsafe.Sizeof(vkDeviceCreateInfo{}), 72}, - {"VkSurfaceCapabilitiesKHR", unsafe.Sizeof(vkSurfaceCapabilities{}), 52}, - {"VkSwapchainCreateInfoKHR", unsafe.Sizeof(vkSwapchainCreateInfo{}), 104}, - {"VkImageViewCreateInfo", unsafe.Sizeof(vkImageViewCreateInfo{}), 80}, - {"VkAttachmentDescription", unsafe.Sizeof(vkAttachmentDescription{}), 36}, - {"VkSubpassDescription", unsafe.Sizeof(vkSubpassDescription{}), 72}, - {"VkRenderPassCreateInfo", unsafe.Sizeof(vkRenderPassCreateInfo{}), 64}, - {"VkFramebufferCreateInfo", unsafe.Sizeof(vkFramebufferCreateInfo{}), 64}, - {"VkCommandPoolCreateInfo", unsafe.Sizeof(vkCommandPoolCreateInfo{}), 24}, - {"VkCommandBufferAllocateInfo", unsafe.Sizeof(vkCommandBufferAllocateInfo{}), 32}, - {"VkCommandBufferBeginInfo", unsafe.Sizeof(vkCommandBufferBeginInfo{}), 32}, - {"VkClearAttachment", unsafe.Sizeof(vkClearAttachment{}), 24}, - {"VkClearRect", unsafe.Sizeof(vkClearRect{}), 24}, - {"VkRenderPassBeginInfo", unsafe.Sizeof(vkRenderPassBeginInfo{}), 64}, - {"VkSemaphoreCreateInfo", unsafe.Sizeof(vkSemaphoreCreateInfo{}), 24}, - {"VkSubmitInfo", unsafe.Sizeof(vkSubmitInfo{}), 72}, - {"VkPresentInfoKHR", unsafe.Sizeof(vkPresentInfo{}), 64}, - {"VkPhysicalDeviceMemoryProperties", unsafe.Sizeof(vkPhysicalDeviceMemoryProperties{}), 520}, - {"VkMemoryRequirements", unsafe.Sizeof(vkMemoryRequirements{}), 24}, - {"VkBufferCreateInfo", unsafe.Sizeof(vkBufferCreateInfo{}), 56}, - {"VkMemoryAllocateInfo", unsafe.Sizeof(vkMemoryAllocateInfo{}), 32}, - {"VkShaderModuleCreateInfo", unsafe.Sizeof(vkShaderModuleCreateInfo{}), 40}, - {"VkPipelineShaderStageCreateInfo", unsafe.Sizeof(vkPipelineShaderStageCreateInfo{}), 48}, - {"VkVertexInputBindingDescription", unsafe.Sizeof(vkVertexInputBindingDescription{}), 12}, - {"VkVertexInputAttributeDescription", unsafe.Sizeof(vkVertexInputAttributeDescription{}), 16}, - {"VkPipelineVertexInputStateCreateInfo", unsafe.Sizeof(vkPipelineVertexInputStateCreateInfo{}), 48}, - {"VkPipelineInputAssemblyStateCreateInfo", unsafe.Sizeof(vkPipelineInputAssemblyStateCreateInfo{}), 32}, - {"VkPipelineViewportStateCreateInfo", unsafe.Sizeof(vkPipelineViewportStateCreateInfo{}), 48}, - {"VkPipelineRasterizationStateCreateInfo", unsafe.Sizeof(vkPipelineRasterizationStateCreateInfo{}), 64}, - {"VkPipelineMultisampleStateCreateInfo", unsafe.Sizeof(vkPipelineMultisampleStateCreateInfo{}), 48}, - {"VkPipelineColorBlendAttachmentState", unsafe.Sizeof(vkPipelineColorBlendAttachmentState{}), 32}, - {"VkPipelineColorBlendStateCreateInfo", unsafe.Sizeof(vkPipelineColorBlendStateCreateInfo{}), 56}, - {"VkPipelineDynamicStateCreateInfo", unsafe.Sizeof(vkPipelineDynamicStateCreateInfo{}), 32}, - {"VkPushConstantRange", unsafe.Sizeof(vkPushConstantRange{}), 12}, - {"VkPipelineLayoutCreateInfo", unsafe.Sizeof(vkPipelineLayoutCreateInfo{}), 48}, - {"VkGraphicsPipelineCreateInfo", unsafe.Sizeof(vkGraphicsPipelineCreateInfo{}), 144}, - {"VkViewport", unsafe.Sizeof(vkViewport{}), 24}, - {"VkExtent3D", unsafe.Sizeof(vkExtent3D{}), 12}, - {"VkImageCreateInfo", unsafe.Sizeof(vkImageCreateInfo{}), 88}, - {"VkSamplerCreateInfo", unsafe.Sizeof(vkSamplerCreateInfo{}), 80}, - {"VkDescriptorSetLayoutBinding", unsafe.Sizeof(vkDescriptorSetLayoutBinding{}), 24}, - {"VkDescriptorSetLayoutCreateInfo", unsafe.Sizeof(vkDescriptorSetLayoutCreateInfo{}), 32}, - {"VkDescriptorPoolSize", unsafe.Sizeof(vkDescriptorPoolSize{}), 8}, - {"VkDescriptorPoolCreateInfo", unsafe.Sizeof(vkDescriptorPoolCreateInfo{}), 40}, - {"VkDescriptorSetAllocateInfo", unsafe.Sizeof(vkDescriptorSetAllocateInfo{}), 40}, - {"VkDescriptorImageInfo", unsafe.Sizeof(vkDescriptorImageInfo{}), 24}, - {"VkWriteDescriptorSet", unsafe.Sizeof(vkWriteDescriptorSet{}), 64}, - {"VkImageMemoryBarrier", unsafe.Sizeof(vkImageMemoryBarrier{}), 72}, - {"VkImageSubresourceLayers", unsafe.Sizeof(vkImageSubresourceLayers{}), 16}, - {"VkBufferImageCopy", unsafe.Sizeof(vkBufferImageCopy{}), 56}, - {"scene instance", unsafe.Sizeof(vulkanRectangleInstance{}), 80}, } { if layout.size != layout.want { t.Errorf("%s size %d, want %d", layout.name, layout.size, layout.want) } } - if offset := unsafe.Offsetof(vkImageCreateInfo{}.QueueFamilies); offset != 72 { - t.Errorf("VkImageCreateInfo.pQueueFamilyIndices offset %d, want 72", offset) - } - if offset := unsafe.Offsetof(vkImageCreateInfo{}.InitialLayout); offset != 80 { - t.Errorf("VkImageCreateInfo.initialLayout offset %d, want 80", offset) - } -} - -func TestClamp(t *testing.T) { - if clamp(1, 2, 4) != 2 || clamp(3, 2, 4) != 3 || clamp(5, 2, 4) != 4 { - t.Fatal("clamp result mismatch") - } -} - -func TestVulkanResult(t *testing.T) { - if vkCheck(vkSuccess, "test") != nil || vkCheck(-1, "test") == nil { - t.Fatal("Vulkan result classification mismatch") - } } func TestValidateConfig(t *testing.T) { @@ -174,283 +94,6 @@ func TestValidateConfig(t *testing.T) { } } -func TestRectangleClearClipsAndClamps(t *testing.T) { - attachment, clear, visible := rectangleClear(render.Rectangle{ - Bounds: scene.Rect{X: -2.25, Y: 1.2, Width: 5, Height: 3.1}, - Color: scene.Color{Red: -1, Green: 0.5, Blue: 2, Alpha: 1}, - }, 4, 4) - if !visible { - t.Fatal("partially visible rectangle was discarded") - } - if clear.Rect.Offset != [2]int32{0, 1} || clear.Rect.Extent != (vkExtent2D{Width: 3, Height: 3}) { - t.Fatalf("clear bounds = %+v", clear.Rect) - } - if clear.BaseArrayLayer != 0 || clear.LayerCount != 1 { - t.Fatalf("clear layers = %d..%d", clear.BaseArrayLayer, clear.LayerCount) - } - if attachment.AspectMask != vkImageAspectColor || attachment.ColorAttachment != 0 { - t.Fatalf("clear attachment = %+v", attachment) - } - if attachment.ClearValue.Color != [4]float32{0, 0.5, 1, 1} { - t.Fatalf("clear color = %v", attachment.ClearValue.Color) - } - - for _, bounds := range []scene.Rect{ - {X: 4, Width: 1, Height: 1}, - {Y: 4, Width: 1, Height: 1}, - {Width: 0, Height: 1}, - {Width: 1, Height: -1}, - } { - if _, _, visible := rectangleClear(render.Rectangle{Bounds: bounds}, 4, 4); visible { - t.Fatalf("invisible bounds %+v produced a clear", bounds) - } - } -} - -func TestRecordCommandsDrawsSceneInstances(t *testing.T) { - var begins, renderBegins, renderEnds, ends, binds, draws int - renderer := vulkanRenderer{ - api: &vulkanAPI{ - beginCommandBuffer: func(uintptr, *vkCommandBufferBeginInfo) int32 { - begins++ - return vkSuccess - }, - cmdBeginRenderPass: func(uintptr, *vkRenderPassBeginInfo, uint32) { - renderBegins++ - }, - cmdBindPipeline: func(_ uintptr, bindPoint uint32, pipeline uintptr) { - if bindPoint != vkPipelineBindPointGraphics || pipeline != 7 { - t.Fatalf("pipeline = %d, %d", bindPoint, pipeline) - } - binds++ - }, - cmdSetViewport: func(uintptr, uint32, uint32, *vkViewport) {}, - cmdSetScissor: func(uintptr, uint32, uint32, *vkRect2D) {}, - cmdPushConstants: func(uintptr, uintptr, uint32, uint32, uint32, unsafe.Pointer) {}, - cmdBindVertexBuffers: func(_ uintptr, _ uint32, count uint32, buffers *uintptr, offsets *uint64) { - if count != 1 || *buffers != 8 || *offsets != 0 { - t.Fatalf("vertex binding = %d, %d, %d", count, *buffers, *offsets) - } - }, - cmdDraw: func(_ uintptr, vertices, instances, firstVertex, firstInstance uint32) { - if vertices != 6 || instances != 2 || firstVertex != 0 || firstInstance != 0 { - t.Fatalf("draw = %d, %d, %d, %d", vertices, instances, firstVertex, firstInstance) - } - draws++ - }, - cmdEndRenderPass: func(uintptr) { - renderEnds++ - }, - endCommandBuffer: func(uintptr) int32 { - ends++ - return vkSuccess - }, - }, - commands: []uintptr{1, 2}, - framebuffers: []uintptr{3, 4}, - scene: vulkanScene{pipeline: 7, pipelineLayout: 9, buffer: 8, instances: make([]vulkanRectangleInstance, 2)}, - rectangleBatches: []render.Batch{{First: 0, Count: 2}}, - compositingBatches: []compositingBatch{{Kind: compositeRectangles, First: 0, Count: 2}}, - } - if err := renderer.recordCommands(vkExtent2D{Width: 4, Height: 4}); err != nil { - t.Fatal(err) - } - if begins != 2 || renderBegins != 2 || renderEnds != 2 || ends != 2 { - t.Fatalf("command lifecycle = %d %d %d %d", begins, renderBegins, renderEnds, ends) - } - if binds != 2 || draws != 2 { - t.Fatalf("scene commands = %d binds, %d draws", binds, draws) - } -} - -func TestRecordCommandsScissorsClippedBatches(t *testing.T) { - var events []string - var scissor vkRect2D - renderer := vulkanRenderer{ - api: &vulkanAPI{ - beginCommandBuffer: func(uintptr, *vkCommandBufferBeginInfo) int32 { return vkSuccess }, - cmdBeginRenderPass: func(uintptr, *vkRenderPassBeginInfo, uint32) {}, - cmdBindPipeline: func(uintptr, uint32, uintptr) {}, - cmdSetViewport: func(uintptr, uint32, uint32, *vkViewport) {}, - cmdSetScissor: func(_ uintptr, _, _ uint32, rect *vkRect2D) { - scissor = *rect - events = append(events, fmt.Sprintf("scissor %d,%d %dx%d", rect.Offset[0], rect.Offset[1], rect.Extent.Width, rect.Extent.Height)) - }, - cmdPushConstants: func(uintptr, uintptr, uint32, uint32, uint32, unsafe.Pointer) {}, - cmdBindVertexBuffers: func(uintptr, uint32, uint32, *uintptr, *uint64) {}, - cmdDraw: func(_ uintptr, _, _, _, first uint32) { - events = append(events, fmt.Sprintf("draw %d with %d,%d %dx%d", first, scissor.Offset[0], scissor.Offset[1], scissor.Extent.Width, scissor.Extent.Height)) - }, - cmdEndRenderPass: func(uintptr) {}, - endCommandBuffer: func(uintptr) int32 { return vkSuccess }, - }, - commands: []uintptr{1}, - framebuffers: []uintptr{2}, - scene: vulkanScene{pipeline: 7, pipelineLayout: 9, buffer: 8, instances: make([]vulkanRectangleInstance, 3)}, - compositingBatches: []compositingBatch{ - {Kind: compositeRectangles, Clipped: true, Clip: scene.Rect{X: 2, Y: 3, Width: 4, Height: 5}, First: 0, Count: 1}, - {Kind: compositeRectangles, Clipped: true, Clip: scene.Rect{X: 100, Y: 100, Width: 4, Height: 4}, First: 1, Count: 1}, - {Kind: compositeRectangles, First: 2, Count: 1}, - }, - } - if err := renderer.recordCommands(vkExtent2D{Width: 20, Height: 30}); err != nil { - t.Fatal(err) - } - want := []string{ - "scissor 2,3 4x5", "draw 0 with 2,3 4x5", - "scissor 0,0 20x30", "draw 2 with 0,0 20x30", - } - if !slices.Equal(events, want) { - t.Fatalf("events = %q, want %q", events, want) - } -} - -func TestVulkanRectangleInstancesMatchNativeBackends(t *testing.T) { - rectangle := makeVulkanRectangleInstance(render.Rectangle{ - Bounds: scene.Rect{X: 1, Y: 2, Width: 3, Height: 4}, - Color: scene.Color{Red: 0.1, Green: 0.2, Blue: 0.3, Alpha: 0.4}, Radius: 5, - }) - if rectangle.Bounds != [4]float32{1, 2, 3, 4} || rectangle.Color != [4]float32{0.1, 0.2, 0.3, 0.4} || rectangle.Style != [4]float32{5, 0, 0, 0} { - t.Fatalf("rectangle instance = %+v", rectangle) - } - triangle := makeVulkanRectangleInstance(render.Rectangle{ - Kind: scene.KindTriangle, Points: [3]scene.Point{{X: 1, Y: 2}, {X: 3, Y: 4}, {X: 5, Y: 6}}, - Color: scene.Color{Alpha: 1}, Layer: 9, EdgeMask: 5, - }) - if triangle.Bounds != [4]float32{1, 2, 3, 4} || triangle.Style != [4]float32{5, 9, 6, 6} { - t.Fatalf("triangle instance = %+v", triangle) - } -} - -func TestVulkanSceneUploadWritesOnlyChangedRange(t *testing.T) { - storage := make([]byte, 3*vkInstanceBytes) - sceneState := vulkanScene{capacity: 3, mapped: unsafe.Pointer(&storage[0])} - rectangles := []render.Rectangle{ - {Bounds: scene.Rect{X: 1, Width: 10}, Color: scene.Color{Alpha: 1}}, - {Bounds: scene.Rect{X: 2, Width: 20}, Color: scene.Color{Alpha: 1}}, - {Bounds: scene.Rect{X: 3, Width: 30}, Color: scene.Color{Alpha: 1}}, - } - if err := sceneState.upload(&vulkanRenderer{}, rectangles, render.Update{Count: len(rectangles), Rebuild: true}); err != nil { - t.Fatal(err) - } - first := append([]byte(nil), storage[:vkInstanceBytes]...) - last := append([]byte(nil), storage[2*vkInstanceBytes:]...) - rectangles[1].Bounds.Width = 99 - if err := sceneState.upload(&vulkanRenderer{}, rectangles, render.Update{First: 1, Count: 1}); err != nil { - t.Fatal(err) - } - if !bytes.Equal(storage[:vkInstanceBytes], first) || !bytes.Equal(storage[2*vkInstanceBytes:], last) { - t.Fatal("partial upload changed untouched GPU instance ranges") - } - if sceneState.instances[1].Bounds[2] != 99 { - t.Fatalf("updated instance width = %g", sceneState.instances[1].Bounds[2]) - } -} - -func TestVulkanSceneUploadShrinksRetainedInstances(t *testing.T) { - storage := make([]byte, 3*vkInstanceBytes) - sceneState := vulkanScene{capacity: 3, mapped: unsafe.Pointer(&storage[0])} - rectangles := []render.Rectangle{ - {Bounds: scene.Rect{X: 1, Width: 10}, Color: scene.Color{Alpha: 1}}, - {Bounds: scene.Rect{X: 2, Width: 20}, Color: scene.Color{Alpha: 1}}, - {Bounds: scene.Rect{X: 3, Width: 30}, Color: scene.Color{Alpha: 1}}, - } - if err := sceneState.upload(&vulkanRenderer{}, rectangles, render.Update{Count: len(rectangles), Rebuild: true}); err != nil { - t.Fatal(err) - } - rectangles[1].Bounds.Width = 99 - if err := sceneState.upload(&vulkanRenderer{}, rectangles[:2], render.Update{First: 1, Count: 1, Shrink: true}); err != nil { - t.Fatal(err) - } - if len(sceneState.instances) != 2 || sceneState.instances[1].Bounds[2] != 99 { - t.Fatalf("shrunk instances = %d, second width %g", len(sceneState.instances), sceneState.instances[1].Bounds[2]) - } - if err := sceneState.upload(&vulkanRenderer{}, rectangles[:1], render.Update{First: 1, Count: 0}); err == nil { - t.Fatal("shrink without Shrink accepted") - } -} - -func TestSwapchainStatusClassification(t *testing.T) { - if swapchainNeedsRebuild(vkSuccess) || swapchainNeedsRebuild(vkSuboptimal) || !swapchainNeedsRebuild(vkErrorOutOfDate) { - t.Fatal("unexpected swapchain status classification") - } -} - -func TestVulkanRectangleSmoke(t *testing.T) { - if testing.Short() || os.Getenv("VIVA_LINUX_VULKAN_SMOKE") == "" { - t.Skip("set VIVA_LINUX_VULKAN_SMOKE=1 with an X11 display and Vulkan driver") - } - t.Setenv("VIVA_TEST_AUTOCLOSE", "1") - err := Run(platform.Config{ - Title: "Viva Linux text smoke", - Width: 160, - Height: 100, - WindowMode: platform.WindowTitled, - ClearColor: platform.Color{Red: 0.05, Green: 0.05, Blue: 0.05, Alpha: 1}, - Rectangles: []render.Rectangle{ - {Bounds: scene.Rect{X: 8, Y: 8, Width: 96, Height: 56}, Radius: 12, Color: scene.Color{Red: 1, Alpha: 0.8}}, - {Bounds: scene.Rect{X: 48, Y: 32, Width: 96, Height: 56}, Radius: 18, Color: scene.Color{Blue: 1, Alpha: 0.8}}, - {Kind: scene.KindTriangle, Points: [3]scene.Point{{X: 20, Y: 90}, {X: 80, Y: 20}, {X: 140, Y: 90}}, Color: scene.Color{Green: 1, Alpha: 0.7}, EdgeMask: 7}, - }, - TextLabels: []platform.TextLabel{ - {Value: "Viva 原生界面", X: 16, Y: 10, Width: 132, Height: 24, FontSize: 16, Color: platform.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1}, Layer: 2}, - }, - }) - if err != nil { - t.Fatal(err) - } -} - -func TestCreateSwapchainCleansPartialResources(t *testing.T) { - var destroyed uintptr - renderer := vulkanRenderer{ - api: &vulkanAPI{ - getSurfaceCapabilities: func(_ uintptr, _ uintptr, capabilities *vkSurfaceCapabilities) int32 { - *capabilities = vkSurfaceCapabilities{ - MinImages: 1, - MaxImages: 2, - Current: vkExtent2D{Width: 640, Height: 480}, - CompositeAlpha: vkCompositeOpaque, - Usage: vkImageUsageColorAttachment, - } - return vkSuccess - }, - getSurfaceFormats: func(_ uintptr, _ uintptr, count *uint32, formats *vkSurfaceFormat) int32 { - *count = 1 - if formats != nil { - *formats = vkSurfaceFormat{Format: vkFormatBGRA8, ColorSpace: vkColorSpaceSRGB} - } - return vkSuccess - }, - createSwapchain: func(_ uintptr, _ *vkSwapchainCreateInfo, _ unsafe.Pointer, swapchain *uintptr) int32 { - *swapchain = 42 - return vkSuccess - }, - getSwapchainImages: func(_ uintptr, _ uintptr, _ *uint32, _ *uintptr) int32 { - return -1 - }, - destroySwapchain: func(_ uintptr, swapchain uintptr, _ unsafe.Pointer) { - destroyed = swapchain - }, - }, - physical: 1, - device: 2, - surface: 3, - width: 640, - height: 480, - } - - if err := renderer.createSwapchain(); err == nil { - t.Fatal("createSwapchain succeeded") - } - if destroyed != 42 { - t.Fatalf("destroyed swapchain %d, want 42", destroyed) - } - if renderer.swapchain != 0 { - t.Fatalf("swapchain retained after failure: %d", renderer.swapchain) - } -} - // The fields the status-area code reads sit where the X11 protocol puts them: a // wrong offset would read the wrong byte of an event without any error. func TestStatusAreaEventFieldOffsets(t *testing.T) { @@ -470,550 +113,6 @@ func TestStatusAreaEventFieldOffsets(t *testing.T) { } } -// A machine with no Vulkan reports it as platform.ErrNoGraphics, so an -// application can tell "this server has no graphics" from a real failure, and the -// text carries the cause and what to install. -func TestMissingVulkanIsNamedAndSaysWhatToInstall(t *testing.T) { - cause := errors.New("libvulkan.so.1: cannot open shared object file") - for name, err := range map[string]error{ - "no loader": noVulkan("libvulkan.so.1 is not installed", cause), - "no device": noVulkan("Vulkan reports no device", nil), - } { - if !errors.Is(err, platform.ErrNoGraphics) { - t.Errorf("%s: %v does not wrap platform.ErrNoGraphics", name, err) - } - if !strings.Contains(err.Error(), "mesa-vulkan-drivers") { - t.Errorf("%s: %q does not say what to install", name, err) - } - } - if err := noVulkan("x", cause); !errors.Is(err, cause) { - t.Errorf("the cause is lost: %v", err) - } -} - -func TestVulkanDriverManifestDetection(t *testing.T) { - dir := t.TempDir() - if err := os.WriteFile(filepath.Join(dir, "notes.txt"), []byte("not a driver"), 0o600); err != nil { - t.Fatal(err) - } - if vulkanDriverManifestsExist([]string{dir}) { - t.Fatal("a directory without an ICD manifest counts as a Vulkan driver") - } - manifest := filepath.Join(dir, "driver.json") - if err := os.WriteFile(manifest, []byte("{}"), 0o600); err != nil { - t.Fatal(err) - } - if !vulkanDriverManifestsExist([]string{dir}) || !vulkanDriverManifestsExist([]string{manifest}) { - t.Fatal("an ICD manifest was not detected") - } -} - -func TestVulkanWithoutDriverManifestDoesNotLoadDriver(t *testing.T) { - t.Setenv("VK_DRIVER_FILES", filepath.Join(t.TempDir(), "missing.json")) - t.Setenv("VK_ICD_FILENAMES", "") - t.Setenv("VK_ADD_DRIVER_FILES", "") - if vulkanDriverConfigured() { - t.Fatal("a missing ICD manifest counts as a Vulkan driver") - } - _, err := openVulkan() - if !errors.Is(err, platform.ErrNoGraphics) { - t.Fatalf("openVulkan error = %v, want platform.ErrNoGraphics", err) - } -} - -func TestVulkanEmptyICDOverrideDoesNotUseDefaultManifests(t *testing.T) { - root := t.TempDir() - t.Setenv("HOME", root) - t.Setenv("XDG_DATA_HOME", root) - writeVulkanManifest(t, filepath.Join(root, "vulkan", "icd.d")) - t.Setenv("VK_DRIVER_FILES", "") - t.Setenv("VK_ICD_FILENAMES", "") - unsetTestEnv(t, "VK_ADD_DRIVER_FILES") - if vulkanDriverConfigured() { - t.Fatal("an empty ICD override falls back to the default driver manifests") - } -} - -// The default search reads each XDG base the loader reads. Only positive cases are -// checked: the system's /etc/vulkan/icd.d is always searched, so an empty result -// cannot be asserted on a machine that has a driver installed. -func TestVulkanDefaultManifestSearchFindsEachXDGDirectory(t *testing.T) { - cases := []struct { - name string - // env sets the search variables under root, and returns the base whose - // vulkan/icd.d holds the manifest. - env func(t *testing.T, root string) string - }{ - {"config home", func(t *testing.T, root string) string { - t.Setenv("XDG_CONFIG_HOME", filepath.Join(root, "config")) - return filepath.Join(root, "config") - }}, - {"home default config", func(t *testing.T, root string) string { - t.Setenv("HOME", root) - return filepath.Join(root, ".config") - }}, - {"config dirs", func(t *testing.T, root string) string { - t.Setenv("XDG_CONFIG_DIRS", filepath.Join(root, "missing")+":"+filepath.Join(root, "xdg")) - return filepath.Join(root, "xdg") - }}, - {"data home", func(t *testing.T, root string) string { - t.Setenv("XDG_DATA_HOME", filepath.Join(root, "data")) - return filepath.Join(root, "data") - }}, - {"data dirs", func(t *testing.T, root string) string { - t.Setenv("XDG_DATA_DIRS", filepath.Join(root, "share")) - return filepath.Join(root, "share") - }}, - } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - root := t.TempDir() - t.Setenv("HOME", filepath.Join(root, "home")) - t.Setenv("XDG_CONFIG_DIRS", "") - t.Setenv("XDG_DATA_DIRS", "") - unsetTestEnv(t, "XDG_CONFIG_HOME") - unsetTestEnv(t, "XDG_DATA_HOME") - unsetTestEnv(t, "VK_DRIVER_FILES") - unsetTestEnv(t, "VK_ICD_FILENAMES") - unsetTestEnv(t, "VK_ADD_DRIVER_FILES") - base := tc.env(t, root) - writeVulkanManifest(t, filepath.Join(base, "vulkan", "icd.d")) - if !vulkanDriverConfigured() { - t.Fatalf("a manifest under the %s was not found", tc.name) - } - }) - } -} - -// unsetTestEnv removes name for the rest of the test. t.Setenv restores the original -// value at cleanup, which the bare os.Unsetenv alone would not. -func unsetTestEnv(t *testing.T, name string) { - t.Helper() - t.Setenv(name, "") - if err := os.Unsetenv(name); err != nil { - t.Fatal(err) - } -} - -func writeVulkanManifest(t *testing.T, dir string) { - t.Helper() - if err := os.MkdirAll(dir, 0o700); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(filepath.Join(dir, "driver.json"), []byte("{}"), 0o600); err != nil { - t.Fatal(err) - } -} - -// A loader whose installed drivers fail to initialize fails enumeration with -// VK_ERROR_INITIALIZATION_FAILED (a driver-less loader gives -// VK_ERROR_INCOMPATIBLE_DRIVER). That is still a machine that cannot draw, not a -// rendering failure: the application must be able to tell them apart and the text -// must say what to install. Any other enumeration result stays a real failure. -func TestUnusableVulkanDriverIsNamedAndSaysWhatToInstall(t *testing.T) { - device := func(status int32) *vulkanDevice { - return &vulkanDevice{api: &vulkanAPI{ - enumeratePhysicalDevices: func(uintptr, *uint32, *uintptr) int32 { return status }, - }} - } - for _, status := range []int32{vkErrorInitializationFailed, vkErrorIncompatibleDriver} { - err := device(status).selectPhysical(0) - if !errors.Is(err, platform.ErrNoGraphics) { - t.Errorf("result %d: %v does not wrap platform.ErrNoGraphics", status, err) - } - if !strings.Contains(err.Error(), "mesa-vulkan-drivers") { - t.Errorf("result %d: %q does not say what to install", status, err) - } - if !strings.Contains(err.Error(), fmt.Sprint(status)) { - t.Errorf("result %d: %q does not report the Vulkan result", status, err) - } - } - if err := device(-1).selectPhysical(0); errors.Is(err, platform.ErrNoGraphics) { - t.Errorf("a real failure is reported as no graphics: %v", err) - } -} - -func newSuboptimalTestRenderer(acquireStatus, presentStatus int32, recreations *int) *vulkanRenderer { - return &vulkanRenderer{ - device: 10, - queue: 20, - swapchain: 30, - commands: []uintptr{40}, - framebuffers: []uintptr{45}, - fence: 50, - api: &vulkanAPI{ - waitForFences: func(uintptr, uint32, *uintptr, uint32, uint64) int32 { return vkSuccess }, - resetFences: func(uintptr, uint32, *uintptr) int32 { return vkSuccess }, - acquireNextImage: func(_, swapchain uintptr, _ uint64, _, _ uintptr, image *uint32) int32 { - *image = 0 - if swapchain == 30 { - return acquireStatus - } - return vkSuccess - }, - queueSubmit: func(uintptr, uint32, *vkSubmitInfo, uintptr) int32 { return vkSuccess }, - queuePresent: func(_ uintptr, present *vkPresentInfo) int32 { - if *present.Swapchains == 30 { - return presentStatus - } - return vkSuccess - }, - deviceWaitIdle: func(uintptr) int32 { - *recreations++ - return vkSuccess - }, - getSurfaceCapabilities: func(_, _ uintptr, capabilities *vkSurfaceCapabilities) int32 { - capabilities.Current = vkExtent2D{Width: 100, Height: 100} - capabilities.MinImages = 2 - capabilities.CompositeAlpha = vkCompositeOpaque - capabilities.Usage = vkImageUsageColorAttachment - return vkSuccess - }, - getSurfaceFormats: func(_, _ uintptr, count *uint32, formats *vkSurfaceFormat) int32 { - *count = 1 - if formats != nil { - *formats = vkSurfaceFormat{Format: vkFormatBGRA8, ColorSpace: vkColorSpaceSRGB} - } - return vkSuccess - }, - createSwapchain: func(_ uintptr, _ *vkSwapchainCreateInfo, _ unsafe.Pointer, swapchain *uintptr) int32 { - *swapchain = 99 - return vkSuccess - }, - destroySwapchain: func(uintptr, uintptr, unsafe.Pointer) {}, - destroyImageView: func(uintptr, uintptr, unsafe.Pointer) {}, - destroyRenderPass: func(uintptr, uintptr, unsafe.Pointer) {}, - destroyFramebuffer: func(uintptr, uintptr, unsafe.Pointer) {}, - destroyCommandPool: func(uintptr, uintptr, unsafe.Pointer) {}, - destroyPipelineLayout: func(uintptr, uintptr, unsafe.Pointer) {}, - destroyPipeline: func(uintptr, uintptr, unsafe.Pointer) {}, - getSwapchainImages: func(_, _ uintptr, count *uint32, images *uintptr) int32 { - if images == nil { - *count = 1 - return vkSuccess - } - *images = 101 - return vkSuccess - }, - createImageView: func(_ uintptr, _ *vkImageViewCreateInfo, _ unsafe.Pointer, view *uintptr) int32 { - *view = 201 - return vkSuccess - }, - createRenderPass: func(_ uintptr, _ *vkRenderPassCreateInfo, _ unsafe.Pointer, renderPass *uintptr) int32 { - *renderPass = 301 - return vkSuccess - }, - createFramebuffer: func(_ uintptr, _ *vkFramebufferCreateInfo, _ unsafe.Pointer, framebuffer *uintptr) int32 { - *framebuffer = 401 - return vkSuccess - }, - createCommandPool: func(_ uintptr, _ *vkCommandPoolCreateInfo, _ unsafe.Pointer, pool *uintptr) int32 { - *pool = 501 - return vkSuccess - }, - allocateCommandBuffers: func(_ uintptr, _ *vkCommandBufferAllocateInfo, buffers *uintptr) int32 { - *buffers = 601 - return vkSuccess - }, - createPipelineLayout: func(_ uintptr, _ *vkPipelineLayoutCreateInfo, _ unsafe.Pointer, layout *uintptr) int32 { - *layout = 701 - return vkSuccess - }, - createShaderModule: func(_ uintptr, _ *vkShaderModuleCreateInfo, _ unsafe.Pointer, module *uintptr) int32 { - *module = 801 - return vkSuccess - }, - destroyShaderModule: func(uintptr, uintptr, unsafe.Pointer) {}, - createGraphicsPipelines: func(_, _ uintptr, _ uint32, _ *vkGraphicsPipelineCreateInfo, _ unsafe.Pointer, pipeline *uintptr) int32 { - *pipeline = 901 - return vkSuccess - }, - beginCommandBuffer: func(uintptr, *vkCommandBufferBeginInfo) int32 { return vkSuccess }, - cmdBeginRenderPass: func(uintptr, *vkRenderPassBeginInfo, uint32) {}, - cmdEndRenderPass: func(uintptr) {}, - endCommandBuffer: func(uintptr) int32 { return vkSuccess }, - }, - } -} - -func TestSuboptimalRecreatesAfterCompletedFrame(t *testing.T) { - for _, test := range []struct { - name string - acquireStatus int32 - presentStatus int32 - }{ - {name: "acquire", acquireStatus: vkSuboptimal, presentStatus: vkSuccess}, - {name: "present", acquireStatus: vkSuccess, presentStatus: vkSuboptimal}, - } { - t.Run(test.name, func(t *testing.T) { - recreations := 0 - renderer := newSuboptimalTestRenderer(test.acquireStatus, test.presentStatus, &recreations) - var presented []uintptr - basePresent := renderer.api.queuePresent - renderer.api.queuePresent = func(queue uintptr, present *vkPresentInfo) int32 { - presented = append(presented, *present.Swapchains) - return basePresent(queue, present) - } - if err := renderer.presentRebuilding(); err != nil { - t.Fatalf("presentRebuilding returned error: %v", err) - } - if renderer.submissions != 2 { - t.Fatalf("completed submissions = %d, want old and new swapchain frames", renderer.submissions) - } - if recreations != 1 { - t.Fatalf("swapchain recreations = %d, want 1", recreations) - } - if renderer.swapchain != 99 { - t.Fatalf("swapchain = %d, want recreated handle 99", renderer.swapchain) - } - if !slices.Equal(presented, []uintptr{30, 99}) { - t.Fatalf("presented swapchains = %v, want [30 99]", presented) - } - if renderer.swapchainSuboptimal { - t.Fatal("suboptimal flag survived successful recreation") - } - }) - } -} - -func TestSuboptimalRecreationConvergesAcrossFrames(t *testing.T) { - for _, test := range []struct { - name string - acquireStatus int32 - presentStatus int32 - keepReporting func(*vulkanRenderer) - }{ - { - name: "acquire", - acquireStatus: vkSuboptimal, - presentStatus: vkSuccess, - keepReporting: func(renderer *vulkanRenderer) { - renderer.api.acquireNextImage = func(_, _ uintptr, _ uint64, _, _ uintptr, image *uint32) int32 { - *image = 0 - return vkSuboptimal - } - }, - }, - { - name: "present", - acquireStatus: vkSuccess, - presentStatus: vkSuboptimal, - keepReporting: func(renderer *vulkanRenderer) { - renderer.api.queuePresent = func(uintptr, *vkPresentInfo) int32 { return vkSuboptimal } - }, - }, - { - name: "both", - acquireStatus: vkSuboptimal, - presentStatus: vkSuboptimal, - keepReporting: func(renderer *vulkanRenderer) { - renderer.api.acquireNextImage = func(_, _ uintptr, _ uint64, _, _ uintptr, image *uint32) int32 { - *image = 0 - return vkSuboptimal - } - renderer.api.queuePresent = func(uintptr, *vkPresentInfo) int32 { return vkSuboptimal } - }, - }, - } { - t.Run(test.name, func(t *testing.T) { - recreations := 0 - renderer := newSuboptimalTestRenderer(test.acquireStatus, test.presentStatus, &recreations) - test.keepReporting(renderer) - - for frame := 0; frame < 3; frame++ { - if err := renderer.presentRebuilding(); err != nil { - t.Fatalf("frame %d: presentRebuilding returned error: %v", frame, err) - } - if recreations != 1 { - t.Fatalf("frame %d: swapchain recreations = %d, want 1", frame, recreations) - } - if renderer.swapchain != 99 { - t.Fatalf("frame %d: swapchain = %d, want recreated handle 99", frame, renderer.swapchain) - } - if !renderer.swapchainSuboptimal { - t.Fatalf("frame %d: accepted swapchain forgot its SUBOPTIMAL status", frame) - } - } - if renderer.submissions != 4 { - t.Fatalf("completed submissions = %d, want the old and recreated frame plus two later frames", renderer.submissions) - } - }) - } -} - -func TestSuboptimalStatusClearsAfterHealthyFrame(t *testing.T) { - recreations := 0 - renderer := newSuboptimalTestRenderer(vkSuccess, vkSuboptimal, &recreations) - renderer.api.queuePresent = func(uintptr, *vkPresentInfo) int32 { return vkSuboptimal } - - if err := renderer.presentRebuilding(); err != nil { - t.Fatalf("presentRebuilding returned error: %v", err) - } - if recreations != 1 { - t.Fatalf("swapchain recreations = %d, want 1", recreations) - } - - // A healthy frame clears the accepted status without another recreation. - renderer.api.queuePresent = func(uintptr, *vkPresentInfo) int32 { return vkSuccess } - if err := renderer.presentRebuilding(); err != nil { - t.Fatalf("healthy frame returned error: %v", err) - } - if renderer.swapchainSuboptimal { - t.Fatal("healthy frame kept the accepted SUBOPTIMAL status") - } - if recreations != 1 { - t.Fatalf("healthy frame recreated the swapchain: recreations = %d, want 1", recreations) - } - - // A later SUBOPTIMAL is a fresh signal and gets its own single rebuild. - renderer.api.queuePresent = func(uintptr, *vkPresentInfo) int32 { return vkSuboptimal } - if err := renderer.presentRebuilding(); err != nil { - t.Fatalf("SUBOPTIMAL after healthy frame returned error: %v", err) - } - if recreations != 2 { - t.Fatalf("swapchain recreations = %d, want 2 after a fresh SUBOPTIMAL", recreations) - } - if !renderer.swapchainSuboptimal { - t.Fatal("fresh SUBOPTIMAL was not recorded") - } -} - -func TestOutOfDateRecoveryStaysBounded(t *testing.T) { - recreations := 0 - renderer := newSuboptimalTestRenderer(vkErrorOutOfDate, vkSuccess, &recreations) - - // The recreated swapchain is out of date as well. - renderer.api.acquireNextImage = func(_, _ uintptr, _ uint64, _, _ uintptr, image *uint32) int32 { - *image = 0 - return vkErrorOutOfDate - } - - if err := renderer.presentRebuilding(); err == nil { - t.Fatal("presentRebuilding accepted a swapchain that stayed out of date") - } - if recreations != 1 { - t.Fatalf("swapchain recreations = %d, want 1", recreations) - } - if renderer.swapchain != 99 { - t.Fatalf("swapchain = %d, want recreated handle 99", renderer.swapchain) - } - if renderer.submissions != 0 { - t.Fatalf("completed submissions = %d, want none for out-of-date frames", renderer.submissions) - } -} - -func TestOutOfDateRecoveryAcceptsResidualSuboptimal(t *testing.T) { - recreations := 0 - renderer := newSuboptimalTestRenderer(vkErrorOutOfDate, vkSuccess, &recreations) - // The old swapchain is out of date; the recreated one is suboptimal. - renderer.api.acquireNextImage = func(_, swapchain uintptr, _ uint64, _, _ uintptr, image *uint32) int32 { - *image = 0 - if swapchain == 30 { - return vkErrorOutOfDate - } - return vkSuboptimal - } - - if err := renderer.presentRebuilding(); err != nil { - t.Fatalf("presentRebuilding returned error: %v", err) - } - if recreations != 1 { - t.Fatalf("swapchain recreations = %d, want 1", recreations) - } - if !renderer.swapchainSuboptimal || !renderer.swapchainSuboptimalRebuilt { - t.Fatal("residual SUBOPTIMAL after OUT_OF_DATE recovery was not accepted") - } -} - -func TestPresentOutOfDateRebuilds(t *testing.T) { - recreations := 0 - renderer := newSuboptimalTestRenderer(vkSuccess, vkErrorOutOfDate, &recreations) - // Only the old swapchain presents out of date; the recreated one presents. - renderer.api.queuePresent = func(_ uintptr, present *vkPresentInfo) int32 { - if *present.Swapchains == 30 { - return vkErrorOutOfDate - } - return vkSuccess - } - - if err := renderer.presentRebuilding(); err != nil { - t.Fatalf("presentRebuilding returned error: %v", err) - } - if recreations != 1 { - t.Fatalf("swapchain recreations = %d, want 1", recreations) - } - if renderer.swapchain != 99 { - t.Fatalf("swapchain = %d, want recreated handle 99", renderer.swapchain) - } - if renderer.submissions != 2 { - t.Fatalf("completed submissions = %d, want the out-of-date present and the recreated one", renderer.submissions) - } -} - -func TestResizeRecordsStagedCommandsAtAnAlreadyMatchingExtent(t *testing.T) { - recreations, recordings := 0, 0 - renderer := newSuboptimalTestRenderer(vkSuccess, vkSuccess, &recreations) - renderer.width, renderer.height = 100, 100 - renderer.framebuffers = []uintptr{60} - renderer.api.resetCommandPool = func(uintptr, uintptr, uint32) int32 { return vkSuccess } - renderer.api.endCommandBuffer = func(uintptr) int32 { - recordings++ - return vkSuccess - } - // A staged scene makes the commands stale; a resize to the extent the - // surface already has rebuilds nothing, and the stale commands are recorded - // once, when their image is submitted. - if changed, err := renderer.stage(platform.Frame{TextLabels: []platform.TextLabel{}}); !changed || err != nil { - t.Fatalf("stage: changed=%v err=%v", changed, err) - } - if err := renderer.resize(100, 100); err != nil { - t.Fatal(err) - } - if recordings != 0 || recreations != 0 { - t.Fatalf("matching extent recorded %d times and rebuilt %d times", recordings, recreations) - } - for range 2 { - if err := renderer.ensureRecorded(0); err != nil { - t.Fatal(err) - } - } - if recordings != 1 { - t.Fatalf("submitting the stale image recorded it %d times, want once", recordings) - } -} - -func TestResizeOnceSuppressesSecondSuboptimalSwapchainRebuildDuringPresent(t *testing.T) { - recreations := 0 - renderer := newSuboptimalTestRenderer(vkSuccess, vkSuboptimal, &recreations) - renderer.width, renderer.height = 100, 100 - renderer.api.getSurfaceCapabilities = func(_, _ uintptr, capabilities *vkSurfaceCapabilities) int32 { - capabilities.Current = vkExtent2D{Width: renderer.width, Height: renderer.height} - capabilities.MinImages = 2 - capabilities.CompositeAlpha = vkCompositeOpaque - capabilities.Usage = vkImageUsageColorAttachment - return vkSuccess - } - renderer.api.queuePresent = func(uintptr, *vkPresentInfo) int32 { - return vkSuboptimal - } - - if err := renderer.resizeOnce(200, 150); err != nil { - t.Fatalf("resizeOnce returned error: %v", err) - } - if recreations != 1 { - t.Fatalf("recreations after resizeOnce = %d, want 1", recreations) - } - if err := renderer.presentRebuilding(); err != nil { - t.Fatalf("presentRebuilding returned error: %v", err) - } - if recreations != 1 { - t.Fatalf("recreations after presentRebuilding = %d, want 1 (no mid-present double rebuild)", recreations) - } - if renderer.submissions != 1 { - t.Fatalf("completed submissions = %d, want 1", renderer.submissions) - } -} - func TestNextEventCoalescesConfigureNotifyAndInterleavedSyncAndExpose(t *testing.T) { type rawEvent [32]byte var queue []unsafe.Pointer @@ -1117,119 +216,28 @@ func TestNextEventCoalescesConfigureNotifyAndInterleavedSyncAndExpose(t *testing } } -func TestTextureContentChangedPreservesLabelRunsTextureWhenGrowingWithinPreviousWidth(t *testing.T) { - runs := []gfx.TextRun{{Column: 0, Bytes: 5, Cells: 5}} - prev := platform.TextLabel{ - Value: "hello", - Width: 60, - Height: 20, - FontSize: 14, - CellWidth: 8, - Runs: runs, - } - nextWider := prev - nextWider.Width = 120 - if textureContentChanged(prev, nextWider) { - t.Fatal("textureContentChanged invalidated fixed-pitch run label when growing width past unchanged runs") - } - nextClipped := prev - nextClipped.Width = 40 - if !textureContentChanged(prev, nextClipped) { - t.Fatal("textureContentChanged did not invalidate fixed-pitch run label when shrinking width") - } -} - -func TestVulkanTextUpdatePreservesTexturesAcrossIndexShift(t *testing.T) { - makeLabel := func(val string, y float32) platform.TextLabel { - return platform.TextLabel{ - Value: val, - X: 10, - Y: y, - Width: 100, - Height: 20, - FontSize: 14, - CellWidth: 8, - Runs: []gfx.TextRun{{Column: 0, Bytes: int32(len(val)), Cells: int32(len(val))}}, - } - } - var textState vulkanText - initial := []platform.TextLabel{ - makeLabel("row-0", 0), - makeLabel("row-1", 20), - makeLabel("status-bar", 400), - } - if err := textState.update(nil, initial); err != nil { - t.Fatalf("initial update failed: %v", err) - } - // Simulate uploaded GPU handles on each slot. - for i := range textState.labels { - textState.labels[i].view = uintptr(100 + i) - textState.labels[i].image = uintptr(200 + i) - textState.labels[i].set = uintptr(300 + i) - } - - // Now insert a wrapped line between row-0 and row-1 during resize; - // row-1 and status-bar shift to indices 2 and 3. - shifted := []platform.TextLabel{ - makeLabel("row-0", 0), - makeLabel("wrapped-cont", 20), - makeLabel("row-1", 40), - makeLabel("status-bar", 420), - } - if err := textState.update(nil, shifted); err != nil { - t.Fatalf("shifted update failed: %v", err) - } - if textState.labels[0].view != 100 { - t.Fatalf("row-0 view = %d, want 100", textState.labels[0].view) - } - if textState.labels[1].view != 0 { - t.Fatalf("new wrapped-cont view = %d, want 0 (needs upload)", textState.labels[1].view) - } - if textState.labels[2].view != 101 || textState.labels[2].set != 301 { - t.Fatalf("shifted row-1 view/set = %d/%d, want 101/301", textState.labels[2].view, textState.labels[2].set) - } - if textState.labels[3].view != 102 || textState.labels[3].set != 302 { - t.Fatalf("shifted status-bar view/set = %d/%d, want 102/302", textState.labels[3].view, textState.labels[3].set) +func TestVulkanRectangleSmoke(t *testing.T) { + if testing.Short() || os.Getenv("VIVA_LINUX_VULKAN_SMOKE") == "" { + t.Skip("set VIVA_LINUX_VULKAN_SMOKE=1 with an X11 display and Vulkan driver") } -} - -func TestSelectPresentModePrefersFIFOWithMailboxFallback(t *testing.T) { - renderer := &vulkanRenderer{ - physical: 1, - surface: 2, - api: &vulkanAPI{ - getSurfacePresentModes: func(_, _ uintptr, count *uint32, modes *uint32) int32 { - offered := []uint32{vkPresentFIFO, vkPresentMailbox} - if modes == nil { - *count = uint32(len(offered)) - return vkSuccess - } - copy(unsafe.Slice(modes, int(*count)), offered) - return vkSuccess - }, + t.Setenv("VIVA_TEST_AUTOCLOSE", "1") + err := Run(platform.Config{ + Title: "Viva Linux text smoke", + Width: 160, + Height: 100, + WindowMode: platform.WindowTitled, + ClearColor: platform.Color{Red: 0.05, Green: 0.05, Blue: 0.05, Alpha: 1}, + Rectangles: []render.Rectangle{ + {Bounds: scene.Rect{X: 8, Y: 8, Width: 96, Height: 56}, Radius: 12, Color: scene.Color{Red: 1, Alpha: 0.8}}, + {Bounds: scene.Rect{X: 48, Y: 32, Width: 96, Height: 56}, Radius: 18, Color: scene.Color{Blue: 1, Alpha: 0.8}}, + {Kind: scene.KindTriangle, Points: [3]scene.Point{{X: 20, Y: 90}, {X: 80, Y: 20}, {X: 140, Y: 90}}, Color: scene.Color{Green: 1, Alpha: 0.7}, EdgeMask: 7}, }, - } - if got := renderer.selectPresentMode(); got != vkPresentFIFO { - t.Fatalf("selectPresentMode() = %d, want vkPresentFIFO (%d)", got, vkPresentFIFO) - } - - fifoOnly := &vulkanRenderer{ - physical: 1, - surface: 2, - api: &vulkanAPI{ - getSurfacePresentModes: func(_, _ uintptr, count *uint32, modes *uint32) int32 { - offered := []uint32{vkPresentFIFO} - if modes == nil { - *count = uint32(len(offered)) - return vkSuccess - } - copy(unsafe.Slice(modes, int(*count)), offered) - return vkSuccess - }, + TextLabels: []platform.TextLabel{ + {Value: "Viva 原生界面", X: 16, Y: 10, Width: 132, Height: 24, FontSize: 16, Color: platform.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1}, Layer: 2}, }, - } - if got := fifoOnly.selectPresentMode(); got != vkPresentFIFO { - t.Fatalf("selectPresentMode() = %d, want vkPresentFIFO (%d)", got, vkPresentFIFO) + }) + if err != nil { + t.Fatal(err) } } diff --git a/internal/platform/linux/cpu_lcd_linux_test.go b/internal/platform/linux/cpu_lcd_linux_test.go index 3ce2aa7fe..51ac9ef70 100644 --- a/internal/platform/linux/cpu_lcd_linux_test.go +++ b/internal/platform/linux/cpu_lcd_linux_test.go @@ -105,7 +105,7 @@ func TestCPULCDTextMatchesTheGPUPath(t *testing.T) { if err != nil { t.Fatal(err) } - dualSource := gpu.renderer.dualSource + dualSource := gpu.DualSource() if err := gpu.Set(nil, labels); err != nil { gpu.Close() t.Fatal(err) diff --git a/internal/platform/linux/cpu_offscreen_linux.go b/internal/platform/linux/cpu_offscreen_linux.go index b9e36ee7d..4c9f717df 100644 --- a/internal/platform/linux/cpu_offscreen_linux.go +++ b/internal/platform/linux/cpu_offscreen_linux.go @@ -30,12 +30,12 @@ type CPUOffscreen struct { // NewCPUOffscreen is NewOffscreen for the CPU: a width x height scene in logical pixels, drawn at // scale device pixels per logical pixel and cleared to clear before each render. func NewCPUOffscreen(width, height int, scale float64, clear platform.Color) (*CPUOffscreen, error) { - if width < 1 || height < 1 || width > offscreenLimit || height > offscreenLimit || math.IsNaN(scale) || scale < 1 || scale > maxScale { + if width < 1 || height < 1 || width > platform.MaxOffscreenSize || height > platform.MaxOffscreenSize || math.IsNaN(scale) || scale < 1 || scale > maxScale { return nil, fmt.Errorf("linux: invalid offscreen size %dx%d at %gx", width, height, scale) } deviceWidth, deviceHeight := int(math.Ceil(float64(width)*scale)), int(math.Ceil(float64(height)*scale)) - if deviceWidth > offscreenLimit || deviceHeight > offscreenLimit { - return nil, fmt.Errorf("linux: offscreen size %dx%d at %gx is beyond %d device pixels", width, height, scale, offscreenLimit) + if deviceWidth > platform.MaxOffscreenSize || deviceHeight > platform.MaxOffscreenSize { + return nil, fmt.Errorf("linux: offscreen size %dx%d at %gx is beyond %d device pixels", width, height, scale, platform.MaxOffscreenSize) } services, err := newTextServices() if err != nil { @@ -161,7 +161,7 @@ func rasterizeLabel(services *textServices, l platform.TextLabel, scale float32, case shownWidth <= width && shownHeight <= height && (shownWidth < width || shownHeight < height): return labelImage{pixels: platform.ResampleBGRA(l.Bitmap, l.BitmapStride, width, height, shownWidth, shownHeight), width: shownWidth, height: shownHeight}, true, nil } - return labelImage{pixels: tightBitmap(l.Bitmap, width, height, l.BitmapStride), width: width, height: height}, true, nil + return labelImage{pixels: platform.TightBitmap(l.Bitmap, width, height, l.BitmapStride), width: width, height: height}, true, nil } skip, width, height, wide, shown := textWindow(l, scale, canvasWidth, have) if !shown { @@ -176,8 +176,8 @@ func rasterizeLabel(services *textServices, l platform.TextLabel, scale float32, image.spans = make([]raster.Span, len(services.spans)) for index, span := range services.spans { image.spans[index] = raster.Span{ - From: span.left, To: span.right, - Color: scene.Color{Red: span.color[0], Green: span.color[1], Blue: span.color[2], Alpha: span.color[3]}, + From: span.Left, To: span.Right, + Color: scene.Color{Red: span.Color[0], Green: span.Color[1], Blue: span.Color[2], Alpha: span.Color[3]}, } } } diff --git a/internal/platform/linux/cpu_window_linux.go b/internal/platform/linux/cpu_window_linux.go index 69f30745f..8e989e112 100644 --- a/internal/platform/linux/cpu_window_linux.go +++ b/internal/platform/linux/cpu_window_linux.go @@ -4,6 +4,8 @@ import ( "fmt" "math" + "github.com/vivaui/viva/internal/platform/windowframe" + "github.com/vivaui/viva/internal/platform" "github.com/vivaui/viva/internal/raster" "github.com/vivaui/viva/internal/render" @@ -42,7 +44,7 @@ type cpuWindowRenderer struct { // cornerBox and cornerShadow keep the shadow under the four corner squares, // captured before the content covers it, so a damaged corner is composed // again from the content and the shadow instead of from the previous result. - cornerBox [4]pixelBox + cornerBox [4]windowframe.Box cornerShadow [4][]byte // full says the next present composes the whole window again. full bool @@ -66,7 +68,7 @@ func newCPUWindowRenderer(win *window, scale float32, clear platform.Color, rect if err != nil { return nil, err } - contentWidth, contentHeight := contentSize(win.width, win.margin), contentSize(win.height, win.margin) + contentWidth, contentHeight := windowframe.ContentSize(win.width, win.margin), windowframe.ContentSize(win.height, win.margin) scene, err := newSoftScene(services, int(contentWidth), int(contentHeight), scale, clear, rectangles, labels) if err != nil { services.close() @@ -194,25 +196,25 @@ func (renderer *cpuWindowRenderer) copyContent() { // shadowRectangle is the shadow the drawn frame casts: the content's rounded // rectangle, offset down and blurred, with the caster cut out by the rasterizer. func (renderer *cpuWindowRenderer) shadowRectangle() render.Rectangle { - box := frameContent(renderer.width, renderer.height, renderer.margin) + box := windowframe.Content(renderer.width, renderer.height, renderer.margin) scale := renderer.scale return render.Rectangle{ Kind: scene.KindShadow, - Bounds: scene.Rect{X: float32(box.x) / scale, Y: float32(box.y) / scale, Width: float32(box.width) / scale, Height: float32(box.height) / scale}, - Radius: frameRadiusLogical, - Color: scene.Color{Alpha: frameShadowAlpha}, - Shadow: scene.Shadow{OffsetY: frameShadowOffset, Blur: frameShadowBlur}, + Bounds: scene.Rect{X: float32(box.X) / scale, Y: float32(box.Y) / scale, Width: float32(box.Width) / scale, Height: float32(box.Height) / scale}, + Radius: windowframe.RadiusLogical, + Color: scene.Color{Alpha: windowframe.ShadowAlpha}, + Shadow: scene.Shadow{OffsetY: windowframe.ShadowOffset, Blur: windowframe.ShadowBlur}, } } // cacheCorners keeps the shadow under the four corner squares before the // content covers it, and the boxes those squares occupy. func (renderer *cpuWindowRenderer) cacheCorners() { - renderer.cornerBox = frameCorners(renderer.width, renderer.height, renderer.margin, frameRadiusLogical*renderer.scale) + renderer.cornerBox = windowframe.Corners(renderer.width, renderer.height, renderer.margin, windowframe.RadiusLogical*renderer.scale) for index, box := range renderer.cornerBox { box = clampBox(box, renderer.out) renderer.cornerBox[index] = box - width, height := int(box.width), int(box.height) + width, height := int(box.Width), int(box.Height) if width <= 0 || height <= 0 { renderer.cornerShadow[index] = nil continue @@ -223,7 +225,7 @@ func (renderer *cpuWindowRenderer) cacheCorners() { } shadow := renderer.cornerShadow[index][:need] for row := 0; row < height; row++ { - from := (int(box.y)+row)*renderer.out.Stride + int(box.x)*4 + from := (int(box.Y)+row)*renderer.out.Stride + int(box.X)*4 copy(shadow[row*width*4:(row+1)*width*4], renderer.out.Pix[from:from+width*4]) } renderer.cornerShadow[index] = shadow @@ -237,7 +239,7 @@ func (renderer *cpuWindowRenderer) maskCorner(index int, area render.Scissor) { if len(shadow) == 0 { return } - width := int(box.width) + width := int(box.Width) if width <= 0 { return } @@ -246,8 +248,8 @@ func (renderer *cpuWindowRenderer) maskCorner(index int, area render.Scissor) { rect := scene.Rect{X: float32(offset) / renderer.scale, Y: float32(offset) / renderer.scale, Width: float32(src.Width) / renderer.scale, Height: float32(src.Height) / renderer.scale} for y := area.Top; y < area.Bottom; y++ { for x := area.Left; x < area.Right; x++ { - coverage := raster.Coverage(rect, frameRadiusLogical, renderer.scale, x, y) - shadowAt := ((y-int(box.y))*width + (x - int(box.x))) * 4 + coverage := raster.Coverage(rect, windowframe.RadiusLogical, renderer.scale, x, y) + shadowAt := ((y-int(box.Y))*width + (x - int(box.X))) * 4 contentAt := (y-offset)*src.Stride + (x-offset)*4 pixel := y*out.Stride + x*4 for channel := 0; channel < 4; channel++ { @@ -311,7 +313,7 @@ func (renderer *cpuWindowRenderer) resize(width, height uint32) error { return nil } renderer.width, renderer.height = width, height - contentWidth, contentHeight := contentSize(width, renderer.margin), contentSize(height, renderer.margin) + contentWidth, contentHeight := windowframe.ContentSize(width, renderer.margin), windowframe.ContentSize(height, renderer.margin) if int(contentWidth) != renderer.scene.canvas.Width || int(contentHeight) != renderer.scene.canvas.Height { if err := renderer.scene.resize(int(contentWidth), int(contentHeight)); err != nil { return err @@ -344,7 +346,7 @@ func (renderer *cpuWindowRenderer) setFrameMargin(margin uint32) error { return nil } renderer.margin = margin - contentWidth, contentHeight := contentSize(renderer.width, margin), contentSize(renderer.height, margin) + contentWidth, contentHeight := windowframe.ContentSize(renderer.width, margin), windowframe.ContentSize(renderer.height, margin) if int(contentWidth) != renderer.scene.canvas.Width || int(contentHeight) != renderer.scene.canvas.Height { if err := renderer.scene.resize(int(contentWidth), int(contentHeight)); err != nil { return err @@ -408,14 +410,14 @@ func (renderer *cpuWindowRenderer) close() { renderer.cornerShadow = [4][]byte{} } -func scissorOfBox(box pixelBox) render.Scissor { - return render.Scissor{Left: int(box.x), Top: int(box.y), Right: int(box.x + box.width), Bottom: int(box.y + box.height)} +func scissorOfBox(box windowframe.Box) render.Scissor { + return render.Scissor{Left: int(box.X), Top: int(box.Y), Right: int(box.X + box.Width), Bottom: int(box.Y + box.Height)} } -func clampBox(box pixelBox, canvas *raster.Canvas) pixelBox { - left, top := max(box.x, 0), max(box.y, 0) - right, bottom := min(box.x+box.width, int32(canvas.Width)), min(box.y+box.height, int32(canvas.Height)) - return pixelBox{x: left, y: top, width: max(right-left, 0), height: max(bottom-top, 0)} +func clampBox(box windowframe.Box, canvas *raster.Canvas) windowframe.Box { + left, top := max(box.X, 0), max(box.Y, 0) + right, bottom := min(box.X+box.Width, int32(canvas.Width)), min(box.Y+box.Height, int32(canvas.Height)) + return windowframe.Box{X: left, Y: top, Width: max(right-left, 0), Height: max(bottom-top, 0)} } func intersectDamage(a, b render.Scissor) render.Scissor { diff --git a/internal/platform/linux/cpu_window_linux_test.go b/internal/platform/linux/cpu_window_linux_test.go index 7e3ca62f0..bf0b6699c 100644 --- a/internal/platform/linux/cpu_window_linux_test.go +++ b/internal/platform/linux/cpu_window_linux_test.go @@ -2,10 +2,11 @@ package linux import ( "bytes" - "encoding/binary" "testing" "unsafe" + "github.com/vivaui/viva/internal/platform/windowframe" + "github.com/vivaui/viva/internal/platform" "github.com/vivaui/viva/internal/raster" "github.com/vivaui/viva/internal/render" @@ -246,66 +247,13 @@ func BenchmarkCPUWindowPresent(b *testing.B) { }) } -// fakeVulkanAPI answers just enough for selectPhysical: the given physical -// devices in order and one graphics family that presents everywhere. -func fakeVulkanAPI(devices []uintptr, kinds map[uintptr]uint32) *vulkanAPI { - return &vulkanAPI{ - enumeratePhysicalDevices: func(_ uintptr, count *uint32, list *uintptr) int32 { - *count = uint32(len(devices)) - if list != nil { - copy(unsafe.Slice(list, len(devices)), devices) - } - return vkSuccess - }, - getQueueFamilyProperties: func(_ uintptr, count *uint32, families *vkQueueFamilyProperties) { - *count = 1 - if families != nil { - *families = vkQueueFamilyProperties{Flags: vkQueueGraphics, Count: 1} - } - }, - getSurfaceSupport: func(_ uintptr, _ uint32, _ uintptr, supported *uint32) int32 { - *supported = 1 - return vkSuccess - }, - getPhysicalDeviceProperties: func(device uintptr, properties *[vkPropertiesSize]byte) { - binary.LittleEndian.PutUint32(properties[vkPropertiesDeviceTypeOffset:], kinds[device]) - }, - } -} - -// A software Vulkan device is never preferred over a hardware one, and a machine -// whose only device is software is reported as such, so the CPU renderer can -// take over. -func TestSelectDevicePrefersHardwareAndReportsSoftware(t *testing.T) { - hardware := uint32(2) // VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU - for _, test := range []struct { - name string - devices []uintptr - kinds map[uintptr]uint32 - physical uintptr - software bool - }{ - {"software first", []uintptr{11, 22}, map[uintptr]uint32{11: vkPhysicalDeviceTypeCPU, 22: hardware}, 22, false}, - {"hardware first", []uintptr{22, 11}, map[uintptr]uint32{22: hardware, 11: vkPhysicalDeviceTypeCPU}, 22, false}, - {"only software", []uintptr{11}, map[uintptr]uint32{11: vkPhysicalDeviceTypeCPU}, 11, true}, - } { - device := &vulkanDevice{api: fakeVulkanAPI(test.devices, test.kinds), instance: 1} - if err := device.selectPhysical(2); err != nil { - t.Fatalf("%s: %v", test.name, err) - } - if device.physical != test.physical || device.software != test.software { - t.Errorf("%s: device %d software=%v, want %d software=%v", test.name, device.physical, device.software, test.physical, test.software) - } - } -} - // framedCPUWindow makes a CPU renderer of a 100x80 window with the standard // margin and a content rectangle, without an X server or text services. func framedCPUWindow(t *testing.T) (*cpuWindowRenderer, *[]putCall) { t.Helper() const width, height, margin = 100, 80, 24 var calls []putCall - content := raster.NewCanvas(int(contentSize(width, margin)), int(contentSize(height, margin))) + content := raster.NewCanvas(int(windowframe.ContentSize(width, margin)), int(windowframe.ContentSize(height, margin))) renderer := &cpuWindowRenderer{ scene: &softScene{canvas: content, scale: 1, clear: scene.Color{Alpha: 1}, rects: []render.Rectangle{{ Kind: scene.KindRectangle, @@ -423,7 +371,7 @@ func TestCPUWindowDropsTheFrameMargin(t *testing.T) { func BenchmarkCPUWindowFramePresent(b *testing.B) { const width, height, margin = 1280, 800, 24 var calls []putCall - content := raster.NewCanvas(int(contentSize(width, margin)), int(contentSize(height, margin))) + content := raster.NewCanvas(int(windowframe.ContentSize(width, margin)), int(windowframe.ContentSize(height, margin))) renderer := &cpuWindowRenderer{ scene: &softScene{canvas: content, scale: 1, clear: scene.Color{Alpha: 1}, rects: []render.Rectangle{{ Kind: scene.KindRectangle, diff --git a/internal/platform/linux/cpu_window_live_linux_test.go b/internal/platform/linux/cpu_window_live_linux_test.go index cfb4bc2eb..e9b230426 100644 --- a/internal/platform/linux/cpu_window_live_linux_test.go +++ b/internal/platform/linux/cpu_window_live_linux_test.go @@ -5,6 +5,9 @@ import ( "testing" "unsafe" + "github.com/vivaui/viva/internal/platform/vulkan" + "github.com/vivaui/viva/internal/platform/windowframe" + "github.com/ebitengine/purego" "github.com/vivaui/viva/internal/platform" @@ -120,7 +123,7 @@ func TestSoftwareVulkanDeviceDrawsOnTheCPU(t *testing.T) { } t.Cleanup(application.closeAll) state := control.(*nativeWindow).state - if !vulkanDeviceIsSoftware() { + if !vulkan.DeviceIsSoftware() { t.Skip("this machine has a hardware Vulkan device") } if _, ok := state.renderer.(*cpuWindowRenderer); !ok { @@ -163,9 +166,9 @@ func TestSoftwareRendererDrawsTheFrame(t *testing.T) { if err := state.renderer.present(); err != nil { t.Fatal(err) } - content := frameContent(win.width, win.height, win.margin) + content := windowframe.Content(win.width, win.height, win.margin) margin := int(win.margin) - centerX, centerY := margin+int(content.width)/2, margin+int(content.height)/2 + centerX, centerY := margin+int(content.Width)/2, margin+int(content.Height)/2 center := readWindowPixels(t, win, int16(centerX), int16(centerY), 1, 1) if center[0] != 0 || center[1] != 0 || center[2] != 255 || center[3] != 255 { diff --git a/internal/platform/linux/desktop_fonts_linux_test.go b/internal/platform/linux/desktop_fonts_linux_test.go index 30cf5c4f0..a64874b8a 100644 --- a/internal/platform/linux/desktop_fonts_linux_test.go +++ b/internal/platform/linux/desktop_fonts_linux_test.go @@ -28,7 +28,7 @@ func TestTheLabelsOnScreenAreDrawnAgainWhenTheDesktopSwitchesToLCDText(t *testin t.Fatalf("the switch reported %v, want the fonts", change) } refreshTextEngine() - if err := offscreen.renderer.refreshText(); err != nil { + if err := offscreen.RefreshText(); err != nil { t.Fatal(err) } image, err := offscreen.Image() diff --git a/internal/platform/linux/display_scale.go b/internal/platform/linux/display_scale.go index 070adad80..0700ff52f 100644 --- a/internal/platform/linux/display_scale.go +++ b/internal/platform/linux/display_scale.go @@ -6,6 +6,8 @@ import ( "math" "strconv" "strings" + + "github.com/vivaui/viva/internal/platform" ) // Display scale on X11. @@ -49,7 +51,7 @@ const ( const ( minScale = 1.0 - maxScale = 8.0 + maxScale = platform.MaxDisplayScale scaleStep = 0.25 baseDPI = 96.0 ) diff --git a/internal/platform/linux/ink_overflow_linux_test.go b/internal/platform/linux/ink_overflow_linux_test.go index 19caa8513..f5baec1df 100644 --- a/internal/platform/linux/ink_overflow_linux_test.go +++ b/internal/platform/linux/ink_overflow_linux_test.go @@ -7,6 +7,7 @@ import ( "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/internal/platform/vulkan" ) // testIconsFont is a fixed-pitch font of 600 units whose private-use glyphs have ink from 120 to @@ -41,7 +42,7 @@ type gridResult struct { width int height int lcd bool - spans []colorSpan + spans []vulkan.ColorSpan } func gridLine(t *testing.T, services *textServices, face gfx.MonoFace, size, cell float32, value string, runs []gfx.TextRun, cells int) gridResult { @@ -55,7 +56,7 @@ func gridLine(t *testing.T, services *textServices, face gfx.MonoFace, size, cel if err != nil { t.Fatal(err) } - result := gridResult{coverage: make([]byte, width), pixels: pixels, width: width, height: height, lcd: lcd, spans: append([]colorSpan(nil), services.spans...)} + result := gridResult{coverage: make([]byte, width), pixels: pixels, width: width, height: height, lcd: lcd, spans: append([]vulkan.ColorSpan(nil), services.spans...)} for y := 0; y < height; y++ { for x := 0; x < width; x++ { result.coverage[x] = max(result.coverage[x], pixels[(y*width+x)*4+3]) @@ -69,8 +70,8 @@ func gridLine(t *testing.T, services *textServices, face gfx.MonoFace, size, cel func (result gridResult) white(column int) bool { if result.lcd { for _, span := range result.spans { - if column >= span.left && column < span.right { - return span.color[0] == 1 && span.color[1] == 1 && span.color[2] == 1 + if column >= span.Left && column < span.Right { + return span.Color[0] == 1 && span.Color[1] == 1 && span.Color[2] == 1 } } return false diff --git a/internal/platform/linux/input_linux_test.go b/internal/platform/linux/input_linux_test.go index bf3fcf902..117049051 100644 --- a/internal/platform/linux/input_linux_test.go +++ b/internal/platform/linux/input_linux_test.go @@ -12,7 +12,6 @@ import ( "github.com/vivaui/viva/internal/input" "github.com/vivaui/viva/internal/platform" "github.com/vivaui/viva/internal/render" - "github.com/vivaui/viva/internal/scene" "github.com/vivaui/viva/text" ) @@ -214,97 +213,6 @@ func TestEventRouterSkipsUnknownKeysAndPropagatesErrors(t *testing.T) { } } -// A frame stages its scene and leaves the commands to the next submit: an image is -// recorded once for a scene, a frame that only changes instance data (a caret -// blinking) records nothing, and one that changes the batches records again. -func TestRendererRecordsAnImageOnlyWhenItsCommandsAreStale(t *testing.T) { - waits, resets, begins, ends := 0, 0, 0, 0 - storage := make([]byte, 64*vkInstanceBytes) - renderer := vulkanRenderer{ - api: &vulkanAPI{ - waitForFences: func(uintptr, uint32, *uintptr, uint32, uint64) int32 { - waits++ - return vkSuccess - }, - resetCommandPool: func(uintptr, uintptr, uint32) int32 { - resets++ - return vkSuccess - }, - beginCommandBuffer: func(uintptr, *vkCommandBufferBeginInfo) int32 { - begins++ - return vkSuccess - }, - cmdBeginRenderPass: func(uintptr, *vkRenderPassBeginInfo, uint32) {}, - cmdClearAttachments: func(uintptr, uint32, *vkClearAttachment, uint32, *vkClearRect) {}, - cmdBindPipeline: func(uintptr, uint32, uintptr) {}, - cmdSetViewport: func(uintptr, uint32, uint32, *vkViewport) {}, - cmdSetScissor: func(uintptr, uint32, uint32, *vkRect2D) {}, - cmdPushConstants: func(uintptr, uintptr, uint32, uint32, uint32, unsafe.Pointer) {}, - cmdBindVertexBuffers: func(uintptr, uint32, uint32, *uintptr, *uint64) {}, - cmdDraw: func(uintptr, uint32, uint32, uint32, uint32) {}, - cmdEndRenderPass: func(uintptr) {}, - endCommandBuffer: func(uintptr) int32 { - ends++ - return vkSuccess - }, - }, - device: 1, - commandPool: 2, - fence: 3, - width: 100, - height: 80, - commands: []uintptr{4, 5}, - framebuffers: []uintptr{6, 7}, - scene: vulkanScene{capacity: 64, mapped: unsafe.Pointer(&storage[0])}, - } - if changed, err := renderer.apply(platform.Frame{}); err != nil || changed { - t.Fatalf("empty apply changed=%v err=%v", changed, err) - } - if waits != 0 || resets != 0 { - t.Fatalf("empty apply waited=%d reset=%d", waits, resets) - } - renderer.recordExtent = vkExtent2D{Width: 100, Height: 80} - rectangles := []render.Rectangle{{Bounds: scene.Rect{Width: 10, Height: 10}, Color: scene.Color{Alpha: 1}}} - changed, err := renderer.apply(platform.Frame{Update: render.Update{Rebuild: true, Count: 1}, Rectangles: rectangles}) - if err != nil || !changed { - t.Fatalf("changed apply changed=%v err=%v", changed, err) - } - if waits != 1 || resets != 0 || begins != 0 { - t.Fatalf("staging waits=%d resets=%d begins=%d, want the fence and no recording", waits, resets, begins) - } - submit := func() { - t.Helper() - if err := renderer.ensureRecorded(0); err != nil { - t.Fatal(err) - } - } - submit() - submit() - if begins != 1 || ends != 1 { - t.Fatalf("one scene recorded image 0 begins=%d ends=%d, want once", begins, ends) - } - rectangles[0].Color.Alpha = 0.5 // a caret fading: new instance data, same batches - if _, err := renderer.apply(platform.Frame{Update: render.Update{First: 0, Count: 1}, Rectangles: rectangles}); err != nil { - t.Fatal(err) - } - submit() - if begins != 1 { - t.Fatalf("a frame that changed instance data recorded again: begins=%d", begins) - } - rectangles = append(rectangles, render.Rectangle{Bounds: scene.Rect{Width: 5, Height: 5}, Color: scene.Color{Alpha: 1}, Layer: 3}) - if _, err := renderer.apply(platform.Frame{Update: render.Update{First: 1, Count: 1}, Rectangles: rectangles}); err != nil { - t.Fatal(err) - } - submit() - if begins != 2 { - t.Fatalf("a frame that changed the batches did not record again: begins=%d", begins) - } - rectangles[0].Bounds.Width = 99 - if renderer.rectangles[0].Bounds.Width != 10 { - t.Fatal("renderer retained caller-owned rectangle storage") - } -} - func TestEventRouterNumbersConsecutivePressesAsClicks(t *testing.T) { var got []platform.PointerEvent router := eventRouter{ @@ -734,6 +642,7 @@ func TestX11FocusInForgetsHeldKeys(t *testing.T) { state := &linuxWindowState{ win: &window{}, application: &linuxApplication{}, + text: &linuxTextInput{}, router: eventRouter{modifierKeys: tracker}, } previous := activeWindow.Load() @@ -957,9 +866,11 @@ func TestX11FocusOutSynthesizesReleasesForTerminal(t *testing.T) { tracker.press(10, keysymShiftL, input.KeyShiftLeft) keymap := xcbKeymap{first: 9, last: 10, perKeycode: 2, keysyms: []uint32{'a', 'A', keysymShiftL, 0}} + terminalInput := &linuxTextInput{enabled: true, input: platform.TextInput{Terminal: true, KeyReleases: true}} state := &linuxWindowState{ win: &window{keymap: keymap}, application: &linuxApplication{}, + text: terminalInput, router: eventRouter{ config: platform.Config{ OnKey: func(event platform.KeyEvent) (platform.Frame, error) { @@ -967,7 +878,7 @@ func TestX11FocusOutSynthesizesReleasesForTerminal(t *testing.T) { return platform.Frame{}, nil }, }, - text: &linuxTextInput{enabled: true, input: platform.TextInput{Terminal: true, KeyReleases: true}}, + text: terminalInput, present: func(platform.Frame) error { return nil }, modifierKeys: tracker, }, diff --git a/internal/platform/linux/offscreen_linux.go b/internal/platform/linux/offscreen_linux.go index 8e425978a..54e8649a2 100644 --- a/internal/platform/linux/offscreen_linux.go +++ b/internal/platform/linux/offscreen_linux.go @@ -1,277 +1,20 @@ -//go:build linux - package linux import ( - "fmt" - "image" - "math" - "unsafe" - "github.com/vivaui/viva/internal/platform" - "github.com/vivaui/viva/internal/render" -) - -const ( - vkImageUsageTransferSource = 0x1 - vkBufferUsageTransferDestination = 0x2 - vkImageLayoutTransferSource = 6 - vkAccessColorAttachmentWrite = 0x100 - vkAccessTransferRead = 0x800 - vkPipelineStageTransferBit = 0x1000 - offscreenLimit = 16384 + "github.com/vivaui/viva/internal/platform/vulkan" ) -// Offscreen renders scenes to pixels with the window's own Vulkan pipelines -// and command recording but without an X window, a surface or a swapchain: the -// target is a plain color image that is copied to host memory. A screenshot or -// a pixel test therefore shows what the window would. It is not safe for +// Offscreen renders scenes to pixels with the window's own Vulkan pipelines and +// command recording but without an X window, a surface or a swapchain, so a +// screenshot or a pixel test shows what the window would. It is not safe for // concurrent use. -type Offscreen struct { - renderer *vulkanRenderer -} - -// vulkanOffscreen is the renderer's offscreen target: the color image the -// scene is drawn into and the host buffer it is read back through. -type vulkanOffscreen struct { - image, memory uintptr - readback, readbackMemory uintptr - readbackCommand uintptr - readbackSize uint64 -} +type Offscreen = vulkan.Offscreen // NewOffscreen creates a renderer for a width x height scene in logical pixels, -// drawn at scale device pixels per logical pixel (the image is -// ceil(width*scale) by ceil(height*scale)), cleared to clear before each render. -// It fails with platform.ErrNoGraphics when the machine has no Vulkan driver. +// drawn at scale device pixels per logical pixel, with this desktop's text +// services drawing the glyphs. It fails with platform.ErrNoGraphics when the +// machine has no Vulkan driver. func NewOffscreen(width, height int, scale float64, clear platform.Color) (*Offscreen, error) { - if width < 1 || height < 1 || width > offscreenLimit || height > offscreenLimit || math.IsNaN(scale) || scale < 1 || scale > maxScale { - return nil, fmt.Errorf("linux: invalid offscreen size %dx%d at %gx", width, height, scale) - } - deviceWidth, deviceHeight := int(math.Ceil(float64(width)*scale)), int(math.Ceil(float64(height)*scale)) - if deviceWidth > offscreenLimit || deviceHeight > offscreenLimit { - return nil, fmt.Errorf("linux: offscreen size %dx%d at %gx is beyond %d device pixels", width, height, scale, offscreenLimit) - } - api, err := loadVulkan() - if err != nil { - return nil, err - } - renderer := &vulkanRenderer{api: api, width: uint32(deviceWidth), height: uint32(deviceHeight), scale: float32(scale), color: clear} - if err := renderer.initializeOffscreen(); err != nil { - renderer.close() - return nil, err - } - return &Offscreen{renderer: renderer}, nil -} - -// Set replaces the scene: rectangle and triangle instances in paint order and -// text labels. -func (offscreen *Offscreen) Set(rectangles []render.Rectangle, labels []platform.TextLabel) error { - if offscreen.renderer == nil { - return fmt.Errorf("linux: offscreen renderer is closed") - } - if labels == nil { - labels = []platform.TextLabel{} - } - _, err := offscreen.renderer.apply(platform.Frame{ - Update: render.Update{Count: len(rectangles), Rebuild: true}, - Rectangles: rectangles, - TextLabels: labels, - }) - return err -} - -// Image draws the scene and returns its pixels, top row first. The image is -// premultiplied RGBA, the format of the color target converted from the -// target's BGRA byte order; the target is not sRGB, so values are the ones the -// shaders wrote. -func (offscreen *Offscreen) Image() (*image.RGBA, error) { - if offscreen.renderer == nil { - return nil, fmt.Errorf("linux: offscreen renderer is closed") - } - return offscreen.renderer.readImage() -} - -// Close releases the renderer. -func (offscreen *Offscreen) Close() { - if offscreen.renderer != nil { - offscreen.renderer.close() - offscreen.renderer = nil - } -} - -func (renderer *vulkanRenderer) initializeOffscreen() error { - device := vulkanDevice{api: renderer.api} - if err := device.open(); err != nil { - return err - } - renderer.adopt(&device) - if err := renderer.scene.upload(renderer, nil, render.Update{Rebuild: true}); err != nil { - return err - } - if err := renderer.createOffscreenTarget(); err != nil { - return err - } - semaphoreInfo := vkSemaphoreCreateInfo{SType: vkStructureSemaphoreCreateInfo} - if err := vkCheck(renderer.api.createSemaphore(renderer.device, &semaphoreInfo, nil, &renderer.imageAvailable), "create acquire semaphore"); err != nil { - return err - } - fenceInfo := vkFenceCreateInfo{SType: vkStructureFenceCreateInfo, Flags: vkFenceSignaled} - return vkCheck(renderer.api.createFence(renderer.device, &fenceInfo, nil, &renderer.fence), "create frame fence") -} - -// createOffscreenTarget builds what createSwapchain builds for a window, with -// one color image instead of the swapchain's: image, view, render pass, -// framebuffer and commands, then the shared pipelines. The render pass leaves -// the image ready to be copied. -func (renderer *vulkanRenderer) createOffscreenTarget() (err error) { - defer func() { - if err != nil { - renderer.destroySwapchain() - renderer.destroyOffscreen() - } - }() - target := &renderer.offscreen - extent := vkExtent2D{Width: renderer.width, Height: renderer.height} - imageInfo := vkImageCreateInfo{ - SType: vkStructureTextImageCreateInfo, ImageType: vkImageType2D, Format: vkFormatBGRA8, - Extent: vkExtent3D{Width: extent.Width, Height: extent.Height, Depth: 1}, MipLevels: 1, ArrayLayers: 1, - Samples: vkSampleCountOne, Tiling: vkImageTilingOptimal, - Usage: vkImageUsageColorAttachment | vkImageUsageTransferSource, SharingMode: vkSharingExclusive, - } - if err := vkCheck(renderer.api.createImage(renderer.device, &imageInfo, nil, &target.image), "create offscreen image"); err != nil { - return err - } - var requirements vkMemoryRequirements - renderer.api.getImageMemoryRequirements(renderer.device, target.image, &requirements) - memoryType, ok := renderer.memoryType(requirements.MemoryTypeBits, vkMemoryDeviceLocal) - if !ok { - return fmt.Errorf("linux: Vulkan device has no device-local image memory") - } - allocation := vkMemoryAllocateInfo{SType: vkStructureMemoryAllocateInfo, AllocationSize: requirements.Size, MemoryTypeIndex: memoryType} - if err := vkCheck(renderer.api.allocateMemory(renderer.device, &allocation, nil, &target.memory), "allocate offscreen image memory"); err != nil { - return err - } - if err := vkCheck(renderer.api.bindImageMemory(renderer.device, target.image, target.memory, 0), "bind offscreen image memory"); err != nil { - return err - } - renderer.views = make([]uintptr, 1) - viewInfo := vkImageViewCreateInfo{SType: vkStructureImageViewCreateInfo, Image: target.image, ViewType: vkImageViewType2D, Format: vkFormatBGRA8, Range: vkSubresourceRange{Aspect: vkImageAspectColor, LevelCount: 1, LayerCount: 1}} - if err := vkCheck(renderer.api.createImageView(renderer.device, &viewInfo, nil, &renderer.views[0]), "create offscreen image view"); err != nil { - return err - } - if err := renderer.createRenderPass(vkFormatBGRA8, vkImageLayoutTransferSource); err != nil { - return err - } - renderer.framebuffers = make([]uintptr, 1) - view := renderer.views[0] - framebufferInfo := vkFramebufferCreateInfo{SType: vkStructureFramebufferCreateInfo, RenderPass: renderer.renderPass, AttachmentCount: 1, Attachments: &view, Width: extent.Width, Height: extent.Height, Layers: 1} - if err := vkCheck(renderer.api.createFramebuffer(renderer.device, &framebufferInfo, nil, &renderer.framebuffers[0]), "create offscreen framebuffer"); err != nil { - return err - } - if err := renderer.createCommands(1); err != nil { - return err - } - // The readback buffer is host memory the image is copied into. - target.readbackSize = uint64(extent.Width) * uint64(extent.Height) * 4 - bufferInfo := vkBufferCreateInfo{SType: vkStructureBufferCreateInfo, Size: target.readbackSize, Usage: vkBufferUsageTransferDestination, SharingMode: vkSharingExclusive} - if err := vkCheck(renderer.api.createBuffer(renderer.device, &bufferInfo, nil, &target.readback), "create readback buffer"); err != nil { - return err - } - renderer.api.getBufferMemoryRequirements(renderer.device, target.readback, &requirements) - memoryType, ok = renderer.memoryType(requirements.MemoryTypeBits, vkMemoryHostVisible|vkMemoryHostCoherent) - if !ok { - return fmt.Errorf("linux: Vulkan device has no coherent host-visible memory for readback") - } - allocation = vkMemoryAllocateInfo{SType: vkStructureMemoryAllocateInfo, AllocationSize: requirements.Size, MemoryTypeIndex: memoryType} - if err := vkCheck(renderer.api.allocateMemory(renderer.device, &allocation, nil, &target.readbackMemory), "allocate readback memory"); err != nil { - return err - } - if err := vkCheck(renderer.api.bindBufferMemory(renderer.device, target.readback, target.readbackMemory, 0), "bind readback memory"); err != nil { - return err - } - allocate := vkCommandBufferAllocateInfo{SType: vkStructureCommandAllocateInfo, Pool: renderer.commandPool, Level: vkCommandBufferPrimary, Count: 1} - if err := vkCheck(renderer.api.allocateCommandBuffers(renderer.device, &allocate, &target.readbackCommand), "allocate readback command"); err != nil { - return err - } - if err := renderer.createScenePipelines(extent); err != nil { - return err - } - renderer.format = vkFormatBGRA8 - return nil -} - -// readImage submits the recorded scene and a copy of the target into the -// readback buffer, waits for them and converts the bytes to an image. -func (renderer *vulkanRenderer) readImage() (*image.RGBA, error) { - target := &renderer.offscreen - if err := vkCheck(renderer.api.waitForFences(renderer.device, 1, &renderer.fence, 1, math.MaxUint64), "wait before readback"); err != nil { - return nil, err - } - if err := renderer.ensureRecorded(0); err != nil { - return nil, err - } - begin := vkCommandBufferBeginInfo{SType: vkStructureCommandBeginInfo, Flags: vkCommandOneTimeSubmit} - if err := vkCheck(renderer.api.beginCommandBuffer(target.readbackCommand, &begin), "begin readback command"); err != nil { - return nil, err - } - // The render pass already left the image in the copy layout; the barrier - // makes its writes visible to the copy. - barrier := vkImageMemoryBarrier{ - SType: vkStructureImageMemoryBarrier, SourceAccess: vkAccessColorAttachmentWrite, DestinationAccess: vkAccessTransferRead, - OldLayout: vkImageLayoutTransferSource, NewLayout: vkImageLayoutTransferSource, - SourceQueueFamily: vkQueueFamilyIgnored, DestinationQueueFamily: vkQueueFamilyIgnored, Image: target.image, - Range: vkSubresourceRange{Aspect: vkImageAspectColor, LevelCount: 1, LayerCount: 1}, - } - renderer.api.cmdPipelineBarrier(target.readbackCommand, vkPipelineStageColorOutput, vkPipelineStageTransferBit, 0, 0, nil, 0, nil, 1, &barrier) - region := vkBufferImageCopy{ - ImageSubresource: vkImageSubresourceLayers{Aspect: vkImageAspectColor, LayerCount: 1}, - ImageExtent: vkExtent3D{Width: renderer.width, Height: renderer.height, Depth: 1}, - } - renderer.api.cmdCopyImageToBuffer(target.readbackCommand, target.image, vkImageLayoutTransferSource, target.readback, 1, ®ion) - if err := vkCheck(renderer.api.endCommandBuffer(target.readbackCommand), "end readback command"); err != nil { - return nil, err - } - if err := vkCheck(renderer.api.resetFences(renderer.device, 1, &renderer.fence), "reset frame fence"); err != nil { - return nil, err - } - commands := [2]uintptr{renderer.commands[0], target.readbackCommand} - submit := vkSubmitInfo{SType: vkStructureSubmitInfo, CommandCount: 2, Commands: &commands[0]} - if err := vkCheck(renderer.api.queueSubmit(renderer.queue, 1, &submit, renderer.fence), "submit offscreen render"); err != nil { - return nil, err - } - if err := vkCheck(renderer.api.waitForFences(renderer.device, 1, &renderer.fence, 1, math.MaxUint64), "wait for offscreen render"); err != nil { - return nil, err - } - var mapped unsafe.Pointer - if err := vkCheck(renderer.api.mapMemory(renderer.device, target.readbackMemory, 0, target.readbackSize, 0, &mapped), "map readback memory"); err != nil { - return nil, err - } - defer renderer.api.unmapMemory(renderer.device, target.readbackMemory) - bgra := unsafe.Slice((*byte)(mapped), int(target.readbackSize)) - result := image.NewRGBA(image.Rect(0, 0, int(renderer.width), int(renderer.height))) - for offset := 0; offset+3 < len(bgra); offset += 4 { - result.Pix[offset], result.Pix[offset+1], result.Pix[offset+2], result.Pix[offset+3] = bgra[offset+2], bgra[offset+1], bgra[offset], bgra[offset+3] - } - renderer.submissions++ - return result, nil -} - -func (renderer *vulkanRenderer) destroyOffscreen() { - target := &renderer.offscreen - if renderer.device != 0 { - if target.readback != 0 { - renderer.api.destroyBuffer(renderer.device, target.readback, nil) - } - if target.readbackMemory != 0 { - renderer.api.freeMemory(renderer.device, target.readbackMemory, nil) - } - if target.image != 0 { - renderer.api.destroyImage(renderer.device, target.image, nil) - } - if target.memory != 0 { - renderer.api.freeMemory(renderer.device, target.memory, nil) - } - } - *target = vulkanOffscreen{} + return vulkan.NewOffscreen(width, height, scale, clear, newWindowRasterizer) } diff --git a/internal/platform/linux/shared_api_linux_test.go b/internal/platform/linux/shared_api_linux_test.go index 9ee56bb19..c7d72a510 100644 --- a/internal/platform/linux/shared_api_linux_test.go +++ b/internal/platform/linux/shared_api_linux_test.go @@ -2,20 +2,15 @@ package linux import "testing" -// The libxcb and libvulkan libraries are opened once per process, and a machine +// The libxcb library is opened once per process, and a machine // without one is found once; every caller gets its own copy of the bound table, // so wrapping one window's functions leaves another's alone. -func TestFunctionTablesAreLoadedOnce(t *testing.T) { +func TestXCBTableIsLoadedOnce(t *testing.T) { x1, xErr1 := loadXCB() x2, xErr2 := loadXCB() if xErr1 != xErr2 || (xErr1 == nil && (x1.library != x2.library || x1 == x2)) { t.Fatalf("loadXCB gave %p, %v then %p, %v", x1, xErr1, x2, xErr2) } - v1, vErr1 := loadVulkan() - v2, vErr2 := loadVulkan() - if vErr1 != vErr2 || (vErr1 == nil && (v1.library != v2.library || v1 == v2)) { - t.Fatalf("loadVulkan gave %p, %v then %p, %v", v1, vErr1, v2, vErr2) - } if xErr1 == nil { x1.connect = nil if x2.connect == nil { diff --git a/internal/platform/linux/soft_scene_linux.go b/internal/platform/linux/soft_scene_linux.go index 368c5c560..a29e5fe2b 100644 --- a/internal/platform/linux/soft_scene_linux.go +++ b/internal/platform/linux/soft_scene_linux.go @@ -99,7 +99,7 @@ func (s *softScene) apply(frame platform.Frame) (bool, error) { s.setViews(frame.NativeViews) } if frame.TextLabels != nil { - if err := validateInitialTextLabels(frame.TextLabels); err != nil { + if err := platform.ValidateTextLabels(frame.TextLabels); err != nil { return false, err } if err := s.setLabels(frame.TextLabels); err != nil { @@ -114,7 +114,7 @@ func (s *softScene) pending() bool { } func (s *softScene) applyRectangles(frame platform.Frame) error { - if err := validateRectangles(frame.Rectangles); err != nil { + if err := render.ValidateRectangles(frame.Rectangles); err != nil { return err } update := frame.Update @@ -230,9 +230,9 @@ func labelContentChanged(previous, next platform.TextLabel) bool { return previous.Value != next.Value || previous.Width != next.Width || previous.Height != next.Height || previous.FontSize != next.FontSize || previous.Italic != next.Italic || previous.Weight != next.Weight || previous.Color != next.Color || previous.FontGeneration != next.FontGeneration || previous.Mono != next.Mono || previous.MonoFace != next.MonoFace || previous.CellWidth != next.CellWidth || previous.Baseline != next.Baseline || - !sameTextRuns(previous.Runs, next.Runs) || previous.BitmapID != next.BitmapID || previous.BitmapVersion != next.BitmapVersion || + !platform.SameTextRuns(previous.Runs, next.Runs) || previous.BitmapID != next.BitmapID || previous.BitmapVersion != next.BitmapVersion || previous.BitmapWidth != next.BitmapWidth || previous.BitmapHeight != next.BitmapHeight || previous.BitmapStride != next.BitmapStride || - !sameBitmapBytes(previous.Bitmap, next.Bitmap) + !platform.SameBitmapBytes(previous.Bitmap, next.Bitmap) } // bitmapShownChanged reports whether an image covers a different number of device pixels than it diff --git a/internal/platform/linux/status_item_linux.go b/internal/platform/linux/status_item_linux.go index 3fb66c36c..857e09061 100644 --- a/internal/platform/linux/status_item_linux.go +++ b/internal/platform/linux/status_item_linux.go @@ -11,6 +11,8 @@ import ( "time" "unsafe" + "github.com/vivaui/viva/internal/platform/windowframe" + "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/internal/dbus" "github.com/vivaui/viva/internal/dbusmenu" @@ -179,7 +181,7 @@ func (state *linuxWindowState) command(command uint32, data []byte) error { height := int(binary.LittleEndian.Uint32(data[8:12])) margin := uint32(0) if win.margin > 0 { - margin = frameMargin(win.displayScale()) + margin = windowframe.Margin(win.displayScale()) } if width < 1 || height < 1 { return nil @@ -295,7 +297,7 @@ func (window *nativeWindow) Frame() (gfx.Rect, bool) { } x, y := win.contentOrigin() scale := win.displayScale() - return gfx.Rect{X: float32(x) / scale, Y: float32(y) / scale, Width: float32(contentSize(win.width, win.margin)) / scale, Height: float32(contentSize(win.height, win.margin)) / scale}, true + return gfx.Rect{X: float32(x) / scale, Y: float32(y) / scale, Width: float32(windowframe.ContentSize(win.width, win.margin)) / scale, Height: float32(windowframe.ContentSize(win.height, win.margin)) / scale}, true } // Hide and Show post to the window's loop, so they may be called anywhere. diff --git a/internal/platform/linux/text_engine_linux.go b/internal/platform/linux/text_engine_linux.go index 639915104..494437da3 100644 --- a/internal/platform/linux/text_engine_linux.go +++ b/internal/platform/linux/text_engine_linux.go @@ -206,7 +206,7 @@ func (engine *textEngine) shape(value string, size, weight float32) (*shapedLine func (engine *textEngine) shapeStyle(value string, size, weight float32, italic bool) (*shapedLine, error) { services := engine.services - if !validFontSize(size) { + if !platform.ValidFontSize(size) { return nil, fmt.Errorf("linux: invalid font size") } if !utf8.ValidString(value) { diff --git a/internal/platform/linux/text_input_linux.go b/internal/platform/linux/text_input_linux.go index e98ca94bc..c021d3ae5 100644 --- a/internal/platform/linux/text_input_linux.go +++ b/internal/platform/linux/text_input_linux.go @@ -151,7 +151,7 @@ func validateLinuxTextInput(inputState *platform.TextInput) error { if inputState == nil { return nil } - if inputState.Width <= 0 || inputState.Height <= 0 || !validFontSize(inputState.FontSize) { + if inputState.Width <= 0 || inputState.Height <= 0 || !platform.ValidFontSize(inputState.FontSize) { return fmt.Errorf("linux: text input dimensions and font size must be positive") } if inputState.OnEvent == nil { diff --git a/internal/platform/linux/text_linux.go b/internal/platform/linux/text_linux.go index 12f260df9..a0f9593e0 100644 --- a/internal/platform/linux/text_linux.go +++ b/internal/platform/linux/text_linux.go @@ -8,6 +8,8 @@ import ( "unicode" "unicode/utf8" + "github.com/vivaui/viva/internal/platform/vulkan" + "github.com/ebitengine/purego" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/internal/platform" @@ -25,7 +27,7 @@ type textServices struct { context, layout uintptr // spans are the colors of the last LCD grid label rasterized, valid until the next call. - spans []colorSpan + spans []vulkan.ColorSpan owner platform.GridOwner // which run owns which column of a grid label ink []platform.GridInk // how far each run's glyphs reach past its cells @@ -286,10 +288,6 @@ func cString(value string) []byte { return result } -func validFontSize(size float32) bool { - return size > 0 && !math.IsNaN(float64(size)) && !math.IsInf(float64(size), 0) -} - func pangoWeight(weight float32) int32 { switch { case weight >= 0.35: @@ -339,7 +337,7 @@ func (services *textServices) description(family string, size, weight float32, i } func (services *textServices) configureLayout(value, family string, size, weight float32, italic bool) (text.Metrics, error) { - if !validFontSize(size) { + if !platform.ValidFontSize(size) { return text.Metrics{}, fmt.Errorf("linux: invalid font size") } if !utf8.ValidString(value) { @@ -377,7 +375,7 @@ func (services *textServices) layoutValue(description uintptr, value string) (lo // thicknesses of the strokes the face draws a light and a heavy box drawing line with, in // logical pixels. The stroke is the ink width of the stem glyph in the face's own family. func (services *textServices) configureMonoLayout(family string, size float32) (text.Metrics, error) { - if !validFontSize(size) { + if !platform.ValidFontSize(size) { return text.Metrics{}, fmt.Errorf("linux: invalid font size") } description, err := services.description(family, size, 0, false) @@ -513,7 +511,7 @@ func (services *textServices) draw(label platform.TextLabel, scale float32, skip if !platform.LabelTextureFits(width, height) || skip < 0 { return nil, fmt.Errorf("linux: label texture exceeds bounded size") } - if !validFontSize(label.FontSize) || scale <= 0 || math.IsNaN(float64(scale)) || math.IsInf(float64(scale), 0) { + if !platform.ValidFontSize(label.FontSize) || scale <= 0 || math.IsNaN(float64(scale)) || math.IsInf(float64(scale), 0) { return nil, fmt.Errorf("linux: invalid label font size or scale") } pixels := make([]byte, width*height*4) @@ -626,14 +624,6 @@ func clampUnit64(value float64) float64 { return min(max(value, 0), 1) } -// colorSpan is the columns of an LCD grid label's texture, left to right in device pixels, that -// are text of one color. Its coverage is the same for every color, so the renderer draws the -// one texture once per span, with the span's color, scissored to its columns. -type colorSpan struct { - left, right int - color [4]float32 -} - // drawRuns draws a fixed-pitch label's runs. With lcd they are drawn white, for their coverage, // and the color of each run is recorded in services.spans instead. The surface is the device // columns from skip to skip+width of the line, translated onto them: a run outside them is not @@ -759,11 +749,11 @@ func (services *textServices) drawRuns(context uintptr, label platform.TextLabel // addSpan records a run's columns and color, joined to the span before it when they touch and // the color is the same. func (services *textServices) addSpan(left, right int, color [4]float32) { - if n := len(services.spans); n > 0 && services.spans[n-1].color == color && services.spans[n-1].right >= left { - services.spans[n-1].right = max(services.spans[n-1].right, right) + if n := len(services.spans); n > 0 && services.spans[n-1].Color == color && services.spans[n-1].Right >= left { + services.spans[n-1].Right = max(services.spans[n-1].Right, right) return } - services.spans = append(services.spans, colorSpan{left: left, right: right, color: color}) + services.spans = append(services.spans, vulkan.ColorSpan{Left: left, Right: right, Color: color}) } func printableASCII(value string) bool { @@ -788,3 +778,13 @@ func isSingleCharacter(value string) bool { } return count == 1 } + +// Rasterize, Spans and Close make the text services the Vulkan renderer's +// rasterizer (vulkan.TextRasterizer). +func (services *textServices) Rasterize(label platform.TextLabel, scale float32, skip, width, height int, allowLCD bool) ([]byte, bool, error) { + return services.rasterizeWindow(label, scale, skip, width, height, allowLCD) +} + +func (services *textServices) Spans() []vulkan.ColorSpan { return services.spans } + +func (services *textServices) Close() { services.close() } diff --git a/internal/platform/linux/text_resize_linux_test.go b/internal/platform/linux/text_resize_linux_test.go index 22ae06388..6ba3d8330 100644 --- a/internal/platform/linux/text_resize_linux_test.go +++ b/internal/platform/linux/text_resize_linux_test.go @@ -8,10 +8,10 @@ import ( "math" "strings" "testing" - "unsafe" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/internal/platform/vulkan" ) func resizeTestLabels(count int, width float32) []platform.TextLabel { @@ -27,89 +27,6 @@ func resizeTestLabels(count int, width float32) []platform.TextLabel { return labels } -func BenchmarkVulkanTextLiveResize(b *testing.B) { - for _, count := range []int{256, 1024} { - b.Run(fmt.Sprintf("ClippedWidths/%d", count), func(b *testing.B) { - narrow := resizeTestLabels(count, 60) - wide := append([]platform.TextLabel(nil), narrow...) - for i := range wide { - wide[i].Width++ - } - var state vulkanText - if err := state.update(nil, narrow); err != nil { - b.Fatal(err) - } - for _, labels := range [][]platform.TextLabel{wide, narrow} { - if err := state.update(nil, labels); err != nil { - b.Fatal(err) - } - } - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - labels := narrow - if i&1 == 0 { - labels = wide - } - if err := state.update(nil, labels); err != nil { - b.Fatal(err) - } - } - }) - b.Run(fmt.Sprintf("Unchanged/%d", count), func(b *testing.B) { - labels := resizeTestLabels(count, 800) - var state vulkanText - if err := state.update(nil, labels); err != nil { - b.Fatal(err) - } - if err := state.update(nil, labels); err != nil { - b.Fatal(err) - } - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - if err := state.update(nil, labels); err != nil { - b.Fatal(err) - } - } - }) - b.Run(fmt.Sprintf("RepeatedClippedWidths/%d", count), func(b *testing.B) { - narrow := resizeTestLabels(count, 60) - for i := range narrow { - narrow[i].Value, narrow[i].Runs = narrow[0].Value, narrow[0].Runs - } - wide := append([]platform.TextLabel(nil), narrow...) - for i := range wide { - wide[i].Width++ - } - var state vulkanText - for _, labels := range [][]platform.TextLabel{narrow, wide, narrow} { - if err := state.update(nil, labels); err != nil { - b.Fatal(err) - } - } - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - // The old textures were clipped at the previous width. Growing - // beyond them requires new pictures, even for duplicate rows. - for j := range state.labels { - state.labels[j].view = uintptr(j + 1) - state.labels[j].scale = 1 - state.labels[j].width = int(state.labels[j].label.Width) - } - labels := narrow - if i&1 == 0 { - labels = wide - } - if err := state.update(nil, labels); err != nil { - b.Fatal(err) - } - } - }) - } -} - func TestVulkanProportionalTextureKeepsGlyphOverhang(t *testing.T) { services, err := newTextServices() if err != nil { @@ -125,7 +42,7 @@ func TestVulkanProportionalTextureKeepsGlyphOverhang(t *testing.T) { } height := int(math.Ceil(float64(label.Height * scale))) width := int(math.Ceil(float64(label.Width * scale))) - reserved := labelRasterWidth(label, scale, height) + reserved := vulkan.LabelRasterWidth(label, scale, height) pixels, _, err := services.rasterize(label, scale, width, height, false) if err != nil { t.Fatal(err) @@ -142,112 +59,6 @@ func TestVulkanProportionalTextureKeepsGlyphOverhang(t *testing.T) { } } -func TestVulkanTextResizeKeepsDistinctDuplicateTextures(t *testing.T) { - labels := resizeTestLabels(3, 800) - labels[1].Value, labels[1].Runs = labels[0].Value, labels[0].Runs - var state vulkanText - if err := state.update(nil, labels); err != nil { - t.Fatal(err) - } - for i := range state.labels { - state.labels[i].view = uintptr(i + 1) - } - next := []platform.TextLabel{labels[2], labels[0], labels[1]} - if err := state.update(nil, next); err != nil { - t.Fatal(err) - } - seen := make(map[uintptr]bool) - for i, label := range state.labels { - if label.view == 0 || seen[label.view] { - t.Fatalf("slot %d retained invalid or duplicate image view %d", i, label.view) - } - seen[label.view] = true - } - if state.labels[0].view != 3 { - t.Fatalf("moved unique label view = %d, want 3", state.labels[0].view) - } -} - -func TestVulkanTextResizeInvalidLabelKeepsPreviousFrame(t *testing.T) { - labels := resizeTestLabels(3, 800) - var state vulkanText - if err := state.update(nil, labels); err != nil { - t.Fatal(err) - } - state.labels[0].view = 42 - next := append([]platform.TextLabel(nil), labels...) - next[0].Value = "changed" - next[2].Width = -1 - if err := state.update(nil, next); err == nil { - t.Fatal("accepted negative width") - } - if state.labels[0].view != 42 || state.labels[0].label.Value != labels[0].Value { - t.Fatal("invalid update discarded the previous frame") - } -} - -func TestVulkanGridResizeReusesReservedColumnsAcrossIndexShift(t *testing.T) { - labels := resizeTestLabels(2, 70) - var state vulkanText - if err := state.update(nil, labels); err != nil { - t.Fatal(err) - } - for i := range state.labels { - state.labels[i].view = uintptr(i + 1) - state.labels[i].width = 128 - state.labels[i].scale = 1 - } - next := []platform.TextLabel{labels[1], labels[0]} - next[0].Width, next[1].Width = 105, 35 - if err := state.update(nil, next); err != nil { - t.Fatal(err) - } - for i, want := range []uintptr{2, 1} { - if state.labels[i].view != want || state.labels[i].label.Width != next[i].Width { - t.Fatalf("row %d lost its texture or new visible width: %+v", i, state.labels[i]) - } - } - next[0].Width = 129 - if err := state.update(nil, next); err != nil { - t.Fatal(err) - } - if state.labels[0].view != 0 || state.labels[1].view != 1 { - t.Fatal("growing beyond the reserved columns did not invalidate only the wider row") - } - next[1].Runs = append([]gfx.TextRun(nil), next[1].Runs...) - next[1].Runs[0].Color = gfx.RGB(255, 0, 0) - if err := state.update(nil, next); err != nil { - t.Fatal(err) - } - if state.labels[1].view != 0 { - t.Fatal("a changed run color kept its old texture") - } -} - -func TestVulkanGridTextureReservationIsBounded(t *testing.T) { - label := resizeTestLabels(1, 70)[0] - if got := labelRasterWidth(label, 1, 20); got != 128 { - t.Fatalf("reserved width = %d, want 128", got) - } - label.Value = "hello" - label.Runs = []gfx.TextRun{{Bytes: 5, Cells: 5}} - if got := labelRasterWidth(label, 1, 20); got != 50 { - t.Fatalf("short row width = %d, want its ink and overhang only", got) - } - label.Value = strings.Repeat("x", 100000) - label.Runs = []gfx.TextRun{{Bytes: int32(len(label.Value)), Cells: int32(len(label.Value))}} - for _, test := range []struct { - width float32 - height int - want int - }{{70, 20, 128}, {16360, 20, 16384}, {1000, 16384, 1024}} { - label.Width = test.width - if got := labelRasterWidth(label, 1, test.height); got != test.want { - t.Fatalf("width %g height %d reserves %d pixels, want %d", test.width, test.height, got, test.want) - } - } -} - // The same texture must survive both shrinking and growing, while the pixels // remain an exact crop of the full row: colors, wide glyphs and icon overhang // keep their original placement, also at a fractional display scale. @@ -266,13 +77,12 @@ func TestVulkanGridResizeKeepsTextureAndClipsItsPixels(t *testing.T) { }, } full := renderScene(t, offscreen, nil, []platform.TextLabel{label}) - renderer := offscreen.renderer - creates := 0 - createImage := renderer.api.createImage - renderer.api.createImage = func(device uintptr, info *vkImageCreateInfo, allocator unsafe.Pointer, image *uintptr) int32 { - creates++ - return createImage(device, info, allocator, image) + services, err := newTextServices() + if err != nil { + t.Skipf("no text services: %v", err) } + defer services.close() + textures := offscreen.Stats().Textures for _, width := range []float32{53.5, 67.25, 99.5, 120.25, 41.5} { label.Width = width label.Clipped = width == 99.5 @@ -283,14 +93,14 @@ func TestVulkanGridResizeKeepsTextureAndClipsItsPixels(t *testing.T) { // This also checks ownership of the blank after the icon. deviceWidth := int(math.Ceil(float64(label.Width * float32(scale)))) deviceHeight := int(math.Ceil(float64(label.Height * float32(scale)))) - reservedWidth := labelRasterWidth(label, float32(scale), deviceHeight) - needed, _ := neededLabelWidth(label) + reservedWidth := vulkan.LabelRasterWidth(label, float32(scale), deviceHeight) + needed, _ := vulkan.NeededLabelWidth(label) fullWidth := int(math.Ceil(float64(needed * float32(scale)))) - complete, _, err := renderer.text.services.rasterize(label, float32(scale), fullWidth, deviceHeight, false) + complete, _, err := services.rasterize(label, float32(scale), fullWidth, deviceHeight, false) if err != nil { t.Fatal(err) } - reserved, _, err := renderer.text.services.rasterize(label, float32(scale), reservedWidth, deviceHeight, false) + reserved, _, err := services.rasterize(label, float32(scale), reservedWidth, deviceHeight, false) if err != nil { t.Fatal(err) } @@ -302,8 +112,8 @@ func TestVulkanGridResizeKeepsTextureAndClipsItsPixels(t *testing.T) { } } pixels := renderScene(t, offscreen, nil, []platform.TextLabel{label}) - if creates != 0 { - t.Fatalf("width %g recreated %d images inside reserved columns", width, creates) + if made := offscreen.Stats().Textures - textures; made != 0 { + t.Fatalf("width %g recreated %d images inside reserved columns", width, made) } x := platform.DevicePosition(label.X, label.OriginX, float32(scale)) left, right := x, x+int(math.Ceil(float64(label.Width*float32(scale)))) @@ -328,57 +138,3 @@ func TestVulkanGridResizeKeepsTextureAndClipsItsPixels(t *testing.T) { }) } } - -func TestVulkanTextResizeMatchesUnclippedWidthAndRejectsClippedWidth(t *testing.T) { - labels := resizeTestLabels(2, 80) - labels[1].Value = "short" - labels[1].Runs = []gfx.TextRun{{Bytes: 5, Cells: 5}} - var state vulkanText - if err := state.update(nil, labels); err != nil { - t.Fatal(err) - } - state.labels[0].view, state.labels[1].view = 41, 42 - next := []platform.TextLabel{labels[1], labels[0]} - next[0].Width, next[1].Width = 200, 85 - if err := state.update(nil, next); err != nil { - t.Fatal(err) - } - if state.labels[0].view != 42 { - t.Fatalf("unclipped moved text view = %d, want 42", state.labels[0].view) - } - if state.labels[1].view != 0 { - t.Fatal("reused texture that was clipped at a narrower width") - } - state.labels[1].view = 99 - next[1].Width = 80 - if err := state.update(nil, next); err != nil { - t.Fatal(err) - } - if state.labels[0].view != 42 || state.labels[1].view != 0 { - t.Fatal("shrinking a clipped label did not retain only the unaffected texture") - } -} - -func TestVulkanTextResizeBitmapMatchesSourceAndKeepsDrawSize(t *testing.T) { - one, two := []byte{0, 0, 255, 255}, []byte{0, 0, 255, 255} - labels := []platform.TextLabel{ - {Width: 10, Height: 10, Bitmap: one, BitmapWidth: 1, BitmapHeight: 1, BitmapStride: 4, BitmapID: 1}, - {Width: 10, Height: 10, Bitmap: two, BitmapWidth: 1, BitmapHeight: 1, BitmapStride: 4, BitmapID: 1}, - } - var state vulkanText - if err := state.update(nil, labels); err != nil { - t.Fatal(err) - } - state.labels[0].view, state.labels[1].view = 41, 42 - next := []platform.TextLabel{labels[1], labels[0]} - next[0].Width, next[0].Height = 20, 30 - if err := state.update(nil, next); err != nil { - t.Fatal(err) - } - if state.labels[0].view != 42 || state.labels[1].view != 41 { - t.Fatal("bitmap source identity was lost when the labels moved") - } - if state.labels[0].label.Width != 20 || state.labels[0].label.Height != 30 { - t.Fatal("retained bitmap did not take its new drawn dimensions") - } -} diff --git a/internal/platform/linux/vulkan_window_linux.go b/internal/platform/linux/vulkan_window_linux.go index f3e56eae7..eb5dd9993 100644 --- a/internal/platform/linux/vulkan_window_linux.go +++ b/internal/platform/linux/vulkan_window_linux.go @@ -1,30 +1,110 @@ package linux -import "github.com/vivaui/viva/internal/render" +import ( + "unsafe" -// The windowRenderer methods that only adapt *vulkanRenderer to the window's -// seam. Everything the window actually does (apply, present, resize, scale, -// frame margin) lives with the Vulkan implementation. + "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/internal/platform/vulkan" + "github.com/vivaui/viva/internal/render" +) -// presentFull presents the retained swapchain image again. Vulkan keeps the -// frame it last presented, so this is the same as present. -func (renderer *vulkanRenderer) presentFull() error { return renderer.present() } +const ( + vkStructureXcbSurfaceCreateInfo = 1000005000 + vkSuccess = 0 +) -func (renderer *vulkanRenderer) forgetSurfaceCapabilities() { renderer.hasPendingCapabilities = false } - -func (renderer *vulkanRenderer) alpha() bool { return renderer.frame.alpha } +type vkXcbSurfaceCreateInfo struct { + SType uint32 + Padding0 uint32 + Next uintptr + Flags uint32 + Padding1 uint32 + Connection uintptr + Window uint32 + Padding2 uint32 +} -func (renderer *vulkanRenderer) frameMargin() uint32 { return renderer.frame.margin } +// xcbSurfaceSource makes the surface of an X window for the Vulkan renderer. +func xcbSurfaceSource(connection uintptr, window uint32) (vulkan.SurfaceSource, error) { + var create func(uintptr, *vkXcbSurfaceCreateInfo, unsafe.Pointer, *uintptr) int32 + if err := vulkan.Bind(&create, "vkCreateXcbSurfaceKHR"); err != nil { + return vulkan.SurfaceSource{}, err + } + return vulkan.SurfaceSource{ + Extension: "VK_KHR_xcb_surface", + Create: func(instance uintptr) (uintptr, error) { + info := vkXcbSurfaceCreateInfo{SType: vkStructureXcbSurfaceCreateInfo, Connection: connection, Window: window} + var surface uintptr + if err := vulkan.Check(create(instance, &info, nil, &surface), "create XCB surface"); err != nil { + return 0, err + } + return surface, nil + }, + }, nil +} -func (renderer *vulkanRenderer) deviceSize() (uint32, uint32) { return renderer.width, renderer.height } +// newVulkanWindow makes the Vulkan renderer of an X window, with the text services +// of this desktop drawing its glyphs. +func newVulkanWindow(win *window, scale float32, clear platform.Color, rectangles []render.Rectangle, labels []platform.TextLabel) (*vulkanWindow, error) { + source, err := xcbSurfaceSource(win.connection, win.id) + if err != nil { + return nil, err + } + renderer, err := vulkan.New(vulkan.Config{ + Surface: source, Width: win.width, Height: win.height, Scale: scale, Clear: clear, + Rectangles: rectangles, Labels: labels, FrameMargin: win.margin, Rasterizer: newWindowRasterizer, + }) + if err != nil { + return nil, err + } + return &vulkanWindow{renderer}, nil +} -func (renderer *vulkanRenderer) firstRectangle() (render.Rectangle, bool) { - if len(renderer.rectangles) == 0 { - return render.Rectangle{}, false +// newWindowRasterizer makes the text services a Vulkan renderer draws glyphs with. +func newWindowRasterizer() (vulkan.TextRasterizer, error) { + services, err := newTextServices() + if err != nil { + return nil, err } - return renderer.rectangles[0], true + return services, nil } -func (renderer *vulkanRenderer) stats() rendererStats { - return rendererStats{backend: "vulkan", presents: renderer.submissions, rebuilds: renderer.rebuilds, partials: renderer.partials} +// vulkanWindow adapts the Vulkan renderer to the window's seam (windowRenderer). +type vulkanWindow struct{ renderer *vulkan.Renderer } + +func (window *vulkanWindow) apply(frame platform.Frame) (bool, error) { + return window.renderer.Apply(frame) } +func (window *vulkanWindow) stage(frame platform.Frame) (bool, error) { + return window.renderer.Stage(frame) +} +func (window *vulkanWindow) present() error { return window.renderer.Present() } +func (window *vulkanWindow) presentFull() error { return window.renderer.PresentFull() } +func (window *vulkanWindow) resize(width, height uint32) error { + return window.renderer.Resize(width, height) +} +func (window *vulkanWindow) setScale(scale float32) error { return window.renderer.SetScale(scale) } +func (window *vulkanWindow) setFrameMargin(margin uint32) error { + return window.renderer.SetFrameMargin(margin) +} +func (window *vulkanWindow) surfaceSize(width, height uint32) (uint32, uint32) { + return window.renderer.SurfaceSize(width, height) +} +func (window *vulkanWindow) refreshText() error { return window.renderer.RefreshText() } +func (window *vulkanWindow) forgetSurfaceCapabilities() { window.renderer.ForgetSurfaceCapabilities() } +func (window *vulkanWindow) alpha() bool { return window.renderer.Alpha() } +func (window *vulkanWindow) frameMargin() uint32 { return window.renderer.FrameMargin() } +func (window *vulkanWindow) deviceSize() (uint32, uint32) { + return window.renderer.DeviceSize() +} +func (window *vulkanWindow) firstRectangle() (render.Rectangle, bool) { + return window.renderer.FirstRectangle() +} +func (window *vulkanWindow) stats() rendererStats { + stats := window.renderer.Stats() + return rendererStats{backend: "vulkan", presents: stats.Presents, rebuilds: stats.Rebuilds, partials: stats.Partials} +} +func (window *vulkanWindow) close() { window.renderer.Close() } + +// software reports whether the device is a CPU rasterizer (lavapipe). +func (window *vulkanWindow) software() bool { return window.renderer.Software() } diff --git a/internal/platform/linux/wide_label_linux_test.go b/internal/platform/linux/wide_label_linux_test.go index e320d7d4f..17b6bbdd6 100644 --- a/internal/platform/linux/wide_label_linux_test.go +++ b/internal/platform/linux/wide_label_linux_test.go @@ -71,59 +71,6 @@ var wideBackends = []struct { }, func(a, b color.RGBA) bool { return a == b }}, } -// A line wider than a texture holds gets a texture of the window of it that the viewport and -// its clip show, with or without runs. A scroll inside that window keeps the texture and one -// past it rasterizes the line again; a line scrolled out of view, or too tall for any texture, -// is dropped and not rasterized again every frame for that. -func TestVulkanWideLabelWindowFollowsTheViewport(t *testing.T) { - const scale, viewport = 1.5, 600 - for _, runs := range [][]gfx.TextRun{nil, wholeRun(wideValue)} { - label := vulkanLabelTexture{label: wideMonoLine(wideValue, 0, runs)} - if skip, width, height, wide, ok := label.window(scale, viewport); !ok || !wide || skip != 0 || width != 1800 || height != 27 { - t.Errorf("runs %d, start of the line: window = %d, %d, %d, %v, %v; want 0, 1800, 27, wide", len(runs), skip, width, height, wide, ok) - } - label.label.X = -20000 // 30000 device pixels scrolled off the left - if skip, width, _, _, ok := label.window(scale, viewport); !ok || skip != 30000-600 || width != 1800 { - t.Errorf("runs %d, scrolled: window = %d, %d, %v; want 29400, 1800", len(runs), skip, width, ok) - } - if !label.needsUpload(scale, viewport) { - t.Errorf("runs %d: a wide line without a texture is not rasterized", len(runs)) - } - label.view, label.scale, label.skip, label.width, label.height, label.wide = 1, scale, 29400, 1800, 27, true - label.label.X = -20100 - if label.needsUpload(scale, viewport) { - t.Errorf("runs %d: a scroll inside the texture's window rasterizes the line again", len(runs)) - } - label.label.X = -21000 - if !label.needsUpload(scale, viewport) { - t.Errorf("runs %d: a scroll past the texture's window keeps the texture", len(runs)) - } - label.label.X = -40000 - if !label.needsUpload(scale, viewport) { - t.Errorf("runs %d: a line scrolled out of view keeps its texture", len(runs)) - } - if _, _, _, wide, ok := label.window(scale, viewport); ok || !wide { - t.Errorf("runs %d: a line scrolled out of view has a window", len(runs)) - } - label.drop(nil, scale, true) - if label.needsUpload(scale, viewport) { - t.Errorf("runs %d: a dropped line out of view is rasterized again", len(runs)) - } - label.label.X = -20000 - if !label.needsUpload(scale, viewport) { - t.Errorf("runs %d: a dropped line scrolled back into view is not rasterized", len(runs)) - } - label.label.Height = 12000 // 18000 device pixels - if _, _, _, _, ok := label.window(scale, viewport); ok { - t.Errorf("runs %d: a line too tall for any texture has a window", len(runs)) - } - label.drop(nil, scale, false) - if label.needsUpload(scale, viewport) { - t.Errorf("runs %d: a dropped line too tall for any texture is rasterized again", len(runs)) - } - } -} - // A monospaced line wider than any texture, such as a long log line shown unwrapped, is drawn // from a window of it at its start and scrolled, on an opaque target and a transparent one, // without and with runs, by the Vulkan renderer and by the CPU one. Its pixels are the pixels diff --git a/internal/platform/linux/window_controls_linux.go b/internal/platform/linux/window_controls_linux.go index bac82042c..8a9629067 100644 --- a/internal/platform/linux/window_controls_linux.go +++ b/internal/platform/linux/window_controls_linux.go @@ -6,6 +6,8 @@ import ( "math" "unsafe" + "github.com/vivaui/viva/internal/platform/windowframe" + "github.com/vivaui/viva/internal/platform" ) @@ -307,7 +309,7 @@ func (win *window) beginWindowMove(config platform.Config, event *xcbInputEvent) direction, ok := uint32(moveResizeMove), false if !win.frame.maximized { // The top edge yields to a control, so the buttons work up to the top. - edge := platform.EdgeAt(x, y, float32(contentSize(win.width, win.margin))/scale, float32(contentSize(win.height, win.margin))/scale, press == platform.PressControl) + edge := platform.EdgeAt(x, y, float32(windowframe.ContentSize(win.width, win.margin))/scale, float32(windowframe.ContentSize(win.height, win.margin))/scale, press == platform.PressControl) if ok = edge != platform.EdgeNone; ok { direction = moveResizeDirection(edge) } diff --git a/internal/platform/linux/window_frame.go b/internal/platform/linux/window_frame.go deleted file mode 100644 index c3803cfae..000000000 --- a/internal/platform/linux/window_frame.go +++ /dev/null @@ -1,84 +0,0 @@ -package linux - -import "math" - -// A window the application draws the frame of (platform.WindowCustomTitlebar) -// has no frame from the window manager, so on a desktop that composites windows -// it also has no shadow and square corners, where the macOS and Windows windows -// have both. Viva draws them: the X window is larger than the content by a margin -// on every side, the margin is transparent except for a soft shadow, and the -// content's corners are rounded. The margin is announced to the window manager -// as _GTK_FRAME_EXTENTS, which is how it knows where the window really is: it -// places, snaps and maximizes the content, not the margin. -// -// Everything here is in device pixels unless it says logical. - -const ( - // frameMarginLogical is the margin around the content, which holds the shadow. - frameMarginLogical = 24 - // frameRadiusLogical is the radius of the content's corners. - frameRadiusLogical = 10 - // frameGripLogical is how much of the margin takes input: a press there - // resizes the window, the rest of the margin lets the pointer through to the - // window behind. - frameGripLogical = 8 - // frameShadow is the shadow's blur, offset down, and strength (logical). - frameShadowBlur = 18 - frameShadowOffset = 4 - frameShadowAlpha = 0.38 -) - -// frameMargin is the margin in device pixels at a display scale. -func frameMargin(scale float32) uint32 { - return uint32(math.Round(float64(frameMarginLogical) * float64(max(scale, 1)))) -} - -// pixelBox is a rectangle in device pixels. -type pixelBox struct{ x, y, width, height int32 } - -// contentSize is the size of the content of a window of a total size with a -// margin on every side; a margin that leaves nothing leaves one pixel. -func contentSize(total, margin uint32) uint32 { - if total <= 2*margin { - return 1 - } - return total - 2*margin -} - -// frameContent is the content rectangle of a window of width x height. -func frameContent(width, height, margin uint32) pixelBox { - return pixelBox{int32(margin), int32(margin), int32(contentSize(width, margin)), int32(contentSize(height, margin))} -} - -// frameBands are the four strips of the margin, which the shadow is drawn in: -// top and bottom across the whole width, left and right between them. -func frameBands(width, height, margin uint32) [4]pixelBox { - m, w, h := int32(margin), int32(width), int32(height) - return [4]pixelBox{ - {0, 0, w, m}, - {0, h - m, w, m}, - {0, m, m, h - 2*m}, - {w - m, m, m, h - 2*m}, - } -} - -// frameCorners are the squares at the four corners of the content that its -// rounded corners are cut in; each is a pixel larger than the radius so the -// edge of the cut is not clipped. -func frameCorners(width, height, margin uint32, radius float32) [4]pixelBox { - side := int32(math.Ceil(float64(radius))) + 1 - c := frameContent(width, height, margin) - return [4]pixelBox{ - {c.x, c.y, side, side}, - {c.x + c.width - side, c.y, side, side}, - {c.x, c.y + c.height - side, side, side}, - {c.x + c.width - side, c.y + c.height - side, side, side}, - } -} - -// frameInput is the part of the window that takes input: the content and a grip -// around it that is used to resize. -func frameInput(width, height, margin, grip uint32) pixelBox { - reach := min(grip, margin) - return pixelBox{int32(margin - reach), int32(margin - reach), int32(width - 2*(margin-reach)), int32(height - 2*(margin-reach))} -} diff --git a/internal/platform/linux/window_frame_linux_test.go b/internal/platform/linux/window_frame_linux_test.go index 13ebf687e..68d5347d6 100644 --- a/internal/platform/linux/window_frame_linux_test.go +++ b/internal/platform/linux/window_frame_linux_test.go @@ -8,6 +8,8 @@ import ( "testing" "unsafe" + "github.com/vivaui/viva/internal/platform/windowframe" + "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/internal/platform" ) @@ -120,8 +122,8 @@ func TestFramedWindowKeepsItsContentWhenTheScaleChanges(t *testing.T) { t.Fatal(err) } win := state.win - if win.margin != frameMargin(2) || state.renderer.frameMargin() != frameMargin(2) { - t.Fatalf("margin %d (renderer %d), want %d at 2x", win.margin, state.renderer.frameMargin(), frameMargin(2)) + if win.margin != windowframe.Margin(2) || state.renderer.frameMargin() != windowframe.Margin(2) { + t.Fatalf("margin %d (renderer %d), want %d at 2x", win.margin, state.renderer.frameMargin(), windowframe.Margin(2)) } if size := win.logicalSize(); size.Scale != 2 { t.Fatalf("scale %v", size.Scale) @@ -159,7 +161,7 @@ func TestFramedWindowSuppressesFrameChangeWhileMaximized(t *testing.T) { // When restored, reportFrame reports the restored frame. win.frame.maximized = false scale := win.displayScale() - win.margin = frameMargin(scale) + win.margin = windowframe.Margin(scale) win.width = deviceLength(300, scale) + 2*win.margin win.height = deviceLength(200, scale) + 2*win.margin // Simulate move to a different position @@ -224,8 +226,8 @@ func TestConfigureNotifySynchronizesMarginAndGeometry(t *testing.T) { win.api.flush(win.connection) resizesCountBeforeRestore := len(resizes) - restoreWidth := deviceLength(300, scale) + 2*frameMargin(scale) - restoreHeight := deviceLength(200, scale) + 2*frameMargin(scale) + restoreWidth := deviceLength(300, scale) + 2*windowframe.Margin(scale) + restoreHeight := deviceLength(200, scale) + 2*windowframe.Margin(scale) restoreConfigure := xcbConfigureEvent{ ResponseType: xcbConfigureNotify, Width: uint16(restoreWidth), @@ -236,8 +238,8 @@ func TestConfigureNotifySynchronizesMarginAndGeometry(t *testing.T) { t.Fatalf("handleEvent restore configure: close=%v, err=%v", closeWin, err) } - if win.margin != frameMargin(scale) { - t.Fatalf("win.margin = %d, want %d after restore", win.margin, frameMargin(scale)) + if win.margin != windowframe.Margin(scale) { + t.Fatalf("win.margin = %d, want %d after restore", win.margin, windowframe.Margin(scale)) } if win.frame.maximized { t.Fatal("win.frame.maximized = true, want false") @@ -306,8 +308,8 @@ func TestPropertyNotifyBeforeConfigureNotifyDoesNotGlitch(t *testing.T) { } // Now deliver ConfigureNotify - restoreWidth := deviceLength(300, scale) + 2*frameMargin(scale) - restoreHeight := deviceLength(200, scale) + 2*frameMargin(scale) + restoreWidth := deviceLength(300, scale) + 2*windowframe.Margin(scale) + restoreHeight := deviceLength(200, scale) + 2*windowframe.Margin(scale) restoreConfigure := xcbConfigureEvent{ ResponseType: xcbConfigureNotify, Width: uint16(restoreWidth), @@ -415,8 +417,8 @@ func TestConfigureNotifyBeforePropertyNotifySynchronizesMargin(t *testing.T) { // Now test restore with ConfigureNotify FIRST, PropertyNotify SECOND: win.toggleMaximize() resizesBeforeRestore := len(resizes) - restoreWidth := deviceLength(300, scale) + 2*frameMargin(scale) - restoreHeight := deviceLength(200, scale) + 2*frameMargin(scale) + restoreWidth := deviceLength(300, scale) + 2*windowframe.Margin(scale) + restoreHeight := deviceLength(200, scale) + 2*windowframe.Margin(scale) restoreConfigure := xcbConfigureEvent{ ResponseType: xcbConfigureNotify, Width: uint16(restoreWidth), @@ -450,8 +452,8 @@ func TestConfigureNotifyBeforePropertyNotifySynchronizesMargin(t *testing.T) { } // Verify margin was restored and final size is 300x200 - if win.margin != frameMargin(scale) { - t.Fatalf("win.margin = %d, want %d after restore", win.margin, frameMargin(scale)) + if win.margin != windowframe.Margin(scale) { + t.Fatalf("win.margin = %d, want %d after restore", win.margin, windowframe.Margin(scale)) } if win.frame.maximized { t.Fatal("win.frame.maximized = true, want false after restore") diff --git a/internal/platform/linux/window_linux.go b/internal/platform/linux/window_linux.go index 6fa133622..4bdde0dea 100644 --- a/internal/platform/linux/window_linux.go +++ b/internal/platform/linux/window_linux.go @@ -12,6 +12,9 @@ import ( "time" "unsafe" + "github.com/vivaui/viva/internal/platform/windowframe" + "github.com/vivaui/viva/internal/render" + "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/internal/diag" "github.com/vivaui/viva/internal/input" @@ -131,7 +134,7 @@ func (win *window) storeScale(scale float32) { win.scaleBits.Store(math.Float32b // logicalSize is the window's size in logical pixels. func (win *window) logicalSize() platform.Size { scale := win.displayScale() - return platform.Size{Width: float32(contentSize(win.width, win.margin)) / scale, Height: float32(contentSize(win.height, win.margin)) / scale, Scale: scale} + return platform.Size{Width: float32(windowframe.ContentSize(win.width, win.margin)) / scale, Height: float32(windowframe.ContentSize(win.height, win.margin)) / scale, Scale: scale} } func Run(config platform.Config) error { @@ -350,7 +353,7 @@ func (application *linuxApplication) OpenWindow(config platform.Config) (platfor } state.renderer = renderer if config.SetFrameInterval != nil { - if _, vulkan := renderer.(*vulkanRenderer); vulkan { + if _, vulkan := renderer.(*vulkanWindow); vulkan { // A FIFO present blocks until the compositor takes the frame, so the // display paces the window; the runtime asks for the next frame as // soon as the last one is shown. @@ -849,7 +852,7 @@ func (state *linuxWindowState) reportFrame() (int32, int32, bool) { scale := win.displayScale() frame := gfx.Rect{ X: float32(x) / scale, Y: float32(y) / scale, - Width: float32(contentSize(win.width, win.margin)) / scale, Height: float32(contentSize(win.height, win.margin)) / scale, + Width: float32(windowframe.ContentSize(win.width, win.margin)) / scale, Height: float32(windowframe.ContentSize(win.height, win.margin)) / scale, } if frame == win.lastFrame { return x, y, true @@ -1298,8 +1301,8 @@ func (state *linuxWindowState) refreshScale(reload bool) error { func (state *linuxWindowState) applyScale(scale float32) error { win := state.win old := win.displayScale() - logicalWidth := int(math.Round(float64(contentSize(win.width, win.margin)) / float64(old))) - logicalHeight := int(math.Round(float64(contentSize(win.height, win.margin)) / float64(old))) + logicalWidth := int(math.Round(float64(windowframe.ContentSize(win.width, win.margin)) / float64(old))) + logicalHeight := int(math.Round(float64(windowframe.ContentSize(win.height, win.margin)) / float64(old))) win.storeScale(scale) if err := state.renderer.setScale(scale); err != nil { return err @@ -1307,7 +1310,7 @@ func (state *linuxWindowState) applyScale(scale float32) error { margin := uint32(0) if win.margin > 0 { // The margin is a whole number of device pixels at every scale. - margin = frameMargin(scale) + margin = windowframe.Margin(scale) win.setMargin(margin) if err := state.renderer.setFrameMargin(margin); err != nil { return err @@ -1343,10 +1346,10 @@ func validateConfig(config platform.Config) error { if config.WindowMode > platform.WindowNotification { return fmt.Errorf("linux: invalid window mode %d", config.WindowMode) } - if err := validateRectangles(config.Rectangles); err != nil { + if err := render.ValidateRectangles(config.Rectangles); err != nil { return err } - if err := validateInitialTextLabels(config.TextLabels); err != nil { + if err := platform.ValidateTextLabels(config.TextLabels); err != nil { return err } return nil @@ -1403,7 +1406,7 @@ func (application *linuxApplication) openWindow(config platform.Config) (*window // composites it draws the shadow and the round corners too, in a margin. if visual, framed := win.wantsFrame(screenIndex); framed { frameVisual, win.frameWanted = visual, true - win.margin = frameMargin(scale) + win.margin = windowframe.Margin(scale) win.width, win.height = win.width+2*win.margin, win.height+2*win.margin } } diff --git a/internal/platform/linux/window_margin_linux.go b/internal/platform/linux/window_margin_linux.go index f50a88ba3..f114f36c6 100644 --- a/internal/platform/linux/window_margin_linux.go +++ b/internal/platform/linux/window_margin_linux.go @@ -5,6 +5,9 @@ import ( "strconv" "unsafe" + "github.com/vivaui/viva/internal/platform/vulkan" + "github.com/vivaui/viva/internal/platform/windowframe" + "github.com/ebitengine/purego" ) @@ -119,7 +122,7 @@ func (win *window) wantsFrame(screenIndex int32) (visual uint32, ok bool) { // alpha window: Mesa before 23 drew nothing into one. The CPU renderer // composites in software, so the drawn frame is kept for it. "on" asks // for it anyway. - if mode != "on" && vulkanRenderingRequested() && vulkanDeviceIsSoftware() { + if mode != "on" && vulkanRenderingRequested() && vulkan.DeviceIsSoftware() { return 0, false } // Synchronized resize (_NET_WM_SYNC_REQUEST) would keep the inset margin @@ -192,9 +195,9 @@ func (win *window) updateInputRegion() { purego.RegisterLibFunc(&win.shapeRectangles, library, "xcb_shape_rectangles") win.shapeLibrary = library } - grip := uint32(float32(frameGripLogical) * win.displayScale()) - box := frameInput(win.width, win.height, win.margin, grip) - rectangle := [4]uint16{uint16(box.x), uint16(box.y), uint16(box.width), uint16(box.height)} + grip := uint32(float32(windowframe.GripLogical) * win.displayScale()) + box := windowframe.Input(win.width, win.height, win.margin, grip) + rectangle := [4]uint16{uint16(box.X), uint16(box.Y), uint16(box.Width), uint16(box.Height)} win.shapeRectangles(win.connection, shapeSet, shapeInput, 0, win.id, 0, 0, 1, unsafe.Pointer(&rectangle[0])) } @@ -242,7 +245,7 @@ func (state *linuxWindowState) syncMargin() (bool, error) { } margin := uint32(0) if !win.frame.maximized && !win.fullscreen.Load() { - margin = frameMargin(win.displayScale()) + margin = windowframe.Margin(win.displayScale()) } if margin == win.margin { return false, nil diff --git a/internal/platform/linux/window_renderer_fake_linux_test.go b/internal/platform/linux/window_renderer_fake_linux_test.go new file mode 100644 index 000000000..29e738c42 --- /dev/null +++ b/internal/platform/linux/window_renderer_fake_linux_test.go @@ -0,0 +1,96 @@ +//go:build linux + +package linux + +import ( + "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/internal/render" +) + +// fakeWindowRenderer is a windowRenderer that records the calls a window makes, for the +// tests of what the window does with its renderer (the renderers have their own). +type fakeWindowRenderer struct { + calls []string + width, scale float32 + deviceWidth uint32 + deviceHeight uint32 + // serverSize is what surfaceSize reports: the size the surface has now. + serverSize [2]uint32 + // failAt2x makes present fail while the scale is 2. + failAt2x bool + // shared, when set, also gets every call, to order them against what else a test records. + shared *[]string +} + +func (renderer *fakeWindowRenderer) record(call string) { + renderer.calls = append(renderer.calls, call) + if renderer.shared != nil { + *renderer.shared = append(*renderer.shared, call) + } +} + +func (renderer *fakeWindowRenderer) apply(platform.Frame) (bool, error) { + renderer.record("apply") + return true, nil +} +func (renderer *fakeWindowRenderer) stage(platform.Frame) (bool, error) { + renderer.record("stage") + return true, nil +} +func (renderer *fakeWindowRenderer) present() error { + renderer.record("present") + if renderer.failAt2x && renderer.scale == 2 { + return errFakeLoss + } + return nil +} +func (renderer *fakeWindowRenderer) presentFull() error { return renderer.present() } +func (renderer *fakeWindowRenderer) resize(width, height uint32) error { + renderer.record("resize") + renderer.deviceWidth, renderer.deviceHeight = width, height + return nil +} +func (renderer *fakeWindowRenderer) setScale(scale float32) error { + renderer.record("setScale") + renderer.scale = scale + return nil +} +func (renderer *fakeWindowRenderer) setFrameMargin(uint32) error { return nil } +func (renderer *fakeWindowRenderer) surfaceSize(width, height uint32) (uint32, uint32) { + renderer.record("surfaceSize") + if renderer.serverSize != [2]uint32{} { + return renderer.serverSize[0], renderer.serverSize[1] + } + return width, height +} +func (renderer *fakeWindowRenderer) refreshText() error { return nil } +func (renderer *fakeWindowRenderer) forgetSurfaceCapabilities() { + renderer.record("forget") +} +func (renderer *fakeWindowRenderer) alpha() bool { return false } +func (renderer *fakeWindowRenderer) frameMargin() uint32 { return 0 } +func (renderer *fakeWindowRenderer) deviceSize() (uint32, uint32) { + return renderer.deviceWidth, renderer.deviceHeight +} +func (renderer *fakeWindowRenderer) firstRectangle() (render.Rectangle, bool) { + return render.Rectangle{}, false +} +func (renderer *fakeWindowRenderer) stats() rendererStats { return rendererStats{backend: "fake"} } +func (renderer *fakeWindowRenderer) close() {} + +// count is how many times call was made. +func (renderer *fakeWindowRenderer) count(call string) int { + n := 0 + for _, made := range renderer.calls { + if made == call { + n++ + } + } + return n +} + +type fakeLoss struct{} + +func (fakeLoss) Error() string { return "fake: the device was lost" } + +var errFakeLoss error = fakeLoss{} diff --git a/internal/platform/linux/window_renderer_linux.go b/internal/platform/linux/window_renderer_linux.go index 83621c76b..544d99d0e 100644 --- a/internal/platform/linux/window_renderer_linux.go +++ b/internal/platform/linux/window_renderer_linux.go @@ -77,9 +77,9 @@ func newWindowPainter(win *window, scale float32, clear platform.Color, rectangl if cpuRendererPreferred.Load() && !vulkanRenderingRequested() { return cpu() } - vulkan, err := newVulkanRenderer(win.connection, win.id, win.width, win.height, scale, clear, rectangles, labels, win.margin) + vulkan, err := newVulkanWindow(win, scale, clear, rectangles, labels) if err == nil { - if !vulkan.software || vulkanRenderingRequested() { + if !vulkan.software() || vulkanRenderingRequested() { return vulkan, nil } vulkan.close() diff --git a/internal/platform/linux/window_resize_bench_linux_test.go b/internal/platform/linux/window_resize_bench_linux_test.go index 89dd01861..ecd3ca0c9 100644 --- a/internal/platform/linux/window_resize_bench_linux_test.go +++ b/internal/platform/linux/window_resize_bench_linux_test.go @@ -9,7 +9,6 @@ import ( "slices" "testing" "time" - "unsafe" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/internal/platform" @@ -19,7 +18,8 @@ import ( // BenchmarkX11WindowLiveResize is opt-in because it briefly opens a real window. // It includes the WM's configure round-trip, text preparation, swapchain rebuild, -// and present; the extra metrics separate driver waits from application work. +// and present; BenchmarkLiveResize in the vulkan package separates driver waits from +// application work. func BenchmarkX11WindowLiveResize(b *testing.B) { if os.Getenv("VIVA_LINUX_RESIZE_BENCH") == "" || os.Getenv("DISPLAY") == "" { b.Skip("set VIVA_LINUX_RESIZE_BENCH=1 with an X11 display and Vulkan driver") @@ -69,61 +69,10 @@ func BenchmarkX11WindowLiveResize(b *testing.B) { defer application.atspiClose() state := control.(*nativeWindow).state win := state.win - renderer, ok := state.renderer.(*vulkanRenderer) - if !ok { + if _, ok := state.renderer.(*vulkanWindow); !ok { b.Skip("this machine has no Vulkan renderer") } - var idleTime, createTime, destroyTime, submitTime, presentTime, acquireTime, fenceTime, dispatchTime time.Duration - var creates int - idle := renderer.api.deviceWaitIdle - renderer.api.deviceWaitIdle = func(device uintptr) int32 { - start := time.Now() - result := idle(device) - idleTime += time.Since(start) - return result - } - create := renderer.api.createSwapchain - renderer.api.createSwapchain = func(device uintptr, info *vkSwapchainCreateInfo, allocator unsafe.Pointer, swapchain *uintptr) int32 { - start := time.Now() - result := create(device, info, allocator, swapchain) - createTime += time.Since(start) - creates++ - return result - } - destroy := renderer.api.destroySwapchain - renderer.api.destroySwapchain = func(device, swapchain uintptr, allocator unsafe.Pointer) { - start := time.Now() - destroy(device, swapchain, allocator) - destroyTime += time.Since(start) - } - submit := renderer.api.queueSubmit - renderer.api.queueSubmit = func(queue uintptr, count uint32, info *vkSubmitInfo, fence uintptr) int32 { - start := time.Now() - result := submit(queue, count, info, fence) - submitTime += time.Since(start) - return result - } - present := renderer.api.queuePresent - renderer.api.queuePresent = func(queue uintptr, info *vkPresentInfo) int32 { - start := time.Now() - result := present(queue, info) - presentTime += time.Since(start) - return result - } - acquire := renderer.api.acquireNextImage - renderer.api.acquireNextImage = func(device, swapchain uintptr, timeout uint64, semaphore, fence uintptr, image *uint32) int32 { - start := time.Now() - result := acquire(device, swapchain, timeout, semaphore, fence, image) - acquireTime += time.Since(start) - return result - } - wait := renderer.api.waitForFences - renderer.api.waitForFences = func(device uintptr, count uint32, fences *uintptr, all uint32, timeout uint64) int32 { - start := time.Now() - result := wait(device, count, fences, all, timeout) - fenceTime += time.Since(start) - return result - } + var dispatchTime time.Duration resize := func(width, height uint32) { b.Helper() size := [2]uint32{width, height} @@ -149,8 +98,7 @@ func BenchmarkX11WindowLiveResize(b *testing.B) { } } resize(641, 481) - idleTime, createTime, presentTime, acquireTime, fenceTime, dispatchTime, creates = 0, 0, 0, 0, 0, 0, 0 - destroyTime, submitTime = 0, 0 + dispatchTime = 0 samples := make([]time.Duration, b.N) b.ReportAllocs() b.ResetTimer() @@ -163,10 +111,7 @@ func BenchmarkX11WindowLiveResize(b *testing.B) { slices.Sort(samples) b.ReportMetric(float64(samples[(len(samples)*95-1)/100].Nanoseconds()), "p95-ns/op") b.ReportMetric(float64(samples[len(samples)-1].Nanoseconds()), "max-ns/op") - for name, duration := range map[string]time.Duration{"idle": idleTime, "create": createTime, "destroy": destroyTime, "submit": submitTime, "present": presentTime, "acquire": acquireTime, "fence": fenceTime, "dispatch": dispatchTime} { - b.ReportMetric(float64(duration.Nanoseconds())/float64(b.N), name+"-ns/op") - } - b.ReportMetric(float64(creates)/float64(b.N), "swapchains/op") + b.ReportMetric(float64(dispatchTime.Nanoseconds())/float64(b.N), "dispatch-ns/op") }) } } diff --git a/internal/platform/linux/window_resize_linux_test.go b/internal/platform/linux/window_resize_linux_test.go index f71304b87..508e99d22 100644 --- a/internal/platform/linux/window_resize_linux_test.go +++ b/internal/platform/linux/window_resize_linux_test.go @@ -1,6 +1,9 @@ +//go:build linux + package linux import ( + "slices" "testing" "unsafe" @@ -8,22 +11,17 @@ import ( "github.com/vivaui/viva/internal/platform" ) -func TestMovingWindowDoesNotQueryVulkanSurface(t *testing.T) { - queries := 0 +// Moving a window changes no size: the renderer is not asked about its surface, not +// resized, and the window still reports where its content is. +func TestMovingWindowDoesNotResizeOrQueryTheSurface(t *testing.T) { var frames []gfx.Rect + renderer := &fakeWindowRenderer{deviceWidth: 100, deviceHeight: 100} state := &linuxWindowState{ win: &window{id: 1, width: 100, height: 100}, config: platform.Config{ OnFrameChange: func(frame gfx.Rect) { frames = append(frames, frame) }, }, - renderer: &vulkanRenderer{ - physical: 1, surface: 2, width: 100, height: 100, - api: &vulkanAPI{getSurfaceCapabilities: func(_, _ uintptr, caps *vkSurfaceCapabilities) int32 { - queries++ - caps.Current = vkExtent2D{Width: 100, Height: 100} - return vkSuccess - }}, - }, + renderer: renderer, } for x := int16(10); x < 30; x++ { event := xcbConfigureEvent{ResponseType: xcbConfigureNotify | 0x80, Window: 1, X: x, Y: 20, Width: 100, Height: 100} @@ -31,63 +29,49 @@ func TestMovingWindowDoesNotQueryVulkanSurface(t *testing.T) { t.Fatalf("move: closed=%v err=%v", closed, err) } } - if queries != 0 || state.resizeEvents != 0 { - t.Fatalf("pure movement queried the surface %d times and resized %d times", queries, state.resizeEvents) + if renderer.count("surfaceSize") != 0 || renderer.count("resize") != 0 || state.resizeEvents != 0 { + t.Fatalf("pure movement asked about the surface %d times, resized %d times and reported %d resizes: %v", + renderer.count("surfaceSize"), renderer.count("resize"), state.resizeEvents, renderer.calls) } if len(frames) != 20 || frames[len(frames)-1] != (gfx.Rect{X: 29, Y: 20, Width: 100, Height: 100}) { t.Fatalf("movement stopped reporting the content frame: %v", frames) } } -func TestObsoleteConfigureDoesNotCacheSurfaceForLaterPresent(t *testing.T) { - recreations := 0 - renderer := newSuboptimalTestRenderer(vkErrorOutOfDate, vkSuccess, &recreations) - renderer.physical, renderer.surface = 1, 2 - renderer.width, renderer.height = 100, 100 - queries := 0 - current := uint32(100) - baseQuery := renderer.api.getSurfaceCapabilities - renderer.api.getSurfaceCapabilities = func(device, surface uintptr, caps *vkSurfaceCapabilities) int32 { - queries++ - status := baseQuery(device, surface, caps) - caps.Current.Width = current - return status - } +// What a configure event made the renderer read about its surface is not kept for later: +// an obsolete event that needed no resize must not leave capabilities for a later +// present to rebuild the swapchain by. +func TestConfigureDoesNotLeaveSurfaceCapabilitiesBehind(t *testing.T) { + renderer := &fakeWindowRenderer{deviceWidth: 100, deviceHeight: 100, serverSize: [2]uint32{100, 100}} state := &linuxWindowState{win: &window{id: 1, width: 100, height: 100}, renderer: renderer} - // The server has already reached the size we drew; this queued intermediate - // Configure must not leave its capabilities for a later OUT_OF_DATE recovery. + // The server has already reached the size we drew: this queued intermediate + // Configure needs no resize. event := xcbConfigureEvent{ResponseType: xcbConfigureNotify | 0x80, Window: 1, Width: 90, Height: 100} if closed, err := state.handleEvent(unsafe.Pointer(&event)); closed || err != nil { t.Fatalf("obsolete configure: closed=%v err=%v", closed, err) } - current = 120 - if err := renderer.presentRebuilding(); err != nil { - t.Fatal(err) + if renderer.count("resize") != 0 { + t.Fatalf("an obsolete configure resized the renderer: %v", renderer.calls) } - if queries != 2 || renderer.width != current || recreations != 1 { - t.Fatalf("recovery used obsolete geometry: queries=%d width=%d recreations=%d", queries, renderer.width, recreations) + if last := renderer.calls[len(renderer.calls)-1]; last != "forget" { + t.Fatalf("the configure left the surface capabilities it read: %v", renderer.calls) } } -func TestResizeSharesSurfaceQueryOnlyWithItsOwnSwapchain(t *testing.T) { - recreations := 0 - renderer := newSuboptimalTestRenderer(vkSuccess, vkSuccess, &recreations) - renderer.physical, renderer.surface = 1, 2 - renderer.width, renderer.height = 100, 100 - queries := 0 - baseQuery := renderer.api.getSurfaceCapabilities - renderer.api.getSurfaceCapabilities = func(device, surface uintptr, caps *vkSurfaceCapabilities) int32 { - queries++ - status := baseQuery(device, surface, caps) - caps.Current.Width = 120 - return status - } +// A resize reads the surface once and resizes the swapchain by that reading: the window +// asks the renderer for the surface's size, then resizes it, then presents. +func TestResizeAsksForTheSurfaceThenResizesThenPresents(t *testing.T) { + renderer := &fakeWindowRenderer{deviceWidth: 100, deviceHeight: 100} state := &linuxWindowState{win: &window{id: 1, width: 100, height: 100}, renderer: renderer} event := xcbConfigureEvent{ResponseType: xcbConfigureNotify | 0x80, Window: 1, Width: 120, Height: 100} if closed, err := state.handleEvent(unsafe.Pointer(&event)); closed || err != nil { t.Fatalf("resize: closed=%v err=%v", closed, err) } - if queries != 1 || recreations != 1 || renderer.width != 120 || renderer.hasPendingCapabilities { - t.Fatalf("resize queries=%d recreations=%d width=%d pending=%v", queries, recreations, renderer.width, renderer.hasPendingCapabilities) + surface, resize, present := slices.Index(renderer.calls, "surfaceSize"), slices.Index(renderer.calls, "resize"), slices.Index(renderer.calls, "present") + if surface < 0 || !(surface < resize && resize < present) { + t.Fatalf("a resize made the calls %v, want surfaceSize, resize, present in that order", renderer.calls) + } + if renderer.deviceWidth != 120 || state.resizeEvents != 1 { + t.Fatalf("the renderer is %d wide after %d resize events", renderer.deviceWidth, state.resizeEvents) } } diff --git a/internal/platform/linux/window_size_linux_test.go b/internal/platform/linux/window_size_linux_test.go index 2aa833790..b62d1f6cc 100644 --- a/internal/platform/linux/window_size_linux_test.go +++ b/internal/platform/linux/window_size_linux_test.go @@ -4,6 +4,8 @@ import ( "encoding/binary" "testing" "unsafe" + + "github.com/vivaui/viva/internal/platform/windowframe" ) func TestSetSizeCommandUsesLogicalContentSize(t *testing.T) { @@ -12,7 +14,7 @@ func TestSetSizeCommandUsesLogicalContentSize(t *testing.T) { flushed := false win := &window{ id: 7, - margin: frameMargin(1.5), + margin: windowframe.Margin(1.5), api: &xcbAPI{ configureWindow: func(_ uintptr, window uint32, mask uint16, values *uint32) xcbVoidCookie { if window != 7 { @@ -38,7 +40,7 @@ func TestSetSizeCommandUsesLogicalContentSize(t *testing.T) { if err := state.command(commandSetSize, data); err != nil { t.Fatal(err) } - margin := 2 * frameMargin(1.5) + margin := 2 * windowframe.Margin(1.5) if want := deviceLength(420, 1.5) + margin; gotWidth != want { t.Fatalf("configured width = %d, want %d", gotWidth, want) } diff --git a/internal/platform/linux/window_sync_resize_linux_test.go b/internal/platform/linux/window_sync_resize_linux_test.go index d70f56218..054b8e172 100644 --- a/internal/platform/linux/window_sync_resize_linux_test.go +++ b/internal/platform/linux/window_sync_resize_linux_test.go @@ -1,3 +1,5 @@ +//go:build linux + package linux import ( @@ -6,6 +8,9 @@ import ( "unsafe" ) +// A configure that changes the display scale presents again at the new scale, and the +// window answers the window manager's sync request only after that frame, and only if it +// was presented. func TestConfigureAnswersSyncAfterScaleRefresh(t *testing.T) { for _, failScaleFrame := range []bool{false, true} { name := "presented" @@ -14,23 +19,7 @@ func TestConfigureAnswersSyncAfterScaleRefresh(t *testing.T) { } t.Run(name, func(t *testing.T) { var order []string - recreations := 0 - renderer := newSuboptimalTestRenderer(vkSuccess, vkSuccess, &recreations) - renderer.physical, renderer.surface = 1, 2 - renderer.width, renderer.height = 100, 100 - baseQuery := renderer.api.getSurfaceCapabilities - renderer.api.getSurfaceCapabilities = func(device, surface uintptr, caps *vkSurfaceCapabilities) int32 { - status := baseQuery(device, surface, caps) - caps.Current.Width = 120 - return status - } - renderer.api.queuePresent = func(uintptr, *vkPresentInfo) int32 { - order = append(order, "present") - if failScaleFrame && renderer.pixelScale() == 2 { - return vkErrorDeviceLost - } - return vkSuccess - } + renderer := &fakeWindowRenderer{deviceWidth: 100, deviceHeight: 100, scale: 1, failAt2x: failScaleFrame, shared: &order} win := &window{ id: 1, width: 100, height: 100, api: &xcbAPI{ @@ -59,13 +48,15 @@ func TestConfigureAnswersSyncAfterScaleRefresh(t *testing.T) { if closed || (err != nil) != failScaleFrame { t.Fatalf("configure: closed=%v err=%v, want failure=%v", closed, err, failScaleFrame) } - if win.displayScale() != 2 || renderer.pixelScale() != 2 { - t.Fatalf("scale refresh did not reach 2x: window=%v renderer=%v", win.displayScale(), renderer.pixelScale()) + if win.displayScale() != 2 || renderer.scale != 2 { + t.Fatalf("scale refresh did not reach 2x: window=%v renderer=%v", win.displayScale(), renderer.scale) } want := []string{"present", "present", "sync"} if failScaleFrame { want = want[:2] } + // Only the frames and the answer to the window manager are in question. + order = slices.DeleteFunc(order, func(call string) bool { return call != "present" && call != "sync" }) if !slices.Equal(order, want) { t.Fatalf("configure order = %v, want %v", order, want) } diff --git a/internal/platform/vulkan/abi_test.go b/internal/platform/vulkan/abi_test.go new file mode 100644 index 000000000..479ba37a7 --- /dev/null +++ b/internal/platform/vulkan/abi_test.go @@ -0,0 +1,85 @@ +//go:build linux + +package vulkan + +import ( + "testing" + "unsafe" +) + +func TestVulkanStructureABI(t *testing.T) { + if unsafe.Sizeof(uintptr(0)) != 8 { + t.Fatal("only 64-bit platforms are supported") + } + for _, layout := range []struct { + name string + size uintptr + want uintptr + }{ + {"VkApplicationInfo", unsafe.Sizeof(vkApplicationInfo{}), 48}, + {"VkInstanceCreateInfo", unsafe.Sizeof(vkInstanceCreateInfo{}), 64}, + {"VkQueueFamilyProperties", unsafe.Sizeof(vkQueueFamilyProperties{}), 24}, + {"VkDeviceQueueCreateInfo", unsafe.Sizeof(vkDeviceQueueCreateInfo{}), 40}, + {"VkDeviceCreateInfo", unsafe.Sizeof(vkDeviceCreateInfo{}), 72}, + {"VkSurfaceCapabilitiesKHR", unsafe.Sizeof(vkSurfaceCapabilities{}), 52}, + {"VkSwapchainCreateInfoKHR", unsafe.Sizeof(vkSwapchainCreateInfo{}), 104}, + {"VkImageViewCreateInfo", unsafe.Sizeof(vkImageViewCreateInfo{}), 80}, + {"VkAttachmentDescription", unsafe.Sizeof(vkAttachmentDescription{}), 36}, + {"VkSubpassDescription", unsafe.Sizeof(vkSubpassDescription{}), 72}, + {"VkRenderPassCreateInfo", unsafe.Sizeof(vkRenderPassCreateInfo{}), 64}, + {"VkFramebufferCreateInfo", unsafe.Sizeof(vkFramebufferCreateInfo{}), 64}, + {"VkCommandPoolCreateInfo", unsafe.Sizeof(vkCommandPoolCreateInfo{}), 24}, + {"VkCommandBufferAllocateInfo", unsafe.Sizeof(vkCommandBufferAllocateInfo{}), 32}, + {"VkCommandBufferBeginInfo", unsafe.Sizeof(vkCommandBufferBeginInfo{}), 32}, + {"VkClearAttachment", unsafe.Sizeof(vkClearAttachment{}), 24}, + {"VkClearRect", unsafe.Sizeof(vkClearRect{}), 24}, + {"VkRenderPassBeginInfo", unsafe.Sizeof(vkRenderPassBeginInfo{}), 64}, + {"VkSemaphoreCreateInfo", unsafe.Sizeof(vkSemaphoreCreateInfo{}), 24}, + {"VkSubmitInfo", unsafe.Sizeof(vkSubmitInfo{}), 72}, + {"VkPresentInfoKHR", unsafe.Sizeof(vkPresentInfo{}), 64}, + {"VkPhysicalDeviceMemoryProperties", unsafe.Sizeof(vkPhysicalDeviceMemoryProperties{}), 520}, + {"VkMemoryRequirements", unsafe.Sizeof(vkMemoryRequirements{}), 24}, + {"VkBufferCreateInfo", unsafe.Sizeof(vkBufferCreateInfo{}), 56}, + {"VkMemoryAllocateInfo", unsafe.Sizeof(vkMemoryAllocateInfo{}), 32}, + {"VkShaderModuleCreateInfo", unsafe.Sizeof(vkShaderModuleCreateInfo{}), 40}, + {"VkPipelineShaderStageCreateInfo", unsafe.Sizeof(vkPipelineShaderStageCreateInfo{}), 48}, + {"VkVertexInputBindingDescription", unsafe.Sizeof(vkVertexInputBindingDescription{}), 12}, + {"VkVertexInputAttributeDescription", unsafe.Sizeof(vkVertexInputAttributeDescription{}), 16}, + {"VkPipelineVertexInputStateCreateInfo", unsafe.Sizeof(vkPipelineVertexInputStateCreateInfo{}), 48}, + {"VkPipelineInputAssemblyStateCreateInfo", unsafe.Sizeof(vkPipelineInputAssemblyStateCreateInfo{}), 32}, + {"VkPipelineViewportStateCreateInfo", unsafe.Sizeof(vkPipelineViewportStateCreateInfo{}), 48}, + {"VkPipelineRasterizationStateCreateInfo", unsafe.Sizeof(vkPipelineRasterizationStateCreateInfo{}), 64}, + {"VkPipelineMultisampleStateCreateInfo", unsafe.Sizeof(vkPipelineMultisampleStateCreateInfo{}), 48}, + {"VkPipelineColorBlendAttachmentState", unsafe.Sizeof(vkPipelineColorBlendAttachmentState{}), 32}, + {"VkPipelineColorBlendStateCreateInfo", unsafe.Sizeof(vkPipelineColorBlendStateCreateInfo{}), 56}, + {"VkPipelineDynamicStateCreateInfo", unsafe.Sizeof(vkPipelineDynamicStateCreateInfo{}), 32}, + {"VkPushConstantRange", unsafe.Sizeof(vkPushConstantRange{}), 12}, + {"VkPipelineLayoutCreateInfo", unsafe.Sizeof(vkPipelineLayoutCreateInfo{}), 48}, + {"VkGraphicsPipelineCreateInfo", unsafe.Sizeof(vkGraphicsPipelineCreateInfo{}), 144}, + {"VkViewport", unsafe.Sizeof(vkViewport{}), 24}, + {"VkExtent3D", unsafe.Sizeof(vkExtent3D{}), 12}, + {"VkImageCreateInfo", unsafe.Sizeof(vkImageCreateInfo{}), 88}, + {"VkSamplerCreateInfo", unsafe.Sizeof(vkSamplerCreateInfo{}), 80}, + {"VkDescriptorSetLayoutBinding", unsafe.Sizeof(vkDescriptorSetLayoutBinding{}), 24}, + {"VkDescriptorSetLayoutCreateInfo", unsafe.Sizeof(vkDescriptorSetLayoutCreateInfo{}), 32}, + {"VkDescriptorPoolSize", unsafe.Sizeof(vkDescriptorPoolSize{}), 8}, + {"VkDescriptorPoolCreateInfo", unsafe.Sizeof(vkDescriptorPoolCreateInfo{}), 40}, + {"VkDescriptorSetAllocateInfo", unsafe.Sizeof(vkDescriptorSetAllocateInfo{}), 40}, + {"VkDescriptorImageInfo", unsafe.Sizeof(vkDescriptorImageInfo{}), 24}, + {"VkWriteDescriptorSet", unsafe.Sizeof(vkWriteDescriptorSet{}), 64}, + {"VkImageMemoryBarrier", unsafe.Sizeof(vkImageMemoryBarrier{}), 72}, + {"VkImageSubresourceLayers", unsafe.Sizeof(vkImageSubresourceLayers{}), 16}, + {"VkBufferImageCopy", unsafe.Sizeof(vkBufferImageCopy{}), 56}, + {"scene instance", unsafe.Sizeof(vulkanRectangleInstance{}), 80}, + } { + if layout.size != layout.want { + t.Errorf("%s size %d, want %d", layout.name, layout.size, layout.want) + } + } + if offset := unsafe.Offsetof(vkImageCreateInfo{}.QueueFamilies); offset != 72 { + t.Errorf("VkImageCreateInfo.pQueueFamilyIndices offset %d, want 72", offset) + } + if offset := unsafe.Offsetof(vkImageCreateInfo{}.InitialLayout); offset != 80 { + t.Errorf("VkImageCreateInfo.initialLayout offset %d, want 80", offset) + } +} diff --git a/internal/platform/vulkan/api_vulkan_test.go b/internal/platform/vulkan/api_vulkan_test.go new file mode 100644 index 000000000..afb9f0b0d --- /dev/null +++ b/internal/platform/vulkan/api_vulkan_test.go @@ -0,0 +1,999 @@ +//go:build linux + +package vulkan + +import ( + "bytes" + "errors" + "fmt" + "os" + "path/filepath" + "slices" + "strings" + "testing" + "unsafe" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/internal/render" + "github.com/vivaui/viva/internal/scene" +) + +func TestVulkanResult(t *testing.T) { + if vkCheck(vkSuccess, "test") != nil || vkCheck(-1, "test") == nil { + t.Fatal("Vulkan result classification mismatch") + } +} + +func TestRectangleClearClipsAndClamps(t *testing.T) { + attachment, clear, visible := rectangleClear(render.Rectangle{ + Bounds: scene.Rect{X: -2.25, Y: 1.2, Width: 5, Height: 3.1}, + Color: scene.Color{Red: -1, Green: 0.5, Blue: 2, Alpha: 1}, + }, 4, 4) + if !visible { + t.Fatal("partially visible rectangle was discarded") + } + if clear.Rect.Offset != [2]int32{0, 1} || clear.Rect.Extent != (vkExtent2D{Width: 3, Height: 3}) { + t.Fatalf("clear bounds = %+v", clear.Rect) + } + if clear.BaseArrayLayer != 0 || clear.LayerCount != 1 { + t.Fatalf("clear layers = %d..%d", clear.BaseArrayLayer, clear.LayerCount) + } + if attachment.AspectMask != vkImageAspectColor || attachment.ColorAttachment != 0 { + t.Fatalf("clear attachment = %+v", attachment) + } + if attachment.ClearValue.Color != [4]float32{0, 0.5, 1, 1} { + t.Fatalf("clear color = %v", attachment.ClearValue.Color) + } + + for _, bounds := range []scene.Rect{ + {X: 4, Width: 1, Height: 1}, + {Y: 4, Width: 1, Height: 1}, + {Width: 0, Height: 1}, + {Width: 1, Height: -1}, + } { + if _, _, visible := rectangleClear(render.Rectangle{Bounds: bounds}, 4, 4); visible { + t.Fatalf("invisible bounds %+v produced a clear", bounds) + } + } +} + +func TestRecordCommandsDrawsSceneInstances(t *testing.T) { + var begins, renderBegins, renderEnds, ends, binds, draws int + renderer := Renderer{ + api: &vulkanAPI{ + beginCommandBuffer: func(uintptr, *vkCommandBufferBeginInfo) int32 { + begins++ + return vkSuccess + }, + cmdBeginRenderPass: func(uintptr, *vkRenderPassBeginInfo, uint32) { + renderBegins++ + }, + cmdBindPipeline: func(_ uintptr, bindPoint uint32, pipeline uintptr) { + if bindPoint != vkPipelineBindPointGraphics || pipeline != 7 { + t.Fatalf("pipeline = %d, %d", bindPoint, pipeline) + } + binds++ + }, + cmdSetViewport: func(uintptr, uint32, uint32, *vkViewport) {}, + cmdSetScissor: func(uintptr, uint32, uint32, *vkRect2D) {}, + cmdPushConstants: func(uintptr, uintptr, uint32, uint32, uint32, unsafe.Pointer) {}, + cmdBindVertexBuffers: func(_ uintptr, _ uint32, count uint32, buffers *uintptr, offsets *uint64) { + if count != 1 || *buffers != 8 || *offsets != 0 { + t.Fatalf("vertex binding = %d, %d, %d", count, *buffers, *offsets) + } + }, + cmdDraw: func(_ uintptr, vertices, instances, firstVertex, firstInstance uint32) { + if vertices != 6 || instances != 2 || firstVertex != 0 || firstInstance != 0 { + t.Fatalf("draw = %d, %d, %d, %d", vertices, instances, firstVertex, firstInstance) + } + draws++ + }, + cmdEndRenderPass: func(uintptr) { + renderEnds++ + }, + endCommandBuffer: func(uintptr) int32 { + ends++ + return vkSuccess + }, + }, + commands: []uintptr{1, 2}, + framebuffers: []uintptr{3, 4}, + scene: vulkanScene{pipeline: 7, pipelineLayout: 9, buffer: 8, instances: make([]vulkanRectangleInstance, 2)}, + rectangleBatches: []render.Batch{{First: 0, Count: 2}}, + compositingBatches: []compositingBatch{{Kind: compositeRectangles, First: 0, Count: 2}}, + } + if err := renderer.recordCommands(vkExtent2D{Width: 4, Height: 4}); err != nil { + t.Fatal(err) + } + if begins != 2 || renderBegins != 2 || renderEnds != 2 || ends != 2 { + t.Fatalf("command lifecycle = %d %d %d %d", begins, renderBegins, renderEnds, ends) + } + if binds != 2 || draws != 2 { + t.Fatalf("scene commands = %d binds, %d draws", binds, draws) + } +} + +func TestRecordCommandsScissorsClippedBatches(t *testing.T) { + var events []string + var scissor vkRect2D + renderer := Renderer{ + api: &vulkanAPI{ + beginCommandBuffer: func(uintptr, *vkCommandBufferBeginInfo) int32 { return vkSuccess }, + cmdBeginRenderPass: func(uintptr, *vkRenderPassBeginInfo, uint32) {}, + cmdBindPipeline: func(uintptr, uint32, uintptr) {}, + cmdSetViewport: func(uintptr, uint32, uint32, *vkViewport) {}, + cmdSetScissor: func(_ uintptr, _, _ uint32, rect *vkRect2D) { + scissor = *rect + events = append(events, fmt.Sprintf("scissor %d,%d %dx%d", rect.Offset[0], rect.Offset[1], rect.Extent.Width, rect.Extent.Height)) + }, + cmdPushConstants: func(uintptr, uintptr, uint32, uint32, uint32, unsafe.Pointer) {}, + cmdBindVertexBuffers: func(uintptr, uint32, uint32, *uintptr, *uint64) {}, + cmdDraw: func(_ uintptr, _, _, _, first uint32) { + events = append(events, fmt.Sprintf("draw %d with %d,%d %dx%d", first, scissor.Offset[0], scissor.Offset[1], scissor.Extent.Width, scissor.Extent.Height)) + }, + cmdEndRenderPass: func(uintptr) {}, + endCommandBuffer: func(uintptr) int32 { return vkSuccess }, + }, + commands: []uintptr{1}, + framebuffers: []uintptr{2}, + scene: vulkanScene{pipeline: 7, pipelineLayout: 9, buffer: 8, instances: make([]vulkanRectangleInstance, 3)}, + compositingBatches: []compositingBatch{ + {Kind: compositeRectangles, Clipped: true, Clip: scene.Rect{X: 2, Y: 3, Width: 4, Height: 5}, First: 0, Count: 1}, + {Kind: compositeRectangles, Clipped: true, Clip: scene.Rect{X: 100, Y: 100, Width: 4, Height: 4}, First: 1, Count: 1}, + {Kind: compositeRectangles, First: 2, Count: 1}, + }, + } + if err := renderer.recordCommands(vkExtent2D{Width: 20, Height: 30}); err != nil { + t.Fatal(err) + } + want := []string{ + "scissor 2,3 4x5", "draw 0 with 2,3 4x5", + "scissor 0,0 20x30", "draw 2 with 0,0 20x30", + } + if !slices.Equal(events, want) { + t.Fatalf("events = %q, want %q", events, want) + } +} + +func TestVulkanRectangleInstancesMatchNativeBackends(t *testing.T) { + rectangle := makeVulkanRectangleInstance(render.Rectangle{ + Bounds: scene.Rect{X: 1, Y: 2, Width: 3, Height: 4}, + Color: scene.Color{Red: 0.1, Green: 0.2, Blue: 0.3, Alpha: 0.4}, Radius: 5, + }) + if rectangle.Bounds != [4]float32{1, 2, 3, 4} || rectangle.Color != [4]float32{0.1, 0.2, 0.3, 0.4} || rectangle.Style != [4]float32{5, 0, 0, 0} { + t.Fatalf("rectangle instance = %+v", rectangle) + } + triangle := makeVulkanRectangleInstance(render.Rectangle{ + Kind: scene.KindTriangle, Points: [3]scene.Point{{X: 1, Y: 2}, {X: 3, Y: 4}, {X: 5, Y: 6}}, + Color: scene.Color{Alpha: 1}, Layer: 9, EdgeMask: 5, + }) + if triangle.Bounds != [4]float32{1, 2, 3, 4} || triangle.Style != [4]float32{5, 9, 6, 6} { + t.Fatalf("triangle instance = %+v", triangle) + } +} + +func TestVulkanSceneUploadWritesOnlyChangedRange(t *testing.T) { + storage := make([]byte, 3*vkInstanceBytes) + sceneState := vulkanScene{capacity: 3, mapped: unsafe.Pointer(&storage[0])} + rectangles := []render.Rectangle{ + {Bounds: scene.Rect{X: 1, Width: 10}, Color: scene.Color{Alpha: 1}}, + {Bounds: scene.Rect{X: 2, Width: 20}, Color: scene.Color{Alpha: 1}}, + {Bounds: scene.Rect{X: 3, Width: 30}, Color: scene.Color{Alpha: 1}}, + } + if err := sceneState.upload(&Renderer{}, rectangles, render.Update{Count: len(rectangles), Rebuild: true}); err != nil { + t.Fatal(err) + } + first := append([]byte(nil), storage[:vkInstanceBytes]...) + last := append([]byte(nil), storage[2*vkInstanceBytes:]...) + rectangles[1].Bounds.Width = 99 + if err := sceneState.upload(&Renderer{}, rectangles, render.Update{First: 1, Count: 1}); err != nil { + t.Fatal(err) + } + if !bytes.Equal(storage[:vkInstanceBytes], first) || !bytes.Equal(storage[2*vkInstanceBytes:], last) { + t.Fatal("partial upload changed untouched GPU instance ranges") + } + if sceneState.instances[1].Bounds[2] != 99 { + t.Fatalf("updated instance width = %g", sceneState.instances[1].Bounds[2]) + } +} + +func TestVulkanSceneUploadShrinksRetainedInstances(t *testing.T) { + storage := make([]byte, 3*vkInstanceBytes) + sceneState := vulkanScene{capacity: 3, mapped: unsafe.Pointer(&storage[0])} + rectangles := []render.Rectangle{ + {Bounds: scene.Rect{X: 1, Width: 10}, Color: scene.Color{Alpha: 1}}, + {Bounds: scene.Rect{X: 2, Width: 20}, Color: scene.Color{Alpha: 1}}, + {Bounds: scene.Rect{X: 3, Width: 30}, Color: scene.Color{Alpha: 1}}, + } + if err := sceneState.upload(&Renderer{}, rectangles, render.Update{Count: len(rectangles), Rebuild: true}); err != nil { + t.Fatal(err) + } + rectangles[1].Bounds.Width = 99 + if err := sceneState.upload(&Renderer{}, rectangles[:2], render.Update{First: 1, Count: 1, Shrink: true}); err != nil { + t.Fatal(err) + } + if len(sceneState.instances) != 2 || sceneState.instances[1].Bounds[2] != 99 { + t.Fatalf("shrunk instances = %d, second width %g", len(sceneState.instances), sceneState.instances[1].Bounds[2]) + } + if err := sceneState.upload(&Renderer{}, rectangles[:1], render.Update{First: 1, Count: 0}); err == nil { + t.Fatal("shrink without Shrink accepted") + } +} + +func TestSwapchainStatusClassification(t *testing.T) { + if swapchainNeedsRebuild(vkSuccess) || swapchainNeedsRebuild(vkSuboptimal) || !swapchainNeedsRebuild(vkErrorOutOfDate) { + t.Fatal("unexpected swapchain status classification") + } +} + +func TestCreateSwapchainCleansPartialResources(t *testing.T) { + var destroyed uintptr + renderer := Renderer{ + api: &vulkanAPI{ + getSurfaceCapabilities: func(_ uintptr, _ uintptr, capabilities *vkSurfaceCapabilities) int32 { + *capabilities = vkSurfaceCapabilities{ + MinImages: 1, + MaxImages: 2, + Current: vkExtent2D{Width: 640, Height: 480}, + CompositeAlpha: vkCompositeOpaque, + Usage: vkImageUsageColorAttachment, + } + return vkSuccess + }, + getSurfaceFormats: func(_ uintptr, _ uintptr, count *uint32, formats *vkSurfaceFormat) int32 { + *count = 1 + if formats != nil { + *formats = vkSurfaceFormat{Format: vkFormatBGRA8, ColorSpace: vkColorSpaceSRGB} + } + return vkSuccess + }, + createSwapchain: func(_ uintptr, _ *vkSwapchainCreateInfo, _ unsafe.Pointer, swapchain *uintptr) int32 { + *swapchain = 42 + return vkSuccess + }, + getSwapchainImages: func(_ uintptr, _ uintptr, _ *uint32, _ *uintptr) int32 { + return -1 + }, + destroySwapchain: func(_ uintptr, swapchain uintptr, _ unsafe.Pointer) { + destroyed = swapchain + }, + }, + physical: 1, + device: 2, + surface: 3, + width: 640, + height: 480, + } + + if err := renderer.createSwapchain(); err == nil { + t.Fatal("createSwapchain succeeded") + } + if destroyed != 42 { + t.Fatalf("destroyed swapchain %d, want 42", destroyed) + } + if renderer.swapchain != 0 { + t.Fatalf("swapchain retained after failure: %d", renderer.swapchain) + } +} + +// A machine with no Vulkan reports it as platform.ErrNoGraphics, so an +// application can tell "this server has no graphics" from a real failure, and the +// text carries the cause and what to install. +func TestMissingVulkanIsNamedAndSaysWhatToInstall(t *testing.T) { + cause := errors.New("libvulkan.so.1: cannot open shared object file") + for name, err := range map[string]error{ + "no loader": noVulkan("libvulkan.so.1 is not installed", cause), + "no device": noVulkan("Vulkan reports no device", nil), + } { + if !errors.Is(err, platform.ErrNoGraphics) { + t.Errorf("%s: %v does not wrap platform.ErrNoGraphics", name, err) + } + if !strings.Contains(err.Error(), "mesa-vulkan-drivers") { + t.Errorf("%s: %q does not say what to install", name, err) + } + } + if err := noVulkan("x", cause); !errors.Is(err, cause) { + t.Errorf("the cause is lost: %v", err) + } +} + +func TestVulkanDriverManifestDetection(t *testing.T) { + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "notes.txt"), []byte("not a driver"), 0o600); err != nil { + t.Fatal(err) + } + if vulkanDriverManifestsExist([]string{dir}) { + t.Fatal("a directory without an ICD manifest counts as a Vulkan driver") + } + manifest := filepath.Join(dir, "driver.json") + if err := os.WriteFile(manifest, []byte("{}"), 0o600); err != nil { + t.Fatal(err) + } + if !vulkanDriverManifestsExist([]string{dir}) || !vulkanDriverManifestsExist([]string{manifest}) { + t.Fatal("an ICD manifest was not detected") + } +} + +func TestVulkanWithoutDriverManifestDoesNotLoadDriver(t *testing.T) { + t.Setenv("VK_DRIVER_FILES", filepath.Join(t.TempDir(), "missing.json")) + t.Setenv("VK_ICD_FILENAMES", "") + t.Setenv("VK_ADD_DRIVER_FILES", "") + if vulkanDriverConfigured() { + t.Fatal("a missing ICD manifest counts as a Vulkan driver") + } + _, err := openVulkan() + if !errors.Is(err, platform.ErrNoGraphics) { + t.Fatalf("openVulkan error = %v, want platform.ErrNoGraphics", err) + } +} + +func TestVulkanEmptyICDOverrideDoesNotUseDefaultManifests(t *testing.T) { + root := t.TempDir() + t.Setenv("HOME", root) + t.Setenv("XDG_DATA_HOME", root) + writeVulkanManifest(t, filepath.Join(root, "vulkan", "icd.d")) + t.Setenv("VK_DRIVER_FILES", "") + t.Setenv("VK_ICD_FILENAMES", "") + unsetTestEnv(t, "VK_ADD_DRIVER_FILES") + if vulkanDriverConfigured() { + t.Fatal("an empty ICD override falls back to the default driver manifests") + } +} + +// The default search reads each XDG base the loader reads. Only positive cases are +// checked: the system's /etc/vulkan/icd.d is always searched, so an empty result +// cannot be asserted on a machine that has a driver installed. +func TestVulkanDefaultManifestSearchFindsEachXDGDirectory(t *testing.T) { + cases := []struct { + name string + // env sets the search variables under root, and returns the base whose + // vulkan/icd.d holds the manifest. + env func(t *testing.T, root string) string + }{ + {"config home", func(t *testing.T, root string) string { + t.Setenv("XDG_CONFIG_HOME", filepath.Join(root, "config")) + return filepath.Join(root, "config") + }}, + {"home default config", func(t *testing.T, root string) string { + t.Setenv("HOME", root) + return filepath.Join(root, ".config") + }}, + {"config dirs", func(t *testing.T, root string) string { + t.Setenv("XDG_CONFIG_DIRS", filepath.Join(root, "missing")+":"+filepath.Join(root, "xdg")) + return filepath.Join(root, "xdg") + }}, + {"data home", func(t *testing.T, root string) string { + t.Setenv("XDG_DATA_HOME", filepath.Join(root, "data")) + return filepath.Join(root, "data") + }}, + {"data dirs", func(t *testing.T, root string) string { + t.Setenv("XDG_DATA_DIRS", filepath.Join(root, "share")) + return filepath.Join(root, "share") + }}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + root := t.TempDir() + t.Setenv("HOME", filepath.Join(root, "home")) + t.Setenv("XDG_CONFIG_DIRS", "") + t.Setenv("XDG_DATA_DIRS", "") + unsetTestEnv(t, "XDG_CONFIG_HOME") + unsetTestEnv(t, "XDG_DATA_HOME") + unsetTestEnv(t, "VK_DRIVER_FILES") + unsetTestEnv(t, "VK_ICD_FILENAMES") + unsetTestEnv(t, "VK_ADD_DRIVER_FILES") + base := tc.env(t, root) + writeVulkanManifest(t, filepath.Join(base, "vulkan", "icd.d")) + if !vulkanDriverConfigured() { + t.Fatalf("a manifest under the %s was not found", tc.name) + } + }) + } +} + +// unsetTestEnv removes name for the rest of the test. t.Setenv restores the original +// value at cleanup, which the bare os.Unsetenv alone would not. +func unsetTestEnv(t *testing.T, name string) { + t.Helper() + t.Setenv(name, "") + if err := os.Unsetenv(name); err != nil { + t.Fatal(err) + } +} + +func writeVulkanManifest(t *testing.T, dir string) { + t.Helper() + if err := os.MkdirAll(dir, 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "driver.json"), []byte("{}"), 0o600); err != nil { + t.Fatal(err) + } +} + +// A loader whose installed drivers fail to initialize fails enumeration with +// VK_ERROR_INITIALIZATION_FAILED (a driver-less loader gives +// VK_ERROR_INCOMPATIBLE_DRIVER). That is still a machine that cannot draw, not a +// rendering failure: the application must be able to tell them apart and the text +// must say what to install. Any other enumeration result stays a real failure. +func TestUnusableVulkanDriverIsNamedAndSaysWhatToInstall(t *testing.T) { + device := func(status int32) *vulkanDevice { + return &vulkanDevice{api: &vulkanAPI{ + enumeratePhysicalDevices: func(uintptr, *uint32, *uintptr) int32 { return status }, + }} + } + for _, status := range []int32{vkErrorInitializationFailed, vkErrorIncompatibleDriver} { + err := device(status).selectPhysical(0) + if !errors.Is(err, platform.ErrNoGraphics) { + t.Errorf("result %d: %v does not wrap platform.ErrNoGraphics", status, err) + } + if !strings.Contains(err.Error(), "mesa-vulkan-drivers") { + t.Errorf("result %d: %q does not say what to install", status, err) + } + if !strings.Contains(err.Error(), fmt.Sprint(status)) { + t.Errorf("result %d: %q does not report the Vulkan result", status, err) + } + } + if err := device(-1).selectPhysical(0); errors.Is(err, platform.ErrNoGraphics) { + t.Errorf("a real failure is reported as no graphics: %v", err) + } +} + +func newSuboptimalTestRenderer(acquireStatus, presentStatus int32, recreations *int) *Renderer { + return &Renderer{ + device: 10, + queue: 20, + swapchain: 30, + commands: []uintptr{40}, + framebuffers: []uintptr{45}, + fence: 50, + api: &vulkanAPI{ + waitForFences: func(uintptr, uint32, *uintptr, uint32, uint64) int32 { return vkSuccess }, + resetFences: func(uintptr, uint32, *uintptr) int32 { return vkSuccess }, + acquireNextImage: func(_, swapchain uintptr, _ uint64, _, _ uintptr, image *uint32) int32 { + *image = 0 + if swapchain == 30 { + return acquireStatus + } + return vkSuccess + }, + queueSubmit: func(uintptr, uint32, *vkSubmitInfo, uintptr) int32 { return vkSuccess }, + queuePresent: func(_ uintptr, present *vkPresentInfo) int32 { + if *present.Swapchains == 30 { + return presentStatus + } + return vkSuccess + }, + deviceWaitIdle: func(uintptr) int32 { + *recreations++ + return vkSuccess + }, + getSurfaceCapabilities: func(_, _ uintptr, capabilities *vkSurfaceCapabilities) int32 { + capabilities.Current = vkExtent2D{Width: 100, Height: 100} + capabilities.MinImages = 2 + capabilities.CompositeAlpha = vkCompositeOpaque + capabilities.Usage = vkImageUsageColorAttachment + return vkSuccess + }, + getSurfaceFormats: func(_, _ uintptr, count *uint32, formats *vkSurfaceFormat) int32 { + *count = 1 + if formats != nil { + *formats = vkSurfaceFormat{Format: vkFormatBGRA8, ColorSpace: vkColorSpaceSRGB} + } + return vkSuccess + }, + createSwapchain: func(_ uintptr, _ *vkSwapchainCreateInfo, _ unsafe.Pointer, swapchain *uintptr) int32 { + *swapchain = 99 + return vkSuccess + }, + destroySwapchain: func(uintptr, uintptr, unsafe.Pointer) {}, + destroyImageView: func(uintptr, uintptr, unsafe.Pointer) {}, + destroyRenderPass: func(uintptr, uintptr, unsafe.Pointer) {}, + destroyFramebuffer: func(uintptr, uintptr, unsafe.Pointer) {}, + destroyCommandPool: func(uintptr, uintptr, unsafe.Pointer) {}, + destroyPipelineLayout: func(uintptr, uintptr, unsafe.Pointer) {}, + destroyPipeline: func(uintptr, uintptr, unsafe.Pointer) {}, + getSwapchainImages: func(_, _ uintptr, count *uint32, images *uintptr) int32 { + if images == nil { + *count = 1 + return vkSuccess + } + *images = 101 + return vkSuccess + }, + createImageView: func(_ uintptr, _ *vkImageViewCreateInfo, _ unsafe.Pointer, view *uintptr) int32 { + *view = 201 + return vkSuccess + }, + createRenderPass: func(_ uintptr, _ *vkRenderPassCreateInfo, _ unsafe.Pointer, renderPass *uintptr) int32 { + *renderPass = 301 + return vkSuccess + }, + createFramebuffer: func(_ uintptr, _ *vkFramebufferCreateInfo, _ unsafe.Pointer, framebuffer *uintptr) int32 { + *framebuffer = 401 + return vkSuccess + }, + createCommandPool: func(_ uintptr, _ *vkCommandPoolCreateInfo, _ unsafe.Pointer, pool *uintptr) int32 { + *pool = 501 + return vkSuccess + }, + allocateCommandBuffers: func(_ uintptr, _ *vkCommandBufferAllocateInfo, buffers *uintptr) int32 { + *buffers = 601 + return vkSuccess + }, + createPipelineLayout: func(_ uintptr, _ *vkPipelineLayoutCreateInfo, _ unsafe.Pointer, layout *uintptr) int32 { + *layout = 701 + return vkSuccess + }, + createShaderModule: func(_ uintptr, _ *vkShaderModuleCreateInfo, _ unsafe.Pointer, module *uintptr) int32 { + *module = 801 + return vkSuccess + }, + destroyShaderModule: func(uintptr, uintptr, unsafe.Pointer) {}, + createGraphicsPipelines: func(_, _ uintptr, _ uint32, _ *vkGraphicsPipelineCreateInfo, _ unsafe.Pointer, pipeline *uintptr) int32 { + *pipeline = 901 + return vkSuccess + }, + beginCommandBuffer: func(uintptr, *vkCommandBufferBeginInfo) int32 { return vkSuccess }, + cmdBeginRenderPass: func(uintptr, *vkRenderPassBeginInfo, uint32) {}, + cmdEndRenderPass: func(uintptr) {}, + endCommandBuffer: func(uintptr) int32 { return vkSuccess }, + }, + } +} + +func TestSuboptimalRecreatesAfterCompletedFrame(t *testing.T) { + for _, test := range []struct { + name string + acquireStatus int32 + presentStatus int32 + }{ + {name: "acquire", acquireStatus: vkSuboptimal, presentStatus: vkSuccess}, + {name: "present", acquireStatus: vkSuccess, presentStatus: vkSuboptimal}, + } { + t.Run(test.name, func(t *testing.T) { + recreations := 0 + renderer := newSuboptimalTestRenderer(test.acquireStatus, test.presentStatus, &recreations) + var presented []uintptr + basePresent := renderer.api.queuePresent + renderer.api.queuePresent = func(queue uintptr, present *vkPresentInfo) int32 { + presented = append(presented, *present.Swapchains) + return basePresent(queue, present) + } + if err := renderer.presentRebuilding(); err != nil { + t.Fatalf("presentRebuilding returned error: %v", err) + } + if renderer.submissions != 2 { + t.Fatalf("completed submissions = %d, want old and new swapchain frames", renderer.submissions) + } + if recreations != 1 { + t.Fatalf("swapchain recreations = %d, want 1", recreations) + } + if renderer.swapchain != 99 { + t.Fatalf("swapchain = %d, want recreated handle 99", renderer.swapchain) + } + if !slices.Equal(presented, []uintptr{30, 99}) { + t.Fatalf("presented swapchains = %v, want [30 99]", presented) + } + if renderer.swapchainSuboptimal { + t.Fatal("suboptimal flag survived successful recreation") + } + }) + } +} + +func TestSuboptimalRecreationConvergesAcrossFrames(t *testing.T) { + for _, test := range []struct { + name string + acquireStatus int32 + presentStatus int32 + keepReporting func(*Renderer) + }{ + { + name: "acquire", + acquireStatus: vkSuboptimal, + presentStatus: vkSuccess, + keepReporting: func(renderer *Renderer) { + renderer.api.acquireNextImage = func(_, _ uintptr, _ uint64, _, _ uintptr, image *uint32) int32 { + *image = 0 + return vkSuboptimal + } + }, + }, + { + name: "present", + acquireStatus: vkSuccess, + presentStatus: vkSuboptimal, + keepReporting: func(renderer *Renderer) { + renderer.api.queuePresent = func(uintptr, *vkPresentInfo) int32 { return vkSuboptimal } + }, + }, + { + name: "both", + acquireStatus: vkSuboptimal, + presentStatus: vkSuboptimal, + keepReporting: func(renderer *Renderer) { + renderer.api.acquireNextImage = func(_, _ uintptr, _ uint64, _, _ uintptr, image *uint32) int32 { + *image = 0 + return vkSuboptimal + } + renderer.api.queuePresent = func(uintptr, *vkPresentInfo) int32 { return vkSuboptimal } + }, + }, + } { + t.Run(test.name, func(t *testing.T) { + recreations := 0 + renderer := newSuboptimalTestRenderer(test.acquireStatus, test.presentStatus, &recreations) + test.keepReporting(renderer) + + for frame := 0; frame < 3; frame++ { + if err := renderer.presentRebuilding(); err != nil { + t.Fatalf("frame %d: presentRebuilding returned error: %v", frame, err) + } + if recreations != 1 { + t.Fatalf("frame %d: swapchain recreations = %d, want 1", frame, recreations) + } + if renderer.swapchain != 99 { + t.Fatalf("frame %d: swapchain = %d, want recreated handle 99", frame, renderer.swapchain) + } + if !renderer.swapchainSuboptimal { + t.Fatalf("frame %d: accepted swapchain forgot its SUBOPTIMAL status", frame) + } + } + if renderer.submissions != 4 { + t.Fatalf("completed submissions = %d, want the old and recreated frame plus two later frames", renderer.submissions) + } + }) + } +} + +func TestSuboptimalStatusClearsAfterHealthyFrame(t *testing.T) { + recreations := 0 + renderer := newSuboptimalTestRenderer(vkSuccess, vkSuboptimal, &recreations) + renderer.api.queuePresent = func(uintptr, *vkPresentInfo) int32 { return vkSuboptimal } + + if err := renderer.presentRebuilding(); err != nil { + t.Fatalf("presentRebuilding returned error: %v", err) + } + if recreations != 1 { + t.Fatalf("swapchain recreations = %d, want 1", recreations) + } + + // A healthy frame clears the accepted status without another recreation. + renderer.api.queuePresent = func(uintptr, *vkPresentInfo) int32 { return vkSuccess } + if err := renderer.presentRebuilding(); err != nil { + t.Fatalf("healthy frame returned error: %v", err) + } + if renderer.swapchainSuboptimal { + t.Fatal("healthy frame kept the accepted SUBOPTIMAL status") + } + if recreations != 1 { + t.Fatalf("healthy frame recreated the swapchain: recreations = %d, want 1", recreations) + } + + // A later SUBOPTIMAL is a fresh signal and gets its own single rebuild. + renderer.api.queuePresent = func(uintptr, *vkPresentInfo) int32 { return vkSuboptimal } + if err := renderer.presentRebuilding(); err != nil { + t.Fatalf("SUBOPTIMAL after healthy frame returned error: %v", err) + } + if recreations != 2 { + t.Fatalf("swapchain recreations = %d, want 2 after a fresh SUBOPTIMAL", recreations) + } + if !renderer.swapchainSuboptimal { + t.Fatal("fresh SUBOPTIMAL was not recorded") + } +} + +func TestOutOfDateRecoveryStaysBounded(t *testing.T) { + recreations := 0 + renderer := newSuboptimalTestRenderer(vkErrorOutOfDate, vkSuccess, &recreations) + + // The recreated swapchain is out of date as well. + renderer.api.acquireNextImage = func(_, _ uintptr, _ uint64, _, _ uintptr, image *uint32) int32 { + *image = 0 + return vkErrorOutOfDate + } + + if err := renderer.presentRebuilding(); err == nil { + t.Fatal("presentRebuilding accepted a swapchain that stayed out of date") + } + if recreations != 1 { + t.Fatalf("swapchain recreations = %d, want 1", recreations) + } + if renderer.swapchain != 99 { + t.Fatalf("swapchain = %d, want recreated handle 99", renderer.swapchain) + } + if renderer.submissions != 0 { + t.Fatalf("completed submissions = %d, want none for out-of-date frames", renderer.submissions) + } +} + +func TestOutOfDateRecoveryAcceptsResidualSuboptimal(t *testing.T) { + recreations := 0 + renderer := newSuboptimalTestRenderer(vkErrorOutOfDate, vkSuccess, &recreations) + // The old swapchain is out of date; the recreated one is suboptimal. + renderer.api.acquireNextImage = func(_, swapchain uintptr, _ uint64, _, _ uintptr, image *uint32) int32 { + *image = 0 + if swapchain == 30 { + return vkErrorOutOfDate + } + return vkSuboptimal + } + + if err := renderer.presentRebuilding(); err != nil { + t.Fatalf("presentRebuilding returned error: %v", err) + } + if recreations != 1 { + t.Fatalf("swapchain recreations = %d, want 1", recreations) + } + if !renderer.swapchainSuboptimal || !renderer.swapchainSuboptimalRebuilt { + t.Fatal("residual SUBOPTIMAL after OUT_OF_DATE recovery was not accepted") + } +} + +func TestPresentOutOfDateRebuilds(t *testing.T) { + recreations := 0 + renderer := newSuboptimalTestRenderer(vkSuccess, vkErrorOutOfDate, &recreations) + // Only the old swapchain presents out of date; the recreated one presents. + renderer.api.queuePresent = func(_ uintptr, present *vkPresentInfo) int32 { + if *present.Swapchains == 30 { + return vkErrorOutOfDate + } + return vkSuccess + } + + if err := renderer.presentRebuilding(); err != nil { + t.Fatalf("presentRebuilding returned error: %v", err) + } + if recreations != 1 { + t.Fatalf("swapchain recreations = %d, want 1", recreations) + } + if renderer.swapchain != 99 { + t.Fatalf("swapchain = %d, want recreated handle 99", renderer.swapchain) + } + if renderer.submissions != 2 { + t.Fatalf("completed submissions = %d, want the out-of-date present and the recreated one", renderer.submissions) + } +} + +func TestResizeRecordsStagedCommandsAtAnAlreadyMatchingExtent(t *testing.T) { + recreations, recordings := 0, 0 + renderer := newSuboptimalTestRenderer(vkSuccess, vkSuccess, &recreations) + renderer.width, renderer.height = 100, 100 + renderer.framebuffers = []uintptr{60} + renderer.api.resetCommandPool = func(uintptr, uintptr, uint32) int32 { return vkSuccess } + renderer.api.endCommandBuffer = func(uintptr) int32 { + recordings++ + return vkSuccess + } + // A staged scene makes the commands stale; a resize to the extent the + // surface already has rebuilds nothing, and the stale commands are recorded + // once, when their image is submitted. + if changed, err := renderer.Stage(platform.Frame{TextLabels: []platform.TextLabel{}}); !changed || err != nil { + t.Fatalf("stage: changed=%v err=%v", changed, err) + } + if err := renderer.Resize(100, 100); err != nil { + t.Fatal(err) + } + if recordings != 0 || recreations != 0 { + t.Fatalf("matching extent recorded %d times and rebuilt %d times", recordings, recreations) + } + for range 2 { + if err := renderer.ensureRecorded(0); err != nil { + t.Fatal(err) + } + } + if recordings != 1 { + t.Fatalf("submitting the stale image recorded it %d times, want once", recordings) + } +} + +func TestResizeOnceSuppressesSecondSuboptimalSwapchainRebuildDuringPresent(t *testing.T) { + recreations := 0 + renderer := newSuboptimalTestRenderer(vkSuccess, vkSuboptimal, &recreations) + renderer.width, renderer.height = 100, 100 + renderer.api.getSurfaceCapabilities = func(_, _ uintptr, capabilities *vkSurfaceCapabilities) int32 { + capabilities.Current = vkExtent2D{Width: renderer.width, Height: renderer.height} + capabilities.MinImages = 2 + capabilities.CompositeAlpha = vkCompositeOpaque + capabilities.Usage = vkImageUsageColorAttachment + return vkSuccess + } + renderer.api.queuePresent = func(uintptr, *vkPresentInfo) int32 { + return vkSuboptimal + } + + if err := renderer.resizeOnce(200, 150); err != nil { + t.Fatalf("resizeOnce returned error: %v", err) + } + if recreations != 1 { + t.Fatalf("recreations after resizeOnce = %d, want 1", recreations) + } + if err := renderer.presentRebuilding(); err != nil { + t.Fatalf("presentRebuilding returned error: %v", err) + } + if recreations != 1 { + t.Fatalf("recreations after presentRebuilding = %d, want 1 (no mid-present double rebuild)", recreations) + } + if renderer.submissions != 1 { + t.Fatalf("completed submissions = %d, want 1", renderer.submissions) + } +} + +func TestTextureContentChangedPreservesLabelRunsTextureWhenGrowingWithinPreviousWidth(t *testing.T) { + runs := []gfx.TextRun{{Column: 0, Bytes: 5, Cells: 5}} + prev := platform.TextLabel{ + Value: "hello", + Width: 60, + Height: 20, + FontSize: 14, + CellWidth: 8, + Runs: runs, + } + nextWider := prev + nextWider.Width = 120 + if textureContentChanged(prev, nextWider) { + t.Fatal("textureContentChanged invalidated fixed-pitch run label when growing width past unchanged runs") + } + nextClipped := prev + nextClipped.Width = 40 + if !textureContentChanged(prev, nextClipped) { + t.Fatal("textureContentChanged did not invalidate fixed-pitch run label when shrinking width") + } +} + +func TestVulkanTextUpdatePreservesTexturesAcrossIndexShift(t *testing.T) { + makeLabel := func(val string, y float32) platform.TextLabel { + return platform.TextLabel{ + Value: val, + X: 10, + Y: y, + Width: 100, + Height: 20, + FontSize: 14, + CellWidth: 8, + Runs: []gfx.TextRun{{Column: 0, Bytes: int32(len(val)), Cells: int32(len(val))}}, + } + } + var textState vulkanText + initial := []platform.TextLabel{ + makeLabel("row-0", 0), + makeLabel("row-1", 20), + makeLabel("status-bar", 400), + } + if err := textState.update(nil, initial); err != nil { + t.Fatalf("initial update failed: %v", err) + } + // Simulate uploaded GPU handles on each slot. + for i := range textState.labels { + textState.labels[i].view = uintptr(100 + i) + textState.labels[i].image = uintptr(200 + i) + textState.labels[i].set = uintptr(300 + i) + } + + // Now insert a wrapped line between row-0 and row-1 during resize; + // row-1 and status-bar shift to indices 2 and 3. + shifted := []platform.TextLabel{ + makeLabel("row-0", 0), + makeLabel("wrapped-cont", 20), + makeLabel("row-1", 40), + makeLabel("status-bar", 420), + } + if err := textState.update(nil, shifted); err != nil { + t.Fatalf("shifted update failed: %v", err) + } + if textState.labels[0].view != 100 { + t.Fatalf("row-0 view = %d, want 100", textState.labels[0].view) + } + if textState.labels[1].view != 0 { + t.Fatalf("new wrapped-cont view = %d, want 0 (needs upload)", textState.labels[1].view) + } + if textState.labels[2].view != 101 || textState.labels[2].set != 301 { + t.Fatalf("shifted row-1 view/set = %d/%d, want 101/301", textState.labels[2].view, textState.labels[2].set) + } + if textState.labels[3].view != 102 || textState.labels[3].set != 302 { + t.Fatalf("shifted status-bar view/set = %d/%d, want 102/302", textState.labels[3].view, textState.labels[3].set) + } +} + +func TestSelectPresentModePrefersFIFOWithMailboxFallback(t *testing.T) { + renderer := &Renderer{ + physical: 1, + surface: 2, + api: &vulkanAPI{ + getSurfacePresentModes: func(_, _ uintptr, count *uint32, modes *uint32) int32 { + offered := []uint32{vkPresentFIFO, vkPresentMailbox} + if modes == nil { + *count = uint32(len(offered)) + return vkSuccess + } + copy(unsafe.Slice(modes, int(*count)), offered) + return vkSuccess + }, + }, + } + if got := renderer.selectPresentMode(); got != vkPresentFIFO { + t.Fatalf("selectPresentMode() = %d, want vkPresentFIFO (%d)", got, vkPresentFIFO) + } + + fifoOnly := &Renderer{ + physical: 1, + surface: 2, + api: &vulkanAPI{ + getSurfacePresentModes: func(_, _ uintptr, count *uint32, modes *uint32) int32 { + offered := []uint32{vkPresentFIFO} + if modes == nil { + *count = uint32(len(offered)) + return vkSuccess + } + copy(unsafe.Slice(modes, int(*count)), offered) + return vkSuccess + }, + }, + } + if got := fifoOnly.selectPresentMode(); got != vkPresentFIFO { + t.Fatalf("selectPresentMode() = %d, want vkPresentFIFO (%d)", got, vkPresentFIFO) + } +} + +func TestClamp(t *testing.T) { + if clamp(1, 2, 4) != 2 || clamp(3, 2, 4) != 3 || clamp(5, 2, 4) != 4 { + t.Fatal("clamp result mismatch") + } +} + +// A surface reading that a resize shares is used by that resize only: the window asks the +// surface its size, and the swapchain it then resizes is made from that reading, with no +// second query. +func TestResizeSharesSurfaceQueryOnlyWithItsOwnSwapchain(t *testing.T) { + recreations := 0 + renderer := newSuboptimalTestRenderer(vkSuccess, vkSuccess, &recreations) + renderer.physical, renderer.surface = 1, 2 + renderer.width, renderer.height = 100, 100 + queries := 0 + baseQuery := renderer.api.getSurfaceCapabilities + renderer.api.getSurfaceCapabilities = func(device, surface uintptr, caps *vkSurfaceCapabilities) int32 { + queries++ + status := baseQuery(device, surface, caps) + caps.Current.Width = 120 + return status + } + if width, _ := renderer.SurfaceSize(120, 100); width != 120 { + t.Fatalf("the surface is %d wide, want 120", width) + } + if err := renderer.Resize(120, 100); err != nil { + t.Fatal(err) + } + if queries != 1 || recreations != 1 || renderer.width != 120 || renderer.hasPendingCapabilities { + t.Fatalf("resize queries=%d recreations=%d width=%d pending=%v", queries, recreations, renderer.width, renderer.hasPendingCapabilities) + } +} + +// A reading the window asked for and then forgot (an obsolete configure that needed no +// resize) must not be what a later present rebuilds the swapchain by: it queries the +// surface again. +func TestForgottenSurfaceCapabilitiesAreNotUsedByALaterPresent(t *testing.T) { + recreations := 0 + renderer := newSuboptimalTestRenderer(vkErrorOutOfDate, vkSuccess, &recreations) + renderer.physical, renderer.surface = 1, 2 + renderer.width, renderer.height = 100, 100 + queries := 0 + current := uint32(100) + baseQuery := renderer.api.getSurfaceCapabilities + renderer.api.getSurfaceCapabilities = func(device, surface uintptr, caps *vkSurfaceCapabilities) int32 { + queries++ + status := baseQuery(device, surface, caps) + caps.Current.Width = current + return status + } + renderer.SurfaceSize(90, 100) + renderer.ForgetSurfaceCapabilities() + current = 120 + if err := renderer.presentRebuilding(); err != nil { + t.Fatal(err) + } + if queries != 2 || renderer.width != current || recreations != 1 { + t.Fatalf("recovery used obsolete geometry: queries=%d width=%d recreations=%d", queries, renderer.width, recreations) + } +} diff --git a/internal/platform/vulkan/driver_android.go b/internal/platform/vulkan/driver_android.go new file mode 100644 index 000000000..c0208f5ce --- /dev/null +++ b/internal/platform/vulkan/driver_android.go @@ -0,0 +1,10 @@ +//go:build android + +package vulkan + +// Android ships the loader as libvulkan.so, with the drivers of the device behind +// it, and has no manifests to look for: whether a driver works is found when the +// instance is made. +const vulkanLibraryName = "libvulkan.so" + +func vulkanDriverConfigured() bool { return true } diff --git a/internal/platform/vulkan/driver_desktop_linux.go b/internal/platform/vulkan/driver_desktop_linux.go new file mode 100644 index 000000000..42e4eccd5 --- /dev/null +++ b/internal/platform/vulkan/driver_desktop_linux.go @@ -0,0 +1,92 @@ +//go:build linux && !android + +package vulkan + +import ( + "os" + "path/filepath" +) + +// A desktop Linux has Vulkan when the loader finds a driver manifest; the loader's +// library is libvulkan.so.1. +const vulkanLibraryName = "libvulkan.so.1" + +// Loader 1.1.97 segfaults in vkCreateInstance when no ICD manifest exists. +func vulkanDriverConfigured() bool { + var paths []string + if files, ok := os.LookupEnv("VK_DRIVER_FILES"); ok { + paths = filepath.SplitList(files) + } else if files, ok := os.LookupEnv("VK_ICD_FILENAMES"); ok { + paths = filepath.SplitList(files) + } else { + paths = vulkanDefaultManifestDirs() + } + if files := os.Getenv("VK_ADD_DRIVER_FILES"); files != "" { + paths = append(paths, filepath.SplitList(files)...) + } + return vulkanDriverManifestsExist(paths) +} + +// vulkanDefaultManifestDirs lists the directories the loader searches for ICD manifests +// when no override is set, in its order: the user's config and data homes, then the +// system lists under each XDG base. +func vulkanDefaultManifestDirs() []string { + home := os.Getenv("HOME") + configHome := os.Getenv("XDG_CONFIG_HOME") + if configHome == "" && home != "" { + configHome = filepath.Join(home, ".config") + } + dataHome := os.Getenv("XDG_DATA_HOME") + if dataHome == "" && home != "" { + dataHome = filepath.Join(home, ".local", "share") + } + var paths []string + if configHome != "" { + paths = append(paths, filepath.Join(configHome, "vulkan", "icd.d")) + } + paths = appendVulkanDirs(paths, os.Getenv("XDG_CONFIG_DIRS"), "/etc/xdg") + if dataHome != "" { + paths = append(paths, filepath.Join(dataHome, "vulkan", "icd.d")) + } + paths = appendVulkanDirs(paths, os.Getenv("XDG_DATA_DIRS"), "/usr/local/share:/usr/share") + return append(paths, "/etc/vulkan/icd.d") +} + +// appendVulkanDirs adds the vulkan/icd.d directory under each entry of an XDG search list, +// or under the fallback list when the variable is unset. +func appendVulkanDirs(paths []string, list, fallback string) []string { + if list == "" { + list = fallback + } + for _, dir := range filepath.SplitList(list) { + if dir != "" { + paths = append(paths, filepath.Join(dir, "vulkan", "icd.d")) + } + } + return paths +} + +func vulkanDriverManifestsExist(paths []string) bool { + for _, path := range paths { + if path == "" { + continue + } + info, err := os.Stat(path) + if err != nil { + continue + } + if !info.IsDir() { + return true + } + entries, err := os.ReadDir(path) + if err != nil { + continue + } + for _, entry := range entries { + if !entry.IsDir() && filepath.Ext(entry.Name()) == ".json" { + return true + } + } + } + return false +} diff --git a/internal/platform/vulkan/helpers_test.go b/internal/platform/vulkan/helpers_test.go new file mode 100644 index 000000000..123beabc5 --- /dev/null +++ b/internal/platform/vulkan/helpers_test.go @@ -0,0 +1,155 @@ +//go:build linux + +package vulkan + +import ( + "errors" + "fmt" + "image" + "strings" + "testing" + "unsafe" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/internal/render" +) + +// solidRasterizer draws every label as a solid block of its size: the tests of the +// renderer check where and how a label's texture is drawn, not the shapes of glyphs, +// which belong to the platform's text engine. +type solidRasterizer struct{} + +func (solidRasterizer) Rasterize(label platform.TextLabel, scale float32, skip, width, height int, allowLCD bool) ([]byte, bool, error) { + pixels := make([]byte, width*height*4) + for index := range pixels { + pixels[index] = 0xff + } + return pixels, false, nil +} +func (solidRasterizer) Spans() []ColorSpan { return nil } +func (solidRasterizer) Close() {} + +func newSolidRasterizer() (TextRasterizer, error) { return solidRasterizer{}, nil } + +// newTestOffscreen skips the test on a machine with no Vulkan driver, as the +// other graphics tests do, and fails on any other error. +func newTestOffscreen(t *testing.T, width, height int) *Offscreen { + t.Helper() + return newScaledOffscreen(t, width, height, 1) +} + +// newScaledOffscreen is newTestOffscreen at a display scale. +func newScaledOffscreen(t *testing.T, width, height int, scale float64) *Offscreen { + t.Helper() + offscreen, err := NewOffscreen(width, height, scale, platform.Color{Alpha: 1}, newSolidRasterizer) + if errors.Is(err, platform.ErrNoGraphics) { + t.Skipf("no Vulkan device: %v", err) + } + if err != nil { + t.Fatal(err) + } + t.Cleanup(offscreen.Close) + return offscreen +} + +func renderScene(t *testing.T, offscreen *Offscreen, rectangles []render.Rectangle, labels []platform.TextLabel) *image.RGBA { + t.Helper() + if err := offscreen.Set(rectangles, labels); err != nil { + t.Fatal(err) + } + pixels, err := offscreen.Image() + if err != nil { + t.Fatal(err) + } + return pixels +} + +func rgbaAt(pixels *image.RGBA, x, y int) (red, green, blue, alpha byte) { + offset := pixels.PixOffset(x, y) + return pixels.Pix[offset], pixels.Pix[offset+1], pixels.Pix[offset+2], pixels.Pix[offset+3] +} + +func isPainted(pixels *image.RGBA, x, y int) bool { + red, green, blue, _ := rgbaAt(pixels, x, y) + return int(red)+int(green)+int(blue) > 60 +} + +// vkStructureHeadlessSurfaceCreateInfo is VK_STRUCTURE_TYPE_HEADLESS_SURFACE_CREATE_INFO_EXT. +const vkStructureHeadlessSurfaceCreateInfo = 1000256000 + +type vkHeadlessSurfaceCreateInfo struct { + SType uint32 + _ uint32 + Next uintptr + Flags uint32 + _ uint32 +} + +// headlessSurfaceSource makes surfaces with VK_EXT_headless_surface, which needs no +// window system: what a window renderer presents to when there is no display. +func headlessSurfaceSource(t testing.TB) SurfaceSource { + t.Helper() + var create func(uintptr, *vkHeadlessSurfaceCreateInfo, unsafe.Pointer, *uintptr) int32 + if err := Bind(&create, "vkCreateHeadlessSurfaceEXT"); err != nil { + if errors.Is(err, platform.ErrNoGraphics) { + t.Skipf("no Vulkan device: %v", err) + } + t.Fatal(err) + } + return SurfaceSource{ + Extension: "VK_EXT_headless_surface", + Create: func(instance uintptr) (uintptr, error) { + info := vkHeadlessSurfaceCreateInfo{SType: vkStructureHeadlessSurfaceCreateInfo} + var surface uintptr + if err := vkCheck(create(instance, &info, nil, &surface), "create headless surface"); err != nil { + return 0, err + } + return surface, nil + }, + } +} + +func resizeTestLabels(count int, width float32) []platform.TextLabel { + labels := make([]platform.TextLabel, count) + for i := range labels { + value := fmt.Sprintf("row-%04d-%s", i, strings.Repeat("x", 80)) + labels[i] = platform.TextLabel{ + Value: value, Y: float32(i * 20), Width: width, Height: 20, + FontSize: 14, Mono: true, CellWidth: 8, + Runs: []gfx.TextRun{{Bytes: int32(len(value)), Cells: int32(len(value))}}, + } + } + return labels +} + +// wideValue is a log line of 4096 characters: at 8 logical pixels a cell and 150% it is +// 49152 device pixels wide, three times what a texture holds. +var wideValue = strings.Repeat("0123456789abcdef", 256) + +func wideMonoLine(value string, x float32, runs []gfx.TextRun) platform.TextLabel { + return platform.TextLabel{ + Value: value, X: x, Y: 4, Width: float32(len(value))*8 + 8, Height: 18, FontSize: 13, CellWidth: 8, + Mono: true, Runs: runs, Color: platform.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1}, + Clipped: true, Clip: gfx.Rect{Width: 400, Height: 40}, + } +} + +func wholeRun(value string) []gfx.TextRun { + return []gfx.TextRun{{Bytes: int32(len(value)), Cells: int32(len(value)), Weight: 400, Color: gfx.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1}}} +} + +// windowSurface is a surface for a renderer to present to: an X window where there is a +// display (which every Vulkan driver presents to), else a headless surface. The +// returned resize changes the surface's size where it can, and reports false where the +// surface has no size of its own. +func windowSurface(t testing.TB, width, height uint32) (source SurfaceSource, resize func(width, height uint32) bool) { + t.Helper() + if windowSystemSurface != nil { + return windowSystemSurface(t, width, height) + } + return headlessSurfaceSource(t), func(uint32, uint32) bool { return false } +} + +// windowSystemSurface is set by the files that know a window system. +var windowSystemSurface func(t testing.TB, width, height uint32) (SurfaceSource, func(width, height uint32) bool) diff --git a/internal/platform/vulkan/input_vulkan_test.go b/internal/platform/vulkan/input_vulkan_test.go new file mode 100644 index 000000000..7bfc10fa5 --- /dev/null +++ b/internal/platform/vulkan/input_vulkan_test.go @@ -0,0 +1,103 @@ +//go:build linux + +package vulkan + +import ( + "testing" + "unsafe" + + "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/internal/render" + "github.com/vivaui/viva/internal/scene" +) + +// A frame stages its scene and leaves the commands to the next submit: an image is +// recorded once for a scene, a frame that only changes instance data (a caret +// blinking) records nothing, and one that changes the batches records again. +func TestRendererRecordsAnImageOnlyWhenItsCommandsAreStale(t *testing.T) { + waits, resets, begins, ends := 0, 0, 0, 0 + storage := make([]byte, 64*vkInstanceBytes) + renderer := Renderer{ + api: &vulkanAPI{ + waitForFences: func(uintptr, uint32, *uintptr, uint32, uint64) int32 { + waits++ + return vkSuccess + }, + resetCommandPool: func(uintptr, uintptr, uint32) int32 { + resets++ + return vkSuccess + }, + beginCommandBuffer: func(uintptr, *vkCommandBufferBeginInfo) int32 { + begins++ + return vkSuccess + }, + cmdBeginRenderPass: func(uintptr, *vkRenderPassBeginInfo, uint32) {}, + cmdClearAttachments: func(uintptr, uint32, *vkClearAttachment, uint32, *vkClearRect) {}, + cmdBindPipeline: func(uintptr, uint32, uintptr) {}, + cmdSetViewport: func(uintptr, uint32, uint32, *vkViewport) {}, + cmdSetScissor: func(uintptr, uint32, uint32, *vkRect2D) {}, + cmdPushConstants: func(uintptr, uintptr, uint32, uint32, uint32, unsafe.Pointer) {}, + cmdBindVertexBuffers: func(uintptr, uint32, uint32, *uintptr, *uint64) {}, + cmdDraw: func(uintptr, uint32, uint32, uint32, uint32) {}, + cmdEndRenderPass: func(uintptr) {}, + endCommandBuffer: func(uintptr) int32 { + ends++ + return vkSuccess + }, + }, + device: 1, + commandPool: 2, + fence: 3, + width: 100, + height: 80, + commands: []uintptr{4, 5}, + framebuffers: []uintptr{6, 7}, + scene: vulkanScene{capacity: 64, mapped: unsafe.Pointer(&storage[0])}, + } + if changed, err := renderer.Apply(platform.Frame{}); err != nil || changed { + t.Fatalf("empty apply changed=%v err=%v", changed, err) + } + if waits != 0 || resets != 0 { + t.Fatalf("empty apply waited=%d reset=%d", waits, resets) + } + renderer.recordExtent = vkExtent2D{Width: 100, Height: 80} + rectangles := []render.Rectangle{{Bounds: scene.Rect{Width: 10, Height: 10}, Color: scene.Color{Alpha: 1}}} + changed, err := renderer.Apply(platform.Frame{Update: render.Update{Rebuild: true, Count: 1}, Rectangles: rectangles}) + if err != nil || !changed { + t.Fatalf("changed apply changed=%v err=%v", changed, err) + } + if waits != 1 || resets != 0 || begins != 0 { + t.Fatalf("staging waits=%d resets=%d begins=%d, want the fence and no recording", waits, resets, begins) + } + submit := func() { + t.Helper() + if err := renderer.ensureRecorded(0); err != nil { + t.Fatal(err) + } + } + submit() + submit() + if begins != 1 || ends != 1 { + t.Fatalf("one scene recorded image 0 begins=%d ends=%d, want once", begins, ends) + } + rectangles[0].Color.Alpha = 0.5 // a caret fading: new instance data, same batches + if _, err := renderer.Apply(platform.Frame{Update: render.Update{First: 0, Count: 1}, Rectangles: rectangles}); err != nil { + t.Fatal(err) + } + submit() + if begins != 1 { + t.Fatalf("a frame that changed instance data recorded again: begins=%d", begins) + } + rectangles = append(rectangles, render.Rectangle{Bounds: scene.Rect{Width: 5, Height: 5}, Color: scene.Color{Alpha: 1}, Layer: 3}) + if _, err := renderer.Apply(platform.Frame{Update: render.Update{First: 1, Count: 1}, Rectangles: rectangles}); err != nil { + t.Fatal(err) + } + submit() + if begins != 2 { + t.Fatalf("a frame that changed the batches did not record again: begins=%d", begins) + } + rectangles[0].Bounds.Width = 99 + if renderer.rectangles[0].Bounds.Width != 10 { + t.Fatal("renderer retained caller-owned rectangle storage") + } +} diff --git a/internal/platform/linux/layers.go b/internal/platform/vulkan/layers.go similarity index 92% rename from internal/platform/linux/layers.go rename to internal/platform/vulkan/layers.go index 3ec1775a1..e33957d6d 100644 --- a/internal/platform/linux/layers.go +++ b/internal/platform/vulkan/layers.go @@ -1,11 +1,10 @@ //go:build linux -package linux +package vulkan import ( "slices" - "github.com/vivaui/viva/internal/platform" "github.com/vivaui/viva/internal/render" "github.com/vivaui/viva/internal/scene" ) @@ -92,12 +91,3 @@ func groupCompositingLayers(rectangles []render.Batch, labels []vulkanLabelTextu } return batches } - -func validateInitialTextLabels(labels []platform.TextLabel) error { - for index, label := range labels { - if err := validateTextLabel(index, label); err != nil { - return err - } - } - return nil -} diff --git a/internal/platform/linux/layers_test.go b/internal/platform/vulkan/layers_test.go similarity index 99% rename from internal/platform/linux/layers_test.go rename to internal/platform/vulkan/layers_test.go index d2230b7c2..491ba83d7 100644 --- a/internal/platform/linux/layers_test.go +++ b/internal/platform/vulkan/layers_test.go @@ -1,6 +1,6 @@ //go:build linux -package linux +package vulkan import ( "testing" diff --git a/internal/platform/vulkan/offscreen_linux.go b/internal/platform/vulkan/offscreen_linux.go new file mode 100644 index 000000000..9e3556f89 --- /dev/null +++ b/internal/platform/vulkan/offscreen_linux.go @@ -0,0 +1,300 @@ +//go:build linux + +package vulkan + +import ( + "fmt" + "image" + "math" + "unsafe" + + "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/internal/render" +) + +const ( + vkImageUsageTransferSource = 0x1 + vkBufferUsageTransferDestination = 0x2 + vkImageLayoutTransferSource = 6 + vkAccessColorAttachmentWrite = 0x100 + vkAccessTransferRead = 0x800 + vkPipelineStageTransferBit = 0x1000 + // maxScale is the largest display scale a scene is drawn at. + maxScale = platform.MaxDisplayScale +) + +// Offscreen renders scenes to pixels with the window's own Vulkan pipelines +// and command recording but without an X window, a surface or a swapchain: the +// target is a plain color image that is copied to host memory. A screenshot or +// a pixel test therefore shows what the window would. It is not safe for +// concurrent use. +type Offscreen struct { + renderer *Renderer +} + +// vulkanOffscreen is the renderer's offscreen target: the color image the +// scene is drawn into and the host buffer it is read back through. +type vulkanOffscreen struct { + image, memory uintptr + readback, readbackMemory uintptr + readbackCommand uintptr + readbackSize uint64 +} + +// NewOffscreen creates a renderer for a width x height scene in logical pixels, +// drawn at scale device pixels per logical pixel (the image is +// ceil(width*scale) by ceil(height*scale)), cleared to clear before each render. +// It fails with platform.ErrNoGraphics when the machine has no Vulkan driver. +// rasterizer makes what draws the glyphs of the labels. +func NewOffscreen(width, height int, scale float64, clear platform.Color, rasterizer NewTextRasterizer) (*Offscreen, error) { + if width < 1 || height < 1 || width > platform.MaxOffscreenSize || height > platform.MaxOffscreenSize || math.IsNaN(scale) || scale < 1 || scale > maxScale { + return nil, fmt.Errorf("vulkan: invalid offscreen size %dx%d at %gx", width, height, scale) + } + deviceWidth, deviceHeight := int(math.Ceil(float64(width)*scale)), int(math.Ceil(float64(height)*scale)) + if deviceWidth > platform.MaxOffscreenSize || deviceHeight > platform.MaxOffscreenSize { + return nil, fmt.Errorf("vulkan: offscreen size %dx%d at %gx is beyond %d device pixels", width, height, scale, platform.MaxOffscreenSize) + } + api, err := loadVulkan() + if err != nil { + return nil, err + } + renderer := &Renderer{api: api, width: uint32(deviceWidth), height: uint32(deviceHeight), scale: float32(scale), color: clear, newRasterizer: rasterizer} + if err := renderer.initializeOffscreen(); err != nil { + renderer.Close() + return nil, err + } + return &Offscreen{renderer: renderer}, nil +} + +// Set replaces the scene: rectangle and triangle instances in paint order and +// text labels. +func (offscreen *Offscreen) Set(rectangles []render.Rectangle, labels []platform.TextLabel) error { + if offscreen.renderer == nil { + return fmt.Errorf("vulkan: offscreen renderer is closed") + } + if labels == nil { + labels = []platform.TextLabel{} + } + _, err := offscreen.renderer.Apply(platform.Frame{ + Update: render.Update{Count: len(rectangles), Rebuild: true}, + Rectangles: rectangles, + TextLabels: labels, + }) + return err +} + +// Image draws the scene and returns its pixels, top row first. The image is +// premultiplied RGBA, the format of the color target converted from the +// target's BGRA byte order; the target is not sRGB, so values are the ones the +// shaders wrote. +func (offscreen *Offscreen) Image() (*image.RGBA, error) { + if offscreen.renderer == nil { + return nil, fmt.Errorf("vulkan: offscreen renderer is closed") + } + return offscreen.renderer.readImage() +} + +// Close releases the renderer. +// Stats reports the renderer's counters. +func (offscreen *Offscreen) Stats() Stats { + if offscreen.renderer == nil { + return Stats{} + } + return offscreen.renderer.Stats() +} + +// RefreshText draws the labels again with the text engine's current settings. +func (offscreen *Offscreen) RefreshText() error { + if offscreen.renderer == nil { + return fmt.Errorf("vulkan: offscreen renderer is closed") + } + return offscreen.renderer.RefreshText() +} + +// DualSource reports whether the device blends dual-source, which LCD text needs. +func (offscreen *Offscreen) DualSource() bool { + return offscreen.renderer != nil && offscreen.renderer.dualSource +} + +func (offscreen *Offscreen) Close() { + if offscreen.renderer != nil { + offscreen.renderer.Close() + offscreen.renderer = nil + } +} + +func (renderer *Renderer) initializeOffscreen() error { + device := vulkanDevice{api: renderer.api} + if err := device.open(); err != nil { + return err + } + renderer.adopt(&device) + if err := renderer.scene.upload(renderer, nil, render.Update{Rebuild: true}); err != nil { + return err + } + if err := renderer.createOffscreenTarget(); err != nil { + return err + } + semaphoreInfo := vkSemaphoreCreateInfo{SType: vkStructureSemaphoreCreateInfo} + if err := vkCheck(renderer.api.createSemaphore(renderer.device, &semaphoreInfo, nil, &renderer.imageAvailable), "create acquire semaphore"); err != nil { + return err + } + fenceInfo := vkFenceCreateInfo{SType: vkStructureFenceCreateInfo, Flags: vkFenceSignaled} + return vkCheck(renderer.api.createFence(renderer.device, &fenceInfo, nil, &renderer.fence), "create frame fence") +} + +// createOffscreenTarget builds what createSwapchain builds for a window, with +// one color image instead of the swapchain's: image, view, render pass, +// framebuffer and commands, then the shared pipelines. The render pass leaves +// the image ready to be copied. +func (renderer *Renderer) createOffscreenTarget() (err error) { + defer func() { + if err != nil { + renderer.destroySwapchain() + renderer.destroyOffscreen() + } + }() + target := &renderer.offscreen + extent := vkExtent2D{Width: renderer.width, Height: renderer.height} + imageInfo := vkImageCreateInfo{ + SType: vkStructureTextImageCreateInfo, ImageType: vkImageType2D, Format: vkFormatBGRA8, + Extent: vkExtent3D{Width: extent.Width, Height: extent.Height, Depth: 1}, MipLevels: 1, ArrayLayers: 1, + Samples: vkSampleCountOne, Tiling: vkImageTilingOptimal, + Usage: vkImageUsageColorAttachment | vkImageUsageTransferSource, SharingMode: vkSharingExclusive, + } + if err := vkCheck(renderer.api.createImage(renderer.device, &imageInfo, nil, &target.image), "create offscreen image"); err != nil { + return err + } + var requirements vkMemoryRequirements + renderer.api.getImageMemoryRequirements(renderer.device, target.image, &requirements) + memoryType, ok := renderer.memoryType(requirements.MemoryTypeBits, vkMemoryDeviceLocal) + if !ok { + return fmt.Errorf("vulkan: Vulkan device has no device-local image memory") + } + allocation := vkMemoryAllocateInfo{SType: vkStructureMemoryAllocateInfo, AllocationSize: requirements.Size, MemoryTypeIndex: memoryType} + if err := vkCheck(renderer.api.allocateMemory(renderer.device, &allocation, nil, &target.memory), "allocate offscreen image memory"); err != nil { + return err + } + if err := vkCheck(renderer.api.bindImageMemory(renderer.device, target.image, target.memory, 0), "bind offscreen image memory"); err != nil { + return err + } + renderer.views = make([]uintptr, 1) + viewInfo := vkImageViewCreateInfo{SType: vkStructureImageViewCreateInfo, Image: target.image, ViewType: vkImageViewType2D, Format: vkFormatBGRA8, Range: vkSubresourceRange{Aspect: vkImageAspectColor, LevelCount: 1, LayerCount: 1}} + if err := vkCheck(renderer.api.createImageView(renderer.device, &viewInfo, nil, &renderer.views[0]), "create offscreen image view"); err != nil { + return err + } + if err := renderer.createRenderPass(vkFormatBGRA8, vkImageLayoutTransferSource); err != nil { + return err + } + renderer.framebuffers = make([]uintptr, 1) + view := renderer.views[0] + framebufferInfo := vkFramebufferCreateInfo{SType: vkStructureFramebufferCreateInfo, RenderPass: renderer.renderPass, AttachmentCount: 1, Attachments: &view, Width: extent.Width, Height: extent.Height, Layers: 1} + if err := vkCheck(renderer.api.createFramebuffer(renderer.device, &framebufferInfo, nil, &renderer.framebuffers[0]), "create offscreen framebuffer"); err != nil { + return err + } + if err := renderer.createCommands(1); err != nil { + return err + } + // The readback buffer is host memory the image is copied into. + target.readbackSize = uint64(extent.Width) * uint64(extent.Height) * 4 + bufferInfo := vkBufferCreateInfo{SType: vkStructureBufferCreateInfo, Size: target.readbackSize, Usage: vkBufferUsageTransferDestination, SharingMode: vkSharingExclusive} + if err := vkCheck(renderer.api.createBuffer(renderer.device, &bufferInfo, nil, &target.readback), "create readback buffer"); err != nil { + return err + } + renderer.api.getBufferMemoryRequirements(renderer.device, target.readback, &requirements) + memoryType, ok = renderer.memoryType(requirements.MemoryTypeBits, vkMemoryHostVisible|vkMemoryHostCoherent) + if !ok { + return fmt.Errorf("vulkan: Vulkan device has no coherent host-visible memory for readback") + } + allocation = vkMemoryAllocateInfo{SType: vkStructureMemoryAllocateInfo, AllocationSize: requirements.Size, MemoryTypeIndex: memoryType} + if err := vkCheck(renderer.api.allocateMemory(renderer.device, &allocation, nil, &target.readbackMemory), "allocate readback memory"); err != nil { + return err + } + if err := vkCheck(renderer.api.bindBufferMemory(renderer.device, target.readback, target.readbackMemory, 0), "bind readback memory"); err != nil { + return err + } + allocate := vkCommandBufferAllocateInfo{SType: vkStructureCommandAllocateInfo, Pool: renderer.commandPool, Level: vkCommandBufferPrimary, Count: 1} + if err := vkCheck(renderer.api.allocateCommandBuffers(renderer.device, &allocate, &target.readbackCommand), "allocate readback command"); err != nil { + return err + } + if err := renderer.createScenePipelines(extent); err != nil { + return err + } + renderer.format = vkFormatBGRA8 + return nil +} + +// readImage submits the recorded scene and a copy of the target into the +// readback buffer, waits for them and converts the bytes to an image. +func (renderer *Renderer) readImage() (*image.RGBA, error) { + target := &renderer.offscreen + if err := vkCheck(renderer.api.waitForFences(renderer.device, 1, &renderer.fence, 1, math.MaxUint64), "wait before readback"); err != nil { + return nil, err + } + if err := renderer.ensureRecorded(0); err != nil { + return nil, err + } + begin := vkCommandBufferBeginInfo{SType: vkStructureCommandBeginInfo, Flags: vkCommandOneTimeSubmit} + if err := vkCheck(renderer.api.beginCommandBuffer(target.readbackCommand, &begin), "begin readback command"); err != nil { + return nil, err + } + // The render pass already left the image in the copy layout; the barrier + // makes its writes visible to the copy. + barrier := vkImageMemoryBarrier{ + SType: vkStructureImageMemoryBarrier, SourceAccess: vkAccessColorAttachmentWrite, DestinationAccess: vkAccessTransferRead, + OldLayout: vkImageLayoutTransferSource, NewLayout: vkImageLayoutTransferSource, + SourceQueueFamily: vkQueueFamilyIgnored, DestinationQueueFamily: vkQueueFamilyIgnored, Image: target.image, + Range: vkSubresourceRange{Aspect: vkImageAspectColor, LevelCount: 1, LayerCount: 1}, + } + renderer.api.cmdPipelineBarrier(target.readbackCommand, vkPipelineStageColorOutput, vkPipelineStageTransferBit, 0, 0, nil, 0, nil, 1, &barrier) + region := vkBufferImageCopy{ + ImageSubresource: vkImageSubresourceLayers{Aspect: vkImageAspectColor, LayerCount: 1}, + ImageExtent: vkExtent3D{Width: renderer.width, Height: renderer.height, Depth: 1}, + } + renderer.api.cmdCopyImageToBuffer(target.readbackCommand, target.image, vkImageLayoutTransferSource, target.readback, 1, ®ion) + if err := vkCheck(renderer.api.endCommandBuffer(target.readbackCommand), "end readback command"); err != nil { + return nil, err + } + if err := vkCheck(renderer.api.resetFences(renderer.device, 1, &renderer.fence), "reset frame fence"); err != nil { + return nil, err + } + commands := [2]uintptr{renderer.commands[0], target.readbackCommand} + submit := vkSubmitInfo{SType: vkStructureSubmitInfo, CommandCount: 2, Commands: &commands[0]} + if err := vkCheck(renderer.api.queueSubmit(renderer.queue, 1, &submit, renderer.fence), "submit offscreen render"); err != nil { + return nil, err + } + if err := vkCheck(renderer.api.waitForFences(renderer.device, 1, &renderer.fence, 1, math.MaxUint64), "wait for offscreen render"); err != nil { + return nil, err + } + var mapped unsafe.Pointer + if err := vkCheck(renderer.api.mapMemory(renderer.device, target.readbackMemory, 0, target.readbackSize, 0, &mapped), "map readback memory"); err != nil { + return nil, err + } + defer renderer.api.unmapMemory(renderer.device, target.readbackMemory) + bgra := unsafe.Slice((*byte)(mapped), int(target.readbackSize)) + result := image.NewRGBA(image.Rect(0, 0, int(renderer.width), int(renderer.height))) + for offset := 0; offset+3 < len(bgra); offset += 4 { + result.Pix[offset], result.Pix[offset+1], result.Pix[offset+2], result.Pix[offset+3] = bgra[offset+2], bgra[offset+1], bgra[offset], bgra[offset+3] + } + renderer.submissions++ + return result, nil +} + +func (renderer *Renderer) destroyOffscreen() { + target := &renderer.offscreen + if renderer.device != 0 { + if target.readback != 0 { + renderer.api.destroyBuffer(renderer.device, target.readback, nil) + } + if target.readbackMemory != 0 { + renderer.api.freeMemory(renderer.device, target.readbackMemory, nil) + } + if target.image != 0 { + renderer.api.destroyImage(renderer.device, target.image, nil) + } + if target.memory != 0 { + renderer.api.freeMemory(renderer.device, target.memory, nil) + } + } + *target = vulkanOffscreen{} +} diff --git a/internal/platform/vulkan/probe_select_test.go b/internal/platform/vulkan/probe_select_test.go new file mode 100644 index 000000000..929e599cd --- /dev/null +++ b/internal/platform/vulkan/probe_select_test.go @@ -0,0 +1,62 @@ +//go:build linux + +package vulkan + +import ( + "encoding/binary" + "testing" + "unsafe" +) + +// fakeVulkanAPI answers just enough for selectPhysical: the given physical +// devices in order and one graphics family that presents everywhere. +func fakeVulkanAPI(devices []uintptr, kinds map[uintptr]uint32) *vulkanAPI { + return &vulkanAPI{ + enumeratePhysicalDevices: func(_ uintptr, count *uint32, list *uintptr) int32 { + *count = uint32(len(devices)) + if list != nil { + copy(unsafe.Slice(list, len(devices)), devices) + } + return vkSuccess + }, + getQueueFamilyProperties: func(_ uintptr, count *uint32, families *vkQueueFamilyProperties) { + *count = 1 + if families != nil { + *families = vkQueueFamilyProperties{Flags: vkQueueGraphics, Count: 1} + } + }, + getSurfaceSupport: func(_ uintptr, _ uint32, _ uintptr, supported *uint32) int32 { + *supported = 1 + return vkSuccess + }, + getPhysicalDeviceProperties: func(device uintptr, properties *[vkPropertiesSize]byte) { + binary.LittleEndian.PutUint32(properties[vkPropertiesDeviceTypeOffset:], kinds[device]) + }, + } +} + +// A software Vulkan device is never preferred over a hardware one, and a machine +// whose only device is software is reported as such, so the CPU renderer can +// take over. +func TestSelectDevicePrefersHardwareAndReportsSoftware(t *testing.T) { + hardware := uint32(2) // VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU + for _, test := range []struct { + name string + devices []uintptr + kinds map[uintptr]uint32 + physical uintptr + software bool + }{ + {"software first", []uintptr{11, 22}, map[uintptr]uint32{11: vkPhysicalDeviceTypeCPU, 22: hardware}, 22, false}, + {"hardware first", []uintptr{22, 11}, map[uintptr]uint32{22: hardware, 11: vkPhysicalDeviceTypeCPU}, 22, false}, + {"only software", []uintptr{11}, map[uintptr]uint32{11: vkPhysicalDeviceTypeCPU}, 11, true}, + } { + device := &vulkanDevice{api: fakeVulkanAPI(test.devices, test.kinds), instance: 1} + if err := device.selectPhysical(2); err != nil { + t.Fatalf("%s: %v", test.name, err) + } + if device.physical != test.physical || device.software != test.software { + t.Errorf("%s: device %d software=%v, want %d software=%v", test.name, device.physical, device.software, test.physical, test.software) + } + } +} diff --git a/internal/platform/vulkan/rasterizer.go b/internal/platform/vulkan/rasterizer.go new file mode 100644 index 000000000..bbbda56f7 --- /dev/null +++ b/internal/platform/vulkan/rasterizer.go @@ -0,0 +1,32 @@ +package vulkan + +import "github.com/vivaui/viva/internal/platform" + +// ColorSpan is the columns of an LCD grid label's texture, left to right in +// device pixels, that are text of one color. The texture's coverage is the same +// for every color, so the renderer draws it once per span, with the span's +// color, scissored to its columns. +type ColorSpan struct { + Left, Right int + Color [4]float32 +} + +// TextRasterizer draws the glyphs of a text label into the coverage bitmap of its +// texture. The renderer owns the texture, its upload and its placement; what draws +// the glyphs is the platform's text engine (Pango on a Linux desktop, the system's +// Paint on Android), which the platform gives the renderer as a factory. +type TextRasterizer interface { + // Rasterize draws the device columns from skip to skip+width of the label, height + // rows tall, at scale. With allowLCD the result may be the coverage of each + // color channel (lcd reports it), to be blended with the label's color by the + // renderer's LCD pipeline. + Rasterize(label platform.TextLabel, scale float32, skip, width, height int, allowLCD bool) (pixels []byte, lcd bool, err error) + // Spans are the colors of the last LCD grid label rasterized, valid until the + // next call of Rasterize; empty for a label that is all in label.Color. + Spans() []ColorSpan + // Close releases what the rasterizer holds. + Close() +} + +// NewTextRasterizer makes the rasterizer of one renderer. +type NewTextRasterizer func() (TextRasterizer, error) diff --git a/internal/platform/linux/shaders/scene.frag b/internal/platform/vulkan/shaders/scene.frag similarity index 100% rename from internal/platform/linux/shaders/scene.frag rename to internal/platform/vulkan/shaders/scene.frag diff --git a/internal/platform/linux/shaders/scene.frag.spv b/internal/platform/vulkan/shaders/scene.frag.spv similarity index 100% rename from internal/platform/linux/shaders/scene.frag.spv rename to internal/platform/vulkan/shaders/scene.frag.spv diff --git a/internal/platform/linux/shaders/scene.vert b/internal/platform/vulkan/shaders/scene.vert similarity index 100% rename from internal/platform/linux/shaders/scene.vert rename to internal/platform/vulkan/shaders/scene.vert diff --git a/internal/platform/linux/shaders/scene.vert.spv b/internal/platform/vulkan/shaders/scene.vert.spv similarity index 100% rename from internal/platform/linux/shaders/scene.vert.spv rename to internal/platform/vulkan/shaders/scene.vert.spv diff --git a/internal/platform/linux/shaders/text.frag b/internal/platform/vulkan/shaders/text.frag similarity index 100% rename from internal/platform/linux/shaders/text.frag rename to internal/platform/vulkan/shaders/text.frag diff --git a/internal/platform/linux/shaders/text.frag.spv b/internal/platform/vulkan/shaders/text.frag.spv similarity index 100% rename from internal/platform/linux/shaders/text.frag.spv rename to internal/platform/vulkan/shaders/text.frag.spv diff --git a/internal/platform/linux/shaders/text.vert b/internal/platform/vulkan/shaders/text.vert similarity index 100% rename from internal/platform/linux/shaders/text.vert rename to internal/platform/vulkan/shaders/text.vert diff --git a/internal/platform/linux/shaders/text.vert.spv b/internal/platform/vulkan/shaders/text.vert.spv similarity index 100% rename from internal/platform/linux/shaders/text.vert.spv rename to internal/platform/vulkan/shaders/text.vert.spv diff --git a/internal/platform/linux/shaders/text_lcd.frag b/internal/platform/vulkan/shaders/text_lcd.frag similarity index 100% rename from internal/platform/linux/shaders/text_lcd.frag rename to internal/platform/vulkan/shaders/text_lcd.frag diff --git a/internal/platform/linux/shaders/text_lcd.frag.spv b/internal/platform/vulkan/shaders/text_lcd.frag.spv similarity index 100% rename from internal/platform/linux/shaders/text_lcd.frag.spv rename to internal/platform/vulkan/shaders/text_lcd.frag.spv diff --git a/internal/platform/linux/shaders_linux.go b/internal/platform/vulkan/shaders_linux.go similarity index 95% rename from internal/platform/linux/shaders_linux.go rename to internal/platform/vulkan/shaders_linux.go index 0d9b400ae..3916035c9 100644 --- a/internal/platform/linux/shaders_linux.go +++ b/internal/platform/vulkan/shaders_linux.go @@ -1,4 +1,4 @@ -package linux +package vulkan import _ "embed" diff --git a/internal/platform/vulkan/shared_api_test.go b/internal/platform/vulkan/shared_api_test.go new file mode 100644 index 000000000..f2039c112 --- /dev/null +++ b/internal/platform/vulkan/shared_api_test.go @@ -0,0 +1,16 @@ +//go:build linux + +package vulkan + +import "testing" + +// The libvulkan library is opened once per process, and a machine without one is +// found once; every caller gets its own copy of the bound table, so wrapping one +// window's functions leaves another's alone. +func TestVulkanTableIsLoadedOnce(t *testing.T) { + v1, vErr1 := loadVulkan() + v2, vErr2 := loadVulkan() + if vErr1 != vErr2 || (vErr1 == nil && (v1.library != v2.library || v1 == v2)) { + t.Fatalf("loadVulkan gave %p, %v then %p, %v", v1, vErr1, v2, vErr2) + } +} diff --git a/internal/platform/vulkan/text_resize_linux_test.go b/internal/platform/vulkan/text_resize_linux_test.go new file mode 100644 index 000000000..c5f5d06db --- /dev/null +++ b/internal/platform/vulkan/text_resize_linux_test.go @@ -0,0 +1,255 @@ +//go:build linux + +package vulkan + +import ( + "fmt" + "strings" + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/platform" +) + +func BenchmarkVulkanTextLiveResize(b *testing.B) { + for _, count := range []int{256, 1024} { + b.Run(fmt.Sprintf("ClippedWidths/%d", count), func(b *testing.B) { + narrow := resizeTestLabels(count, 60) + wide := append([]platform.TextLabel(nil), narrow...) + for i := range wide { + wide[i].Width++ + } + var state vulkanText + if err := state.update(nil, narrow); err != nil { + b.Fatal(err) + } + for _, labels := range [][]platform.TextLabel{wide, narrow} { + if err := state.update(nil, labels); err != nil { + b.Fatal(err) + } + } + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + labels := narrow + if i&1 == 0 { + labels = wide + } + if err := state.update(nil, labels); err != nil { + b.Fatal(err) + } + } + }) + b.Run(fmt.Sprintf("Unchanged/%d", count), func(b *testing.B) { + labels := resizeTestLabels(count, 800) + var state vulkanText + if err := state.update(nil, labels); err != nil { + b.Fatal(err) + } + if err := state.update(nil, labels); err != nil { + b.Fatal(err) + } + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + if err := state.update(nil, labels); err != nil { + b.Fatal(err) + } + } + }) + b.Run(fmt.Sprintf("RepeatedClippedWidths/%d", count), func(b *testing.B) { + narrow := resizeTestLabels(count, 60) + for i := range narrow { + narrow[i].Value, narrow[i].Runs = narrow[0].Value, narrow[0].Runs + } + wide := append([]platform.TextLabel(nil), narrow...) + for i := range wide { + wide[i].Width++ + } + var state vulkanText + for _, labels := range [][]platform.TextLabel{narrow, wide, narrow} { + if err := state.update(nil, labels); err != nil { + b.Fatal(err) + } + } + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + // The old textures were clipped at the previous width. Growing + // beyond them requires new pictures, even for duplicate rows. + for j := range state.labels { + state.labels[j].view = uintptr(j + 1) + state.labels[j].scale = 1 + state.labels[j].width = int(state.labels[j].label.Width) + } + labels := narrow + if i&1 == 0 { + labels = wide + } + if err := state.update(nil, labels); err != nil { + b.Fatal(err) + } + } + }) + } +} + +func TestVulkanTextResizeKeepsDistinctDuplicateTextures(t *testing.T) { + labels := resizeTestLabels(3, 800) + labels[1].Value, labels[1].Runs = labels[0].Value, labels[0].Runs + var state vulkanText + if err := state.update(nil, labels); err != nil { + t.Fatal(err) + } + for i := range state.labels { + state.labels[i].view = uintptr(i + 1) + } + next := []platform.TextLabel{labels[2], labels[0], labels[1]} + if err := state.update(nil, next); err != nil { + t.Fatal(err) + } + seen := make(map[uintptr]bool) + for i, label := range state.labels { + if label.view == 0 || seen[label.view] { + t.Fatalf("slot %d retained invalid or duplicate image view %d", i, label.view) + } + seen[label.view] = true + } + if state.labels[0].view != 3 { + t.Fatalf("moved unique label view = %d, want 3", state.labels[0].view) + } +} + +func TestVulkanTextResizeInvalidLabelKeepsPreviousFrame(t *testing.T) { + labels := resizeTestLabels(3, 800) + var state vulkanText + if err := state.update(nil, labels); err != nil { + t.Fatal(err) + } + state.labels[0].view = 42 + next := append([]platform.TextLabel(nil), labels...) + next[0].Value = "changed" + next[2].Width = -1 + if err := state.update(nil, next); err == nil { + t.Fatal("accepted negative width") + } + if state.labels[0].view != 42 || state.labels[0].label.Value != labels[0].Value { + t.Fatal("invalid update discarded the previous frame") + } +} + +func TestVulkanGridResizeReusesReservedColumnsAcrossIndexShift(t *testing.T) { + labels := resizeTestLabels(2, 70) + var state vulkanText + if err := state.update(nil, labels); err != nil { + t.Fatal(err) + } + for i := range state.labels { + state.labels[i].view = uintptr(i + 1) + state.labels[i].width = 128 + state.labels[i].scale = 1 + } + next := []platform.TextLabel{labels[1], labels[0]} + next[0].Width, next[1].Width = 105, 35 + if err := state.update(nil, next); err != nil { + t.Fatal(err) + } + for i, want := range []uintptr{2, 1} { + if state.labels[i].view != want || state.labels[i].label.Width != next[i].Width { + t.Fatalf("row %d lost its texture or new visible width: %+v", i, state.labels[i]) + } + } + next[0].Width = 129 + if err := state.update(nil, next); err != nil { + t.Fatal(err) + } + if state.labels[0].view != 0 || state.labels[1].view != 1 { + t.Fatal("growing beyond the reserved columns did not invalidate only the wider row") + } + next[1].Runs = append([]gfx.TextRun(nil), next[1].Runs...) + next[1].Runs[0].Color = gfx.RGB(255, 0, 0) + if err := state.update(nil, next); err != nil { + t.Fatal(err) + } + if state.labels[1].view != 0 { + t.Fatal("a changed run color kept its old texture") + } +} + +func TestVulkanGridTextureReservationIsBounded(t *testing.T) { + label := resizeTestLabels(1, 70)[0] + if got := LabelRasterWidth(label, 1, 20); got != 128 { + t.Fatalf("reserved width = %d, want 128", got) + } + label.Value = "hello" + label.Runs = []gfx.TextRun{{Bytes: 5, Cells: 5}} + if got := LabelRasterWidth(label, 1, 20); got != 50 { + t.Fatalf("short row width = %d, want its ink and overhang only", got) + } + label.Value = strings.Repeat("x", 100000) + label.Runs = []gfx.TextRun{{Bytes: int32(len(label.Value)), Cells: int32(len(label.Value))}} + for _, test := range []struct { + width float32 + height int + want int + }{{70, 20, 128}, {16360, 20, 16384}, {1000, 16384, 1024}} { + label.Width = test.width + if got := LabelRasterWidth(label, 1, test.height); got != test.want { + t.Fatalf("width %g height %d reserves %d pixels, want %d", test.width, test.height, got, test.want) + } + } +} + +func TestVulkanTextResizeMatchesUnclippedWidthAndRejectsClippedWidth(t *testing.T) { + labels := resizeTestLabels(2, 80) + labels[1].Value = "short" + labels[1].Runs = []gfx.TextRun{{Bytes: 5, Cells: 5}} + var state vulkanText + if err := state.update(nil, labels); err != nil { + t.Fatal(err) + } + state.labels[0].view, state.labels[1].view = 41, 42 + next := []platform.TextLabel{labels[1], labels[0]} + next[0].Width, next[1].Width = 200, 85 + if err := state.update(nil, next); err != nil { + t.Fatal(err) + } + if state.labels[0].view != 42 { + t.Fatalf("unclipped moved text view = %d, want 42", state.labels[0].view) + } + if state.labels[1].view != 0 { + t.Fatal("reused texture that was clipped at a narrower width") + } + state.labels[1].view = 99 + next[1].Width = 80 + if err := state.update(nil, next); err != nil { + t.Fatal(err) + } + if state.labels[0].view != 42 || state.labels[1].view != 0 { + t.Fatal("shrinking a clipped label did not retain only the unaffected texture") + } +} + +func TestVulkanTextResizeBitmapMatchesSourceAndKeepsDrawSize(t *testing.T) { + one, two := []byte{0, 0, 255, 255}, []byte{0, 0, 255, 255} + labels := []platform.TextLabel{ + {Width: 10, Height: 10, Bitmap: one, BitmapWidth: 1, BitmapHeight: 1, BitmapStride: 4, BitmapID: 1}, + {Width: 10, Height: 10, Bitmap: two, BitmapWidth: 1, BitmapHeight: 1, BitmapStride: 4, BitmapID: 1}, + } + var state vulkanText + if err := state.update(nil, labels); err != nil { + t.Fatal(err) + } + state.labels[0].view, state.labels[1].view = 41, 42 + next := []platform.TextLabel{labels[1], labels[0]} + next[0].Width, next[0].Height = 20, 30 + if err := state.update(nil, next); err != nil { + t.Fatal(err) + } + if state.labels[0].view != 42 || state.labels[1].view != 41 { + t.Fatal("bitmap source identity was lost when the labels moved") + } + if state.labels[0].label.Width != 20 || state.labels[0].label.Height != 30 { + t.Fatal("retained bitmap did not take its new drawn dimensions") + } +} diff --git a/internal/platform/linux/vulkan_bench_linux_test.go b/internal/platform/vulkan/vulkan_bench_linux_test.go similarity index 93% rename from internal/platform/linux/vulkan_bench_linux_test.go rename to internal/platform/vulkan/vulkan_bench_linux_test.go index c4ad90da0..1a603c5ae 100644 --- a/internal/platform/linux/vulkan_bench_linux_test.go +++ b/internal/platform/vulkan/vulkan_bench_linux_test.go @@ -1,6 +1,6 @@ //go:build linux -package linux +package vulkan import ( "errors" @@ -19,7 +19,7 @@ import ( func BenchmarkRendererChangedFrame(benchmark *testing.B) { for _, count := range []int{1, 100, 1000} { benchmark.Run(fmt.Sprintf("rectangles=%d", count), func(benchmark *testing.B) { - offscreen, err := NewOffscreen(800, 600, 1, platform.Color{Alpha: 1}) + offscreen, err := NewOffscreen(800, 600, 1, platform.Color{Alpha: 1}, newSolidRasterizer) if errors.Is(err, platform.ErrNoGraphics) { benchmark.Skipf("no Vulkan device: %v", err) } @@ -42,7 +42,7 @@ func BenchmarkRendererChangedFrame(benchmark *testing.B) { benchmark.ResetTimer() for iteration := range benchmark.N { rectangles[0].Color.Red = float32(iteration&1) * 0.5 - if _, err := renderer.apply(platform.Frame{Update: render.Update{First: 0, Count: 1}, Rectangles: rectangles}); err != nil { + if _, err := renderer.Apply(platform.Frame{Update: render.Update{First: 0, Count: 1}, Rectangles: rectangles}); err != nil { benchmark.Fatal(err) } } diff --git a/internal/platform/linux/vulkan_device_linux.go b/internal/platform/vulkan/vulkan_device_linux.go similarity index 93% rename from internal/platform/linux/vulkan_device_linux.go rename to internal/platform/vulkan/vulkan_device_linux.go index 139854258..4bccd044a 100644 --- a/internal/platform/linux/vulkan_device_linux.go +++ b/internal/platform/vulkan/vulkan_device_linux.go @@ -1,4 +1,4 @@ -package linux +package vulkan import ( "encoding/binary" @@ -39,15 +39,15 @@ var windowDevice struct { // acquireWindowDevice returns the window device, with its instance made; the // window makes its surface on that instance and then attaches it. -func acquireWindowDevice(api *vulkanAPI) (*vulkanDevice, error) { +func acquireWindowDevice(api *vulkanAPI, surfaceExtension string) (*vulkanDevice, error) { windowDevice.Lock() defer windowDevice.Unlock() device := windowDevice.current if device == nil { device = &vulkanDevice{api: api} - surfaceExtension := append([]byte("VK_KHR_surface"), 0) - xcbExtension := append([]byte("VK_KHR_xcb_surface"), 0) - if err := device.createInstance([]*byte{&surfaceExtension[0], &xcbExtension[0]}); err != nil { + baseExtension := append([]byte("VK_KHR_surface"), 0) + systemExtension := append([]byte(surfaceExtension), 0) + if err := device.createInstance([]*byte{&baseExtension[0], &systemExtension[0]}); err != nil { return nil, err } windowDevice.current = device @@ -65,7 +65,7 @@ func (device *vulkanDevice) attach(surface uintptr) error { if device.handle != 0 { var supported uint32 if status := device.api.getSurfaceSupport(device.physical, device.queueFamily, surface, &supported); status != vkSuccess || supported == 0 { - return fmt.Errorf("linux: the Vulkan device the other windows draw with cannot present to this window (result %d)", status) + return fmt.Errorf("vulkan: the Vulkan device the other windows draw with cannot present to this window (result %d)", status) } return nil } @@ -171,7 +171,7 @@ func (device *vulkanDevice) createLogical(extensions []*byte) error { } device.api.getDeviceQueue(device.handle, device.queueFamily, 0, &device.queue) if device.queue == 0 { - return fmt.Errorf("linux: Vulkan returned no graphics queue") + return fmt.Errorf("vulkan: Vulkan returned no graphics queue") } return nil } @@ -194,7 +194,7 @@ func (device *vulkanDevice) selectPhysical(surface uintptr) error { return noVulkan("Vulkan reports no device", nil) } if deviceCount > 32 { - return fmt.Errorf("linux: Vulkan physical device count %d", deviceCount) + return fmt.Errorf("vulkan: Vulkan physical device count %d", deviceCount) } devices := make([]uintptr, deviceCount) if err := vkCheck(device.api.enumeratePhysicalDevices(device.instance, &deviceCount, &devices[0]), "enumerate physical devices"); err != nil { @@ -235,7 +235,7 @@ func (device *vulkanDevice) selectPhysical(surface uintptr) error { device.physical, device.queueFamily, device.software = softwareDevice, softwareFamily, true return nil } - return noVulkan("no Vulkan graphics queue can present to XCB", nil) + return noVulkan("no Vulkan graphics queue can present to the window system", nil) } // physicalDeviceIsCPU reports whether physical is a CPU rasterizer, such as diff --git a/internal/platform/linux/vulkan_device_linux_test.go b/internal/platform/vulkan/vulkan_device_linux_test.go similarity index 79% rename from internal/platform/linux/vulkan_device_linux_test.go rename to internal/platform/vulkan/vulkan_device_linux_test.go index 836fc6f89..f816ba628 100644 --- a/internal/platform/linux/vulkan_device_linux_test.go +++ b/internal/platform/vulkan/vulkan_device_linux_test.go @@ -1,4 +1,4 @@ -package linux +package vulkan import "testing" @@ -6,26 +6,26 @@ import "testing" // device of its own, closing one window leaves the others drawing, and the // device goes when the last window does. func TestWindowsShareOneVulkanDevice(t *testing.T) { - _, first := newWindowRenderer(t, nil) - _, second := newWindowRenderer(t, nil) + first := newWindowRenderer(t, nil) + second := newWindowRenderer(t, nil) if first.shared == nil || first.shared != second.shared || first.device != second.device || first.instance != second.instance { t.Fatalf("windows draw with devices %p and %p", first.shared, second.shared) } shared := first.shared - if err := first.present(); err != nil { + if err := first.Present(); err != nil { t.Fatal(err) } - if err := second.present(); err != nil { + if err := second.Present(); err != nil { t.Fatal(err) } - second.close() + second.Close() if shared.users != 1 || shared.handle == 0 { t.Fatalf("closing one window left %d users, device %d", shared.users, shared.handle) } - if err := first.present(); err != nil { + if err := first.Present(); err != nil { t.Fatalf("the remaining window cannot draw: %v", err) } - first.close() + first.Close() if shared.handle != 0 || shared.instance != 0 || windowDevice.current != nil { t.Fatal("the device outlived its last window") } @@ -35,10 +35,10 @@ func TestWindowsShareOneVulkanDevice(t *testing.T) { // itself again on a new device; another keeps the old one until it finds out // too, and then joins the new one. func TestALostDeviceIsReplacedForEveryWindow(t *testing.T) { - _, first := newWindowRenderer(t, nil) - _, second := newWindowRenderer(t, nil) + first := newWindowRenderer(t, nil) + second := newWindowRenderer(t, nil) old := first.shared - loseOnce := func(renderer *vulkanRenderer) { + loseOnce := func(renderer *Renderer) { present := renderer.api.queuePresent lost := true renderer.api.queuePresent = func(queue uintptr, info *vkPresentInfo) int32 { @@ -50,20 +50,20 @@ func TestALostDeviceIsReplacedForEveryWindow(t *testing.T) { } } loseOnce(first) - if err := first.present(); err != nil { + if err := first.Present(); err != nil { t.Fatalf("present after a lost device: %v", err) } if first.shared == old || !old.lost || second.shared != old { t.Fatalf("after the loss the windows draw with %p and %p (old %p, lost %v)", first.shared, second.shared, old, old.lost) } loseOnce(second) - if err := second.present(); err != nil { + if err := second.Present(); err != nil { t.Fatalf("present after the other window replaced the device: %v", err) } if second.shared != first.shared || old.handle != 0 { t.Fatalf("the second window draws with %p, not the new %p; old device %d", second.shared, first.shared, old.handle) } - if err := first.present(); err != nil { + if err := first.Present(); err != nil { t.Fatal(err) } } diff --git a/internal/platform/linux/vulkan_frame_linux.go b/internal/platform/vulkan/vulkan_frame_linux.go similarity index 77% rename from internal/platform/linux/vulkan_frame_linux.go rename to internal/platform/vulkan/vulkan_frame_linux.go index ac0400a01..2f85e42c5 100644 --- a/internal/platform/linux/vulkan_frame_linux.go +++ b/internal/platform/vulkan/vulkan_frame_linux.go @@ -1,8 +1,10 @@ -package linux +package vulkan import ( "fmt" "unsafe" + + "github.com/vivaui/viva/internal/platform/windowframe" ) const ( @@ -37,13 +39,13 @@ func (frame *vulkanFrame) active() bool { return frame.margin > 0 } // content is the rectangle of the target the scene is drawn in. func (frame *vulkanFrame) content(width, height uint32) (x, y int32, size vkExtent2D) { - box := frameContent(width, height, frame.margin) - return box.x, box.y, vkExtent2D{Width: uint32(box.width), Height: uint32(box.height)} + box := windowframe.Content(width, height, frame.margin) + return box.X, box.Y, vkExtent2D{Width: uint32(box.Width), Height: uint32(box.Height)} } -// setFrameMargin gives the window a frame margin (0 takes it away) and draws +// SetFrameMargin gives the window a frame margin (0 takes it away) and draws // again with it. -func (renderer *vulkanRenderer) setFrameMargin(margin uint32) error { +func (renderer *Renderer) SetFrameMargin(margin uint32) error { if margin == renderer.frame.margin { return nil } @@ -65,7 +67,7 @@ func (renderer *vulkanRenderer) setFrameMargin(margin uint32) error { // create makes the pipeline and the buffer, which the render pass and the // device own; it is called with a swapchain's pipelines, and again when a // margin is given to a window that had none. -func (frame *vulkanFrame) create(renderer *vulkanRenderer) error { +func (frame *vulkanFrame) create(renderer *Renderer) error { if frame.cutPipeline == 0 { pipeline, err := renderer.scene.buildPipeline(renderer, true) if err != nil { @@ -85,7 +87,7 @@ func (frame *vulkanFrame) create(renderer *vulkanRenderer) error { renderer.api.getBufferMemoryRequirements(renderer.device, frame.buffer, &requirements) memoryType, ok := renderer.memoryType(requirements.MemoryTypeBits, vkMemoryHostVisible|vkMemoryHostCoherent) if !ok { - return fmt.Errorf("linux: Vulkan device has no coherent host-visible memory for the window frame") + return fmt.Errorf("vulkan: Vulkan device has no coherent host-visible memory for the window frame") } allocation := vkMemoryAllocateInfo{SType: vkStructureMemoryAllocateInfo, AllocationSize: requirements.Size, MemoryTypeIndex: memoryType} if err := vkCheck(renderer.api.allocateMemory(renderer.device, &allocation, nil, &frame.memory), "allocate frame memory"); err != nil { @@ -98,7 +100,7 @@ func (frame *vulkanFrame) create(renderer *vulkanRenderer) error { } // destroyPipeline releases what a render pass owns. -func (frame *vulkanFrame) destroyPipeline(renderer *vulkanRenderer) { +func (frame *vulkanFrame) destroyPipeline(renderer *Renderer) { if frame.cutPipeline != 0 { renderer.api.destroyPipeline(renderer.device, frame.cutPipeline, nil) frame.cutPipeline = 0 @@ -106,7 +108,7 @@ func (frame *vulkanFrame) destroyPipeline(renderer *vulkanRenderer) { } // close releases the buffer. -func (frame *vulkanFrame) close(renderer *vulkanRenderer) { +func (frame *vulkanFrame) close(renderer *Renderer) { frame.destroyPipeline(renderer) if frame.mapped != nil && frame.memory != 0 { renderer.api.unmapMemory(renderer.device, frame.memory) @@ -125,13 +127,13 @@ func (frame *vulkanFrame) close(renderer *vulkanRenderer) { // upload writes the two instances for a target of width x height device pixels: // slot 0 is the cut, slot 1 the shadow. Both cast from the content rectangle, // in logical pixels of the whole target. -func (frame *vulkanFrame) upload(renderer *vulkanRenderer, width, height uint32) { +func (frame *vulkanFrame) upload(renderer *Renderer, width, height uint32) { if frame.mapped == nil { return } scale := renderer.pixelScale() - box := frameContent(width, height, frame.margin) - bounds := [4]float32{float32(box.x) / scale, float32(box.y) / scale, float32(box.width) / scale, float32(box.height) / scale} + box := windowframe.Content(width, height, frame.margin) + bounds := [4]float32{float32(box.X) / scale, float32(box.Y) / scale, float32(box.Width) / scale, float32(box.Height) / scale} cut := vulkanRectangleInstance{ Bounds: bounds, Color: [4]float32{0, 0, 0, 1}, // The shadow grows by its spread around the corner's circle, and a spread @@ -139,11 +141,11 @@ func (frame *vulkanFrame) upload(renderer *vulkanRenderer, width, height uint32) // the far point of the square is the radius times the square root of two // from the circle's center, less than the radius plus the spread plus the // one pixel of blur that still counts as full strength. - Style: [4]float32{frameRadiusLogical, 0, 1, 0}, Shade1: [4]float32{0, 0, frameRadiusLogical}, + Style: [4]float32{windowframe.RadiusLogical, 0, 1, 0}, Shade1: [4]float32{0, 0, windowframe.RadiusLogical}, } shadow := vulkanRectangleInstance{ - Bounds: bounds, Color: [4]float32{0, 0, 0, frameShadowAlpha}, - Style: [4]float32{frameRadiusLogical, 0, frameShadowBlur, 0}, Shade1: [4]float32{0, frameShadowOffset, 0}, + Bounds: bounds, Color: [4]float32{0, 0, 0, windowframe.ShadowAlpha}, + Style: [4]float32{windowframe.RadiusLogical, 0, windowframe.ShadowBlur, 0}, Shade1: [4]float32{0, windowframe.ShadowOffset, 0}, } instances := (*[vkInstanceSlots]vulkanRectangleInstance)(frame.mapped) instances[0], instances[1] = cut, shadow @@ -151,7 +153,7 @@ func (frame *vulkanFrame) upload(renderer *vulkanRenderer, width, height uint32) // record draws the corner cuts and the shadow after the scene. The scene's // viewport is the content; these are positioned in the whole target. -func (frame *vulkanFrame) record(renderer *vulkanRenderer, command uintptr, extent vkExtent2D) { +func (frame *vulkanFrame) record(renderer *Renderer, command uintptr, extent vkExtent2D) { if frame.mapped == nil || frame.cutPipeline == 0 { return } @@ -164,26 +166,26 @@ func (frame *vulkanFrame) record(renderer *vulkanRenderer, command uintptr, exte scratch.offset = 0 renderer.api.cmdBindVertexBuffers(command, 0, 1, &frame.buffer, &scratch.offset) renderer.api.cmdBindPipeline(command, vkPipelineBindPointGraphics, frame.cutPipeline) - for _, corner := range frameCorners(extent.Width, extent.Height, frame.margin, frameRadiusLogical) { + for _, corner := range windowframe.Corners(extent.Width, extent.Height, frame.margin, windowframe.RadiusLogical) { frame.draw(renderer, command, corner, 0) } // The shadow goes behind the content, so it is drawn where nothing of the // content is left: the margin, and the corner squares the cut just emptied. renderer.api.cmdBindPipeline(command, vkPipelineBindPointGraphics, renderer.scene.pipeline) - for _, band := range frameBands(extent.Width, extent.Height, frame.margin) { + for _, band := range windowframe.Bands(extent.Width, extent.Height, frame.margin) { frame.draw(renderer, command, band, 1) } - for _, corner := range frameCorners(extent.Width, extent.Height, frame.margin, frameRadiusLogical) { + for _, corner := range windowframe.Corners(extent.Width, extent.Height, frame.margin, windowframe.RadiusLogical) { frame.draw(renderer, command, corner, 1) } } -func (frame *vulkanFrame) draw(renderer *vulkanRenderer, command uintptr, box pixelBox, instance uint32) { - if box.width <= 0 || box.height <= 0 { +func (frame *vulkanFrame) draw(renderer *Renderer, command uintptr, box windowframe.Box, instance uint32) { + if box.Width <= 0 || box.Height <= 0 { return } scratch := &renderer.scratch - scratch.scissor = vkRect2D{Offset: [2]int32{box.x, box.y}, Extent: vkExtent2D{Width: uint32(box.width), Height: uint32(box.height)}} + scratch.scissor = vkRect2D{Offset: [2]int32{box.X, box.Y}, Extent: vkExtent2D{Width: uint32(box.Width), Height: uint32(box.Height)}} renderer.api.cmdSetScissor(command, 0, 1, &scratch.scissor) renderer.api.cmdDraw(command, 6, 1, 0, instance) } diff --git a/internal/platform/linux/vulkan_frame_linux_test.go b/internal/platform/vulkan/vulkan_frame_linux_test.go similarity index 97% rename from internal/platform/linux/vulkan_frame_linux_test.go rename to internal/platform/vulkan/vulkan_frame_linux_test.go index 85e3302be..d1fe5d3ec 100644 --- a/internal/platform/linux/vulkan_frame_linux_test.go +++ b/internal/platform/vulkan/vulkan_frame_linux_test.go @@ -1,6 +1,6 @@ //go:build linux -package linux +package vulkan import ( "image" @@ -15,7 +15,7 @@ import ( func TestOffscreenWindowFrameDrawsShadowAndRoundCorners(t *testing.T) { const width, height, margin = 200, 160, 24 offscreen := newTestOffscreen(t, width, height) - if err := offscreen.renderer.setFrameMargin(margin); err != nil { + if err := offscreen.renderer.SetFrameMargin(margin); err != nil { t.Fatal(err) } // The scene is in the content's own coordinates: a red fill of all of it. diff --git a/internal/platform/linux/vulkan_hotpath_linux.go b/internal/platform/vulkan/vulkan_hotpath_linux.go similarity index 98% rename from internal/platform/linux/vulkan_hotpath_linux.go rename to internal/platform/vulkan/vulkan_hotpath_linux.go index 7308359e6..9cc12f36c 100644 --- a/internal/platform/linux/vulkan_hotpath_linux.go +++ b/internal/platform/vulkan/vulkan_hotpath_linux.go @@ -1,6 +1,6 @@ //go:build linux -package linux +package vulkan import ( "fmt" @@ -31,7 +31,7 @@ type vkCall struct { func newVkCall(library uintptr, name string) *vkCall { address, err := purego.Dlsym(library, name) if err != nil { - panic(fmt.Sprintf("linux: Vulkan function %s: %v", name, err)) + panic(fmt.Sprintf("vulkan: Vulkan function %s: %v", name, err)) } return &vkCall{address: address} } diff --git a/internal/platform/linux/vulkan_imagepool_linux.go b/internal/platform/vulkan/vulkan_imagepool_linux.go similarity index 91% rename from internal/platform/linux/vulkan_imagepool_linux.go rename to internal/platform/vulkan/vulkan_imagepool_linux.go index 9dd065f42..703918282 100644 --- a/internal/platform/linux/vulkan_imagepool_linux.go +++ b/internal/platform/vulkan/vulkan_imagepool_linux.go @@ -1,6 +1,6 @@ //go:build linux -package linux +package vulkan import "slices" @@ -32,7 +32,7 @@ const imageBlockSize = 16 << 20 // allocate finds memory of memoryType for an image of requirements, and returns // the memory and offset to bind it at. -func (pool *imagePool) allocate(renderer *vulkanRenderer, memoryType uint32, requirements vkMemoryRequirements) (uintptr, imageSlice, error) { +func (pool *imagePool) allocate(renderer *Renderer, memoryType uint32, requirements vkMemoryRequirements) (uintptr, imageSlice, error) { alignment := max(requirements.Alignment, 1) if requirements.Size > imageBlockSize/4 { memory, err := allocateDeviceMemory(renderer, memoryType, requirements.Size, "allocate text image memory") @@ -85,7 +85,7 @@ func (block *imageBlock) carve(size, alignment uint64) (uint64, bool) { // release gives a label's memory back: to its block, or to the driver when it // had memory of its own. A block that is left empty is freed unless it is the // pool's last one, which a page that changes keeps using. -func (pool *imagePool) release(renderer *vulkanRenderer, memory uintptr, slice imageSlice) { +func (pool *imagePool) release(renderer *Renderer, memory uintptr, slice imageSlice) { block := slice.block if block == nil { if memory != 0 { @@ -123,7 +123,7 @@ func (block *imageBlock) give(offset, size uint64) { } // close frees every block; the images in them are destroyed already. -func (pool *imagePool) close(renderer *vulkanRenderer) { +func (pool *imagePool) close(renderer *Renderer) { if renderer != nil && renderer.api != nil && renderer.device != 0 { for _, block := range pool.blocks { renderer.api.freeMemory(renderer.device, block.memory, nil) @@ -132,7 +132,7 @@ func (pool *imagePool) close(renderer *vulkanRenderer) { pool.blocks = nil } -func allocateDeviceMemory(renderer *vulkanRenderer, memoryType uint32, size uint64, action string) (uintptr, error) { +func allocateDeviceMemory(renderer *Renderer, memoryType uint32, size uint64, action string) (uintptr, error) { var memory uintptr allocation := vkMemoryAllocateInfo{SType: vkStructureMemoryAllocateInfo, AllocationSize: size, MemoryTypeIndex: memoryType} err := vkCheck(renderer.api.allocateMemory(renderer.device, &allocation, nil, &memory), action) diff --git a/internal/platform/linux/vulkan_linux.go b/internal/platform/vulkan/vulkan_linux.go similarity index 85% rename from internal/platform/linux/vulkan_linux.go rename to internal/platform/vulkan/vulkan_linux.go index d2a5512cb..ea85721f2 100644 --- a/internal/platform/linux/vulkan_linux.go +++ b/internal/platform/vulkan/vulkan_linux.go @@ -1,11 +1,9 @@ -package linux +package vulkan import ( "errors" "fmt" "math" - "os" - "path/filepath" "slices" "sync" "unsafe" @@ -13,7 +11,6 @@ import ( "github.com/ebitengine/purego" "github.com/vivaui/viva/internal/platform" "github.com/vivaui/viva/internal/render" - "github.com/vivaui/viva/internal/scene" ) const ( @@ -31,7 +28,6 @@ const ( vkStructureCommandAllocateInfo = 40 vkStructureCommandBeginInfo = 42 vkStructureRenderPassBeginInfo = 43 - vkStructureXcbSurfaceCreateInfo = 1000005000 vkStructureSwapchainCreateInfo = 1000001000 vkStructurePresentInfo = 1000001001 vkQueueGraphics = 1 @@ -94,16 +90,6 @@ type vkInstanceCreateInfo struct { Padding3 uint32 Extensions uintptr } -type vkXcbSurfaceCreateInfo struct { - SType uint32 - Padding0 uint32 - Next uintptr - Flags uint32 - Padding1 uint32 - Connection uintptr - Window uint32 - Padding2 uint32 -} type vkQueueFamilyProperties struct { Flags, Count, TimestampBits uint32 Granularity [3]uint32 @@ -318,7 +304,6 @@ type vulkanAPI struct { getQueueFamilyProperties func(uintptr, *uint32, *vkQueueFamilyProperties) getPhysicalDeviceFeatures func(uintptr, *[vkFeatureCount]uint32) getPhysicalDeviceProperties func(uintptr, *[vkPropertiesSize]byte) - createXcbSurface func(uintptr, *vkXcbSurfaceCreateInfo, unsafe.Pointer, *uintptr) int32 destroySurface func(uintptr, uintptr, unsafe.Pointer) getSurfaceSupport func(uintptr, uint32, uintptr, *uint32) int32 getSurfaceCapabilities func(uintptr, uintptr, *vkSurfaceCapabilities) int32 @@ -394,7 +379,7 @@ type vulkanAPI struct { cmdCopyImageToBuffer func(uintptr, uintptr, uint32, uintptr, uint32, *vkBufferImageCopy) } -type vulkanRenderer struct { +type Renderer struct { api *vulkanAPI instance, surface, physical, device, queue uintptr swapchain, renderPass, commandPool uintptr @@ -444,7 +429,9 @@ type vulkanRenderer struct { compositingBatches []compositingBatch offscreen vulkanOffscreen submissions, rebuilds, partials uint64 - scratch vulkanScratch + // textures counts the label textures made. + textures uint64 + scratch vulkanScratch // swapchainSuboptimal is set when the driver reports VK_SUBOPTIMAL_KHR on // acquire or present. swapchainSuboptimal bool @@ -453,12 +440,13 @@ type vulkanRenderer struct { // present it instead of recreating it again until a frame reports a // healthy status or the swapchain is recreated for another reason. swapchainSuboptimalRebuilt bool - // connection and window are what the surface is made from, kept to make it - // again after a loss; connection is zero for an offscreen renderer, which has - // no surface and is not rebuilt. recoveries counts the rebuilds. - connection uintptr - window uint32 - recoveries uint64 + // source makes the surface, kept to make it again after a loss; its Create is + // nil for an offscreen renderer, which has no surface and is not rebuilt. + // recoveries counts the rebuilds. newRasterizer makes the rasterizer that draws + // the glyphs of the label textures. + source SurfaceSource + newRasterizer NewTextRasterizer + recoveries uint64 // frame is the window frame the renderer draws, if any (vulkan_frame_linux.go). frame vulkanFrame } @@ -491,86 +479,6 @@ type vulkanScratch struct { contentX, contentY int32 } -// Loader 1.1.97 segfaults in vkCreateInstance when no ICD manifest exists. -func vulkanDriverConfigured() bool { - var paths []string - if files, ok := os.LookupEnv("VK_DRIVER_FILES"); ok { - paths = filepath.SplitList(files) - } else if files, ok := os.LookupEnv("VK_ICD_FILENAMES"); ok { - paths = filepath.SplitList(files) - } else { - paths = vulkanDefaultManifestDirs() - } - if files := os.Getenv("VK_ADD_DRIVER_FILES"); files != "" { - paths = append(paths, filepath.SplitList(files)...) - } - return vulkanDriverManifestsExist(paths) -} - -// vulkanDefaultManifestDirs lists the directories the loader searches for ICD manifests -// when no override is set, in its order: the user's config and data homes, then the -// system lists under each XDG base. -func vulkanDefaultManifestDirs() []string { - home := os.Getenv("HOME") - configHome := os.Getenv("XDG_CONFIG_HOME") - if configHome == "" && home != "" { - configHome = filepath.Join(home, ".config") - } - dataHome := os.Getenv("XDG_DATA_HOME") - if dataHome == "" && home != "" { - dataHome = filepath.Join(home, ".local", "share") - } - var paths []string - if configHome != "" { - paths = append(paths, filepath.Join(configHome, "vulkan", "icd.d")) - } - paths = appendVulkanDirs(paths, os.Getenv("XDG_CONFIG_DIRS"), "/etc/xdg") - if dataHome != "" { - paths = append(paths, filepath.Join(dataHome, "vulkan", "icd.d")) - } - paths = appendVulkanDirs(paths, os.Getenv("XDG_DATA_DIRS"), "/usr/local/share:/usr/share") - return append(paths, "/etc/vulkan/icd.d") -} - -// appendVulkanDirs adds the vulkan/icd.d directory under each entry of an XDG search list, -// or under the fallback list when the variable is unset. -func appendVulkanDirs(paths []string, list, fallback string) []string { - if list == "" { - list = fallback - } - for _, dir := range filepath.SplitList(list) { - if dir != "" { - paths = append(paths, filepath.Join(dir, "vulkan", "icd.d")) - } - } - return paths -} - -func vulkanDriverManifestsExist(paths []string) bool { - for _, path := range paths { - if path == "" { - continue - } - info, err := os.Stat(path) - if err != nil { - continue - } - if !info.IsDir() { - return true - } - entries, err := os.ReadDir(path) - if err != nil { - continue - } - for _, entry := range entries { - if !entry.IsDir() && filepath.Ext(entry.Name()) == ".json" { - return true - } - } - } - return false -} - // loadVulkan gives a copy of the process's libvulkan function table, loaded and // bound once and kept for the life of the process; a machine without a driver is // found once. Each renderer owns its copy, as each window owns its xcb table. @@ -593,9 +501,9 @@ func openVulkan() (*vulkanAPI, error) { if !vulkanDriverConfigured() { return nil, noVulkan("Vulkan has no driver (no ICD manifest)", nil) } - library, err := purego.Dlopen("libvulkan.so.1", purego.RTLD_NOW|purego.RTLD_LOCAL) + library, err := purego.Dlopen(vulkanLibraryName, purego.RTLD_NOW|purego.RTLD_LOCAL) if err != nil { - return nil, noVulkan("libvulkan.so.1 is not installed", err) + return nil, noVulkan(vulkanLibraryName+" is not installed", err) } api := &vulkanAPI{library: library} purego.RegisterLibFunc(&api.createInstance, library, "vkCreateInstance") @@ -604,7 +512,6 @@ func openVulkan() (*vulkanAPI, error) { purego.RegisterLibFunc(&api.getQueueFamilyProperties, library, "vkGetPhysicalDeviceQueueFamilyProperties") purego.RegisterLibFunc(&api.getPhysicalDeviceFeatures, library, "vkGetPhysicalDeviceFeatures") purego.RegisterLibFunc(&api.getPhysicalDeviceProperties, library, "vkGetPhysicalDeviceProperties") - purego.RegisterLibFunc(&api.createXcbSurface, library, "vkCreateXcbSurfaceKHR") purego.RegisterLibFunc(&api.destroySurface, library, "vkDestroySurfaceKHR") purego.RegisterLibFunc(&api.getSurfaceSupport, library, "vkGetPhysicalDeviceSurfaceSupportKHR") purego.RegisterLibFunc(&api.getSurfaceCapabilities, library, "vkGetPhysicalDeviceSurfaceCapabilitiesKHR") @@ -638,37 +545,71 @@ func openVulkan() (*vulkanAPI, error) { return api, nil } -func newVulkanRenderer(connection uintptr, window, width, height uint32, scale float32, color platform.Color, rectangles []render.Rectangle, labels []platform.TextLabel, margin uint32) (*vulkanRenderer, error) { +// SurfaceSource says how a window system gives the renderer something to present +// to: the instance extension that makes a VkSurfaceKHR, and the call that makes it. +type SurfaceSource struct { + // Extension is the name of the instance extension the surface needs: + // VK_KHR_xcb_surface, VK_KHR_android_surface. + Extension string + // Create makes the surface on instance. The renderer calls it again after the + // device or the surface was lost. + Create func(instance uintptr) (surface uintptr, err error) +} + +// Config is what a window's renderer is made from. +type Config struct { + Surface SurfaceSource + // Width and Height are the surface's size in device pixels; Scale is the + // display scale. + Width, Height uint32 + Scale float32 + // Clear is what the scene is cleared to before it draws. + Clear platform.Color + Rectangles []render.Rectangle + Labels []platform.TextLabel + // FrameMargin is the margin of a window frame the renderer draws, 0 for none. + FrameMargin uint32 + // Rasterizer makes what draws the glyphs of the label textures. + Rasterizer NewTextRasterizer +} + +// New makes the renderer of a window. It fails with platform.ErrNoGraphics when the +// machine has no usable Vulkan. +func New(config Config) (*Renderer, error) { + if config.Surface.Create == nil || config.Surface.Extension == "" || config.Rasterizer == nil { + return nil, errors.New("vulkan: a window renderer needs a surface source and a text rasterizer") + } api, err := loadVulkan() if err != nil { return nil, err } - renderer := &vulkanRenderer{api: api, width: width, height: height, scale: scale, color: color, connection: connection, window: window} - renderer.frame.margin = margin - renderer.rectangles = append(renderer.rectangles, rectangles...) + renderer := &Renderer{api: api, width: config.Width, height: config.Height, scale: config.Scale, color: config.Clear, source: config.Surface, newRasterizer: config.Rasterizer} + renderer.frame.margin = config.FrameMargin + renderer.rectangles = append(renderer.rectangles, config.Rectangles...) renderer.rectangleBatches = render.GroupBatches(renderer.rectangleBatches, renderer.rectangles) - if err := renderer.text.update(nil, labels); err != nil { - renderer.close() + if err := renderer.text.update(nil, config.Labels); err != nil { + renderer.Close() return nil, err } renderer.compositingBatches = groupCompositingLayers(renderer.rectangleBatches, renderer.text.labels, renderer.text.order, renderer.compositingBatches) - if err := renderer.initialize(connection, window); err != nil { - renderer.close() + if err := renderer.initialize(); err != nil { + renderer.Close() return nil, err } return renderer, nil } -func (renderer *vulkanRenderer) initialize(connection uintptr, window uint32) error { - shared, err := acquireWindowDevice(renderer.api) +func (renderer *Renderer) initialize() error { + shared, err := acquireWindowDevice(renderer.api, renderer.source.Extension) if err != nil { return err } renderer.shared, renderer.instance = shared, shared.instance - surfaceInfo := vkXcbSurfaceCreateInfo{SType: vkStructureXcbSurfaceCreateInfo, Connection: connection, Window: window} - if err := vkCheck(renderer.api.createXcbSurface(renderer.instance, &surfaceInfo, nil, &renderer.surface), "create XCB surface"); err != nil { + surface, err := renderer.source.Create(renderer.instance) + if err != nil { return err } + renderer.surface = surface if err := shared.attach(renderer.surface); err != nil { return err } @@ -695,7 +636,18 @@ func (renderer *vulkanRenderer) initialize(connection uintptr, window uint32) er return vkCheck(renderer.api.createFence(renderer.device, &fenceInfo, nil, &renderer.fence), "create frame fence") } -func (renderer *vulkanRenderer) createSwapchain() (err error) { +// Bind registers the Vulkan function name from the process's loader in the +// pointer to func fn, for a window system's surface call; it fails with +// platform.ErrNoGraphics when the machine has no usable Vulkan. +func Bind(fn any, name string) error { + if _, err := loadVulkan(); err != nil { + return err + } + purego.RegisterLibFunc(fn, vulkanShared.library, name) + return nil +} + +func (renderer *Renderer) createSwapchain() (err error) { oldSwapchain := renderer.swapchain renderer.swapchain = 0 defer func() { @@ -720,7 +672,7 @@ func (renderer *vulkanRenderer) createSwapchain() (err error) { return err } if formatCount == 0 || formatCount > 64 { - return fmt.Errorf("linux: Vulkan surface format count %d", formatCount) + return fmt.Errorf("vulkan: Vulkan surface format count %d", formatCount) } formats := make([]vkSurfaceFormat, formatCount) if err := vkCheck(renderer.api.getSurfaceFormats(renderer.physical, renderer.surface, &formatCount, &formats[0]), "query surface formats"); err != nil { @@ -759,10 +711,10 @@ func (renderer *vulkanRenderer) createSwapchain() (err error) { composite = capabilities.CompositeAlpha & -capabilities.CompositeAlpha } if composite == 0 { - return fmt.Errorf("linux: Vulkan surface supports no composite alpha mode") + return fmt.Errorf("vulkan: Vulkan surface supports no composite alpha mode") } if capabilities.Usage&vkImageUsageColorAttachment == 0 { - return fmt.Errorf("linux: Vulkan surface does not support color attachments") + return fmt.Errorf("vulkan: Vulkan surface does not support color attachments") } presentMode := renderer.selectPresentMode() info := vkSwapchainCreateInfo{SType: vkStructureSwapchainCreateInfo, Surface: renderer.surface, MinImages: imageCount, Format: selected.Format, ColorSpace: selected.ColorSpace, Extent: extent, Layers: 1, Usage: vkImageUsageColorAttachment, SharingMode: vkSharingExclusive, PreTransform: capabilities.CurrentTransform, CompositeAlpha: composite, PresentMode: presentMode, Clipped: 1, OldSwapchain: oldSwapchain} @@ -778,7 +730,7 @@ func (renderer *vulkanRenderer) createSwapchain() (err error) { return err } if imageTotal == 0 || imageTotal > 16 { - return fmt.Errorf("linux: Vulkan swapchain image count %d", imageTotal) + return fmt.Errorf("vulkan: Vulkan swapchain image count %d", imageTotal) } images := make([]uintptr, imageTotal) if err := vkCheck(renderer.api.getSwapchainImages(renderer.device, renderer.swapchain, &imageTotal, &images[0]), "query swapchain images"); err != nil { @@ -825,7 +777,7 @@ func (renderer *vulkanRenderer) createSwapchain() (err error) { // createRenderPass creates the single-subpass render pass that clears one color // attachment of the given format and leaves it in finalLayout. -func (renderer *vulkanRenderer) createRenderPass(format, finalLayout uint32) error { +func (renderer *Renderer) createRenderPass(format, finalLayout uint32) error { attachment := vkAttachmentDescription{Format: format, Samples: vkSampleCountOne, Load: vkAttachmentLoadClear, Store: vkAttachmentStore, StencilLoad: vkAttachmentLoadDontCare, StencilStore: vkAttachmentStoreDontCare, InitialLayout: vkImageLayoutUndefined, FinalLayout: finalLayout} reference := vkAttachmentReference{Layout: vkImageLayoutColorAttachment} subpass := vkSubpassDescription{BindPoint: vkPipelineBindPointGraphics, ColorCount: 1, Colors: uintptr(unsafe.Pointer(&reference))} @@ -835,7 +787,7 @@ func (renderer *vulkanRenderer) createRenderPass(format, finalLayout uint32) err // createCommands creates the command pool and one command buffer per target // image, plus the one the text uploads use. -func (renderer *vulkanRenderer) createCommands(images uint32) error { +func (renderer *Renderer) createCommands(images uint32) error { if renderer.commandPool != 0 { if renderer.api.resetCommandPool != nil && uint32(len(renderer.commands)) == images && renderer.uploadCommand != 0 { return vkCheck(renderer.api.resetCommandPool(renderer.device, renderer.commandPool, 0), "reset command pool") @@ -865,7 +817,7 @@ func (renderer *vulkanRenderer) createCommands(images uint32) error { // pass, uploads the label textures and records the commands of every target // image: everything a window and an offscreen target share after their images // exist. -func (renderer *vulkanRenderer) createScenePipelines(extent vkExtent2D) error { +func (renderer *Renderer) createScenePipelines(extent vkExtent2D) error { if err := renderer.scene.createPipeline(renderer); err != nil { return err } @@ -886,7 +838,7 @@ func (renderer *vulkanRenderer) createScenePipelines(extent vkExtent2D) error { // recordCommands makes every target image's commands stale and records them at // extent now: what a new swapchain, a new frame or a rebuilt device needs before // its first submit. A changed scene only invalidateCommands. -func (renderer *vulkanRenderer) recordCommands(extent vkExtent2D) error { +func (renderer *Renderer) recordCommands(extent vkExtent2D) error { renderer.recordExtent = extent renderer.invalidateCommands() for index := range renderer.commands { @@ -898,10 +850,10 @@ func (renderer *vulkanRenderer) recordCommands(extent vkExtent2D) error { } // invalidateCommands marks every image's commands stale. -func (renderer *vulkanRenderer) invalidateCommands() { renderer.commandGeneration++ } +func (renderer *Renderer) invalidateCommands() { renderer.commandGeneration++ } // ensureRecorded records the commands of target image index when they are stale. -func (renderer *vulkanRenderer) ensureRecorded(index uint32) error { +func (renderer *Renderer) ensureRecorded(index uint32) error { if len(renderer.recorded) != len(renderer.commands) { renderer.recorded = make([]uint64, len(renderer.commands)) renderer.commandGeneration++ // a fresh slice holds zeros: none is current @@ -917,7 +869,7 @@ func (renderer *vulkanRenderer) ensureRecorded(index uint32) error { } // recordImage records the commands that draw the scene into target image index. -func (renderer *vulkanRenderer) recordImage(index uint32, extent vkExtent2D) error { +func (renderer *Renderer) recordImage(index uint32, extent vkExtent2D) error { scratch := &renderer.scratch scratch.clear = vkClearValue{Color: [4]float32{float32(renderer.color.Red), float32(renderer.color.Green), float32(renderer.color.Blue), float32(renderer.color.Alpha)}} // A window frame leaves the margin transparent and draws the scene inside it. @@ -965,38 +917,6 @@ func (renderer *vulkanRenderer) recordImage(index uint32, extent vkExtent2D) err return nil } -func validateRectangles(rectangles []render.Rectangle) error { - for index, rectangle := range rectangles { - bounds := rectangle.Bounds - if !finite32(bounds.X) || !finite32(bounds.Y) || !finite32(bounds.Width) || !finite32(bounds.Height) { - return fmt.Errorf("linux: rectangle %d has non-finite bounds", index) - } - if !finite32(rectangle.Radius) || rectangle.Radius < 0 { - return fmt.Errorf("linux: rectangle %d has invalid radius %g", index, rectangle.Radius) - } - if !finite32(rectangle.Color.Red) || !finite32(rectangle.Color.Green) || !finite32(rectangle.Color.Blue) || !finite32(rectangle.Color.Alpha) { - return fmt.Errorf("linux: rectangle %d has a non-finite color", index) - } - if rectangle.Kind == scene.KindShadow { - shadow := rectangle.Shadow - if !finite32(shadow.OffsetX) || !finite32(shadow.OffsetY) || !finite32(shadow.Blur) || !finite32(shadow.Spread) || shadow.Blur < 0 { - return fmt.Errorf("linux: shadow %d has an invalid blur or offset", index) - } - } - if rectangle.Kind == scene.KindTriangle { - for pointIndex, point := range rectangle.Points { - if !finite32(point.X) || !finite32(point.Y) { - return fmt.Errorf("linux: triangle %d point %d is non-finite", index, pointIndex) - } - } - if rectangle.EdgeMask > 7 { - return fmt.Errorf("linux: triangle %d has invalid edge mask %d", index, rectangle.EdgeMask) - } - } - } - return nil -} - func rectangleClear(rectangle render.Rectangle, width, height uint32) (vkClearAttachment, vkClearRect, bool) { bounds := rectangle.Bounds left := max(float64(bounds.X), 0) @@ -1042,10 +962,10 @@ func swapchainNeedsRebuild(status int32) bool { return status == vkErrorOutOfDate } -// present draws the scene to the next swapchain image. A lost device or +// Present draws the scene to the next swapchain image. A lost device or // surface is rebuilt and the frame drawn again; only a device that keeps // failing ends the window. -func (renderer *vulkanRenderer) present() error { +func (renderer *Renderer) Present() error { for losses := 0; ; losses++ { err := renderer.presentRebuilding() retry, err := renderer.recoverFrom(err, losses) @@ -1058,8 +978,8 @@ func (renderer *vulkanRenderer) present() error { // recoverFrom rebuilds the renderer when err says the device or the surface // was lost, and reports whether the operation that failed is to be run again. // A rebuild that fails gives that failure with err. -func (renderer *vulkanRenderer) recoverFrom(err error, losses int) (retry bool, failure error) { - if err == nil || !isGraphicsLoss(err) || renderer.connection == 0 || losses >= maxLossRecoveries { +func (renderer *Renderer) recoverFrom(err error, losses int) (retry bool, failure error) { + if err == nil || !isGraphicsLoss(err) || renderer.source.Create == nil || losses >= maxLossRecoveries { return false, err } if isDeviceLoss(err) && renderer.shared != nil { @@ -1073,7 +993,7 @@ func (renderer *vulkanRenderer) recoverFrom(err error, losses int) (retry bool, return true, nil } -func (renderer *vulkanRenderer) presentRebuilding() error { +func (renderer *Renderer) presentRebuilding() error { for attempt := 0; attempt < 2; attempt++ { rebuild, err := renderer.presentOnce() if err != nil { @@ -1103,10 +1023,10 @@ func (renderer *vulkanRenderer) presentRebuilding() error { return err } } - return fmt.Errorf("linux: Vulkan swapchain remained out of date after recreation") + return fmt.Errorf("vulkan: Vulkan swapchain remained out of date after recreation") } -func (renderer *vulkanRenderer) presentOnce() (bool, error) { +func (renderer *Renderer) presentOnce() (bool, error) { if err := vkCheck(renderer.api.waitForFences(renderer.device, 1, &renderer.fence, 1, math.MaxUint64), "wait for frame fence"); err != nil { return false, err } @@ -1124,7 +1044,7 @@ func (renderer *vulkanRenderer) presentOnce() (bool, error) { } image := scratch.image if image >= uint32(len(renderer.commands)) { - return false, fmt.Errorf("linux: Vulkan acquired invalid image %d", image) + return false, fmt.Errorf("vulkan: Vulkan acquired invalid image %d", image) } if err := renderer.ensureRecorded(image); err != nil { return false, err @@ -1159,9 +1079,9 @@ func (renderer *vulkanRenderer) presentOnce() (bool, error) { return swapchainNeedsRebuild(status), nil } -// apply takes a frame into the renderer's scene. A frame is idempotent, so one +// Apply takes a frame into the renderer's scene. A frame is idempotent, so one // that met a lost device is applied again to the rebuilt renderer. -func (renderer *vulkanRenderer) apply(frame platform.Frame) (bool, error) { +func (renderer *Renderer) Apply(frame platform.Frame) (bool, error) { for losses := 0; ; losses++ { changed, err := renderer.applyFrame(frame) retry, err := renderer.recoverFrom(err, losses) @@ -1171,10 +1091,10 @@ func (renderer *vulkanRenderer) apply(frame platform.Frame) (bool, error) { } } -// stage uploads a frame's rectangles and text textures into the renderer without +// Stage uploads a frame's rectangles and text textures into the renderer without // recording command buffers yet, so a resize can update the scene first and then // recreate the swapchain and record commands once right before presenting. -func (renderer *vulkanRenderer) stage(frame platform.Frame) (bool, error) { +func (renderer *Renderer) Stage(frame platform.Frame) (bool, error) { for losses := 0; ; losses++ { changed, err := renderer.stageFrame(frame) retry, err := renderer.recoverFrom(err, losses) @@ -1186,24 +1106,24 @@ func (renderer *vulkanRenderer) stage(frame platform.Frame) (bool, error) { // applyFrame stages frame; the commands it makes stale are recorded when their // image is next submitted. -func (renderer *vulkanRenderer) applyFrame(frame platform.Frame) (bool, error) { +func (renderer *Renderer) applyFrame(frame platform.Frame) (bool, error) { return renderer.stageFrame(frame) } -func (renderer *vulkanRenderer) stageFrame(frame platform.Frame) (bool, error) { +func (renderer *Renderer) stageFrame(frame platform.Frame) (bool, error) { if frame.Update.Empty() && frame.TextLabels == nil { return false, nil } if !frame.Update.Empty() { - if err := validateRectangles(frame.Rectangles); err != nil { + if err := render.ValidateRectangles(frame.Rectangles); err != nil { return false, err } if frame.Update.First < 0 || frame.Update.Count < 0 || frame.Update.First > len(frame.Rectangles) || frame.Update.Count > len(frame.Rectangles)-frame.Update.First { - return false, fmt.Errorf("linux: invalid rectangle update") + return false, fmt.Errorf("vulkan: invalid rectangle update") } } if frame.TextLabels != nil { - if err := validateInitialTextLabels(frame.TextLabels); err != nil { + if err := platform.ValidateTextLabels(frame.TextLabels); err != nil { return false, err } } @@ -1230,13 +1150,13 @@ func (renderer *vulkanRenderer) stageFrame(frame platform.Frame) (bool, error) { } else { if len(frame.Rectangles) < len(renderer.rectangles) { if !frame.Update.Shrink || frame.Update.First > len(frame.Rectangles) || frame.Update.First+frame.Update.Count != len(frame.Rectangles) { - return false, fmt.Errorf("linux: rectangle count shrank outside a suffix update") + return false, fmt.Errorf("vulkan: rectangle count shrank outside a suffix update") } renderer.rectangles = renderer.rectangles[:len(frame.Rectangles)] } if len(frame.Rectangles) > len(renderer.rectangles) { if frame.Update.First > len(renderer.rectangles) || frame.Update.First+frame.Update.Count != len(frame.Rectangles) { - return false, fmt.Errorf("linux: rectangle count grew outside a suffix update") + return false, fmt.Errorf("vulkan: rectangle count grew outside a suffix update") } renderer.rectangles = append(renderer.rectangles, frame.Rectangles[len(renderer.rectangles):]...) } @@ -1268,7 +1188,7 @@ func (renderer *vulkanRenderer) stageFrame(frame platform.Frame) (bool, error) { return true, nil } -func (renderer *vulkanRenderer) surfaceSize(width, height uint32) (uint32, uint32) { +func (renderer *Renderer) SurfaceSize(width, height uint32) (uint32, uint32) { if renderer == nil { return width, height } @@ -1290,17 +1210,17 @@ func (renderer *vulkanRenderer) surfaceSize(width, height uint32) (uint32, uint3 } // pixelScale is the device pixels per logical pixel, at least 1. -func (renderer *vulkanRenderer) pixelScale() float32 { +func (renderer *Renderer) pixelScale() float32 { if renderer.scale < 1 { return 1 } return renderer.scale } -// setScale changes the scale of a window that already has a swapchain: the +// SetScale changes the scale of a window that already has a swapchain: the // labels are rasterized again at the new one and every command is recorded // again. The caller sets the new device size with resize. -func (renderer *vulkanRenderer) setScale(scale float32) error { +func (renderer *Renderer) SetScale(scale float32) error { for losses := 0; ; losses++ { retry, err := renderer.recoverFrom(renderer.setScaleOnce(scale), losses) if !retry { @@ -1309,7 +1229,7 @@ func (renderer *vulkanRenderer) setScale(scale float32) error { } } -func (renderer *vulkanRenderer) setScaleOnce(scale float32) error { +func (renderer *Renderer) setScaleOnce(scale float32) error { if scale < 1 || scale == renderer.pixelScale() { return nil } @@ -1326,7 +1246,7 @@ func (renderer *vulkanRenderer) setScaleOnce(scale float32) error { return renderer.recordCommands(vkExtent2D{Width: renderer.width, Height: renderer.height}) } -func (renderer *vulkanRenderer) resize(width, height uint32) error { +func (renderer *Renderer) Resize(width, height uint32) error { for losses := 0; ; losses++ { retry, err := renderer.recoverFrom(renderer.resizeOnce(width, height), losses) if !retry { @@ -1335,7 +1255,7 @@ func (renderer *vulkanRenderer) resize(width, height uint32) error { } } -func (renderer *vulkanRenderer) resizeOnce(width, height uint32) error { +func (renderer *Renderer) resizeOnce(width, height uint32) error { if width == 0 || height == 0 { return nil } @@ -1356,7 +1276,7 @@ func (renderer *vulkanRenderer) resizeOnce(width, height uint32) error { return nil } -func (renderer *vulkanRenderer) recreateSwapchain() error { +func (renderer *Renderer) recreateSwapchain() error { if err := vkCheck(renderer.api.deviceWaitIdle(renderer.device), "wait before swapchain recreation"); err != nil { return err } @@ -1364,7 +1284,7 @@ func (renderer *vulkanRenderer) recreateSwapchain() error { return renderer.createSwapchain() } -func (renderer *vulkanRenderer) destroySwapchainTargets() { +func (renderer *Renderer) destroySwapchainTargets() { if renderer.device == 0 { return } @@ -1382,7 +1302,7 @@ func (renderer *vulkanRenderer) destroySwapchainTargets() { renderer.views = nil } -func (renderer *vulkanRenderer) destroySwapchain() { +func (renderer *Renderer) destroySwapchain() { if renderer.device == 0 { return } @@ -1412,7 +1332,7 @@ func (renderer *vulkanRenderer) destroySwapchain() { // fallback. An ordinary resize retains one old chain until its replacement. const maxRetiredSwapchains = 4 -func (renderer *vulkanRenderer) retireSwapchain(swapchain uintptr) { +func (renderer *Renderer) retireSwapchain(swapchain uintptr) { if len(renderer.retiredSwapchains) == maxRetiredSwapchains { renderer.api.destroySwapchain(renderer.device, renderer.retiredSwapchains[0], nil) copy(renderer.retiredSwapchains, renderer.retiredSwapchains[1:]) @@ -1421,14 +1341,14 @@ func (renderer *vulkanRenderer) retireSwapchain(swapchain uintptr) { renderer.retiredSwapchains = append(renderer.retiredSwapchains, swapchain) } -func (renderer *vulkanRenderer) destroyRetiredSwapchains() { +func (renderer *Renderer) destroyRetiredSwapchains() { for _, swapchain := range renderer.retiredSwapchains { renderer.api.destroySwapchain(renderer.device, swapchain, nil) } renderer.retiredSwapchains = renderer.retiredSwapchains[:0] } -func (renderer *vulkanRenderer) close() { +func (renderer *Renderer) Close() { if renderer.api == nil { return } @@ -1454,7 +1374,7 @@ func (renderer *vulkanRenderer) close() { } // adopt makes the renderer draw with device's instance, queue and features. -func (renderer *vulkanRenderer) adopt(device *vulkanDevice) { +func (renderer *Renderer) adopt(device *vulkanDevice) { renderer.instance, renderer.physical, renderer.device, renderer.queue = device.instance, device.physical, device.handle, device.queue renderer.queueFamily, renderer.software, renderer.dualSource = device.queueFamily, device.software, device.dualSource renderer.enabledFeatures = device.features @@ -1463,7 +1383,7 @@ func (renderer *vulkanRenderer) adopt(device *vulkanDevice) { // dropDevice is the last step of a teardown, once every object the renderer // made on the device is destroyed: the window's surface goes, and the device is // released, or destroyed when the renderer owns it. -func (renderer *vulkanRenderer) dropDevice() { +func (renderer *Renderer) dropDevice() { if renderer.surface != 0 && renderer.instance != 0 { renderer.api.destroySurface(renderer.instance, renderer.surface, nil) } @@ -1482,11 +1402,15 @@ func (renderer *vulkanRenderer) dropDevice() { func noVulkan(reason string, cause error) error { const advice = "install the Vulkan loader (libvulkan1) and a driver; a machine without a GPU can use Mesa's software driver (mesa-vulkan-drivers, lavapipe), and a server with no display needs a virtual one such as Xvfb or the headless build" if cause != nil { - return fmt.Errorf("linux: %s: %w (%w); %s", reason, platform.ErrNoGraphics, cause, advice) + return fmt.Errorf("vulkan: %s: %w (%w); %s", reason, platform.ErrNoGraphics, cause, advice) } - return fmt.Errorf("linux: %s: %w; %s", reason, platform.ErrNoGraphics, advice) + return fmt.Errorf("vulkan: %s: %w; %s", reason, platform.ErrNoGraphics, advice) } +// Check makes the error of a Vulkan call that did not succeed, for a window +// system's surface call. +func Check(status int32, action string) error { return vkCheck(status, action) } + func vkCheck(status int32, action string) error { if status != vkSuccess { return &vulkanResultError{action: action, status: status} @@ -1509,12 +1433,12 @@ func clamp(value, minimum, maximum uint32) uint32 { // swapchain are created anew, then the scene and the label textures are // uploaded again from what the renderer kept. Nothing is lost that the CPU // does not hold, and the window stays where it is. -func (renderer *vulkanRenderer) recoverDevice() error { - if renderer.connection == 0 { - return fmt.Errorf("linux: only a window renderer can be rebuilt") +func (renderer *Renderer) recoverDevice() error { + if renderer.source.Create == nil { + return fmt.Errorf("vulkan: only a window renderer can be rebuilt") } renderer.releaseDevice() - if err := renderer.initialize(renderer.connection, renderer.window); err != nil { + if err := renderer.initialize(); err != nil { return err } renderer.recoveries++ @@ -1525,7 +1449,7 @@ func (renderer *vulkanRenderer) recoverDevice() error { // instance and clears the handles; the scene instances, the label descriptions // and the swapchain size stay. Destroying objects of a lost device is allowed // and its results are not looked at. -func (renderer *vulkanRenderer) releaseDevice() { +func (renderer *Renderer) releaseDevice() { if renderer.device != 0 { renderer.api.deviceWaitIdle(renderer.device) renderer.text.release(renderer) @@ -1553,7 +1477,7 @@ func (renderer *vulkanRenderer) releaseDevice() { renderer.recorded = nil } -func (renderer *vulkanRenderer) selectPresentMode() uint32 { +func (renderer *Renderer) selectPresentMode() uint32 { if renderer.hasPresentMode { return renderer.presentMode } diff --git a/internal/platform/linux/vulkan_loss.go b/internal/platform/vulkan/vulkan_loss.go similarity index 92% rename from internal/platform/linux/vulkan_loss.go rename to internal/platform/vulkan/vulkan_loss.go index a49f3bea8..644c17493 100644 --- a/internal/platform/linux/vulkan_loss.go +++ b/internal/platform/vulkan/vulkan_loss.go @@ -1,4 +1,4 @@ -package linux +package vulkan import ( "errors" @@ -25,7 +25,7 @@ type vulkanResultError struct { } func (err *vulkanResultError) Error() string { - return fmt.Sprintf("linux: %s failed with Vulkan result %d", err.action, err.status) + return fmt.Sprintf("vulkan: %s failed with Vulkan result %d", err.action, err.status) } // isGraphicsLoss reports whether err says the device or the surface was lost. diff --git a/internal/platform/linux/vulkan_loss_test.go b/internal/platform/vulkan/vulkan_loss_test.go similarity index 98% rename from internal/platform/linux/vulkan_loss_test.go rename to internal/platform/vulkan/vulkan_loss_test.go index 0a3f1d92b..992e99cb2 100644 --- a/internal/platform/linux/vulkan_loss_test.go +++ b/internal/platform/vulkan/vulkan_loss_test.go @@ -1,4 +1,4 @@ -package linux +package vulkan import ( "errors" diff --git a/internal/platform/linux/vulkan_probe_linux.go b/internal/platform/vulkan/vulkan_probe_linux.go similarity index 94% rename from internal/platform/linux/vulkan_probe_linux.go rename to internal/platform/vulkan/vulkan_probe_linux.go index 8d9d55d54..10a6aa4c8 100644 --- a/internal/platform/linux/vulkan_probe_linux.go +++ b/internal/platform/vulkan/vulkan_probe_linux.go @@ -1,4 +1,4 @@ -package linux +package vulkan import ( "encoding/binary" @@ -13,14 +13,14 @@ var softwareProbe struct { software bool } -// vulkanDeviceIsSoftware reports whether the device a window would draw with is a +// DeviceIsSoftware reports whether the device a window would draw with is a // CPU rasterizer: the hardware device with a graphics queue if there is one, else // the renderer the window will use (ADR 0075). The answer decides whether the // window gets a frame with a transparent margin (window_margin_linux.go): older // software drivers cannot present to a window with alpha, and the CPU renderer // cannot composite one either. A machine with no usable Vulkan draws on the CPU, // so it answers true. It asks once. -func vulkanDeviceIsSoftware() bool { +func DeviceIsSoftware() bool { softwareProbe.once.Do(func() { api, err := loadVulkan() if err != nil { diff --git a/internal/platform/linux/vulkan_probe_linux_test.go b/internal/platform/vulkan/vulkan_probe_linux_test.go similarity index 83% rename from internal/platform/linux/vulkan_probe_linux_test.go rename to internal/platform/vulkan/vulkan_probe_linux_test.go index ffb816ec1..4cb02acaa 100644 --- a/internal/platform/linux/vulkan_probe_linux_test.go +++ b/internal/platform/vulkan/vulkan_probe_linux_test.go @@ -1,6 +1,6 @@ //go:build linux -package linux +package vulkan import ( "testing" @@ -11,13 +11,13 @@ import ( // way to the first frame; it must not be slow. func TestSoftwareProbeIsQuickAndStable(t *testing.T) { start := time.Now() - first := vulkanDeviceIsSoftware() + first := DeviceIsSoftware() took := time.Since(start) t.Logf("software device: %v, probe took %v", first, took) if took > 2*time.Second { t.Fatalf("the probe took %v", took) } - if vulkanDeviceIsSoftware() != first { + if DeviceIsSoftware() != first { t.Fatal("the answer changed") } } diff --git a/internal/platform/linux/vulkan_recovery_linux_test.go b/internal/platform/vulkan/vulkan_recovery_linux_test.go similarity index 63% rename from internal/platform/linux/vulkan_recovery_linux_test.go rename to internal/platform/vulkan/vulkan_recovery_linux_test.go index 8940b503b..86ab329dd 100644 --- a/internal/platform/linux/vulkan_recovery_linux_test.go +++ b/internal/platform/vulkan/vulkan_recovery_linux_test.go @@ -1,10 +1,9 @@ //go:build linux -package linux +package vulkan import ( "errors" - "os" "testing" "time" @@ -13,33 +12,37 @@ import ( "github.com/vivaui/viva/internal/scene" ) -// newWindowRenderer opens a window and the renderer of it, skipping where there -// is no display or no Vulkan driver. -func newWindowRenderer(t *testing.T, labels []platform.TextLabel) (*window, *vulkanRenderer) { +// newWindowRenderer makes the renderer of a window surface, skipping where there is +// no Vulkan driver or no surface to present to. +func newWindowRenderer(t *testing.T, labels []platform.TextLabel) *Renderer { t.Helper() - if os.Getenv("DISPLAY") == "" { - t.Skip("no X display") - } - win, err := openWindow(platform.Config{Title: "Viva recovery", Width: 120, Height: 80}) - if err != nil { - t.Skipf("no X window: %v", err) - } - t.Cleanup(win.close) + renderer, _ := newResizableRenderer(t, labels) + return renderer +} + +// newResizableRenderer is newWindowRenderer with a function that asks the surface for +// another size, reporting false where the surface has no size of its own. +func newResizableRenderer(t *testing.T, labels []platform.TextLabel) (*Renderer, func(width, height uint32) bool) { + t.Helper() + source, resize := windowSurface(t, 120, 80) rectangles := []render.Rectangle{{Kind: scene.KindRectangle, Bounds: scene.Rect{X: 10, Y: 10, Width: 60, Height: 30}, Color: scene.Color{Red: 1, Alpha: 1}}} - renderer, err := newVulkanRenderer(win.connection, win.id, win.width, win.height, 1, platform.Color{Alpha: 1}, rectangles, labels, 0) + renderer, err := New(Config{ + Surface: source, Width: 120, Height: 80, Scale: 1, Clear: platform.Color{Alpha: 1}, + Rectangles: rectangles, Labels: labels, Rasterizer: newSolidRasterizer, + }) if errors.Is(err, platform.ErrNoGraphics) { t.Skipf("no Vulkan device: %v", err) } if err != nil { - t.Fatal(err) + t.Skipf("no Vulkan surface: %v", err) } - t.Cleanup(renderer.close) - return win, renderer + t.Cleanup(renderer.Close) + return renderer, resize } func TestPresentRebuildsALostDevice(t *testing.T) { - _, renderer := newWindowRenderer(t, []platform.TextLabel{{Value: "recover", X: 10, Y: 50, Width: 80, Height: 20, FontSize: 14, Color: platform.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1}}}) - if err := renderer.present(); err != nil { + renderer := newWindowRenderer(t, []platform.TextLabel{{Value: "recover", X: 10, Y: 50, Width: 80, Height: 20, FontSize: 14, Color: platform.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1}}}) + if err := renderer.Present(); err != nil { t.Fatal(err) } present := renderer.api.queuePresent @@ -51,7 +54,7 @@ func TestPresentRebuildsALostDevice(t *testing.T) { } return present(queue, info) } - if err := renderer.present(); err != nil { + if err := renderer.Present(); err != nil { t.Fatalf("present after a lost device: %v", err) } if renderer.recoveries != 1 { @@ -63,13 +66,13 @@ func TestPresentRebuildsALostDevice(t *testing.T) { if renderer.text.labels[0].view == 0 { t.Fatal("the label texture was not uploaded again") } - if err := renderer.present(); err != nil { + if err := renderer.Present(); err != nil { t.Fatalf("present after recovery: %v", err) } } func TestPresentRebuildsALostSurface(t *testing.T) { - _, renderer := newWindowRenderer(t, nil) + renderer := newWindowRenderer(t, nil) acquire := renderer.api.acquireNextImage lost := 1 renderer.api.acquireNextImage = func(device, swapchain uintptr, timeout uint64, semaphore, fence uintptr, index *uint32) int32 { @@ -79,7 +82,7 @@ func TestPresentRebuildsALostSurface(t *testing.T) { } return acquire(device, swapchain, timeout, semaphore, fence, index) } - if err := renderer.present(); err != nil { + if err := renderer.Present(); err != nil { t.Fatalf("present after a lost surface: %v", err) } if renderer.recoveries != 1 { @@ -88,9 +91,9 @@ func TestPresentRebuildsALostSurface(t *testing.T) { } func TestPresentGivesUpOnADeviceThatStaysLost(t *testing.T) { - _, renderer := newWindowRenderer(t, nil) + renderer := newWindowRenderer(t, nil) renderer.api.queuePresent = func(uintptr, *vkPresentInfo) int32 { return vkErrorDeviceLost } - err := renderer.present() + err := renderer.Present() if !isGraphicsLoss(err) { t.Fatalf("present = %v, want the loss", err) } @@ -105,32 +108,23 @@ func TestResizeRecordsCommandsAfterStageRecovery(t *testing.T) { status int32 }{{"device", vkErrorDeviceLost}, {"surface", vkErrorSurfaceLost}} { t.Run(loss.name, func(t *testing.T) { - win, renderer := newWindowRenderer(t, nil) - size := [2]uint32{160, 100} - win.api.configureWindow(win.connection, win.id, xcbConfigWindowWidth|xcbConfigWindowHeight, &size[0]) - win.api.flush(win.connection) - deadline := time.Now().Add(3 * time.Second) - for { - width, height := renderer.surfaceSize(size[0], size[1]) - if width == size[0] && height == size[1] { - break - } - if time.Now().After(deadline) { - t.Fatalf("surface stayed %dx%d", width, height) + renderer, resize := newResizableRenderer(t, nil) + if resize(160, 100) { + deadline := time.Now().Add(3 * time.Second) + for { + if width, height := renderer.SurfaceSize(160, 100); width == 160 && height == 100 { + break + } + if time.Now().After(deadline) { + t.Fatal("the surface never reached 160x100") + } + time.Sleep(time.Millisecond) } - time.Sleep(time.Millisecond) } - win.width, win.height = size[0], size[1] - if renderer.width == win.width && renderer.height == win.height { - t.Fatal("test needs a pending swapchain resize") + frame := platform.Frame{ + Rectangles: []render.Rectangle{{Kind: scene.KindRectangle, Bounds: scene.Rect{Width: 160, Height: 100}, Color: scene.Color{Red: 1, Alpha: 1}}}, + Update: render.Update{Count: 1, Rebuild: true}, } - config := &platform.Config{OnResize: func(platform.Size) (platform.Frame, error) { - return platform.Frame{ - Rectangles: []render.Rectangle{{Kind: scene.KindRectangle, Bounds: scene.Rect{Width: 160, Height: 100}, Color: scene.Color{Red: 1, Alpha: 1}}}, - Update: render.Update{Count: 1, Rebuild: true}, - }, nil - }} - state := &linuxWindowState{win: win, renderer: renderer, config: *config, text: &linuxTextInput{config: config}} recorded := make(map[uintptr]bool) reset := renderer.api.resetCommandPool @@ -168,9 +162,17 @@ func TestResizeRecordsCommandsAfterStageRecovery(t *testing.T) { } return submit(queue, count, info, fence) } - if err := state.resized(); err != nil { + // What a window does when it grows: stage the new scene, resize the + // swapchain to the new size, present. + if _, err := renderer.Stage(frame); err != nil { + t.Fatalf("stage: %v", err) + } + if err := renderer.Resize(160, 100); err != nil { t.Fatalf("resize: %v", err) } + if err := renderer.Present(); err != nil { + t.Fatalf("present: %v", err) + } if renderer.recoveries != 1 || renderer.submissions != 1 { t.Fatalf("recoveries=%d submissions=%d, want one recovered frame", renderer.recoveries, renderer.submissions) } diff --git a/internal/platform/linux/vulkan_refresh_linux.go b/internal/platform/vulkan/vulkan_refresh_linux.go similarity index 81% rename from internal/platform/linux/vulkan_refresh_linux.go rename to internal/platform/vulkan/vulkan_refresh_linux.go index 3aae4087d..c247841df 100644 --- a/internal/platform/linux/vulkan_refresh_linux.go +++ b/internal/platform/vulkan/vulkan_refresh_linux.go @@ -1,10 +1,10 @@ -package linux +package vulkan import "fmt" -// refreshText rasterizes every label drawn from text again, for a change in how the desktop +// RefreshText rasterizes every label drawn from text again, for a change in how the desktop // draws text (font_settings.go). The window presents afterwards. -func (renderer *vulkanRenderer) refreshText() error { +func (renderer *Renderer) RefreshText() error { if renderer.device == 0 || renderer.commandPool == 0 { return nil } @@ -20,7 +20,7 @@ func (renderer *vulkanRenderer) refreshText() error { } } if err := renderer.text.upload(renderer, renderer.pixelScale(), renderer.textViewport(renderer.width, renderer.height)); err != nil { - return fmt.Errorf("linux: refresh text: %w", err) + return fmt.Errorf("vulkan: refresh text: %w", err) } return renderer.recordCommands(vkExtent2D{Width: renderer.width, Height: renderer.height}) } diff --git a/internal/platform/linux/vulkan_scene_linux.go b/internal/platform/vulkan/vulkan_scene_linux.go similarity index 94% rename from internal/platform/linux/vulkan_scene_linux.go rename to internal/platform/vulkan/vulkan_scene_linux.go index 799a0a323..59f0937f1 100644 --- a/internal/platform/linux/vulkan_scene_linux.go +++ b/internal/platform/vulkan/vulkan_scene_linux.go @@ -1,4 +1,4 @@ -package linux +package vulkan import ( "fmt" @@ -287,7 +287,7 @@ func makeVulkanRectangleInstance(rectangle render.Rectangle) vulkanRectangleInst return instance } -func (sceneState *vulkanScene) upload(renderer *vulkanRenderer, rectangles []render.Rectangle, update render.Update) error { +func (sceneState *vulkanScene) upload(renderer *Renderer, rectangles []render.Rectangle, update render.Update) error { first, count := update.First, update.Count if update.Rebuild { if len(rectangles) > cap(sceneState.instances) { @@ -298,7 +298,7 @@ func (sceneState *vulkanScene) upload(renderer *vulkanRenderer, rectangles []ren first, count = 0, len(rectangles) } else if len(sceneState.instances) > len(rectangles) { if !update.Shrink || update.First > len(rectangles) || update.First+update.Count != len(rectangles) { - return fmt.Errorf("linux: rectangle count shrank outside a suffix update") + return fmt.Errorf("vulkan: rectangle count shrank outside a suffix update") } sceneState.instances = sceneState.instances[:len(rectangles)] } else if len(sceneState.instances) < len(rectangles) { @@ -333,10 +333,10 @@ func (sceneState *vulkanScene) upload(renderer *vulkanRenderer, rectangles []ren return nil } -func (sceneState *vulkanScene) grow(renderer *vulkanRenderer, required int) error { +func (sceneState *vulkanScene) grow(renderer *Renderer, required int) error { capacity := max(required, max(64, sceneState.capacity*2)) if capacity > int(^uint32(0))/vkInstanceBytes { - return fmt.Errorf("linux: rectangle buffer exceeds device limit") + return fmt.Errorf("vulkan: rectangle buffer exceeds device limit") } sceneState.closeBuffer(renderer) info := vkBufferCreateInfo{ @@ -351,7 +351,7 @@ func (sceneState *vulkanScene) grow(renderer *vulkanRenderer, required int) erro memoryType, ok := renderer.memoryType(requirements.MemoryTypeBits, vkMemoryHostVisible|vkMemoryHostCoherent) if !ok { sceneState.closeBuffer(renderer) - return fmt.Errorf("linux: Vulkan device has no coherent host-visible memory for scene data") + return fmt.Errorf("vulkan: Vulkan device has no coherent host-visible memory for scene data") } allocation := vkMemoryAllocateInfo{SType: vkStructureMemoryAllocateInfo, AllocationSize: requirements.Size, MemoryTypeIndex: memoryType} if err := vkCheck(renderer.api.allocateMemory(renderer.device, &allocation, nil, &sceneState.memory), "allocate scene memory"); err != nil { @@ -370,7 +370,7 @@ func (sceneState *vulkanScene) grow(renderer *vulkanRenderer, required int) erro return nil } -func (renderer *vulkanRenderer) memoryType(bits, properties uint32) (uint32, bool) { +func (renderer *Renderer) memoryType(bits, properties uint32) (uint32, bool) { var memory vkPhysicalDeviceMemoryProperties renderer.api.getPhysicalDeviceMemoryProperties(renderer.physical, &memory) for index := uint32(0); index < memory.MemoryTypeCount && index < uint32(len(memory.MemoryTypes)); index++ { @@ -381,7 +381,7 @@ func (renderer *vulkanRenderer) memoryType(bits, properties uint32) (uint32, boo return 0, false } -func (sceneState *vulkanScene) createPipeline(renderer *vulkanRenderer) (err error) { +func (sceneState *vulkanScene) createPipeline(renderer *Renderer) (err error) { if sceneState.pipeline != 0 { return nil } @@ -405,7 +405,7 @@ func (sceneState *vulkanScene) createPipeline(renderer *vulkanRenderer) (err err // buildPipeline creates the scene pipeline for the render pass. With cut it // blends so that what it draws takes away from what is there instead of adding: // the target keeps 1 - alpha of itself (see vulkan_frame_linux.go). -func (sceneState *vulkanScene) buildPipeline(renderer *vulkanRenderer, cut bool) (pipeline uintptr, err error) { +func (sceneState *vulkanScene) buildPipeline(renderer *Renderer, cut bool) (pipeline uintptr, err error) { vertex, err := renderer.shaderModule(sceneVertexShader) if err != nil { return 0, err @@ -459,9 +459,9 @@ func (sceneState *vulkanScene) buildPipeline(renderer *vulkanRenderer, cut bool) return pipeline, vkCheck(renderer.api.createGraphicsPipelines(renderer.device, 0, 1, &info, nil, &pipeline), "create scene pipeline") } -func (renderer *vulkanRenderer) shaderModule(code []byte) (uintptr, error) { +func (renderer *Renderer) shaderModule(code []byte) (uintptr, error) { if len(code) < 4 || len(code)%4 != 0 { - return 0, fmt.Errorf("linux: invalid embedded SPIR-V shader") + return 0, fmt.Errorf("vulkan: invalid embedded SPIR-V shader") } info := vkShaderModuleCreateInfo{ SType: vkStructureShaderModuleCreateInfo, CodeSize: uintptr(len(code)), @@ -474,7 +474,7 @@ func (renderer *vulkanRenderer) shaderModule(code []byte) (uintptr, error) { return module, nil } -func (sceneState *vulkanScene) record(renderer *vulkanRenderer, command uintptr, extent vkExtent2D, batch compositingBatch) { +func (sceneState *vulkanScene) record(renderer *Renderer, command uintptr, extent vkExtent2D, batch compositingBatch) { first, count := batch.First, batch.Count if count <= 0 || first < 0 || first+count > len(sceneState.instances) { return @@ -509,7 +509,7 @@ func (sceneState *vulkanScene) record(renderer *vulkanRenderer, command uintptr, renderer.api.cmdDraw(command, 6, uint32(count), 0, uint32(first)) } -func (sceneState *vulkanScene) destroyPipeline(renderer *vulkanRenderer) { +func (sceneState *vulkanScene) destroyPipeline(renderer *Renderer) { if sceneState.pipeline != 0 { renderer.api.destroyPipeline(renderer.device, sceneState.pipeline, nil) sceneState.pipeline = 0 @@ -520,7 +520,7 @@ func (sceneState *vulkanScene) destroyPipeline(renderer *vulkanRenderer) { } } -func (sceneState *vulkanScene) closeBuffer(renderer *vulkanRenderer) { +func (sceneState *vulkanScene) closeBuffer(renderer *Renderer) { if sceneState.mapped != nil && sceneState.memory != 0 { renderer.api.unmapMemory(renderer.device, sceneState.memory) sceneState.mapped = nil @@ -536,7 +536,7 @@ func (sceneState *vulkanScene) closeBuffer(renderer *vulkanRenderer) { sceneState.capacity = 0 } -func (sceneState *vulkanScene) close(renderer *vulkanRenderer) { +func (sceneState *vulkanScene) close(renderer *Renderer) { sceneState.destroyPipeline(renderer) sceneState.closeBuffer(renderer) } diff --git a/internal/platform/linux/vulkan_staging_linux.go b/internal/platform/vulkan/vulkan_staging_linux.go similarity index 90% rename from internal/platform/linux/vulkan_staging_linux.go rename to internal/platform/vulkan/vulkan_staging_linux.go index d90247322..98e56027b 100644 --- a/internal/platform/linux/vulkan_staging_linux.go +++ b/internal/platform/vulkan/vulkan_staging_linux.go @@ -1,6 +1,6 @@ //go:build linux -package linux +package vulkan import ( "fmt" @@ -33,7 +33,7 @@ const stagingChunkMinimum = 1 << 20 // settle waits for the last upload's copies, after which its chunks and the // images it wrote may be reused or destroyed. -func (staging *textStaging) settle(renderer *vulkanRenderer) error { +func (staging *textStaging) settle(renderer *Renderer) error { if !staging.pending { return nil } @@ -46,7 +46,7 @@ func (staging *textStaging) settle(renderer *vulkanRenderer) error { // begin readies the chunks for an upload: the last one has settled, and the // chunks it needed are one. -func (staging *textStaging) begin(renderer *vulkanRenderer) error { +func (staging *textStaging) begin(renderer *Renderer) error { if err := staging.settle(renderer); err != nil { return err } @@ -74,7 +74,7 @@ func (staging *textStaging) begin(renderer *vulkanRenderer) error { // stage copies pixels into a chunk and returns the buffer and offset the copy // into the image reads them from. -func (staging *textStaging) stage(renderer *vulkanRenderer, pixels []byte) (buffer uintptr, offset uint64, err error) { +func (staging *textStaging) stage(renderer *Renderer, pixels []byte) (buffer uintptr, offset uint64, err error) { need := uint64(len(pixels)) last := len(staging.chunks) - 1 if last < 0 || staging.chunks[last].size-staging.chunks[last].used < need { @@ -98,7 +98,7 @@ func (staging *textStaging) stage(renderer *vulkanRenderer, pixels []byte) (buff } // submit hands the upload command to the queue with the fence. -func (staging *textStaging) submit(renderer *vulkanRenderer, command uintptr) error { +func (staging *textStaging) submit(renderer *Renderer, command uintptr) error { if err := vkCheck(renderer.api.resetFences(renderer.device, 1, &staging.fence), "reset text upload fence"); err != nil { return err } @@ -110,7 +110,7 @@ func (staging *textStaging) submit(renderer *vulkanRenderer, command uintptr) er return nil } -func (staging *textStaging) grow(renderer *vulkanRenderer, size uint64) (err error) { +func (staging *textStaging) grow(renderer *Renderer, size uint64) (err error) { var chunk stagingChunk defer func() { if err != nil { @@ -147,7 +147,7 @@ func (staging *textStaging) grow(renderer *vulkanRenderer, size uint64) (err err return nil } -func (staging *textStaging) closeChunks(renderer *vulkanRenderer) { +func (staging *textStaging) closeChunks(renderer *Renderer) { for index := range staging.chunks { chunk := &staging.chunks[index] renderer.api.unmapMemory(renderer.device, chunk.memory) @@ -158,7 +158,7 @@ func (staging *textStaging) closeChunks(renderer *vulkanRenderer) { } // close destroys the chunks and the fence; the device has finished with them. -func (staging *textStaging) close(renderer *vulkanRenderer) { +func (staging *textStaging) close(renderer *Renderer) { if renderer == nil || renderer.api == nil || renderer.device == 0 { *staging = textStaging{} return diff --git a/internal/platform/linux/vulkan_staging_linux_test.go b/internal/platform/vulkan/vulkan_staging_linux_test.go similarity index 99% rename from internal/platform/linux/vulkan_staging_linux_test.go rename to internal/platform/vulkan/vulkan_staging_linux_test.go index 10db13679..b610e5561 100644 --- a/internal/platform/linux/vulkan_staging_linux_test.go +++ b/internal/platform/vulkan/vulkan_staging_linux_test.go @@ -1,4 +1,4 @@ -package linux +package vulkan import ( "fmt" diff --git a/internal/platform/linux/vulkan_swapchain_retire_linux_test.go b/internal/platform/vulkan/vulkan_swapchain_retire_linux_test.go similarity index 99% rename from internal/platform/linux/vulkan_swapchain_retire_linux_test.go rename to internal/platform/vulkan/vulkan_swapchain_retire_linux_test.go index 119a64e6c..c38a1505e 100644 --- a/internal/platform/linux/vulkan_swapchain_retire_linux_test.go +++ b/internal/platform/vulkan/vulkan_swapchain_retire_linux_test.go @@ -1,6 +1,6 @@ //go:build linux -package linux +package vulkan import ( "slices" @@ -16,7 +16,7 @@ type swapchainRetireEvent struct { // Use distinct handles so a retired chain cannot accidentally alias its replacement. // Every destruction is checked while it happens, including cleanup after a failure. type swapchainRetireHarness struct { - renderer *vulkanRenderer + renderer *Renderer events []swapchainRetireEvent allocated []uintptr destroyed map[uintptr]int diff --git a/internal/platform/linux/vulkan_text_linux.go b/internal/platform/vulkan/vulkan_text_linux.go similarity index 90% rename from internal/platform/linux/vulkan_text_linux.go rename to internal/platform/vulkan/vulkan_text_linux.go index 36cffe70d..e5e68f272 100644 --- a/internal/platform/linux/vulkan_text_linux.go +++ b/internal/platform/vulkan/vulkan_text_linux.go @@ -1,4 +1,4 @@ -package linux +package vulkan import ( "fmt" @@ -181,11 +181,11 @@ type vulkanLabelTexture struct { lcd bool // spans are the columns of an lcd grid label's texture that are text of one color; // empty for a label that is all in label.Color. - spans []colorSpan + spans []ColorSpan } type vulkanText struct { - services *textServices + services TextRasterizer descriptorLayout, descriptorPool uintptr sampler, pipelineLayout, pipeline uintptr lcdPipeline uintptr @@ -248,7 +248,7 @@ func textureKey(label platform.TextLabel) vulkanTextureKey { // A grid texture may cover more than the visible width. Its owner checks // the actual allocation before reusing it at a different width. key.width = 0 - } else if needed, ok := neededLabelWidth(label); ok { + } else if needed, ok := NeededLabelWidth(label); ok { key.width = min(key.width, needed) } return key @@ -271,11 +271,11 @@ func registerVulkanText(api *vulkanAPI, library uintptr) { puregoRegister(&api.cmdCopyBufferToImage, library, "vkCmdCopyBufferToImage") } -func (textState *vulkanText) initialize(renderer *vulkanRenderer) error { +func (textState *vulkanText) initialize(renderer *Renderer) error { if textState.services != nil { return nil } - services, err := newTextServices() + services, err := renderer.newRasterizer() if err != nil { return err } @@ -304,7 +304,7 @@ func (textState *vulkanText) initialize(renderer *vulkanRenderer) error { return nil } -func (textState *vulkanText) createPipeline(renderer *vulkanRenderer) (err error) { +func (textState *vulkanText) createPipeline(renderer *Renderer) (err error) { if textState.services == nil || textState.pipeline != 0 { return nil } @@ -380,19 +380,7 @@ func (textState *vulkanText) createPipeline(renderer *vulkanRenderer) (err error return vkCheck(renderer.api.createGraphicsPipelines(renderer.device, 0, 1, &lcdInfo, nil, &textState.lcdPipeline), "create LCD text pipeline") } -func sameTextRuns(left, right []gfx.TextRun) bool { - if len(left) != len(right) { - return false - } - for index := range left { - if left[index] != right[index] { - return false - } - } - return true -} - -func (label *vulkanLabelTexture) update(renderer *vulkanRenderer, next platform.TextLabel) { +func (label *vulkanLabelTexture) update(renderer *Renderer, next platform.TextLabel) { keptWidth := label.label.Width changed := label.contentChanged(next) if changed { @@ -412,7 +400,7 @@ func (label *vulkanLabelTexture) update(renderer *vulkanRenderer, next platform. func (label *vulkanLabelTexture) contentChanged(next platform.TextLabel) bool { previous := label.label if len(next.Bitmap) == 0 && len(next.Runs) > 0 && label.view != 0 && label.scale > 0 { - if needed, ok := neededLabelWidth(next); ok && + if needed, ok := NeededLabelWidth(next); ok && math.Ceil(float64(min(next.Width, needed)*label.scale)) <= float64(label.width) { previous.Width = next.Width } @@ -425,7 +413,7 @@ func bitmapTextureStale(label *vulkanLabelTexture, scale float32) bool { return len(label.label.Bitmap) > 0 && label.view != 0 && platform.BitmapTextureStale(label.label, scale, label.width, label.height) } -func neededLabelWidth(label platform.TextLabel) (float32, bool) { +func NeededLabelWidth(label platform.TextLabel) (float32, bool) { if len(label.Bitmap) > 0 { return 0, false } @@ -457,9 +445,9 @@ func textureContentChanged(previous, next platform.TextLabel) bool { if previous.Value != next.Value || previous.FontSize != next.FontSize || previous.Weight != next.Weight || previous.Italic != next.Italic || previous.Color != next.Color || previous.FontGeneration != next.FontGeneration || previous.Mono != next.Mono || previous.MonoFace != next.MonoFace || previous.CellWidth != next.CellWidth || previous.Baseline != next.Baseline || - !sameTextRuns(previous.Runs, next.Runs) || previous.BitmapID != next.BitmapID || previous.BitmapVersion != next.BitmapVersion || + !platform.SameTextRuns(previous.Runs, next.Runs) || previous.BitmapID != next.BitmapID || previous.BitmapVersion != next.BitmapVersion || previous.BitmapWidth != next.BitmapWidth || previous.BitmapHeight != next.BitmapHeight || previous.BitmapStride != next.BitmapStride || - !sameBitmapBytes(previous.Bitmap, next.Bitmap) { + !platform.SameBitmapBytes(previous.Bitmap, next.Bitmap) { return true } if len(previous.Bitmap) > 0 || len(next.Bitmap) > 0 { @@ -471,25 +459,18 @@ func textureContentChanged(previous, next platform.TextLabel) bool { if previous.Width == next.Width { return false } - if needed, ok := neededLabelWidth(next); ok { + if needed, ok := NeededLabelWidth(next); ok { return min(previous.Width, needed) != min(next.Width, needed) } return true } -func sameBitmapBytes(left, right []byte) bool { - if len(left) != len(right) { - return false - } - return len(left) == 0 || &left[0] == &right[0] -} - -func (textState *vulkanText) update(renderer *vulkanRenderer, labels []platform.TextLabel) error { +func (textState *vulkanText) update(renderer *Renderer, labels []platform.TextLabel) error { if len(labels) > vkMaximumTextLabels { - return fmt.Errorf("linux: text label count %d exceeds limit %d", len(labels), vkMaximumTextLabels) + return fmt.Errorf("vulkan: text label count %d exceeds limit %d", len(labels), vkMaximumTextLabels) } for index, label := range labels { - if err := validateTextLabel(index, label); err != nil { + if err := platform.ValidateTextLabel(index, label); err != nil { return err } } @@ -591,30 +572,6 @@ func (textState *vulkanText) update(renderer *vulkanRenderer, labels []platform. return nil } -func validateTextLabel(index int, label platform.TextLabel) error { - for _, value := range []float32{label.X, label.Y, label.Width, label.Height, label.FontSize, label.Weight, label.CellWidth} { - if !finite32(value) { - return fmt.Errorf("linux: text label %d has a non-finite metric", index) - } - } - if label.Width < 0 || label.Height < 0 || len(label.Bitmap) == 0 && !validFontSize(label.FontSize) { - return fmt.Errorf("linux: text label %d has invalid bounds or font size", index) - } - if len(label.Runs) > 0 && label.CellWidth <= 0 { - return fmt.Errorf("linux: text label %d has invalid cell width", index) - } - if len(label.Bitmap) > 0 { - if label.BitmapWidth <= 0 || label.BitmapHeight <= 0 || label.BitmapStride < label.BitmapWidth*4 { - return fmt.Errorf("linux: bitmap label %d has invalid dimensions", index) - } - required := (label.BitmapHeight-1)*label.BitmapStride + label.BitmapWidth*4 - if required < 0 || len(label.Bitmap) < required { - return fmt.Errorf("linux: bitmap label %d has a short payload", index) - } - } - return nil -} - // needsUpload reports whether the label is rasterized again at scale for a scene viewport // device pixels wide: it has no texture there, its image's texture no longer suits the size // it is drawn at, or it is a wide line whose texture no longer holds the part of it that can @@ -649,7 +606,7 @@ func (label *vulkanLabelTexture) needsUpload(scale float32, viewport int) bool { // the label. func (label *vulkanLabelTexture) window(scale float32, viewport int) (skip, width, height int, wide, ok bool) { height = int(math.Ceil(float64(label.label.Height * scale))) - full := labelRasterWidth(label.label, scale, height) + full := LabelRasterWidth(label.label, scale, height) haveSkip, haveWidth := 0, 0 if label.view != 0 && label.scale == scale { haveSkip, haveWidth = label.skip, label.width @@ -660,14 +617,14 @@ func (label *vulkanLabelTexture) window(scale float32, viewport int) (skip, widt // drop leaves the label without a texture at scale, for one it cannot have: a label no // texture holds is not drawn, and does not stop the window drawing the others. -func (label *vulkanLabelTexture) drop(renderer *vulkanRenderer, scale float32, wide bool) { +func (label *vulkanLabelTexture) drop(renderer *Renderer, scale float32, wide bool) { label.closeImage(renderer) label.scale, label.wide, label.dropped = scale, wide, true } // textViewport is the device width of the scene in a target width by height: the width a // line wider than a texture holds is windowed to. -func (renderer *vulkanRenderer) textViewport(width, height uint32) int { +func (renderer *Renderer) textViewport(width, height uint32) int { if renderer.frame.active() { _, _, content := renderer.frame.content(width, height) return int(content.Width) @@ -677,7 +634,7 @@ func (renderer *vulkanRenderer) textViewport(width, height uint32) int { // upload rasterizes and uploads every label that needsUpload at scale, for a scene // viewport device pixels wide. -func (textState *vulkanText) upload(renderer *vulkanRenderer, scale float32, viewport int) error { +func (textState *vulkanText) upload(renderer *Renderer, scale float32, viewport int) error { if textState.services == nil || renderer.uploadCommand == 0 { return nil } @@ -708,7 +665,7 @@ func (textState *vulkanText) upload(renderer *vulkanRenderer, scale float32, vie } var pixels []byte lcd, wide := false, false - var spans []colorSpan + var spans []ColorSpan skip, width, height := 0, 0, 0 if len(label.label.Bitmap) > 0 { width, height = label.label.BitmapWidth, label.label.BitmapHeight @@ -724,7 +681,7 @@ func (textState *vulkanText) upload(renderer *vulkanRenderer, scale float32, vie width, height = shown, high } if pixels == nil { - pixels = tightBitmap(label.label.Bitmap, width, height, label.label.BitmapStride) + pixels = platform.TightBitmap(label.label.Bitmap, width, height, label.label.BitmapStride) } } else { var ok bool @@ -736,14 +693,14 @@ func (textState *vulkanText) upload(renderer *vulkanRenderer, scale float32, vie var err error // ClearType-style blending needs an opaque target: a window or an offscreen // image cleared opaque. - pixels, lcd, err = textState.services.rasterizeWindow(label.label, scale, skip, width, height, renderer.dualSource && textState.lcdPipeline != 0 && renderer.color.Alpha >= 1) + pixels, lcd, err = textState.services.Rasterize(label.label, scale, skip, width, height, renderer.dualSource && textState.lcdPipeline != 0 && renderer.color.Alpha >= 1) if err != nil { - return fmt.Errorf("linux: rasterize label %d: %w", index, err) + return fmt.Errorf("vulkan: rasterize label %d: %w", index, err) } - spans = textState.services.spans + spans = textState.services.Spans() } if err := label.createImage(renderer, textState, renderer.uploadCommand, pixels, uint32(width), uint32(height)); err != nil { - return fmt.Errorf("linux: upload label %d: %w", index, err) + return fmt.Errorf("vulkan: upload label %d: %w", index, err) } label.scale, label.lcd = scale, lcd label.width, label.height, label.skip, label.wide = width, height, skip, wide @@ -760,12 +717,12 @@ func (textState *vulkanText) upload(renderer *vulkanRenderer, scale float32, vie // Reserve up to sixteen cells on a grid row, so a pixel-by-pixel window resize // does not rasterize every row again. The reservation ends at the last run's // possible overhang and never exceeds the rasterizer's existing size limits. -func labelRasterWidth(label platform.TextLabel, scale float32, height int) int { +func LabelRasterWidth(label platform.TextLabel, scale float32, height int) int { width := int(math.Ceil(float64(label.Width * scale))) if len(label.Bitmap) > 0 { return width } - needed, ok := neededLabelWidth(label) + needed, ok := NeededLabelWidth(label) if ok { if capped := int(math.Ceil(float64(needed * scale))); capped > 0 && capped < width { width = capped @@ -782,19 +739,9 @@ func labelRasterWidth(label platform.TextLabel, scale float32, height int) int { return width } -func tightBitmap(source []byte, width, height, stride int) []byte { - if stride == width*4 { - return source[:width*height*4] - } - pixels := make([]byte, width*height*4) - for row := 0; row < height; row++ { - copy(pixels[row*width*4:(row+1)*width*4], source[row*stride:row*stride+width*4]) - } - return pixels -} - -func (label *vulkanLabelTexture) createImage(renderer *vulkanRenderer, textState *vulkanText, command uintptr, pixels []byte, width, height uint32) error { +func (label *vulkanLabelTexture) createImage(renderer *Renderer, textState *vulkanText, command uintptr, pixels []byte, width, height uint32) error { label.closeImage(renderer) + renderer.textures++ buffer, offset, err := textState.staging.stage(renderer, pixels) if err != nil { return err @@ -858,7 +805,7 @@ func (label *vulkanLabelTexture) createImage(renderer *vulkanRenderer, textState return nil } -func (textState *vulkanText) record(renderer *vulkanRenderer, command uintptr, extent vkExtent2D, index int) { +func (textState *vulkanText) record(renderer *Renderer, command uintptr, extent vkExtent2D, index int) { if index < 0 || index >= len(textState.labels) { return } @@ -908,14 +855,14 @@ func (textState *vulkanText) record(renderer *vulkanRenderer, command uintptr, e for spanIndex := range label.spans { span := &label.spans[spanIndex] scratch.cut = scratch.scissor - left := max(int64(scratch.cut.Offset[0]), int64(originX)+int64(origin+span.left)) - right := min(int64(scratch.cut.Offset[0])+int64(scratch.cut.Extent.Width), int64(originX)+int64(origin+span.right)) + left := max(int64(scratch.cut.Offset[0]), int64(originX)+int64(origin+span.Left)) + right := min(int64(scratch.cut.Offset[0])+int64(scratch.cut.Extent.Width), int64(originX)+int64(origin+span.Right)) if right <= left { continue } scratch.cut.Offset[0], scratch.cut.Extent.Width = int32(left), uint32(right-left) renderer.api.cmdSetScissor(command, 0, 1, &scratch.cut) - renderer.api.cmdPushConstants(command, textState.pipelineLayout, vkShaderStageFragment, 32, uint32(unsafe.Sizeof(span.color)), unsafe.Pointer(&span.color[0])) + renderer.api.cmdPushConstants(command, textState.pipelineLayout, vkShaderStageFragment, 32, uint32(unsafe.Sizeof(span.Color)), unsafe.Pointer(&span.Color[0])) renderer.api.cmdDraw(command, 6, 1, 0, 0) } } @@ -975,7 +922,7 @@ func labelScissor(label platform.TextLabel, scale float32, extent vkExtent2D) (s }, true } -func (label *vulkanLabelTexture) closeImage(renderer *vulkanRenderer) { +func (label *vulkanLabelTexture) closeImage(renderer *Renderer) { label.skip, label.wide, label.dropped = 0, false, false if renderer == nil || renderer.api == nil || renderer.device == 0 { label.image, label.memory, label.view, label.scale, label.lcd = 0, 0, 0, 0, false @@ -999,7 +946,7 @@ func (label *vulkanLabelTexture) closeImage(renderer *vulkanRenderer) { label.width, label.height, label.spans = 0, 0, label.spans[:0] } -func (textState *vulkanText) destroyPipeline(renderer *vulkanRenderer) { +func (textState *vulkanText) destroyPipeline(renderer *Renderer) { if textState.pipeline != 0 { renderer.api.destroyPipeline(renderer.device, textState.pipeline, nil) } @@ -1012,7 +959,7 @@ func (textState *vulkanText) destroyPipeline(renderer *vulkanRenderer) { textState.pipeline, textState.lcdPipeline, textState.pipelineLayout = 0, 0, 0 } -func (textState *vulkanText) close(renderer *vulkanRenderer) { +func (textState *vulkanText) close(renderer *Renderer) { textState.destroyPipeline(renderer) textState.staging.close(renderer) for index := range textState.labels { @@ -1032,7 +979,7 @@ func (textState *vulkanText) close(renderer *vulkanRenderer) { } } if textState.services != nil { - textState.services.close() + textState.services.Close() } textState.services = nil textState.descriptorPool, textState.sampler, textState.descriptorLayout = 0, 0, 0 @@ -1042,7 +989,7 @@ func (textState *vulkanText) close(renderer *vulkanRenderer) { // release destroys the text objects that belong to the device and the text // services, and keeps the labels' descriptions: each label is uploaded again // the next time the textures are made. -func (textState *vulkanText) release(renderer *vulkanRenderer) { +func (textState *vulkanText) release(renderer *Renderer) { textState.destroyPipeline(renderer) textState.staging.close(renderer) for index := range textState.labels { @@ -1064,7 +1011,7 @@ func (textState *vulkanText) release(renderer *vulkanRenderer) { } } if textState.services != nil { - textState.services.close() + textState.services.Close() } textState.services = nil textState.descriptorPool, textState.sampler, textState.descriptorLayout = 0, 0, 0 diff --git a/internal/platform/linux/vulkan_text_scissor_test.go b/internal/platform/vulkan/vulkan_text_scissor_test.go similarity index 99% rename from internal/platform/linux/vulkan_text_scissor_test.go rename to internal/platform/vulkan/vulkan_text_scissor_test.go index ed13d57fd..578c17580 100644 --- a/internal/platform/linux/vulkan_text_scissor_test.go +++ b/internal/platform/vulkan/vulkan_text_scissor_test.go @@ -1,6 +1,6 @@ //go:build linux -package linux +package vulkan import ( "testing" diff --git a/internal/platform/vulkan/vulkan_window_linux.go b/internal/platform/vulkan/vulkan_window_linux.go new file mode 100644 index 000000000..b2ee70d34 --- /dev/null +++ b/internal/platform/vulkan/vulkan_window_linux.go @@ -0,0 +1,44 @@ +package vulkan + +import "github.com/vivaui/viva/internal/render" + +// Stats is what the startup profile reports about a renderer: the presents it +// made, the full rebuilds of its scene, the partial updates and the label +// textures it made. +type Stats struct { + Presents, Rebuilds, Partials, Textures uint64 +} + +// PresentFull presents the retained swapchain image again. Vulkan keeps the +// frame it last presented, so this is the same as Present. +func (renderer *Renderer) PresentFull() error { return renderer.Present() } + +// ForgetSurfaceCapabilities drops surface capabilities read for a configure event +// that did not resize. +func (renderer *Renderer) ForgetSurfaceCapabilities() { renderer.hasPendingCapabilities = false } + +// Alpha reports whether the surface composites with alpha. +func (renderer *Renderer) Alpha() bool { return renderer.frame.alpha } + +// FrameMargin is the margin of the window frame the renderer draws, 0 for none. +func (renderer *Renderer) FrameMargin() uint32 { return renderer.frame.margin } + +// DeviceSize is the surface's size in device pixels. +func (renderer *Renderer) DeviceSize() (uint32, uint32) { return renderer.width, renderer.height } + +// FirstRectangle is the first shape of the scene, if there is one. +func (renderer *Renderer) FirstRectangle() (render.Rectangle, bool) { + if len(renderer.rectangles) == 0 { + return render.Rectangle{}, false + } + return renderer.rectangles[0], true +} + +// Stats reports the renderer's counters. +func (renderer *Renderer) Stats() Stats { + return Stats{Presents: renderer.submissions, Rebuilds: renderer.rebuilds, Partials: renderer.partials, Textures: renderer.textures} +} + +// Software reports whether the device the renderer draws with is a CPU rasterizer, +// such as Mesa's lavapipe. +func (renderer *Renderer) Software() bool { return renderer.software } diff --git a/internal/platform/vulkan/wide_label_linux_test.go b/internal/platform/vulkan/wide_label_linux_test.go new file mode 100644 index 000000000..594e6c59d --- /dev/null +++ b/internal/platform/vulkan/wide_label_linux_test.go @@ -0,0 +1,62 @@ +//go:build linux + +package vulkan + +import ( + "testing" + + "github.com/vivaui/viva/gfx" +) + +// A line wider than a texture holds gets a texture of the window of it that the viewport and +// its clip show, with or without runs. A scroll inside that window keeps the texture and one +// past it rasterizes the line again; a line scrolled out of view, or too tall for any texture, +// is dropped and not rasterized again every frame for that. +func TestVulkanWideLabelWindowFollowsTheViewport(t *testing.T) { + const scale, viewport = 1.5, 600 + for _, runs := range [][]gfx.TextRun{nil, wholeRun(wideValue)} { + label := vulkanLabelTexture{label: wideMonoLine(wideValue, 0, runs)} + if skip, width, height, wide, ok := label.window(scale, viewport); !ok || !wide || skip != 0 || width != 1800 || height != 27 { + t.Errorf("runs %d, start of the line: window = %d, %d, %d, %v, %v; want 0, 1800, 27, wide", len(runs), skip, width, height, wide, ok) + } + label.label.X = -20000 // 30000 device pixels scrolled off the left + if skip, width, _, _, ok := label.window(scale, viewport); !ok || skip != 30000-600 || width != 1800 { + t.Errorf("runs %d, scrolled: window = %d, %d, %v; want 29400, 1800", len(runs), skip, width, ok) + } + if !label.needsUpload(scale, viewport) { + t.Errorf("runs %d: a wide line without a texture is not rasterized", len(runs)) + } + label.view, label.scale, label.skip, label.width, label.height, label.wide = 1, scale, 29400, 1800, 27, true + label.label.X = -20100 + if label.needsUpload(scale, viewport) { + t.Errorf("runs %d: a scroll inside the texture's window rasterizes the line again", len(runs)) + } + label.label.X = -21000 + if !label.needsUpload(scale, viewport) { + t.Errorf("runs %d: a scroll past the texture's window keeps the texture", len(runs)) + } + label.label.X = -40000 + if !label.needsUpload(scale, viewport) { + t.Errorf("runs %d: a line scrolled out of view keeps its texture", len(runs)) + } + if _, _, _, wide, ok := label.window(scale, viewport); ok || !wide { + t.Errorf("runs %d: a line scrolled out of view has a window", len(runs)) + } + label.drop(nil, scale, true) + if label.needsUpload(scale, viewport) { + t.Errorf("runs %d: a dropped line out of view is rasterized again", len(runs)) + } + label.label.X = -20000 + if !label.needsUpload(scale, viewport) { + t.Errorf("runs %d: a dropped line scrolled back into view is not rasterized", len(runs)) + } + label.label.Height = 12000 // 18000 device pixels + if _, _, _, _, ok := label.window(scale, viewport); ok { + t.Errorf("runs %d: a line too tall for any texture has a window", len(runs)) + } + label.drop(nil, scale, false) + if label.needsUpload(scale, viewport) { + t.Errorf("runs %d: a dropped line too tall for any texture is rasterized again", len(runs)) + } + } +} diff --git a/internal/platform/vulkan/window_resize_bench_linux_test.go b/internal/platform/vulkan/window_resize_bench_linux_test.go new file mode 100644 index 000000000..37e134569 --- /dev/null +++ b/internal/platform/vulkan/window_resize_bench_linux_test.go @@ -0,0 +1,140 @@ +//go:build linux + +package vulkan + +import ( + "errors" + "fmt" + "slices" + "testing" + "time" + "unsafe" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/internal/render" + "github.com/vivaui/viva/internal/scene" +) + +// BenchmarkLiveResize is a window growing and shrinking a pixel at a time: text +// preparation, swapchain rebuild and present, on a surface that needs no window +// system. The extra metrics separate the driver's waits from the renderer's work. +func BenchmarkLiveResize(b *testing.B) { + for _, clipped := range []bool{false, true} { + b.Run(fmt.Sprintf("clipped=%t", clipped), func(b *testing.B) { + labels := make([]platform.TextLabel, 28) + for i := range labels { + value := fmt.Sprintf("row %02d: user@host /workspace/build ready", i) + if clipped { + value += " 0123456789 abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ" + } + labels[i] = platform.TextLabel{ + Value: value, X: 8, Y: float32(8 + i*16), Width: 624, Height: 16, + FontSize: 12, Mono: true, CellWidth: 7, + Color: platform.Color{Red: .9, Green: .9, Blue: .9, Alpha: 1}, + Runs: []gfx.TextRun{{Bytes: int32(len(value)), Cells: int32(len(value)), Color: gfx.RGB(230, 230, 230)}}, + } + } + renderer, err := New(Config{ + Surface: headlessSurfaceSource(b), Width: 640, Height: 480, Scale: 1, + Clear: platform.Color{Red: .08, Green: .08, Blue: .08, Alpha: 1}, Labels: labels, Rasterizer: newSolidRasterizer, + }) + if errors.Is(err, platform.ErrNoGraphics) { + b.Skipf("no Vulkan device: %v", err) + } + if err != nil { + b.Skipf("no headless Vulkan surface: %v", err) + } + defer renderer.Close() + var idleTime, createTime, destroyTime, submitTime, presentTime, acquireTime, fenceTime time.Duration + var creates int + idle := renderer.api.deviceWaitIdle + renderer.api.deviceWaitIdle = func(device uintptr) int32 { + start := time.Now() + result := idle(device) + idleTime += time.Since(start) + return result + } + create := renderer.api.createSwapchain + renderer.api.createSwapchain = func(device uintptr, info *vkSwapchainCreateInfo, allocator unsafe.Pointer, swapchain *uintptr) int32 { + start := time.Now() + result := create(device, info, allocator, swapchain) + createTime += time.Since(start) + creates++ + return result + } + destroy := renderer.api.destroySwapchain + renderer.api.destroySwapchain = func(device, swapchain uintptr, allocator unsafe.Pointer) { + start := time.Now() + destroy(device, swapchain, allocator) + destroyTime += time.Since(start) + } + submit := renderer.api.queueSubmit + renderer.api.queueSubmit = func(queue uintptr, count uint32, info *vkSubmitInfo, fence uintptr) int32 { + start := time.Now() + result := submit(queue, count, info, fence) + submitTime += time.Since(start) + return result + } + present := renderer.api.queuePresent + renderer.api.queuePresent = func(queue uintptr, info *vkPresentInfo) int32 { + start := time.Now() + result := present(queue, info) + presentTime += time.Since(start) + return result + } + acquire := renderer.api.acquireNextImage + renderer.api.acquireNextImage = func(device, swapchain uintptr, timeout uint64, semaphore, fence uintptr, image *uint32) int32 { + start := time.Now() + result := acquire(device, swapchain, timeout, semaphore, fence, image) + acquireTime += time.Since(start) + return result + } + wait := renderer.api.waitForFences + renderer.api.waitForFences = func(device uintptr, count uint32, fences *uintptr, all uint32, timeout uint64) int32 { + start := time.Now() + result := wait(device, count, fences, all, timeout) + fenceTime += time.Since(start) + return result + } + resize := func(width, height uint32) { + b.Helper() + for i := range labels { + labels[i].Width = float32(width) - 16 + } + frame := platform.Frame{ + TextLabels: labels, + Rectangles: []render.Rectangle{{Bounds: scene.Rect{Width: float32(width), Height: float32(height)}, Color: scene.Color{Red: .08, Green: .08, Blue: .08, Alpha: 1}}}, + Update: render.Update{Count: 1, Rebuild: true}, + } + if _, err := renderer.Stage(frame); err != nil { + b.Fatal(err) + } + if err := renderer.Resize(width, height); err != nil { + b.Fatal(err) + } + if err := renderer.Present(); err != nil { + b.Fatal(err) + } + } + resize(641, 481) + idleTime, createTime, destroyTime, submitTime, presentTime, acquireTime, fenceTime, creates = 0, 0, 0, 0, 0, 0, 0, 0 + samples := make([]time.Duration, b.N) + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + start := time.Now() + resize(640+uint32(i%32), 480+uint32(i%16)) + samples[i] = time.Since(start) + } + b.StopTimer() + slices.Sort(samples) + b.ReportMetric(float64(samples[(len(samples)*95-1)/100].Nanoseconds()), "p95-ns/op") + b.ReportMetric(float64(samples[len(samples)-1].Nanoseconds()), "max-ns/op") + for name, duration := range map[string]time.Duration{"idle": idleTime, "create": createTime, "destroy": destroyTime, "submit": submitTime, "present": presentTime, "acquire": acquireTime, "fence": fenceTime} { + b.ReportMetric(float64(duration.Nanoseconds())/float64(b.N), name+"-ns/op") + } + b.ReportMetric(float64(creates)/float64(b.N), "swapchains/op") + }) + } +} diff --git a/internal/platform/vulkan/xcb_test.go b/internal/platform/vulkan/xcb_test.go new file mode 100644 index 000000000..f4d5bbbc5 --- /dev/null +++ b/internal/platform/vulkan/xcb_test.go @@ -0,0 +1,125 @@ +//go:build linux && !android + +package vulkan + +import ( + "errors" + "os" + "testing" + "unsafe" + + "github.com/ebitengine/purego" + "github.com/vivaui/viva/internal/platform" +) + +// The renderer is made for any window system's surface; these tests give it a real +// one, an X window, with the few libxcb calls it takes to make one. Where there is +// no X display they use a headless surface, and skip where there is neither. + +const vkStructureXcbSurfaceCreateInfo = 1000005000 + +type vkXcbSurfaceCreateInfo struct { + SType uint32 + _ uint32 + Next uintptr + Flags uint32 + _ uint32 + Connection uintptr + Window uint32 + _ uint32 +} + +type xcbTestWindow struct { + connection uintptr + id uint32 + configure func(connection uintptr, window uint32, mask uint16, values *uint32) uint32 + flush func(connection uintptr) int32 + disconnect func(connection uintptr) +} + +// newXCBTestWindow opens a window of width x height, closed when the test ends. +func newXCBTestWindow(t testing.TB, width, height uint32) *xcbTestWindow { + t.Helper() + if os.Getenv("DISPLAY") == "" { + t.Skip("no X display") + } + library, err := purego.Dlopen("libxcb.so.1", purego.RTLD_NOW|purego.RTLD_LOCAL) + if err != nil { + t.Skipf("no libxcb: %v", err) + } + var ( + connect func(display uintptr, screen *int32) uintptr + connErr func(connection uintptr) int32 + getSetup func(connection uintptr) unsafe.Pointer + generateID func(connection uintptr) uint32 + create func(connection uintptr, depth uint8, window, parent uint32, x, y int16, width, height, border, class uint16, visual, mask uint32, values uintptr) uint32 + mapWindow func(connection uintptr, window uint32) uint32 + ) + window := &xcbTestWindow{} + purego.RegisterLibFunc(&connect, library, "xcb_connect") + purego.RegisterLibFunc(&connErr, library, "xcb_connection_has_error") + purego.RegisterLibFunc(&getSetup, library, "xcb_get_setup") + purego.RegisterLibFunc(&generateID, library, "xcb_generate_id") + purego.RegisterLibFunc(&create, library, "xcb_create_window") + purego.RegisterLibFunc(&mapWindow, library, "xcb_map_window") + purego.RegisterLibFunc(&window.configure, library, "xcb_configure_window") + purego.RegisterLibFunc(&window.flush, library, "xcb_flush") + purego.RegisterLibFunc(&window.disconnect, library, "xcb_disconnect") + var screen int32 + window.connection = connect(0, &screen) + if window.connection == 0 || connErr(window.connection) != 0 { + t.Skip("cannot connect to the X display") + } + t.Cleanup(func() { window.disconnect(window.connection) }) + // The first screen's root window sits after the setup's fixed 40 bytes, the vendor + // string padded to four and the eight-byte pixmap formats. + setup := getSetup(window.connection) + vendor := uint32(*(*uint16)(unsafe.Add(setup, 24))) + formats := uint32(*(*uint8)(unsafe.Add(setup, 29))) + root := *(*uint32)(unsafe.Add(setup, 40+int((vendor+3)&^3)+int(formats)*8)) + window.id = generateID(window.connection) + create(window.connection, 0, window.id, root, 0, 0, uint16(width), uint16(height), 0, 1, 0, 0, 0) + mapWindow(window.connection, window.id) + window.flush(window.connection) + return window +} + +// resize asks for a size and returns once the server has it, as the surface sees it. +func (window *xcbTestWindow) resize(width, height uint32) { + size := [2]uint32{width, height} + window.configure(window.connection, window.id, 0x4|0x8, &size[0]) + window.flush(window.connection) +} + +// xcbSurfaceSource makes the surface of the X window. +func xcbSurfaceSource(t testing.TB, window *xcbTestWindow) SurfaceSource { + t.Helper() + var create func(uintptr, *vkXcbSurfaceCreateInfo, unsafe.Pointer, *uintptr) int32 + if err := Bind(&create, "vkCreateXcbSurfaceKHR"); err != nil { + if errors.Is(err, platform.ErrNoGraphics) { + t.Skipf("no Vulkan device: %v", err) + } + t.Fatal(err) + } + return SurfaceSource{ + Extension: "VK_KHR_xcb_surface", + Create: func(instance uintptr) (uintptr, error) { + info := vkXcbSurfaceCreateInfo{SType: vkStructureXcbSurfaceCreateInfo, Connection: window.connection, Window: window.id} + var surface uintptr + if err := vkCheck(create(instance, &info, nil, &surface), "create XCB surface"); err != nil { + return 0, err + } + return surface, nil + }, + } +} + +func init() { + windowSystemSurface = func(t testing.TB, width, height uint32) (SurfaceSource, func(width, height uint32) bool) { + if os.Getenv("DISPLAY") == "" { + return headlessSurfaceSource(t), func(uint32, uint32) bool { return false } + } + window := newXCBTestWindow(t, width, height) + return xcbSurfaceSource(t, window), func(width, height uint32) bool { window.resize(width, height); return true } + } +} diff --git a/internal/platform/windowframe/windowframe.go b/internal/platform/windowframe/windowframe.go new file mode 100644 index 000000000..99c985b45 --- /dev/null +++ b/internal/platform/windowframe/windowframe.go @@ -0,0 +1,88 @@ +// Package windowframe is the geometry of the frame Viva draws around a window it +// draws the frame of: the margin that holds the shadow, the rounded corners of the +// content, and the grip that takes resize input. It is pure arithmetic in device +// pixels, shared by the renderers that draw it and the windows that place it. +package windowframe + +import "math" + +// A window the application draws the frame of (platform.WindowCustomTitlebar) +// has no frame from the window manager, so on a desktop that composites windows +// it also has no shadow and square corners, where the macOS and Windows windows +// have both. Viva draws them: the X window is larger than the content by a margin +// on every side, the margin is transparent except for a soft shadow, and the +// content's corners are rounded. The margin is announced to the window manager +// as _GTK_FRAME_EXTENTS, which is how it knows where the window really is: it +// places, snaps and maximizes the content, not the margin. +// +// Everything here is in device pixels unless it says logical. + +const ( + // MarginLogical is the margin around the content, which holds the shadow. + MarginLogical = 24 + // RadiusLogical is the radius of the content's corners. + RadiusLogical = 10 + // GripLogical is how much of the margin takes input: a press there + // resizes the window, the rest of the margin lets the pointer through to the + // window behind. + GripLogical = 8 + // frameShadow is the shadow's blur, offset down, and strength (logical). + ShadowBlur = 18 + ShadowOffset = 4 + ShadowAlpha = 0.38 +) + +// Margin is the margin in device pixels at a display scale. +func Margin(scale float32) uint32 { + return uint32(math.Round(float64(MarginLogical) * float64(max(scale, 1)))) +} + +// Box is a rectangle in device pixels. +type Box struct{ X, Y, Width, Height int32 } + +// ContentSize is the size of the content of a window of a total size with a +// margin on every side; a margin that leaves nothing leaves one pixel. +func ContentSize(total, margin uint32) uint32 { + if total <= 2*margin { + return 1 + } + return total - 2*margin +} + +// Content is the content rectangle of a window of width x height. +func Content(width, height, margin uint32) Box { + return Box{int32(margin), int32(margin), int32(ContentSize(width, margin)), int32(ContentSize(height, margin))} +} + +// Bands are the four strips of the margin, which the shadow is drawn in: +// top and bottom across the whole width, left and right between them. +func Bands(width, height, margin uint32) [4]Box { + m, w, h := int32(margin), int32(width), int32(height) + return [4]Box{ + {0, 0, w, m}, + {0, h - m, w, m}, + {0, m, m, h - 2*m}, + {w - m, m, m, h - 2*m}, + } +} + +// Corners are the squares at the four corners of the content that its +// rounded corners are cut in; each is a pixel larger than the radius so the +// edge of the cut is not clipped. +func Corners(width, height, margin uint32, radius float32) [4]Box { + side := int32(math.Ceil(float64(radius))) + 1 + c := Content(width, height, margin) + return [4]Box{ + {c.X, c.Y, side, side}, + {c.X + c.Width - side, c.Y, side, side}, + {c.X, c.Y + c.Height - side, side, side}, + {c.X + c.Width - side, c.Y + c.Height - side, side, side}, + } +} + +// Input is the part of the window that takes input: the content and a grip +// around it that is used to resize. +func Input(width, height, margin, grip uint32) Box { + reach := min(grip, margin) + return Box{int32(margin - reach), int32(margin - reach), int32(width - 2*(margin-reach)), int32(height - 2*(margin-reach))} +} diff --git a/internal/platform/linux/window_frame_test.go b/internal/platform/windowframe/windowframe_test.go similarity index 57% rename from internal/platform/linux/window_frame_test.go rename to internal/platform/windowframe/windowframe_test.go index 8bbd9a7d2..ae69a6631 100644 --- a/internal/platform/linux/window_frame_test.go +++ b/internal/platform/windowframe/windowframe_test.go @@ -1,4 +1,4 @@ -package linux +package windowframe import "testing" @@ -7,17 +7,17 @@ func TestFrameMarginKeepsWholePixelsAtEveryScale(t *testing.T) { scale float32 want uint32 }{{1, 24}, {1.25, 30}, {1.5, 36}, {2, 48}, {0.5, 24}} { - if got := frameMargin(test.scale); got != test.want { + if got := Margin(test.scale); got != test.want { t.Fatalf("margin at %gx = %d, want %d", test.scale, got, test.want) } } } func TestContentSizeLeavesAtLeastAPixel(t *testing.T) { - if got := contentSize(448, 24); got != 400 { + if got := ContentSize(448, 24); got != 400 { t.Fatalf("content = %d", got) } - if got := contentSize(40, 24); got != 1 { + if got := ContentSize(40, 24); got != 1 { t.Fatalf("a window smaller than its margins has content %d", got) } } @@ -25,17 +25,17 @@ func TestContentSizeLeavesAtLeastAPixel(t *testing.T) { func TestFrameBandsTileTheMarginExactly(t *testing.T) { const width, height, margin = 448, 348, 24 covered := make(map[[2]int32]int) - for _, band := range frameBands(width, height, margin) { - for y := band.y; y < band.y+band.height; y++ { - for x := band.x; x < band.x+band.width; x++ { + for _, band := range Bands(width, height, margin) { + for y := band.Y; y < band.Y+band.Height; y++ { + for x := band.X; x < band.X+band.Width; x++ { covered[[2]int32{x, y}]++ } } } - content := frameContent(width, height, margin) + content := Content(width, height, margin) for y := int32(0); y < height; y++ { for x := int32(0); x < width; x++ { - inside := x >= content.x && x < content.x+content.width && y >= content.y && y < content.y+content.height + inside := x >= content.X && x < content.X+content.Width && y >= content.Y && y < content.Y+content.Height count := covered[[2]int32{x, y}] if inside && count != 0 || !inside && count != 1 { t.Fatalf("pixel %d,%d is in %d bands, inside the content: %v", x, y, count, inside) @@ -46,23 +46,23 @@ func TestFrameBandsTileTheMarginExactly(t *testing.T) { func TestFrameCornersSitInsideTheContent(t *testing.T) { const width, height, margin = 448, 348, 24 - content := frameContent(width, height, margin) - for index, corner := range frameCorners(width, height, margin, 10) { - if corner.width != 11 || corner.height != 11 { - t.Fatalf("corner %d is %dx%d, want the radius and a pixel", index, corner.width, corner.height) + content := Content(width, height, margin) + for index, corner := range Corners(width, height, margin, 10) { + if corner.Width != 11 || corner.Height != 11 { + t.Fatalf("corner %d is %dx%d, want the radius and a pixel", index, corner.Width, corner.Height) } - if corner.x < content.x || corner.y < content.y || corner.x+corner.width > content.x+content.width || corner.y+corner.height > content.y+content.height { + if corner.X < content.X || corner.Y < content.Y || corner.X+corner.Width > content.X+content.Width || corner.Y+corner.Height > content.Y+content.Height { t.Fatalf("corner %d %+v is outside the content %+v", index, corner, content) } } } func TestFrameInputReachesOnlyAGripIntoTheMargin(t *testing.T) { - got := frameInput(448, 348, 24, 8) - if got != (pixelBox{16, 16, 416, 316}) { + got := Input(448, 348, 24, 8) + if got != (Box{16, 16, 416, 316}) { t.Fatalf("input = %+v", got) } - if got := frameInput(448, 348, 4, 8); got != (pixelBox{0, 0, 448, 348}) { + if got := Input(448, 348, 4, 8); got != (Box{0, 0, 448, 348}) { t.Fatalf("a margin smaller than the grip: %+v", got) } } diff --git a/internal/render/validate.go b/internal/render/validate.go new file mode 100644 index 000000000..008df193b --- /dev/null +++ b/internal/render/validate.go @@ -0,0 +1,46 @@ +package render + +import ( + "fmt" + "math" + + "github.com/vivaui/viva/internal/scene" +) + +// ValidateRectangles checks the shapes of a scene before a renderer takes them: no +// non-finite bounds, radius or color, and a triangle with a valid edge mask. +func ValidateRectangles(rectangles []Rectangle) error { + for index, rectangle := range rectangles { + bounds := rectangle.Bounds + if !finiteFloat(bounds.X) || !finiteFloat(bounds.Y) || !finiteFloat(bounds.Width) || !finiteFloat(bounds.Height) { + return fmt.Errorf("render: rectangle %d has non-finite bounds", index) + } + if !finiteFloat(rectangle.Radius) || rectangle.Radius < 0 { + return fmt.Errorf("render: rectangle %d has invalid radius %g", index, rectangle.Radius) + } + if !finiteFloat(rectangle.Color.Red) || !finiteFloat(rectangle.Color.Green) || !finiteFloat(rectangle.Color.Blue) || !finiteFloat(rectangle.Color.Alpha) { + return fmt.Errorf("render: rectangle %d has a non-finite color", index) + } + if rectangle.Kind == scene.KindShadow { + shadow := rectangle.Shadow + if !finiteFloat(shadow.OffsetX) || !finiteFloat(shadow.OffsetY) || !finiteFloat(shadow.Blur) || !finiteFloat(shadow.Spread) || shadow.Blur < 0 { + return fmt.Errorf("render: shadow %d has an invalid blur or offset", index) + } + } + if rectangle.Kind == scene.KindTriangle { + for pointIndex, point := range rectangle.Points { + if !finiteFloat(point.X) || !finiteFloat(point.Y) { + return fmt.Errorf("render: triangle %d point %d is non-finite", index, pointIndex) + } + } + if rectangle.EdgeMask > 7 { + return fmt.Errorf("render: triangle %d has invalid edge mask %d", index, rectangle.EdgeMask) + } + } + } + return nil +} + +func finiteFloat(value float32) bool { + return !math.IsNaN(float64(value)) && !math.IsInf(float64(value), 0) +} From 4472fc85bd62cf9909593d2dad19996cbe80a69d Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 22 Nov 2026 21:40:05 +0800 Subject: [PATCH 28/64] refactor(text): share the line engine between the browser and other platforms The browser's text engine is geometry over two measurements the platform gives: the width of a line and the extent of each grapheme cluster. It has no system call in it, so it moves to internal/lineengine, tested on the host, and the browser supplies its Canvas and DOM measurements as a Measurer. A platform whose system lays a line out for it, such as Android, supplies its own. The interface family and the font generation are process-wide there, as the native engines' are. --- ...s_unsupported.go => mobile_unsupported.go} | 0 .../lineengine.go => lineengine/engine.go} | 129 ++++++++++-------- .../engine_test.go} | 32 ++--- .../working_set_test.go} | 4 +- internal/platform/web/font_register_js.go | 4 +- internal/platform/web/measure.go | 5 +- .../platform/web/text_engine_export_js.go | 3 +- internal/platform/web/textengine_js.go | 6 +- internal/platform/web/textengine_js_test.go | 11 +- internal/platform/web/textmetrics.go | 2 +- internal/platform/web/web.go | 5 +- 11 files changed, 112 insertions(+), 89 deletions(-) rename app/{ios_unsupported.go => mobile_unsupported.go} (100%) rename internal/{platform/web/lineengine.go => lineengine/engine.go} (66%) rename internal/{platform/web/lineengine_test.go => lineengine/engine_test.go} (89%) rename internal/{platform/web/lineengine_working_set_test.go => lineengine/working_set_test.go} (94%) diff --git a/app/ios_unsupported.go b/app/mobile_unsupported.go similarity index 100% rename from app/ios_unsupported.go rename to app/mobile_unsupported.go diff --git a/internal/platform/web/lineengine.go b/internal/lineengine/engine.go similarity index 66% rename from internal/platform/web/lineengine.go rename to internal/lineengine/engine.go index a0f18112f..0a5dfa2b1 100644 --- a/internal/platform/web/lineengine.go +++ b/internal/lineengine/engine.go @@ -1,4 +1,9 @@ -package web +// Package lineengine is the text engine of a platform whose system lays a line out +// for it: it asks the platform for the width of a line and the extent of each of its +// grapheme clusters, and answers carets, selections and clicks from those, keeping +// every line it has measured. The platform is a Measurer; the geometry here has no +// system call in it, so it is tested on the host. +package lineengine import ( "github.com/vivaui/viva/gfx" @@ -17,31 +22,31 @@ import ( // This file has no JavaScript in it, so the geometry is tested on the host; domMeasurer // (measure_js.go) is the browser. -// lineMeasurer is the browser's text layout. -type lineMeasurer interface { - // width is the advance of value drawn in the font of size and weight, with rtl its +// Measurer is the browser's text layout. +type Measurer interface { + // Width is the advance of value drawn in the font of size and weight, with rtl its // paragraph direction. - width(value string, size, weight float32, rtl bool) float32 - // rects fills lefts[i] and rights[i] with the horizontal extent, from the left end + Width(value string, size, weight float32, rtl bool) float32 + // Rects fills lefts[i] and rights[i] with the horizontal extent, from the left end // of the line, of the UTF-16 range [bounds[i], bounds[i+1]) of value. - rects(value string, size, weight float32, rtl bool, bounds []int32, lefts, rights []float32) - // setInvalidate gives the measurer the function to call when measurements made so + Rects(value string, size, weight float32, rtl bool, bounds []int32, lefts, rights []float32) + // SetInvalidate gives the measurer the function to call when measurements made so // far may no longer hold (a font finished loading). - setInvalidate(invalidate func()) + SetInvalidate(invalidate func()) } -type styledLineMeasurer interface { - widthStyle(value string, size, weight float32, italic, rtl bool) float32 - rectsStyle(value string, size, weight float32, italic, rtl bool, bounds []int32, lefts, rights []float32) +type StyledMeasurer interface { + WidthStyle(value string, size, weight float32, italic, rtl bool) float32 + RectsStyle(value string, size, weight float32, italic, rtl bool, bounds []int32, lefts, rights []float32) } -type lineRasterizer interface { - rasterizeText(value string, style gfx.TextStyle, scale float32, width, height int) (gfx.Bitmap, error) +type Rasterizer interface { + RasterizeText(value string, style gfx.TextStyle, scale float32, width, height int) (gfx.Bitmap, error) } -// lineEngine implements gfx.TextEngine over a lineMeasurer. -type lineEngine struct { - measurer lineMeasurer +// Engine implements gfx.TextEngine over a lineMeasurer. +type Engine struct { + measurer Measurer lines *textcache.Cache[*measuredLine] italicLines *textcache.Cache[*measuredLine] resolver bidi.Resolver @@ -49,30 +54,42 @@ type lineEngine struct { generation uint32 } -// interfaceFamily is the CSS family named for proportional text, or "" for the -// browser's system stack. fontGeneration moves whenever the family changes or a -// registered font arrives, so every engine still holding shaped lines knows to -// forget them. +// interfaceFamily is the family named for proportional text, or "" for the +// platform's own interface font. fontGeneration moves whenever the family changes +// or a registered font arrives, so every engine still holding shaped lines knows +// to forget them. Both belong to the process, as the native engines' do. var interfaceFamily string var fontGeneration uint32 +// InterfaceFamily is the family named for proportional text, "" for the platform's +// own interface font. +func InterfaceFamily() string { return interfaceFamily } + +// FontsChanged says the platform's fonts changed (a registered font arrived): every +// engine forgets the lines it has shaped. +func FontsChanged() { fontGeneration++ } + // lineCacheLimit is the line limit of each cache segment (twice as many are kept). const lineCacheLimit = 512 -func newLineEngine(measurer lineMeasurer) *lineEngine { - engine := &lineEngine{measurer: measurer, lines: textcache.New[*measuredLine](lineCacheLimit, nil), generation: fontGeneration} - measurer.setInvalidate(func() { - engine.lines.Clear() - if engine.italicLines != nil { - engine.italicLines.Clear() - } - }) +func New(measurer Measurer) *Engine { + engine := &Engine{measurer: measurer, lines: textcache.New[*measuredLine](lineCacheLimit, nil), generation: fontGeneration} + measurer.SetInvalidate(engine.Forget) return engine } +// Forget drops every line the engine has measured, as the platform does when its +// measurements may no longer hold (a font finished loading). +func (engine *Engine) Forget() { + engine.lines.Clear() + if engine.italicLines != nil { + engine.italicLines.Clear() + } +} + // SetFontFamily implements gfx.FontFamilyAware. The family applies to every -// engine in the page, as the native engines apply theirs to the process. -func (engine *lineEngine) SetFontFamily(family string) { +// engine of the process, as the native engines apply theirs. +func (engine *Engine) SetFontFamily(family string) { if family == interfaceFamily { return } @@ -81,11 +98,11 @@ func (engine *lineEngine) SetFontFamily(family string) { } // FontGeneration implements gfx.FontFamilyAware. -func (engine *lineEngine) FontGeneration() uint32 { return fontGeneration } +func (engine *Engine) FontGeneration() uint32 { return fontGeneration } // syncGeneration drops shaped lines when the page's font state moved since // this engine last measured. -func (engine *lineEngine) syncGeneration() { +func (engine *Engine) syncGeneration() { if engine.generation == fontGeneration { return } @@ -96,12 +113,12 @@ func (engine *lineEngine) syncGeneration() { } } -func (engine *lineEngine) RasterizeText(value string, style gfx.TextStyle, scale float32, width, height int) (gfx.Bitmap, error) { - rasterizer, ok := engine.measurer.(lineRasterizer) +func (engine *Engine) RasterizeText(value string, style gfx.TextStyle, scale float32, width, height int) (gfx.Bitmap, error) { + rasterizer, ok := engine.measurer.(Rasterizer) if !ok { return gfx.Bitmap{}, gfx.ErrTextRasterizerUnavailable } - return rasterizer.rasterizeText(value, style, scale, width, height) + return rasterizer.RasterizeText(value, style, scale, width, height) } type measuredLine struct { @@ -120,11 +137,11 @@ type clusterRects struct { endsAtRTLEdge bool // the last cluster is right-to-left: the end of the line is its left edge } -func (engine *lineEngine) line(value string, size, weight float32) *measuredLine { +func (engine *Engine) line(value string, size, weight float32) *measuredLine { return engine.lineStyle(value, size, weight, false) } -func (engine *lineEngine) lineStyle(value string, size, weight float32, italic bool) *measuredLine { +func (engine *Engine) lineStyle(value string, size, weight float32, italic bool) *measuredLine { engine.syncGeneration() lines := engine.lines if italic { @@ -139,21 +156,21 @@ func (engine *lineEngine) lineStyle(value string, size, weight float32, italic b } rtl := bidi.BaseDirection(value) == bidi.RTL var width float32 - if styled, ok := engine.measurer.(styledLineMeasurer); ok && italic { - width = styled.widthStyle(value, size, weight, italic, rtl) + if styled, ok := engine.measurer.(StyledMeasurer); ok && italic { + width = styled.WidthStyle(value, size, weight, italic, rtl) } else { - width = engine.measurer.width(value, size, weight, rtl) + width = engine.measurer.Width(value, size, weight, rtl) } line := &measuredLine{width: width, rtl: rtl} lines.Put(key, line) return line } -func (engine *lineEngine) geometry(value string, size, weight float32, line *measuredLine) *clusterRects { +func (engine *Engine) geometry(value string, size, weight float32, line *measuredLine) *clusterRects { return engine.geometryStyle(value, size, weight, false, line) } -func (engine *lineEngine) geometryStyle(value string, size, weight float32, italic bool, line *measuredLine) *clusterRects { +func (engine *Engine) geometryStyle(value string, size, weight float32, italic bool, line *measuredLine) *clusterRects { engine.syncGeneration() if line.clusters != nil { return line.clusters @@ -180,10 +197,10 @@ func (engine *lineEngine) geometryStyle(value string, size, weight float32, ital } bounds[count] = units rects := &clusterRects{starts: starts, left: make([]float32, count), right: make([]float32, count), rtl: make([]bool, count)} - if styled, ok := engine.measurer.(styledLineMeasurer); ok && italic { - styled.rectsStyle(value, size, weight, italic, line.rtl, bounds, rects.left, rects.right) + if styled, ok := engine.measurer.(StyledMeasurer); ok && italic { + styled.RectsStyle(value, size, weight, italic, line.rtl, bounds, rects.left, rects.right) } else { - engine.measurer.rects(value, size, weight, line.rtl, bounds, rects.left, rects.right) + engine.measurer.Rects(value, size, weight, line.rtl, bounds, rects.left, rects.right) } direction := bidi.LTR @@ -241,11 +258,11 @@ func (rects *clusterRects) caret(cluster int) float32 { } // Width implements gfx.TextEngine. -func (engine *lineEngine) Width(value string, size, weight float32) float32 { +func (engine *Engine) Width(value string, size, weight float32) float32 { return engine.WidthStyle(value, size, weight, false) } -func (engine *lineEngine) WidthStyle(value string, size, weight float32, italic bool) float32 { +func (engine *Engine) WidthStyle(value string, size, weight float32, italic bool) float32 { if value == "" { return 0 } @@ -253,11 +270,11 @@ func (engine *lineEngine) WidthStyle(value string, size, weight float32, italic } // Caret implements gfx.TextEngine. -func (engine *lineEngine) Caret(value string, size, weight float32, offset int) float32 { +func (engine *Engine) Caret(value string, size, weight float32, offset int) float32 { return engine.CaretStyle(value, size, weight, false, offset) } -func (engine *lineEngine) CaretStyle(value string, size, weight float32, italic bool, offset int) float32 { +func (engine *Engine) CaretStyle(value string, size, weight float32, italic bool, offset int) float32 { if value == "" { return 0 } @@ -272,11 +289,11 @@ func (engine *lineEngine) CaretStyle(value string, size, weight float32, italic // Selection implements gfx.TextEngine. The clusters of [start, end) are joined where the // display puts them side by side, so a selection that crosses a change of direction is // several spans, left to right. -func (engine *lineEngine) Selection(dst []gfx.TextSpan, value string, size, weight float32, start, end int) []gfx.TextSpan { +func (engine *Engine) Selection(dst []gfx.TextSpan, value string, size, weight float32, start, end int) []gfx.TextSpan { return engine.SelectionStyle(dst, value, size, weight, false, start, end) } -func (engine *lineEngine) SelectionStyle(dst []gfx.TextSpan, value string, size, weight float32, italic bool, start, end int) []gfx.TextSpan { +func (engine *Engine) SelectionStyle(dst []gfx.TextSpan, value string, size, weight float32, italic bool, start, end int) []gfx.TextSpan { if value == "" { return dst } @@ -339,11 +356,11 @@ func abuts(a, b float32) bool { // OffsetAt implements gfx.TextEngine: the boundary whose caret is nearest x, the earlier // one when two are equally near. -func (engine *lineEngine) OffsetAt(value string, size, weight, x float32) int { +func (engine *Engine) OffsetAt(value string, size, weight, x float32) int { return engine.OffsetAtStyle(value, size, weight, false, x) } -func (engine *lineEngine) OffsetAtStyle(value string, size, weight float32, italic bool, x float32) int { +func (engine *Engine) OffsetAtStyle(value string, size, weight float32, italic bool, x float32) int { if value == "" { return 0 } @@ -361,5 +378,5 @@ func (engine *lineEngine) OffsetAtStyle(value string, size, weight float32, ital return int(rects.starts[best]) } -var _ gfx.TextEngine = (*lineEngine)(nil) -var _ gfx.StyledTextEngine = (*lineEngine)(nil) +var _ gfx.TextEngine = (*Engine)(nil) +var _ gfx.StyledTextEngine = (*Engine)(nil) diff --git a/internal/platform/web/lineengine_test.go b/internal/lineengine/engine_test.go similarity index 89% rename from internal/platform/web/lineengine_test.go rename to internal/lineengine/engine_test.go index e88e07cad..6a02ea8d3 100644 --- a/internal/platform/web/lineengine_test.go +++ b/internal/lineengine/engine_test.go @@ -1,4 +1,4 @@ -package web +package lineengine import ( "testing" @@ -17,7 +17,7 @@ type fakeBrowser struct { invalidate func() } -func (browser *fakeBrowser) setInvalidate(invalidate func()) { browser.invalidate = invalidate } +func (browser *fakeBrowser) SetInvalidate(invalidate func()) { browser.invalidate = invalidate } func advance(r rune, size float32) float32 { switch { @@ -31,7 +31,7 @@ func advance(r rune, size float32) float32 { return size * 0.5 } -func (browser *fakeBrowser) width(value string, size, weight float32, rtl bool) float32 { +func (browser *fakeBrowser) Width(value string, size, weight float32, rtl bool) float32 { browser.widths++ var total float32 for _, r := range value { @@ -74,7 +74,7 @@ func (browser *fakeBrowser) layout(value string, size float32) (starts []int32, return starts, left, right } -func (browser *fakeBrowser) rects(value string, size, weight float32, rtl bool, bounds []int32, lefts, rights []float32) { +func (browser *fakeBrowser) Rects(value string, size, weight float32, rtl bool, bounds []int32, lefts, rights []float32) { browser.rectCalls++ starts, left, right := browser.layout(value, size) for i := range lefts { @@ -89,16 +89,16 @@ func (browser *fakeBrowser) rects(value string, size, weight float32, rtl bool, type italicBrowser struct{ fakeBrowser } -func (browser *italicBrowser) widthStyle(value string, size, weight float32, italic, rtl bool) float32 { - width := browser.fakeBrowser.width(value, size, weight, rtl) +func (browser *italicBrowser) WidthStyle(value string, size, weight float32, italic, rtl bool) float32 { + width := browser.fakeBrowser.Width(value, size, weight, rtl) if italic { return width * 2 } return width } -func (browser *italicBrowser) rectsStyle(value string, size, weight float32, italic, rtl bool, bounds []int32, lefts, rights []float32) { - browser.fakeBrowser.rects(value, size, weight, rtl, bounds, lefts, rights) +func (browser *italicBrowser) RectsStyle(value string, size, weight float32, italic, rtl bool, bounds []int32, lefts, rights []float32) { + browser.fakeBrowser.Rects(value, size, weight, rtl, bounds, lefts, rights) if italic { for index := range lefts { lefts[index] *= 2 @@ -109,7 +109,7 @@ func (browser *italicBrowser) rectsStyle(value string, size, weight float32, ita func TestItalicBrowserMetricsAndCacheStaySeparate(t *testing.T) { browser := &italicBrowser{} - engine := newLineEngine(browser) + engine := New(browser) if regular, italic := engine.Width("abcd", 10, 0), engine.WidthStyle("abcd", 10, 0, true); regular != 20 || italic != 40 { t.Fatalf("regular/italic width = %v/%v", regular, italic) } @@ -131,13 +131,13 @@ func TestItalicBrowserMetricsAndCacheStaySeparate(t *testing.T) { } func TestLineEnginePassesTheTextEngineContract(t *testing.T) { - textenginetest.Run(t, newLineEngine(&fakeBrowser{})) + textenginetest.Run(t, New(&fakeBrowser{})) } // "abc" then two Hebrew letters: the Hebrew pair is displayed reversed, so the // selection of the last Hebrew letter and the "c" before it are two pieces, not one. func TestASelectionAcrossAChangeOfDirectionIsSeveralSpans(t *testing.T) { - engine := newLineEngine(&fakeBrowser{}) + engine := New(&fakeBrowser{}) const value = "abcאב" // widths at size 10: 5, 5, 5, 6, 6 whole := engine.Selection(nil, value, 10, 0, 0, len(value)) if len(whole) != 1 || whole[0].X != 0 || whole[0].Width != 27 { @@ -159,7 +159,7 @@ func TestASelectionAcrossAChangeOfDirectionIsSeveralSpans(t *testing.T) { } func TestAClusterIsOneCaretStop(t *testing.T) { - engine := newLineEngine(&fakeBrowser{}) + engine := New(&fakeBrowser{}) const value = "éx" // e with a combining acute, then x if got, want := engine.Caret(value, 10, 0, 1), engine.Caret(value, 10, 0, 0); got != want { t.Errorf("a caret inside a cluster is at %v, its start is %v", got, want) @@ -171,7 +171,7 @@ func TestAClusterIsOneCaretStop(t *testing.T) { func TestAMeasuredLineIsNotMeasuredAgainAndAnInvalidationForgetsIt(t *testing.T) { browser := &fakeBrowser{} - engine := newLineEngine(browser) + engine := New(browser) const value = "192.168.1.1 主机" dst := make([]gfx.TextSpan, 0, 4) query := func() { @@ -201,7 +201,7 @@ func TestAMeasuredLineIsNotMeasuredAgainAndAnInvalidationForgetsIt(t *testing.T) func TestUTF16OffsetsCountSurrogatePairs(t *testing.T) { var got []int32 browser := &recordingBrowser{fakeBrowser: &fakeBrowser{}, record: func(bounds []int32) { got = bounds }} - engine := newLineEngine(browser) + engine := New(browser) value := "a👍🏽b" // a, thumbs-up + skin tone modifier (one cluster, two surrogate pairs), b engine.Caret(value, 10, 0, 1) want := []int32{0, 1, 5, 6} @@ -223,7 +223,7 @@ type recordingBrowser struct { record func([]int32) } -func (browser *recordingBrowser) rects(value string, size, weight float32, rtl bool, bounds []int32, lefts, rights []float32) { +func (browser *recordingBrowser) Rects(value string, size, weight float32, rtl bool, bounds []int32, lefts, rights []float32) { browser.record(append([]int32(nil), bounds...)) - browser.fakeBrowser.rects(value, size, weight, rtl, bounds, lefts, rights) + browser.fakeBrowser.Rects(value, size, weight, rtl, bounds, lefts, rights) } diff --git a/internal/platform/web/lineengine_working_set_test.go b/internal/lineengine/working_set_test.go similarity index 94% rename from internal/platform/web/lineengine_working_set_test.go rename to internal/lineengine/working_set_test.go index 6026768bc..5d2ad3df4 100644 --- a/internal/platform/web/lineengine_working_set_test.go +++ b/internal/lineengine/working_set_test.go @@ -1,4 +1,4 @@ -package web +package lineengine import ( "fmt" @@ -7,7 +7,7 @@ import ( func TestDistinctLinesStayMeasuredUntilFontInvalidation(t *testing.T) { browser := &fakeBrowser{} - engine := newLineEngine(browser) + engine := New(browser) lines := make([]string, 2*lineCacheLimit) for index := range lines { lines[index] = fmt.Sprintf("host %04d", index) diff --git a/internal/platform/web/font_register_js.go b/internal/platform/web/font_register_js.go index f96bdd30f..8bd7622b9 100644 --- a/internal/platform/web/font_register_js.go +++ b/internal/platform/web/font_register_js.go @@ -8,6 +8,8 @@ import ( "strconv" "syscall/js" + "github.com/vivaui/viva/internal/lineengine" + "github.com/vivaui/viva/internal/fontname" ) @@ -128,7 +130,7 @@ func normalizedWeight(weight int) int { } func invalidateFonts() { - fontGeneration++ + lineengine.FontsChanged() for _, invalidate := range fontInvalidators { invalidate() } diff --git a/internal/platform/web/measure.go b/internal/platform/web/measure.go index 0d84a218b..86801e493 100644 --- a/internal/platform/web/measure.go +++ b/internal/platform/web/measure.go @@ -8,6 +8,7 @@ import ( "syscall/js" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/lineengine" ) func cssFont(fontSize, weight float32) string { @@ -29,8 +30,8 @@ func cssFontStyle(fontSize, weight float32, italic bool) string { slant = "italic " } family := "system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif" - if interfaceFamily != "" { - family = cssFamily(interfaceFamily) + ", " + family + if named := lineengine.InterfaceFamily(); named != "" { + family = cssFamily(named) + ", " + family } return fmt.Sprintf("%s%d %gpx %s", slant, cssWeight, fontSize, family) } diff --git a/internal/platform/web/text_engine_export_js.go b/internal/platform/web/text_engine_export_js.go index aa2fedd21..601cbb1af 100644 --- a/internal/platform/web/text_engine_export_js.go +++ b/internal/platform/web/text_engine_export_js.go @@ -6,6 +6,7 @@ import ( "syscall/js" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/lineengine" ) // NewTextEngine returns the browser's shaped-line engine over the page's @@ -15,5 +16,5 @@ func NewTextEngine() gfx.TextEngine { if document.Type() != js.TypeObject || document.IsNull() { return nil } - return newLineEngine(newDOMMeasurer(document)) + return lineengine.New(newDOMMeasurer(document)) } diff --git a/internal/platform/web/textengine_js.go b/internal/platform/web/textengine_js.go index bcda4d93c..25e7ef3f2 100644 --- a/internal/platform/web/textengine_js.go +++ b/internal/platform/web/textengine_js.go @@ -51,7 +51,7 @@ func newDOMMeasurer(document js.Value) *domMeasurer { return measurer } -func (measurer *domMeasurer) setInvalidate(invalidate func()) { measurer.invalidate = invalidate } +func (measurer *domMeasurer) SetInvalidate(invalidate func()) { measurer.invalidate = invalidate } func (measurer *domMeasurer) rasterizeText(value string, style gfx.TextStyle, scale float32, width, height int) (gfx.Bitmap, error) { if width <= 0 || height <= 0 || width > 16384 || height > 16384 || width*height > 16*1024*1024 || scale <= 0 { @@ -116,7 +116,7 @@ func (measurer *domMeasurer) setDirection(rtl bool) { measurer.rtl = rtl } -func (measurer *domMeasurer) width(value string, size, weight float32, rtl bool) float32 { +func (measurer *domMeasurer) Width(value string, size, weight float32, rtl bool) float32 { return measurer.widthStyle(value, size, weight, false, rtl) } @@ -151,7 +151,7 @@ func (measurer *domMeasurer) mountRuler() { measurer.span = measurer.document.Call("createRange") } -func (measurer *domMeasurer) rects(value string, size, weight float32, rtl bool, bounds []int32, lefts, rights []float32) { +func (measurer *domMeasurer) Rects(value string, size, weight float32, rtl bool, bounds []int32, lefts, rights []float32) { measurer.rectsStyle(value, size, weight, false, rtl, bounds, lefts, rights) } diff --git a/internal/platform/web/textengine_js_test.go b/internal/platform/web/textengine_js_test.go index f1ba0e2a1..8611bab9e 100644 --- a/internal/platform/web/textengine_js_test.go +++ b/internal/platform/web/textengine_js_test.go @@ -7,18 +7,19 @@ import ( "testing" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/lineengine" "github.com/vivaui/viva/internal/textenginetest" ) // browserEngine is the engine over the page's real document; the tests skip under Node, -// which has none (the geometry is tested on the host in lineengine_test.go). -func browserEngine(tb testing.TB) *lineEngine { +// which has none (the geometry is tested on the host in internal/lineengine). +func browserEngine(tb testing.TB) *lineengine.Engine { tb.Helper() document := js.Global().Get("document") if !document.Truthy() { tb.Skip("no document: run in a browser (see docs/conformance.md)") } - return newLineEngine(newDOMMeasurer(document)) + return lineengine.New(newDOMMeasurer(document)) } func TestBrowserEnginePassesTheTextEngineContract(t *testing.T) { @@ -54,7 +55,7 @@ func BenchmarkBrowserWidthMiss(b *testing.B) { b.ReportAllocs() b.ResetTimer() for i := 0; b.Loop(); i++ { - engine.lines.Clear() + engine.Forget() engine.Width(values[i%len(values)], 14, gfx.WeightRegular) } } @@ -63,7 +64,7 @@ func BenchmarkBrowserGeometryMiss(b *testing.B) { engine := browserEngine(b) b.ReportAllocs() for b.Loop() { - engine.lines.Clear() + engine.Forget() engine.Caret("192.168.1.1 主机 office affine", 14, gfx.WeightRegular, 10) } } diff --git a/internal/platform/web/textmetrics.go b/internal/platform/web/textmetrics.go index 530815385..5a639e211 100644 --- a/internal/platform/web/textmetrics.go +++ b/internal/platform/web/textmetrics.go @@ -66,7 +66,7 @@ func (metrics *textMetrics) width(value string, size, weight float32) float32 { if len(metrics.widths) >= maxCachedWidths { clear(metrics.widths) } - width := metrics.measurer.width(value, size, weight, false) + width := metrics.measurer.Width(value, size, weight, false) metrics.widths[key] = width return width } diff --git a/internal/platform/web/web.go b/internal/platform/web/web.go index 43601c3b4..b62053ed7 100644 --- a/internal/platform/web/web.go +++ b/internal/platform/web/web.go @@ -16,6 +16,7 @@ import ( "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/internal/input" + "github.com/vivaui/viva/internal/lineengine" "github.com/vivaui/viva/internal/platform" "github.com/vivaui/viva/internal/render" ) @@ -213,7 +214,7 @@ func (runtime *runtime) mount() { runtime.canvas = &gfx.Canvas{} } runtime.measurer = newDOMMeasurer(runtime.document) - runtime.canvas.SetTextEngine(newLineEngine(runtime.measurer)) + runtime.canvas.SetTextEngine(lineengine.New(runtime.measurer)) started := time.Now() runtime.canvas.SetClock(func() time.Duration { return time.Since(started) }) runtime.canvas.SetReduceMotion(runtime.window.Call("matchMedia", "(prefers-reduced-motion: reduce)").Get("matches").Bool()) @@ -221,7 +222,7 @@ func (runtime *runtime) mount() { runtime.fullscreen = fullscreenActive(runtime.document) // A font that loads late changes the baselines and widths as it does every line. clearLines := runtime.measurer.invalidate - runtime.measurer.setInvalidate(func() { + runtime.measurer.SetInvalidate(func() { clearLines() runtime.metrics.clear() }) From 7bae397d5654b11a63236783fb503bbe5ad656db Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 22 Nov 2026 22:07:24 +0800 Subject: [PATCH 29/64] feat(android): run an application in an Android process, drawn with Vulkan The program is a shared library that the host's Activity loads; the host owns the UI thread, the surface and the keyboard, and the program draws on the surface with the Vulkan renderer from a thread of its own, idle between the events the host queues. Java reaches Go through fixed JNI entry points, Go reaches the system's text drawing through a few static Java methods, and the program's main runs after the host starts it (go:linkname to main.main). Text is the shared line engine (moved from the browser backend to internal/lineengine) over Paint and Minikin, with labels drawn by Canvas. The renderer keeps its device, scene and label textures when the system takes the surface back and gives it again. viva build --target android writes a signed APK with the NDK's compiler, javac, d8, aapt2, zipalign and apksigner, with no Gradle; viva run --target android installs it with adb and starts it. CI builds hello for both ABIs. GOOS=android satisfies linux, so the desktop Linux files carry !android and the !linux fallbacks include it. Desktop hello sizes: Linux +12,288 bytes, macOS +5,264, Windows unchanged. Not yet: input method, accessibility, insets API, device runs. --- .github/workflows/ci.yml | 16 + app/backend_android.go | 13 + app/backend_linux.go | 2 +- app/clipboard_html_linux.go | 2 +- app/desktop_settings_linux.go | 2 +- app/desktop_settings_other.go | 2 +- app/global_shortcut_linux.go | 2 + app/ios_unsupported.go | 9 + app/keepawake_linux.go | 2 +- app/mobile_unsupported.go | 14 +- app/platform_linux.go | 2 +- app/primary_selection_linux.go | 2 +- app/primary_selection_other.go | 2 +- app/proxy/native_linux.go | 2 +- app/scheme_linux.go | 2 +- app/system_android.go | 13 + app/system_ios.go | 13 + app/system_linux.go | 2 +- app/text_input_linux.go | 2 +- app/text_input_linux_test.go | 2 +- app/text_input_native.go | 2 +- app/window_controls_linux.go | 2 +- app/window_controls_linux_test.go | 2 +- app/window_controls_theme_default.go | 2 +- app/window_controls_viva.go | 2 +- app/window_size_native_test.go | 2 +- audio/output_linux_other.go | 2 +- cmd/viva/android.go | 583 ++++++++++++++++++ cmd/viva/android_test.go | 232 +++++++ cmd/viva/build.go | 39 +- cmd/viva/help.go | 15 +- cmd/viva/ios.go | 11 +- headless/render_linux.go | 2 +- headless/render_none.go | 2 +- internal/autostart/files.go | 2 +- internal/autostart/files_test.go | 2 +- internal/autostart/other.go | 2 +- internal/filewatch/watch_linux.go | 2 +- internal/filewatch/watch_other.go | 2 +- internal/ibus/fcitx_fixture_test.go | 2 +- internal/instance/claim_unix.go | 2 +- internal/instance/instance_unix_test.go | 2 +- internal/instance/owner_unix.go | 2 +- internal/platform/android/android.go | 509 +++++++++++++++ internal/platform/android/exports_android.go | 97 +++ internal/platform/android/hostsrc/embed.go | 12 + .../hostsrc/java/dev/viva/host/Host.java | 38 ++ .../hostsrc/java/dev/viva/host/Native.java | 37 ++ .../hostsrc/java/dev/viva/host/Text.java | 162 +++++ .../java/dev/viva/host/VivaActivity.java | 122 ++++ internal/platform/android/jni_android.c | 210 +++++++ internal/platform/android/jni_android.h | 28 + internal/platform/android/link_android.s | 3 + internal/platform/android/log_android.go | 28 + internal/platform/android/surface_android.go | 54 ++ internal/platform/android/text_android.go | 304 +++++++++ internal/platform/android/touch_android.go | 120 ++++ .../platform/linux/always_on_top_linux.go | 2 +- .../linux/always_on_top_linux_test.go | 2 +- internal/platform/linux/api_linux_test.go | 2 + .../platform/linux/atspi_host_linux_test.go | 2 + internal/platform/linux/atspi_linux.go | 2 + .../platform/linux/atspi_native_linux_test.go | 2 + .../linux/atspi_resize_native_linux_test.go | 2 + .../linux/clipboard_files_linux_test.go | 2 + .../linux/clipboard_files_write_linux.go | 2 + .../linux/clipboard_html_linux_test.go | 2 + .../linux/clipboard_html_write_linux.go | 2 + .../linux/clipboard_image_linux_test.go | 2 + .../linux/clipboard_image_write_linux.go | 2 + .../linux/clipboard_image_write_linux_test.go | 2 + internal/platform/linux/cpu_lcd_linux_test.go | 2 + .../platform/linux/cpu_offscreen_linux.go | 2 + .../linux/cpu_offscreen_linux_test.go | 2 + internal/platform/linux/cpu_window_linux.go | 2 + .../platform/linux/cpu_window_linux_test.go | 2 + .../linux/cpu_window_live_linux_test.go | 2 + internal/platform/linux/cursor_image_linux.go | 2 + .../platform/linux/cursor_image_linux_test.go | 2 + internal/platform/linux/cursor_linux.go | 2 + internal/platform/linux/desktop_bus_linux.go | 2 + .../linux/desktop_fonts_linux_test.go | 2 + .../platform/linux/desktop_live_linux_test.go | 2 + .../linux/desktop_retry_linux_test.go | 2 +- .../platform/linux/desktop_services_linux.go | 2 + internal/platform/linux/dock_badge_linux.go | 2 +- .../platform/linux/dock_progress_linux.go | 2 +- .../linux/dock_progress_linux_test.go | 2 +- internal/platform/linux/drag_linux.go | 2 +- internal/platform/linux/drop_linux.go | 2 +- internal/platform/linux/drop_linux_test.go | 2 +- .../platform/linux/engine_fake_linux_test.go | 2 + .../platform/linux/fidelity_linux_test.go | 2 + .../platform/linux/font_register_linux.go | 2 +- .../platform/linux/font_settings_linux.go | 2 + .../linux/font_settings_linux_test.go | 2 + internal/platform/linux/fonts_linux.go | 2 + .../linux/fractional_scale_linux_test.go | 2 + internal/platform/linux/fullscreen_linux.go | 2 +- .../platform/linux/fullscreen_linux_test.go | 2 + .../platform/linux/global_shortcut_linux.go | 2 + .../linux/global_shortcut_linux_test.go | 2 + .../linux/image_shading_linux_test.go | 2 +- .../platform/linux/ime_bench_linux_test.go | 2 + .../platform/linux/ime_composition_linux.go | 2 + internal/platform/linux/ime_daemon_linux.go | 2 + .../platform/linux/ime_daemon_linux_test.go | 2 + internal/platform/linux/ime_linux.go | 2 + internal/platform/linux/ime_linux_test.go | 2 + .../platform/linux/ime_native_linux_test.go | 2 + .../linux/ime_retirement_linux_test.go | 2 + .../linux/ime_tentative_linux_test.go | 2 + .../platform/linux/ink_overflow_linux_test.go | 2 + internal/platform/linux/input_linux.go | 2 + internal/platform/linux/input_linux_test.go | 2 + .../linux/interface_font_linux_test.go | 2 + .../platform/linux/ligature_linux_test.go | 2 +- internal/platform/linux/memfd_linux_amd64.go | 2 + internal/platform/linux/memfd_linux_arm64.go | 2 + .../platform/linux/mono_family_linux_test.go | 2 + internal/platform/linux/offscreen_linux.go | 2 + .../platform/linux/offscreen_linux_test.go | 2 +- .../platform/linux/open_in_browser_linux.go | 2 + internal/platform/linux/open_with_linux.go | 2 +- .../platform/linux/open_with_linux_test.go | 2 +- internal/platform/linux/placement_linux.go | 2 + internal/platform/linux/post_linux.go | 2 +- internal/platform/linux/post_linux_test.go | 2 +- .../linux/raster_parity_linux_test.go | 2 + .../linux/rasterize_bench_linux_test.go | 2 + internal/platform/linux/reveal_path_linux.go | 2 +- .../platform/linux/reveal_path_linux_test.go | 2 +- internal/platform/linux/scale_x11_linux.go | 2 + internal/platform/linux/scheme_linux.go | 2 +- internal/platform/linux/scheme_linux_test.go | 2 +- internal/platform/linux/secret_linux.go | 2 + internal/platform/linux/selection_linux.go | 2 + .../platform/linux/selection_linux_test.go | 2 + .../linux/selection_live_linux_test.go | 2 + .../platform/linux/shared_api_linux_test.go | 2 + .../platform/linux/sharpness_linux_test.go | 2 + internal/platform/linux/shell_hooks_linux.go | 2 + internal/platform/linux/sleep_linux.go | 2 +- internal/platform/linux/sleep_linux_test.go | 2 +- internal/platform/linux/soft_scene_linux.go | 2 + .../platform/linux/soft_scene_linux_test.go | 2 + internal/platform/linux/status_item_linux.go | 2 + .../platform/linux/status_item_linux_test.go | 2 + .../status_item_registration_linux_test.go | 2 + internal/platform/linux/system_linux.go | 2 + internal/platform/linux/system_linux_test.go | 2 + .../linux/text_callback_linux_test.go | 2 + internal/platform/linux/text_engine_linux.go | 2 + .../platform/linux/text_engine_linux_test.go | 2 + .../linux/text_engine_scale_linux_test.go | 2 + internal/platform/linux/text_ink_linux.go | 2 + internal/platform/linux/text_input_linux.go | 2 + .../platform/linux/text_input_linux_test.go | 2 + internal/platform/linux/text_linux.go | 2 + internal/platform/linux/text_linux_test.go | 2 + .../platform/linux/text_resize_linux_test.go | 2 +- .../platform/linux/vulkan_window_linux.go | 2 + .../platform/linux/wide_label_linux_test.go | 2 + .../linux/window_activation_linux_test.go | 2 + .../platform/linux/window_close_linux_test.go | 2 +- .../platform/linux/window_controls_linux.go | 2 + .../linux/window_controls_linux_test.go | 2 + .../platform/linux/window_frame_linux_test.go | 2 +- internal/platform/linux/window_icon_linux.go | 2 + .../platform/linux/window_icon_linux_test.go | 2 + .../linux/window_icon_update_linux_test.go | 2 + .../platform/linux/window_identity_linux.go | 2 + internal/platform/linux/window_linux.go | 2 + .../platform/linux/window_margin_linux.go | 2 + .../platform/linux/window_minimum_linux.go | 2 + .../linux/window_minimum_linux_test.go | 2 + .../linux/window_motion_linux_test.go | 2 + .../linux/window_notification_linux_test.go | 2 + .../platform/linux/window_preview_linux.go | 2 + .../linux/window_preview_linux_test.go | 2 + .../linux/window_protocols_linux_test.go | 2 +- .../linux/window_readahead_linux_test.go | 2 + .../linux/window_renderer_fake_linux_test.go | 2 +- .../platform/linux/window_renderer_linux.go | 2 + .../linux/window_resize_bench_linux_test.go | 2 +- .../linux/window_resize_linux_test.go | 2 +- internal/platform/linux/window_size_linux.go | 2 + .../platform/linux/window_size_linux_test.go | 2 + internal/platform/linux/window_sync_linux.go | 2 + .../linux/window_sync_resize_linux_test.go | 2 +- internal/platform/linux/window_title_linux.go | 2 + .../platform/linux/window_title_linux_test.go | 2 + internal/platform/linux/wm_class_linux.go | 2 + .../platform/linux/wm_class_linux_test.go | 2 + internal/platform/linux/xcb_linux.go | 2 + internal/platform/vulkan/api_vulkan_test.go | 116 ---- .../vulkan/driver_desktop_linux_test.go | 126 ++++ .../vulkan/surface_lifecycle_linux.go | 57 ++ tools/visualparity/measure_linux.go | 2 +- update/install_linux.go | 2 +- update/install_linux_test.go | 2 +- update/payload_linux.go | 2 +- 202 files changed, 3125 insertions(+), 204 deletions(-) create mode 100644 app/backend_android.go create mode 100644 app/ios_unsupported.go create mode 100644 app/system_android.go create mode 100644 app/system_ios.go create mode 100644 cmd/viva/android.go create mode 100644 cmd/viva/android_test.go create mode 100644 internal/platform/android/android.go create mode 100644 internal/platform/android/exports_android.go create mode 100644 internal/platform/android/hostsrc/embed.go create mode 100644 internal/platform/android/hostsrc/java/dev/viva/host/Host.java create mode 100644 internal/platform/android/hostsrc/java/dev/viva/host/Native.java create mode 100644 internal/platform/android/hostsrc/java/dev/viva/host/Text.java create mode 100644 internal/platform/android/hostsrc/java/dev/viva/host/VivaActivity.java create mode 100644 internal/platform/android/jni_android.c create mode 100644 internal/platform/android/jni_android.h create mode 100644 internal/platform/android/link_android.s create mode 100644 internal/platform/android/log_android.go create mode 100644 internal/platform/android/surface_android.go create mode 100644 internal/platform/android/text_android.go create mode 100644 internal/platform/android/touch_android.go create mode 100644 internal/platform/vulkan/driver_desktop_linux_test.go create mode 100644 internal/platform/vulkan/surface_lifecycle_linux.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b3647a3b1..4845f836e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -154,6 +154,16 @@ jobs: wait "$pid" || status=1 done exit "$status" + # The Android build is the real thing: the program as a shared library with + # the NDK's compiler, the host's Java, and an APK around them with the SDK's + # tools, all of which the runner's image has. It is not run here; the + # runner has no device. + - name: Android build + run: | + export ANDROID_HOME="${ANDROID_HOME:-/usr/local/lib/android/sdk}" + export ANDROID_NDK_HOME="${ANDROID_NDK_HOME:-$(ls -d "$ANDROID_HOME"/ndk/* | sort -V | tail -1)}" + go run ./cmd/viva build --target android ./examples/guides/hello + go run ./cmd/viva build --target android --arch amd64 ./examples/guides/hello - name: Native Linux text rasterization run: | sudo apt-get install -y libpangocairo-1.0-0 fonts-noto-color-emoji || @@ -340,6 +350,12 @@ jobs: VIVA_NATIVE_GLOBAL_SHORTCUT_TEST: '1' run: go test ./internal/platform/darwin -run '^TestNativeCarbonGlobalShortcut$' -count=1 -v + # The iOS build compiles the Metal and UIKit bridge against the simulator + # SDK; it is not run here, since the runner cannot show a simulator. + - name: iOS simulator build + run: go run ./cmd/viva build --target ios-sim ./examples/guides/hello + + windows-materials: needs: changes diff --git a/app/backend_android.go b/app/backend_android.go new file mode 100644 index 000000000..79a40cb14 --- /dev/null +++ b/app/backend_android.go @@ -0,0 +1,13 @@ +//go:build android + +package app + +import ( + "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/internal/platform/android" +) + +func runNative(config platform.Config) error { return android.Run(config) } +func runNativeApplication(start platform.ApplicationStart) error { + return android.RunApplication(start) +} diff --git a/app/backend_linux.go b/app/backend_linux.go index a10f92556..a1142b9be 100644 --- a/app/backend_linux.go +++ b/app/backend_linux.go @@ -1,4 +1,4 @@ -//go:build linux && !vivagtk +//go:build linux && !vivagtk && !android package app diff --git a/app/clipboard_html_linux.go b/app/clipboard_html_linux.go index b3e171b0f..58e14b784 100644 --- a/app/clipboard_html_linux.go +++ b/app/clipboard_html_linux.go @@ -1,4 +1,4 @@ -//go:build linux +//go:build linux && !android package app diff --git a/app/desktop_settings_linux.go b/app/desktop_settings_linux.go index 13c8cb6b3..b0972d9ed 100644 --- a/app/desktop_settings_linux.go +++ b/app/desktop_settings_linux.go @@ -1,4 +1,4 @@ -//go:build linux +//go:build linux && !android package app diff --git a/app/desktop_settings_other.go b/app/desktop_settings_other.go index 09bf1334f..65ee5a562 100644 --- a/app/desktop_settings_other.go +++ b/app/desktop_settings_other.go @@ -1,4 +1,4 @@ -//go:build !linux +//go:build !linux || android package app diff --git a/app/global_shortcut_linux.go b/app/global_shortcut_linux.go index bf703dd7c..a198d9a3d 100644 --- a/app/global_shortcut_linux.go +++ b/app/global_shortcut_linux.go @@ -1,3 +1,5 @@ +//go:build !android + package app import ( diff --git a/app/ios_unsupported.go b/app/ios_unsupported.go new file mode 100644 index 000000000..6356e3dd1 --- /dev/null +++ b/app/ios_unsupported.go @@ -0,0 +1,9 @@ +//go:build ios + +package app + +// What a phone has no use for, and Android answers with its common fallbacks: +// an iPhone has no file icons for the application to ask for, and no reopening. + +func nativeFileIcon(string, int) ([]byte, error) { return nil, ErrUnsupported } +func setReopenHandler(*Config, *Window) {} diff --git a/app/keepawake_linux.go b/app/keepawake_linux.go index 5a9f30883..cb1785300 100644 --- a/app/keepawake_linux.go +++ b/app/keepawake_linux.go @@ -1,4 +1,4 @@ -//go:build linux +//go:build linux && !android package app diff --git a/app/mobile_unsupported.go b/app/mobile_unsupported.go index 26c7ad12c..c6c4be1c2 100644 --- a/app/mobile_unsupported.go +++ b/app/mobile_unsupported.go @@ -1,4 +1,4 @@ -//go:build ios +//go:build ios || android package app @@ -9,15 +9,14 @@ import ( "github.com/vivaui/viva/gfx" ) -// Until the iOS backend provides them (ADR 0095), the platform's native hooks -// report that the system does not offer them: what a window and a UIKit host -// give, such as the clipboard, the cursor, dialogs and notifications, is added -// here one by one, and each moves out of this file as it lands. +// Until the iOS and Android backends provide them (ADR 0095), the platforms' native +// hooks report that the system does not offer them: what a window and a host give, +// such as the clipboard, the cursor, dialogs and notifications, is added one by +// one, and each moves out of this file into the platform's own as it lands. func currentPlatform() Platform { return PlatformUnknown } func nativeReduceMotion() bool { return false } -func nativeTextEngine() gfx.TextEngine { return nil } func nativePreferredLanguages() []string { return languagesFromEnvironment(os.Getenv) } func nativeClipboardText() (string, error) { return "", ErrUnsupported } func nativeSetClipboardText(string) error { return ErrUnsupported } @@ -59,15 +58,12 @@ func nativeStartFileDrag([]string, FileDragEffect) (FileDragEffect, error) { return FileDragNone, ErrUnsupported } -func nativeFileIcon(string, int) ([]byte, error) { return nil, ErrUnsupported } func nativeRegisterGlobalShortcut(GlobalShortcut, func()) (func(), error) { return nil, ErrUnsupported } func nativePreventSleep(string) (func(), error) { return nil, ErrSleepPreventionUnavailable } func nativeSchemeHandlerAvailable(string) (bool, error) { return false, ErrUnsupported } func nativeOpenInBrowser(string) error { return fmt.Errorf("%w: OpenPathInBrowser", ErrUnsupported) } func nativeOpenWith(_, _ string) error { return fmt.Errorf("%w: OpenWith", ErrUnsupported) } -func setReopenHandler(*Config, *Window) {} - // No window buttons: the system owns the window. const controlsDrawnByViva = false diff --git a/app/platform_linux.go b/app/platform_linux.go index 6b1158d98..3c1fb5391 100644 --- a/app/platform_linux.go +++ b/app/platform_linux.go @@ -1,4 +1,4 @@ -//go:build linux +//go:build linux && !android package app diff --git a/app/primary_selection_linux.go b/app/primary_selection_linux.go index 80378a00d..aeb59b0e1 100644 --- a/app/primary_selection_linux.go +++ b/app/primary_selection_linux.go @@ -1,4 +1,4 @@ -//go:build linux +//go:build linux && !android package app diff --git a/app/primary_selection_other.go b/app/primary_selection_other.go index 44246d383..db5a59481 100644 --- a/app/primary_selection_other.go +++ b/app/primary_selection_other.go @@ -1,4 +1,4 @@ -//go:build !linux +//go:build !linux || android package app diff --git a/app/proxy/native_linux.go b/app/proxy/native_linux.go index f4b0a3e86..6aef80d23 100644 --- a/app/proxy/native_linux.go +++ b/app/proxy/native_linux.go @@ -1,4 +1,4 @@ -//go:build linux +//go:build linux && !android package proxy diff --git a/app/scheme_linux.go b/app/scheme_linux.go index f04adfcac..a4bc88efe 100644 --- a/app/scheme_linux.go +++ b/app/scheme_linux.go @@ -1,4 +1,4 @@ -//go:build linux +//go:build linux && !android package app diff --git a/app/system_android.go b/app/system_android.go new file mode 100644 index 000000000..dd2a57a53 --- /dev/null +++ b/app/system_android.go @@ -0,0 +1,13 @@ +//go:build android + +package app + +import ( + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/platform/android" +) + +// What the system gives an Android application grows here as its backend lands; the +// rest is answered in mobile_unsupported.go. + +func nativeTextEngine() gfx.TextEngine { return android.TextEngine() } diff --git a/app/system_ios.go b/app/system_ios.go new file mode 100644 index 000000000..832b55605 --- /dev/null +++ b/app/system_ios.go @@ -0,0 +1,13 @@ +//go:build ios + +package app + +import ( + "github.com/vivaui/viva/gfx" + darwinplatform "github.com/vivaui/viva/internal/platform/darwin" +) + +// What the system gives an iPhone application grows here as its backend lands; the +// rest is answered in mobile_unsupported.go. + +func nativeTextEngine() gfx.TextEngine { return darwinplatform.SharedTextEngine() } diff --git a/app/system_linux.go b/app/system_linux.go index 8d0da1956..50c7eeb8b 100644 --- a/app/system_linux.go +++ b/app/system_linux.go @@ -1,4 +1,4 @@ -//go:build linux +//go:build linux && !android package app diff --git a/app/text_input_linux.go b/app/text_input_linux.go index 9f56e1d03..da386dc0f 100644 --- a/app/text_input_linux.go +++ b/app/text_input_linux.go @@ -1,4 +1,4 @@ -//go:build linux +//go:build linux && !android package app diff --git a/app/text_input_linux_test.go b/app/text_input_linux_test.go index 49798795c..38dffd121 100644 --- a/app/text_input_linux_test.go +++ b/app/text_input_linux_test.go @@ -1,4 +1,4 @@ -//go:build linux +//go:build linux && !android package app diff --git a/app/text_input_native.go b/app/text_input_native.go index 0c1a087da..882cd3919 100644 --- a/app/text_input_native.go +++ b/app/text_input_native.go @@ -1,4 +1,4 @@ -//go:build darwin || windows +//go:build darwin || windows || android package app diff --git a/app/window_controls_linux.go b/app/window_controls_linux.go index 19d640bd5..7b11db408 100644 --- a/app/window_controls_linux.go +++ b/app/window_controls_linux.go @@ -1,4 +1,4 @@ -//go:build linux +//go:build linux && !android package app diff --git a/app/window_controls_linux_test.go b/app/window_controls_linux_test.go index 81e2ce3ff..3fad357ff 100644 --- a/app/window_controls_linux_test.go +++ b/app/window_controls_linux_test.go @@ -1,4 +1,4 @@ -//go:build linux +//go:build linux && !android package app diff --git a/app/window_controls_theme_default.go b/app/window_controls_theme_default.go index 89aa9f732..4602a9498 100644 --- a/app/window_controls_theme_default.go +++ b/app/window_controls_theme_default.go @@ -1,4 +1,4 @@ -//go:build !linux +//go:build !linux || android package app diff --git a/app/window_controls_viva.go b/app/window_controls_viva.go index e8a1982c1..85baacae6 100644 --- a/app/window_controls_viva.go +++ b/app/window_controls_viva.go @@ -1,4 +1,4 @@ -//go:build windows || linux +//go:build (windows || linux) && !android package app diff --git a/app/window_size_native_test.go b/app/window_size_native_test.go index 3ec16584b..bcef2f8ca 100644 --- a/app/window_size_native_test.go +++ b/app/window_size_native_test.go @@ -1,4 +1,4 @@ -//go:build windows || linux +//go:build (windows || linux) && !android package app diff --git a/audio/output_linux_other.go b/audio/output_linux_other.go index 34855d5b2..a3c500d7b 100644 --- a/audio/output_linux_other.go +++ b/audio/output_linux_other.go @@ -1,4 +1,4 @@ -//go:build linux && !amd64 && !arm64 +//go:build linux && !amd64 && !arm64 && !android package audio diff --git a/cmd/viva/android.go b/cmd/viva/android.go new file mode 100644 index 000000000..421ac1d41 --- /dev/null +++ b/cmd/viva/android.go @@ -0,0 +1,583 @@ +package main + +import ( + "archive/zip" + "bytes" + "encoding/xml" + "errors" + "fmt" + "io" + "io/fs" + "os" + "os/exec" + "path" + "path/filepath" + "regexp" + "runtime" + "sort" + "strconv" + "strings" + "time" + + "github.com/vivaui/viva/internal/platform/android/hostsrc" + "github.com/vivaui/viva/tools/manifest" +) + +// An Android build is the program as a shared library (the Go toolchain with the +// NDK's C compiler, which purego and the JNI bridge need), the Java of the host +// (hostsrc) compiled with javac and d8, and an APK assembled from them with aapt2, +// zipalign and apksigner: the tools of the Android SDK and the JDK, with no Gradle. + +const ( + // androidMinSDK is the oldest Android an application runs on: 8.0, which has the + // Vulkan 1.1 and the text APIs the host uses. + androidMinSDK = 26 + // androidTargetSDK is the Android the application is built for. + androidTargetSDK = 35 + // androidActivity is the host's Activity, the launcher entry. + androidActivity = "dev.viva.host.VivaActivity" +) + +// isAndroid reports whether the plan builds an Android package. +func (plan buildPlan) isAndroid() bool { return plan.target == "android" } + +// androidABI is the name Android gives an architecture. +func androidABI(arch string) string { + if arch == "amd64" { + return "x86_64" + } + return "arm64-v8a" +} + +// androidSDK is where the Android tools are. +type androidSDK struct { + home string + ndk string + buildTools string + androidJar string + javac, java string + clangDir string + adb, emulator string +} + +// lookEnv is os.Getenv; tests replace it. +var lookEnv = os.Getenv + +// findAndroidSDK finds the SDK, the NDK and the JDK, and says what to install when +// one is missing. +func findAndroidSDK() (androidSDK, error) { + sdk := androidSDK{} + var candidates []string + for _, name := range []string{"ANDROID_HOME", "ANDROID_SDK_ROOT"} { + if value := lookEnv(name); value != "" { + candidates = append(candidates, value) + } + } + if home, err := os.UserHomeDir(); err == nil { + candidates = append(candidates, + filepath.Join(home, "Library", "Android", "sdk"), // macOS, Android Studio + filepath.Join(home, "Android", "Sdk"), // Linux, Android Studio + filepath.Join(home, "AppData", "Local", "Android", "Sdk")) + } + candidates = append(candidates, "/opt/homebrew/share/android-commandlinetools", "/usr/local/share/android-commandlinetools") + for _, candidate := range candidates { + if info, err := os.Stat(filepath.Join(candidate, "build-tools")); err == nil && info.IsDir() { + sdk.home = candidate + break + } + } + if sdk.home == "" { + return sdk, errors.New("the Android SDK was not found; install it with 'brew install --cask android-commandlinetools' " + + "(or Android Studio) and set ANDROID_HOME, then 'sdkmanager \"platform-tools\" \"platforms;android-35\" \"build-tools;35.0.0\" \"ndk;28.2.13676358\"'") + } + var err error + if sdk.buildTools, err = newestChild(filepath.Join(sdk.home, "build-tools"), func(name string) bool { + return fileExists(filepath.Join(sdk.home, "build-tools", name, executable("aapt2"))) + }); err != nil { + return sdk, fmt.Errorf("no Android build-tools in %s; run sdkmanager \"build-tools;35.0.0\"", sdk.home) + } + sdk.buildTools = filepath.Join(sdk.home, "build-tools", sdk.buildTools) + platform, err := newestPlatform(filepath.Join(sdk.home, "platforms")) + if err != nil { + return sdk, fmt.Errorf("no Android platform (android-%d or newer) in %s; run sdkmanager \"platforms;android-%d\"", androidMinSDK, sdk.home, androidTargetSDK) + } + sdk.androidJar = filepath.Join(sdk.home, "platforms", platform, "android.jar") + if ndk := lookEnv("ANDROID_NDK_HOME"); ndk != "" && fileExists(ndk) { + sdk.ndk = ndk + } else if name, err := newestChild(filepath.Join(sdk.home, "ndk"), func(string) bool { return true }); err == nil { + sdk.ndk = filepath.Join(sdk.home, "ndk", name) + } else { + return sdk, fmt.Errorf("no Android NDK in %s; run sdkmanager \"ndk;28.2.13676358\"", sdk.home) + } + prebuilt, err := fs.Glob(os.DirFS(sdk.ndk), "toolchains/llvm/prebuilt/*") + if err != nil || len(prebuilt) == 0 { + return sdk, fmt.Errorf("the NDK in %s has no LLVM toolchain", sdk.ndk) + } + sdk.clangDir = filepath.Join(sdk.ndk, filepath.FromSlash(prebuilt[0]), "bin") + if sdk.javac, err = findJava("javac"); err != nil { + return sdk, err + } + if sdk.java, err = findJava("java"); err != nil { + return sdk, err + } + sdk.adb = filepath.Join(sdk.home, "platform-tools", executable("adb")) + if !fileExists(sdk.adb) { + if found, err := exec.LookPath("adb"); err == nil { + sdk.adb = found + } + } + sdk.emulator = filepath.Join(sdk.home, "emulator", executable("emulator")) + return sdk, nil +} + +func executable(name string) string { + if runtime.GOOS == "windows" { + switch name { + case "aapt2", "adb", "emulator": + return name + ".exe" + case "zipalign": + return name + ".exe" + case "apksigner", "d8": + return name + ".bat" + } + } + return name +} + +func fileExists(name string) bool { + _, err := os.Stat(name) + return err == nil +} + +// newestChild is the child of dir with the highest version in its name that ok accepts. +func newestChild(dir string, ok func(string) bool) (string, error) { + entries, err := os.ReadDir(dir) + if err != nil { + return "", err + } + var names []string + for _, entry := range entries { + if entry.IsDir() && ok(entry.Name()) { + names = append(names, entry.Name()) + } + } + if len(names) == 0 { + return "", fmt.Errorf("nothing in %s", dir) + } + sort.Slice(names, func(i, j int) bool { return versionLess(versionNumbers(names[i]), versionNumbers(names[j])) }) + return names[len(names)-1], nil +} + +var digits = regexp.MustCompile(`\d+`) + +// versionNumbers are the numbers of a name such as 35.0.0 or android-35, in order. +func versionNumbers(name string) []int { + var numbers []int + for _, part := range digits.FindAllString(name, -1) { + number, _ := strconv.Atoi(part) + numbers = append(numbers, number) + } + return numbers +} + +// newestPlatform is the newest platforms/android-N with N at least the minimum SDK and +// an android.jar in it. +func newestPlatform(dir string) (string, error) { + return newestChild(dir, func(name string) bool { + numbers := versionNumbers(name) + return strings.HasPrefix(name, "android-") && len(numbers) > 0 && numbers[0] >= androidMinSDK && + fileExists(filepath.Join(dir, name, "android.jar")) + }) +} + +// findJava finds a JDK tool: under JAVA_HOME, else on the path. +func findJava(tool string) (string, error) { + if home := lookEnv("JAVA_HOME"); home != "" { + if candidate := filepath.Join(home, "bin", tool); fileExists(candidate) || fileExists(candidate+".exe") { + return candidate, nil + } + } + found, err := exec.LookPath(tool) + if err != nil { + return "", fmt.Errorf("%s was not found: install a JDK (17 or newer) and put it on the path or set JAVA_HOME", tool) + } + return found, nil +} + +// clang is the NDK's C compiler for an architecture and the minimum SDK. +func (sdk androidSDK) clang(arch string) string { + triple := "aarch64-linux-android" + if arch == "amd64" { + triple = "x86_64-linux-android" + } + name := fmt.Sprintf("%s%d-clang", triple, androidMinSDK) + if runtime.GOOS == "windows" { + name += ".cmd" + } + return filepath.Join(sdk.clangDir, name) +} + +// androidEnvironment is what go build needs for Android: cgo with the NDK's compiler. +func (plan buildPlan) androidEnvironment(environment []string) []string { + return append(environment, "CGO_ENABLED=1", "CC="+plan.sdk.clang(plan.arch)) +} + +// checkAndroid reports what a flag combination cannot build. +func checkAndroid(shared buildFlags) error { + if shared.cgo { + return errors.New("--cgo is for Linux and Windows; Android builds always use cgo") + } + return nil +} + +// androidPackageID is the application's identifier on a device. +func (plan buildPlan) androidPackageID() string { + if id := plan.manifest.App.ID; id != "" { + return id + } + return "dev.viva." + strings.ReplaceAll(manifest.Slug(plan.executable), "-", "_") +} + +// versionCode is the integer Android orders releases by: major, minor and patch in +// three digits each, so 1.2.3 is 1002003. A version it cannot read is 1. +func versionCode(version string) int { + numbers := versionNumbers(strings.SplitN(version, "-", 2)[0]) + if len(numbers) == 0 { + return 1 + } + code := 0 + for index := 0; index < 3; index++ { + part := 0 + if index < len(numbers) { + part = min(numbers[index], 999) + } + code = code*1000 + part + } + return max(code, 1) +} + +// androidManifest is AndroidManifest.xml: one activity, the host's, which the +// application's window is. +func androidManifest(id, name, version string) []byte { + var escaped bytes.Buffer + xml.EscapeText(&escaped, []byte(name)) + return []byte(` + + + + + + + + + + + + + + + +`) +} + +// addToAPK writes base (aapt2's package) to out with the dex file and the program's +// library added. The library is stored, not compressed, so the system maps it from the +// package, as zipalign -p then aligns it to a page. +func addToAPK(base, out string, dex []byte, library, abi string) error { + reader, err := zip.OpenReader(base) + if err != nil { + return err + } + defer reader.Close() + file, err := os.Create(out) + if err != nil { + return err + } + defer file.Close() + writer := zip.NewWriter(file) + for _, entry := range reader.File { + if err := writer.Copy(entry); err != nil { + return err + } + } + dexEntry, err := writer.Create("classes.dex") + if err != nil { + return err + } + if _, err := dexEntry.Write(dex); err != nil { + return err + } + libraryEntry, err := writer.CreateHeader(&zip.FileHeader{Name: path.Join("lib", abi, "libviva.so"), Method: zip.Store, Modified: time.Unix(0, 0)}) + if err != nil { + return err + } + source, err := os.Open(library) + if err != nil { + return err + } + defer source.Close() + if _, err := io.Copy(libraryEntry, source); err != nil { + return err + } + return writer.Close() +} + +// runCommand runs a tool and puts its output in the error when it fails. +func runCommand(dir string, name string, arguments ...string) error { + command := exec.Command(name, arguments...) + command.Dir = dir + var output bytes.Buffer + command.Stdout, command.Stderr = &output, &output + if err := command.Run(); err != nil { + return fmt.Errorf("%s: %w\n%s", filepath.Base(name), err, strings.TrimSpace(output.String())) + } + return nil +} + +// debugKeystore is the keystore a debug build is signed with: the one Android Studio +// makes, created when there is none. +func (sdk androidSDK) debugKeystore() (string, error) { + home, err := os.UserHomeDir() + if err != nil { + return "", err + } + keystore := filepath.Join(home, ".android", "debug.keystore") + if fileExists(keystore) { + return keystore, nil + } + if err := os.MkdirAll(filepath.Dir(keystore), 0o700); err != nil { + return "", err + } + keytool, err := findJava("keytool") + if err != nil { + return "", err + } + if err := runCommand("", keytool, "-genkeypair", "-keystore", keystore, "-storepass", "android", "-keypass", "android", + "-alias", "androiddebugkey", "-keyalg", "RSA", "-keysize", "2048", "-validity", "10000", + "-dname", "CN=Android Debug,O=Android,C=US"); err != nil { + return "", err + } + return keystore, nil +} + +// runAndroid builds the program into a library and the package around it. +func (plan buildPlan) runAndroid(errorOutput io.Writer) error { + sdk, err := findAndroidSDK() + if err != nil { + return err + } + plan.sdk = sdk + work, err := os.MkdirTemp("", "viva-android-") + if err != nil { + return err + } + defer os.RemoveAll(work) + abi := androidABI(plan.arch) + + library := filepath.Join(work, "lib", abi, "libviva.so") + if err := plan.buildLibrary(library, errorOutput); err != nil { + return err + } + + classes := filepath.Join(work, "classes") + sources, err := extractHost(work) + if err != nil { + return err + } + if err := os.MkdirAll(classes, 0o755); err != nil { + return err + } + arguments := append([]string{"-source", "8", "-target", "8", "-Xlint:-options", "-nowarn", "-classpath", sdk.androidJar, "-d", classes}, sources...) + if err := runCommand("", sdk.javac, arguments...); err != nil { + return err + } + var classFiles []string + filepath.WalkDir(classes, func(name string, entry fs.DirEntry, err error) error { + if err == nil && !entry.IsDir() && strings.HasSuffix(name, ".class") { + classFiles = append(classFiles, name) + } + return nil + }) + dexDir := filepath.Join(work, "dex") + if err := os.MkdirAll(dexDir, 0o755); err != nil { + return err + } + if err := runCommand("", filepath.Join(sdk.buildTools, executable("d8")), + append([]string{"--min-api", strconv.Itoa(androidMinSDK), "--lib", sdk.androidJar, "--output", dexDir}, classFiles...)...); err != nil { + return err + } + dex, err := os.ReadFile(filepath.Join(dexDir, "classes.dex")) + if err != nil { + return err + } + + name := plan.manifest.App.Name + if name == "" { + name = plan.executable + } + manifestFile := filepath.Join(work, "AndroidManifest.xml") + if err := os.WriteFile(manifestFile, androidManifest(plan.androidPackageID(), name, plan.manifest.App.Version), 0o644); err != nil { + return err + } + base := filepath.Join(work, "base.apk") + if err := runCommand("", filepath.Join(sdk.buildTools, executable("aapt2")), "link", "-o", base, "-I", sdk.androidJar, + "--manifest", manifestFile, "--min-sdk-version", strconv.Itoa(androidMinSDK), "--target-sdk-version", strconv.Itoa(androidTargetSDK)); err != nil { + return err + } + assembled := filepath.Join(work, "assembled.apk") + if err := addToAPK(base, assembled, dex, library, abi); err != nil { + return err + } + aligned := filepath.Join(work, "aligned.apk") + if err := runCommand("", filepath.Join(sdk.buildTools, executable("zipalign")), "-f", "-p", "4", assembled, aligned); err != nil { + return err + } + keystore, err := sdk.debugKeystore() + if err != nil { + return err + } + if err := os.MkdirAll(filepath.Dir(plan.out), 0o755); err != nil { + return err + } + os.Remove(plan.out) + return runCommand("", filepath.Join(sdk.buildTools, executable("apksigner")), "sign", "--ks", keystore, "--ks-pass", "pass:android", + "--key-pass", "pass:android", "--out", plan.out, aligned) +} + +// buildLibrary compiles the program as the library the host loads. +func (plan buildPlan) buildLibrary(output string, errorOutput io.Writer) error { + if err := os.MkdirAll(filepath.Dir(output), 0o755); err != nil { + return err + } + if err := requireGo(errorOutput); err != nil { + return err + } + arguments := []string{"build", "-trimpath", "-buildmode=c-shared", "-ldflags", plan.ldflags()} + if len(plan.tags) > 0 { + arguments = append(arguments, "-tags", strings.Join(plan.tags, ",")) + } + arguments = append(arguments, "-o", output, plan.pkg) + command := exec.Command("go", arguments...) + command.Dir = plan.manifest.Dir + command.Env = plan.environment(os.Environ()) + command.Stdout, command.Stderr = errorOutput, errorOutput + if err := command.Run(); err != nil { + if errors.Is(err, exec.ErrNotFound) { + return errors.New("the go tool was not found in PATH") + } + return fmt.Errorf("go build failed: %w", err) + } + return nil +} + +// extractHost writes the host's Java sources under dir and returns their paths. +func extractHost(dir string) ([]string, error) { + var sources []string + err := fs.WalkDir(hostsrc.Java, "java", func(name string, entry fs.DirEntry, err error) error { + if err != nil || entry.IsDir() { + return err + } + data, err := hostsrc.Java.ReadFile(name) + if err != nil { + return err + } + target := filepath.Join(dir, "host", filepath.FromSlash(strings.TrimPrefix(name, "java/"))) + if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil { + return err + } + sources = append(sources, target) + return os.WriteFile(target, data, 0o644) + }) + return sources, err +} + +// adbDevice is one entry of 'adb devices'. +type adbDevice struct { + Serial string + State string +} + +// parseADBDevices reads the output of 'adb devices'. +func parseADBDevices(output string) []adbDevice { + var devices []adbDevice + for _, line := range strings.Split(output, "\n") { + fields := strings.Fields(line) + if len(fields) == 2 && fields[0] != "List" && !strings.HasPrefix(fields[0], "*") { + devices = append(devices, adbDevice{Serial: fields[0], State: fields[1]}) + } + } + return devices +} + +// chooseDevice picks the device to run on: the one asked for by serial; otherwise the +// only one that is ready, or a real one before an emulator. +func chooseDevice(devices []adbDevice, requested string) (adbDevice, error) { + var ready []adbDevice + for _, device := range devices { + if device.State != "device" { + continue + } + if requested != "" { + if device.Serial == requested { + return device, nil + } + continue + } + ready = append(ready, device) + } + if requested != "" { + return adbDevice{}, fmt.Errorf("no device %q is ready; 'adb devices' lists them", requested) + } + if len(ready) == 0 { + return adbDevice{}, errors.New("no Android device is ready: connect a phone with USB debugging on, or start an emulator") + } + sort.SliceStable(ready, func(i, j int) bool { + return !strings.HasPrefix(ready[i].Serial, "emulator-") && strings.HasPrefix(ready[j].Serial, "emulator-") + }) + return ready[0], nil +} + +// adb runs the Android debug bridge; tests replace it. +var adb = func(sdk androidSDK, serial string, arguments ...string) (string, error) { + if serial != "" { + arguments = append([]string{"-s", serial}, arguments...) + } + command := exec.Command(sdk.adb, arguments...) + var stdout, stderr bytes.Buffer + command.Stdout, command.Stderr = &stdout, &stderr + if err := command.Run(); err != nil { + return stdout.String(), fmt.Errorf("adb %s: %w: %s", strings.Join(arguments, " "), err, strings.TrimSpace(stderr.String())) + } + return stdout.String(), nil +} + +// runOnAndroid installs the built package on a device and starts it. +func runOnAndroid(plan buildPlan, requested string, output io.Writer) error { + sdk, err := findAndroidSDK() + if err != nil { + return err + } + if !fileExists(sdk.adb) && filepath.Base(sdk.adb) == executable("adb") { + return fmt.Errorf("adb was not found in %s; run sdkmanager \"platform-tools\"", sdk.home) + } + listing, err := adb(sdk, "", "devices") + if err != nil { + return err + } + device, err := chooseDevice(parseADBDevices(listing), requested) + if err != nil { + return err + } + if _, err := adb(sdk, device.Serial, "install", "-r", plan.out); err != nil { + return err + } + id := plan.androidPackageID() + if _, err := adb(sdk, device.Serial, "shell", "am", "start", "-n", id+"/"+androidActivity); err != nil { + return err + } + fmt.Fprintf(output, "started %s on %s\n", id, device.Serial) + return nil +} diff --git a/cmd/viva/android_test.go b/cmd/viva/android_test.go new file mode 100644 index 000000000..16388b5aa --- /dev/null +++ b/cmd/viva/android_test.go @@ -0,0 +1,232 @@ +package main + +import ( + "archive/zip" + "encoding/xml" + "io" + "os" + "path/filepath" + "strings" + "testing" +) + +// Releases are ordered by a number: a later version is never a smaller one, and a +// version the tool cannot read still installs. +func TestVersionCodeOrdersReleases(t *testing.T) { + order := []string{"0.0.1", "0.1.0", "0.9.9", "1.0.0", "1.0.1", "1.2.0", "1.10.0", "2.0.0"} + last := 0 + for _, version := range order { + code := versionCode(version) + if code <= last { + t.Errorf("%s has code %d, not above %d", version, code, last) + } + last = code + } + if code := versionCode("1.2.3-beta.4"); code != versionCode("1.2.3") { + t.Errorf("a pre-release of 1.2.3 has code %d, 1.2.3 has %d", code, versionCode("1.2.3")) + } + if versionCode("") < 1 || versionCode("preview") < 1 { + t.Error("an unreadable version has no valid code") + } +} + +func TestAndroidManifestNamesTheApplicationAndTheHost(t *testing.T) { + data := androidManifest("dev.example.notes", "Notes & ", "2.0.1") + var parsed struct { + Package string `xml:"package,attr"` + VersionName string `xml:"versionName,attr"` + Application struct { + Label string `xml:"label,attr"` + Activity struct { + Name string `xml:"name,attr"` + } `xml:"activity"` + } `xml:"application"` + } + if err := xml.Unmarshal(data, &parsed); err != nil { + t.Fatalf("the manifest is not XML: %v\n%s", err, data) + } + if parsed.Package != "dev.example.notes" || parsed.VersionName != "2.0.1" { + t.Errorf("package %q version %q", parsed.Package, parsed.VersionName) + } + if parsed.Application.Label != "Notes & " { + t.Errorf("label %q lost its characters", parsed.Application.Label) + } + if parsed.Application.Activity.Name != androidActivity { + t.Errorf("the launcher activity is %q, want the host's", parsed.Application.Activity.Name) + } + if !strings.Contains(string(data), "android.hardware.vulkan") { + t.Error("the manifest does not ask for Vulkan, which the program draws with") + } +} + +// fakeSDK lays out the parts of an SDK the finder looks at. +func fakeSDK(t *testing.T) string { + t.Helper() + home := t.TempDir() + touch := func(parts ...string) { + path := filepath.Join(append([]string{home}, parts...)...) + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, nil, 0o755); err != nil { + t.Fatal(err) + } + } + for _, version := range []string{"9.0.0", "34.0.0", "35.0.0"} { + touch("build-tools", version, executable("aapt2")) + } + for _, platform := range []string{"android-9", "android-34", "android-35"} { + touch("platforms", platform, "android.jar") + } + os.MkdirAll(filepath.Join(home, "platforms", "android-36"), 0o755) // no jar: not a platform + for _, ndk := range []string{"27.1.0", "28.2.0"} { + os.MkdirAll(filepath.Join(home, "ndk", ndk, "toolchains", "llvm", "prebuilt", "host", "bin"), 0o755) + } + touch("platform-tools", executable("adb")) + jdk := t.TempDir() + touch2 := filepath.Join(jdk, "bin") + os.MkdirAll(touch2, 0o755) + for _, tool := range []string{"javac", "java"} { + os.WriteFile(filepath.Join(touch2, tool), nil, 0o755) + } + t.Setenv("JAVA_HOME", jdk) + t.Setenv("ANDROID_HOME", home) + t.Setenv("ANDROID_SDK_ROOT", "") + t.Setenv("ANDROID_NDK_HOME", "") + return home +} + +// The newest of what is installed is used, by version and not by name ("9" sorts +// after "35"), and a platform too old to run on, or without its jar, is not one. +func TestFindAndroidSDKTakesTheNewestOfEachTool(t *testing.T) { + home := fakeSDK(t) + sdk, err := findAndroidSDK() + if err != nil { + t.Fatal(err) + } + if filepath.Base(sdk.buildTools) != "35.0.0" { + t.Errorf("build-tools %s, want 35.0.0", sdk.buildTools) + } + if filepath.Base(filepath.Dir(sdk.androidJar)) != "android-35" { + t.Errorf("platform %s, want android-35", sdk.androidJar) + } + if filepath.Base(sdk.ndk) != "28.2.0" { + t.Errorf("ndk %s, want 28.2.0", sdk.ndk) + } + if !strings.HasPrefix(sdk.clangDir, home) || filepath.Base(sdk.clangDir) != "bin" { + t.Errorf("the NDK's compiler directory is %s", sdk.clangDir) + } +} + +func TestFindAndroidSDKSaysWhatToInstall(t *testing.T) { + t.Setenv("ANDROID_HOME", t.TempDir()) + t.Setenv("ANDROID_SDK_ROOT", "") + t.Setenv("HOME", t.TempDir()) + t.Setenv("USERPROFILE", t.TempDir()) + if _, err := findAndroidSDK(); err == nil { + t.Skip("this machine has an Android SDK in a default place") + } else if !strings.Contains(err.Error(), "sdkmanager") { + t.Errorf("the error does not say how to install the SDK: %v", err) + } +} + +func TestAndroidEnvironmentUsesTheNDKCompilerOfTheArchitecture(t *testing.T) { + sdk := androidSDK{clangDir: filepath.Join("ndk", "bin")} + for _, test := range []struct{ arch, triple string }{{"arm64", "aarch64-linux-android"}, {"amd64", "x86_64-linux-android"}} { + plan := buildPlan{target: "android", arch: test.arch, sdk: sdk} + goos, goarch := plan.goTarget() + if goos != "android" || goarch != test.arch { + t.Errorf("%s builds for %s/%s", test.arch, goos, goarch) + } + environment := plan.environment(nil) + if lastEnvironment(environment, "CGO_ENABLED") != "1" { + t.Errorf("%s: cgo is off", test.arch) + } + compiler := filepath.Base(lastEnvironment(environment, "CC")) + if !strings.HasPrefix(compiler, test.triple) || !strings.Contains(compiler, "26-clang") { + t.Errorf("%s: compiler %q", test.arch, compiler) + } + } + if checkAndroid(buildFlags{target: "android", cgo: true}) == nil { + t.Error("--cgo was accepted for Android, which always uses cgo") + } +} + +func TestAndroidOutputIsAnAPKOfItsOwn(t *testing.T) { + dir := fixture(t, notesTOML) + plan := buildPlan{manifest: loadPlan(t, dir, buildFlags{target: "linux"}, "").manifest, target: "android", arch: "arm64", executable: "notes"} + if err := plan.outputPath(""); err != nil { + t.Fatal(err) + } + if !strings.HasSuffix(plan.out, "notes-android.apk") { + t.Errorf("output %s", plan.out) + } +} + +func TestChooseDevicePrefersAPhoneToAnEmulator(t *testing.T) { + listing := "List of devices attached\nemulator-5554\tdevice\nR58M123ABC\tdevice\nR58M999XYZ\tunauthorized\n\n" + devices := parseADBDevices(listing) + if len(devices) != 3 { + t.Fatalf("parsed %v", devices) + } + chosen, err := chooseDevice(devices, "") + if err != nil || chosen.Serial != "R58M123ABC" { + t.Fatalf("chose %+v, %v; want the phone that is ready", chosen, err) + } + if chosen, err := chooseDevice(devices, "emulator-5554"); err != nil || chosen.Serial != "emulator-5554" { + t.Fatalf("--device chose %+v, %v", chosen, err) + } + if _, err := chooseDevice(devices, "R58M999XYZ"); err == nil { + t.Error("a device that has not been authorized was chosen") + } + if _, err := chooseDevice(parseADBDevices("List of devices attached\n"), ""); err == nil { + t.Error("no devices, and one was chosen") + } +} + +// The package keeps what aapt2 made, adds the program's library stored and not +// compressed (the system maps it from the package), and the dex. +func TestAddToAPKStoresTheLibraryAndKeepsTheBase(t *testing.T) { + dir := t.TempDir() + base := filepath.Join(dir, "base.apk") + file, err := os.Create(base) + if err != nil { + t.Fatal(err) + } + writer := zip.NewWriter(file) + entry, _ := writer.Create("AndroidManifest.xml") + entry.Write([]byte("manifest")) + writer.Close() + file.Close() + library := filepath.Join(dir, "libviva.so") + if err := os.WriteFile(library, []byte("library bytes"), 0o644); err != nil { + t.Fatal(err) + } + out := filepath.Join(dir, "out.apk") + if err := addToAPK(base, out, []byte("dex bytes"), library, "arm64-v8a"); err != nil { + t.Fatal(err) + } + reader, err := zip.OpenReader(out) + if err != nil { + t.Fatal(err) + } + defer reader.Close() + contents := map[string]string{} + methods := map[string]uint16{} + for _, entry := range reader.File { + opened, err := entry.Open() + if err != nil { + t.Fatal(err) + } + data, _ := io.ReadAll(opened) + opened.Close() + contents[entry.Name], methods[entry.Name] = string(data), entry.Method + } + if contents["AndroidManifest.xml"] != "manifest" || contents["classes.dex"] != "dex bytes" { + t.Errorf("package holds %v", contents) + } + const name = "lib/arm64-v8a/libviva.so" + if contents[name] != "library bytes" || methods[name] != zip.Store { + t.Errorf("library entry %q method %d, want it stored", contents[name], methods[name]) + } +} diff --git a/cmd/viva/build.go b/cmd/viva/build.go index 7642ca12a..4d135f20e 100644 --- a/cmd/viva/build.go +++ b/cmd/viva/build.go @@ -18,7 +18,7 @@ import ( const mebibyte = 1 << 20 var ( - buildTargets = []string{"darwin", "windows", "linux", "web", "ios-sim", "ios"} + buildTargets = []string{"darwin", "windows", "linux", "web", "ios-sim", "ios", "android"} buildArches = []string{"arm64", "amd64"} ) @@ -38,6 +38,8 @@ type buildPlan struct { cgo bool // toolchain is Xcode's compiler and SDK, found when an iOS build starts. toolchain iosToolchain + // sdk is the Android SDK, found when an Android build starts. + sdk androidSDK } // goTarget is the GOOS/GOARCH pair for a target. @@ -47,6 +49,8 @@ func (plan buildPlan) goTarget() (goos, goarch string) { return "js", "wasm" case "ios-sim", "ios": return "ios", plan.arch + case "android": + return "android", plan.arch } return plan.target, plan.arch } @@ -108,6 +112,8 @@ func (plan buildPlan) environment(base []string) []string { } case "ios-sim", "ios": return plan.iosEnvironment(environment, base) + case "android": + return plan.androidEnvironment(environment) case "linux", "windows": // These targets reach the system through purego and the standard // library's own system calls, not through cgo. Go turns cgo on by @@ -142,6 +148,9 @@ func (plan buildPlan) run(output string, errorOutput io.Writer) error { if plan.isIOS() { return plan.runIOS(errorOutput) } + if plan.isAndroid() { + return plan.runAndroid(errorOutput) + } if err := plan.build(output, errorOutput); err != nil { return err } @@ -183,7 +192,7 @@ type buildFlags struct { func (shared *buildFlags) register(flags *flag.FlagSet, defaultTarget string) { flags.StringVar(&shared.dir, "C", ".", "directory holding viva.toml and the Go module") flags.StringVar(&shared.dir, "dir", ".", "same as -C") - flags.StringVar(&shared.target, "target", defaultTarget, "darwin, windows, linux, web, ios-sim (the simulator) or ios (devices)") + flags.StringVar(&shared.target, "target", defaultTarget, "darwin, windows, linux, web, ios-sim (the simulator), ios (devices) or android") flags.StringVar(&shared.arch, "arch", runtime.GOARCH, "arm64 or amd64 (not used by web)") flags.StringVar(&shared.tags, "tags", "", "comma-separated build tags, added to [build] tags") flags.BoolVar(&shared.debug, "debug", false, "keep symbols and debug information (not the release size)") @@ -200,6 +209,11 @@ func newPlan(shared buildFlags, packageArgument string) (buildPlan, error) { return buildPlan{}, err } } + if shared.target == "android" { + if err := checkAndroid(shared); err != nil { + return buildPlan{}, err + } + } if shared.target != "web" && !contains(buildArches, shared.arch) { return buildPlan{}, fmt.Errorf("unknown architecture %q; use one of: %s", shared.arch, strings.Join(buildArches, ", ")) } @@ -281,6 +295,24 @@ func (plan *buildPlan) outputPath(requested string) error { return err } plan.out = filepath.Join(plan.manifest.Path(plan.manifest.Build.Out), "web") + case plan.isAndroid(): + name += "-android" + if plan.arch != "arm64" { + name += "-" + plan.arch + } + name += ".apk" + if requested != "" { + absolute, err := filepath.Abs(requested) + if err != nil { + return err + } + if info, statErr := os.Stat(absolute); statErr == nil && info.IsDir() { + absolute = filepath.Join(absolute, name) + } + plan.out = absolute + } else { + plan.out = filepath.Join(plan.manifest.Path(plan.manifest.Build.Out), name) + } case plan.isIOS(): name += "-" + plan.target + ".app" if requested != "" { @@ -382,6 +414,9 @@ func printBuildDetails(output io.Writer, plan buildPlan, size int64) { if plan.isIOS() { target += " (iOS " + iosMinSystem + " or later)" } + if plan.isAndroid() { + target += fmt.Sprintf(" (Android 8.0, API %d, or later)", androidMinSDK) + } if plan.target == "darwin" { target += " (macOS " + plan.manifest.Mac.MinSystem + " or later)" } diff --git a/cmd/viva/help.go b/cmd/viva/help.go index e97c53cd0..f29d513b8 100644 --- a/cmd/viva/help.go +++ b/cmd/viva/help.go @@ -32,16 +32,19 @@ func commands() []command { "provide the target C compiler and link flags, and check the resulting system dependencies.\n" + "Windows release builds use the GUI subsystem; with --debug they keep the console. --target ios-sim writes\n" + "an .app for the iOS simulator (macOS with Xcode; the Metal and UIKit bridge is built with cgo against\n" + - "the SDK); viva run builds, installs and starts it.", + "the SDK); viva run builds, installs and starts it. --target android writes an .apk (the program as a\n" + + "shared library, built with the NDK's compiler, around the host's Activity, put together with the Android\n" + + "SDK's tools and the JDK, with no Gradle), signed with the debug key.", run: func(arguments []string, output, errorOutput io.Writer) error { return runBuild(arguments, output, errorOutput) }}, {name: "run", usage: "run [flags] [package]", - summary: "Build the application and start it in the iOS simulator.", - detail: "Builds an .app for the simulator (--target ios-sim, the only target run takes), boots a simulator if none\n" + - "is running, installs the app and starts it. --device names the simulator or gives its identifier; without\n" + - "it, an iPhone already booted is used, else the newest iPhone the machine has. The Simulator window is\n" + - "shown unless -open=false. It needs macOS with Xcode. For the desktop, use viva dev.", + summary: "Build the application and start it in the iOS simulator or on an Android device.", + detail: "--target ios-sim builds an .app for the simulator, boots a simulator if none is running, installs the app and\n" + + "starts it. --device names the simulator or gives its identifier; without it, an iPhone already booted is used,\n" + + "else the newest iPhone the machine has. The Simulator window is shown unless -open=false. It needs macOS with\n" + + "Xcode. --target android builds an .apk, installs it with adb on the device that is ready (--device gives its\n" + + "serial; a phone before an emulator) and starts it. For the desktop, use viva dev.", run: func(arguments []string, output, errorOutput io.Writer) error { return runRun(arguments, output, errorOutput) }}, diff --git a/cmd/viva/ios.go b/cmd/viva/ios.go index 3890131a1..b41211aea 100644 --- a/cmd/viva/ios.go +++ b/cmd/viva/ios.go @@ -249,17 +249,17 @@ func runRun(arguments []string, output, errorOutput io.Writer) error { c, _ := findCommand("run") flags := flag.NewFlagSet("run", flag.ContinueOnError) var shared buildFlags - shared.register(flags, "ios-sim") + shared.register(flags, "") var device string open := true - flags.StringVar(&device, "device", "", "simulator name or identifier (default: a booted iPhone, else the newest one installed)") + flags.StringVar(&device, "device", "", "ios-sim: the simulator's name or identifier (default: a booted iPhone, else the newest one installed); android: the device's adb serial (default: the one that is ready)") flags.BoolVar(&open, "open", true, "show the Simulator window") positional, helped, err := parseFlags(c, flags, arguments, output) if helped || err != nil { return err } - if shared.target != "ios-sim" { - return fmt.Errorf("run starts an application in the iOS simulator (--target ios-sim); got %q. Use viva dev for the desktop", shared.target) + if shared.target != "ios-sim" && shared.target != "android" { + return fmt.Errorf("run starts an application on a phone: give --target ios-sim or --target android (got %q). Use viva dev for the desktop", shared.target) } if len(positional) > 1 { return errors.New("run takes at most one package; run 'viva help run'") @@ -278,6 +278,9 @@ func runRun(arguments []string, output, errorOutput io.Writer) error { if err := plan.run(plan.out, errorOutput); err != nil { return err } + if plan.isAndroid() { + return runOnAndroid(plan, device, output) + } listing, err := simctl(errorOutput, "list", "devices", "available", "-j") if err != nil { return err diff --git a/headless/render_linux.go b/headless/render_linux.go index 12b005f52..7e6ac99bf 100644 --- a/headless/render_linux.go +++ b/headless/render_linux.go @@ -1,4 +1,4 @@ -//go:build linux +//go:build linux && !android package headless diff --git a/headless/render_none.go b/headless/render_none.go index 4f309f3ec..5874fccd4 100644 --- a/headless/render_none.go +++ b/headless/render_none.go @@ -1,4 +1,4 @@ -//go:build darwin && !vivahead +//go:build (darwin && !vivahead) || android package headless diff --git a/internal/autostart/files.go b/internal/autostart/files.go index 000dd5bb6..c0e8d0b3a 100644 --- a/internal/autostart/files.go +++ b/internal/autostart/files.go @@ -1,4 +1,4 @@ -//go:build darwin || linux +//go:build (darwin || linux) && !ios && !android package autostart diff --git a/internal/autostart/files_test.go b/internal/autostart/files_test.go index 49fcf41fa..91738e195 100644 --- a/internal/autostart/files_test.go +++ b/internal/autostart/files_test.go @@ -1,4 +1,4 @@ -//go:build darwin || linux +//go:build (darwin || linux) && !android package autostart diff --git a/internal/autostart/other.go b/internal/autostart/other.go index 6e93e707f..2ea9dae9f 100644 --- a/internal/autostart/other.go +++ b/internal/autostart/other.go @@ -1,4 +1,4 @@ -//go:build !darwin && !linux && !windows +//go:build (!darwin || ios) && (!linux || android) && !windows package autostart diff --git a/internal/filewatch/watch_linux.go b/internal/filewatch/watch_linux.go index e4c315e43..daf30e283 100644 --- a/internal/filewatch/watch_linux.go +++ b/internal/filewatch/watch_linux.go @@ -1,4 +1,4 @@ -//go:build linux +//go:build linux && !android package filewatch diff --git a/internal/filewatch/watch_other.go b/internal/filewatch/watch_other.go index 07ca12d54..deb018b83 100644 --- a/internal/filewatch/watch_other.go +++ b/internal/filewatch/watch_other.go @@ -1,4 +1,4 @@ -//go:build !linux && (!darwin || ios) && !windows +//go:build (!linux || android) && (!darwin || ios) && !windows package filewatch diff --git a/internal/ibus/fcitx_fixture_test.go b/internal/ibus/fcitx_fixture_test.go index ac8ba6701..b5da1fe56 100644 --- a/internal/ibus/fcitx_fixture_test.go +++ b/internal/ibus/fcitx_fixture_test.go @@ -1,4 +1,4 @@ -//go:build darwin || linux +//go:build (darwin || linux) && !android package ibus diff --git a/internal/instance/claim_unix.go b/internal/instance/claim_unix.go index 5b1b0bab1..4a15773d6 100644 --- a/internal/instance/claim_unix.go +++ b/internal/instance/claim_unix.go @@ -1,4 +1,4 @@ -//go:build darwin || linux +//go:build (darwin || linux) && !android package instance diff --git a/internal/instance/instance_unix_test.go b/internal/instance/instance_unix_test.go index 21df3fc21..c8e6557c1 100644 --- a/internal/instance/instance_unix_test.go +++ b/internal/instance/instance_unix_test.go @@ -1,4 +1,4 @@ -//go:build darwin || linux +//go:build (darwin || linux) && !android package instance diff --git a/internal/instance/owner_unix.go b/internal/instance/owner_unix.go index 4a1c268cc..ce924fe14 100644 --- a/internal/instance/owner_unix.go +++ b/internal/instance/owner_unix.go @@ -1,4 +1,4 @@ -//go:build darwin || linux +//go:build (darwin || linux) && !android package instance diff --git a/internal/platform/android/android.go b/internal/platform/android/android.go new file mode 100644 index 000000000..befc36f50 --- /dev/null +++ b/internal/platform/android/android.go @@ -0,0 +1,509 @@ +//go:build android + +// Package android runs a Viva program in an Android process. The program is a shared +// library loaded by the host's Activity (hostsrc): the host owns the UI thread, the +// surface and the input method, and the program draws on the surface with Vulkan from +// a thread of its own. What happens on the UI thread reaches the program as events on +// a queue, and the program is idle, with no timer and no wake-up, until one comes. +package android + +/* +#include +#include "jni_android.h" +*/ +import "C" + +import ( + "errors" + "fmt" + "runtime" + "sync" + "sync/atomic" + "unsafe" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/internal/platform/vulkan" +) + +// eventKind is what the host reports. +type eventKind uint8 + +const ( + eventSurface eventKind = iota + 1 // a surface, of a size, on a display of a density + eventSurfaceLost // the surface is going away: let go of it, then answer + eventTouch // a finger, a pen or a mouse + eventVisible // the activity is in front or behind + eventLowMemory // the system is short of memory + eventClose // the user asked to close the window + eventWake // something was posted + eventRedraw // the application asked for a frame +) + +// event is one thing that happened, small enough to queue by value. +type event struct { + kind eventKind + surface *C.ANativeWindow + width int32 + height int32 + density float32 + // A touch: the Android action, the pointer's id, where, the tool, the buttons + // held, the modifier state and when. + action, pointer, tool, buttons, modifiers int32 + x, y float32 + time int64 + // ack is answered once the program no longer uses the surface it is told to let go of. + ack chan struct{} + // visible is eventVisible's state. + visible bool +} + +// queue is the events from the host, in order. Moves of a finger may be dropped when +// the program falls behind; nothing else is. +var queue = make(chan event, 1024) + +// send queues an event for the program. +func send(ev event) { queue <- ev } + +// sendMove queues a finger's move, unless the program is so far behind that there +// are no more places: the next move says where the finger is. +func sendMove(ev event) { + select { + case queue <- ev: + default: + } +} + +// Run enters the program's event loop with one window. +func Run(config platform.Config) error { + return RunApplication(func(application platform.Application) error { + _, err := application.OpenWindow(config) + return err + }) +} + +// RunApplication runs the event loop on the calling goroutine, which stays on one OS +// thread for as long as it does. It returns when the window is closed. +func RunApplication(start platform.ApplicationStart) error { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + if C.viva_attach_thread() == 0 { + return errors.New("android: the process has no Java virtual machine; the program must run as the host's library") + } + app := &application{} + loopApplication.Store(app) + defer loopApplication.Store(nil) + if err := start(app); err != nil { + app.closeWindow() + return err + } + return app.loop() +} + +// loopApplication is the application whose loop runs, for what the host asks of it +// from other threads. +var loopApplication atomic.Pointer[application] + +// application is the one window a phone's application has. +type application struct { + window *window + done bool + err error + + postMu sync.Mutex + posts []func() + pending atomic.Bool // a wake is queued + redraw atomic.Bool // a redraw is queued +} + +var errOneWindow = errors.New("android: an Android application has one window; its surface is the Activity's") + +func (application *application) OpenWindow(config platform.Config) (platform.Window, error) { + if application.window != nil && !application.window.closed { + return nil, errOneWindow + } + win := &window{application: application, config: config, visible: true} + application.window = win + if config.Waker != nil && config.OnRedraw != nil { + config.Waker.Bind(application.wakeRedraw) + } + if config.Title != "" { + setTitle(config.Title) + } + // A surface the host made before the window was asked for waits for it. + if pending := takePendingSurface(); pending != nil { + application.surfaceChanged(*pending) + } + return win, nil +} + +func (application *application) AddStatusItem(platform.StatusItemConfig) (platform.StatusItem, error) { + return nil, platform.ErrStatusAreaUnavailable +} + +func (application *application) SetDockBadge(string) {} + +func (application *application) SetProgress(float32) {} + +// Quit closes the window and ends the loop. +func (application *application) Quit() { + application.Post(func() { application.closeWindow() }) +} + +// Post runs fn on the loop's thread. +func (application *application) Post(fn func()) { + application.postMu.Lock() + application.posts = append(application.posts, fn) + application.postMu.Unlock() + if !application.pending.Swap(true) { + send(event{kind: eventWake}) + } +} + +// wakeRedraw is what the application's waker calls from any goroutine. +func (application *application) wakeRedraw() { + if !application.redraw.Swap(true) { + send(event{kind: eventRedraw}) + } +} + +// loop waits for the host's events and handles them, until the window is closed. +func (application *application) loop() error { + for !application.done { + ev := <-queue + application.handle(ev) + } + return application.err +} + +func (application *application) handle(ev event) { + switch ev.kind { + case eventSurface: + application.surfaceChanged(ev) + case eventSurfaceLost: + application.surfaceLost(ev) + case eventTouch: + application.touch(ev) + case eventVisible: + application.visibility(ev.visible) + case eventClose: + application.closeRequested() + case eventWake: + application.runPosts() + case eventRedraw: + application.redrawNow() + case eventLowMemory: + } +} + +func (application *application) runPosts() { + application.postMu.Lock() + posts := application.posts + application.posts = nil + application.pending.Store(false) + application.postMu.Unlock() + for _, fn := range posts { + fn() + } +} + +// fail ends the window with err. +func (application *application) fail(err error) { + logf(logError, "the window ends: %v", err) + if application.err == nil { + application.err = err + } + application.closeWindow() +} + +// guard turns a panic in the application's handlers into the end of the window, as the +// other adapters do. +func (application *application) guard() { + if recovered := recover(); recovered != nil { + platform.ReportFault("android: event handler", recovered) + application.fail(fmt.Errorf("android: a handler panicked: %v", recovered)) + } +} + +// window is the Activity's surface and what draws on it. +type window struct { + application *application + config platform.Config + closed bool + visible bool + + native *C.ANativeWindow // the surface the host gave, nil when it has none + width uint32 // its size in device pixels + height uint32 + density float32 // device pixels per logical pixel + renderer *vulkan.Renderer +} + +func (win *window) Close() { + win.application.Post(func() { win.application.closeWindow() }) +} + +func (win *window) Hide() {} +func (win *window) Show() {} + +// Frame is the content area: the whole surface, from the screen's corner. +func (win *window) Frame() (gfx.Rect, bool) { + density := win.density + if density <= 0 { + return gfx.Rect{}, false + } + return gfx.Rect{Width: float32(win.width) / density, Height: float32(win.height) / density}, true +} + +func (win *window) size() platform.Size { + density := win.density + return platform.Size{Width: float32(win.width) / density, Height: float32(win.height) / density, Scale: density} +} + +// closeWindow ends the window and the loop. +func (application *application) closeWindow() { + win := application.window + if win == nil || win.closed { + application.done = true + return + } + win.closed = true + if win.config.Waker != nil && win.config.OnRedraw != nil { + win.config.Waker.Unbind() + } + if win.renderer != nil { + win.renderer.Close() + win.renderer = nil + } + win.releaseNative() + application.done = true + if win.config.OnClosed != nil { + win.config.OnClosed() + } +} + +func (win *window) releaseNative() { + if win.native != nil { + C.ANativeWindow_release(win.native) + win.native = nil + } +} + +// pendingSurface is a surface that came before the window was opened. +var pendingSurface struct { + sync.Mutex + event *event +} + +func takePendingSurface() *event { + pendingSurface.Lock() + defer pendingSurface.Unlock() + ev := pendingSurface.event + pendingSurface.event = nil + return ev +} + +// surfaceChanged takes the surface the host gave: the first makes the renderer, a later +// one for the same window is a resize, and a different window a surface to move to. +func (application *application) surfaceChanged(ev event) { + win := application.window + if win == nil || win.closed { + pendingSurface.Lock() + if old := pendingSurface.event; old != nil && old.surface != nil && old.surface != ev.surface { + C.ANativeWindow_release(old.surface) + } + kept := ev + pendingSurface.event = &kept + pendingSurface.Unlock() + return + } + defer application.guard() + if ev.width <= 0 || ev.height <= 0 || ev.density <= 0 { + return + } + density := ev.density + switch { + case win.renderer == nil: + win.native, win.width, win.height, win.density = ev.surface, uint32(ev.width), uint32(ev.height), density + source, err := win.surfaceSource() + if err == nil { + win.renderer, err = vulkan.New(vulkan.Config{ + Surface: source, Width: win.width, Height: win.height, Scale: density, Clear: win.config.ClearColor, + Rectangles: win.config.Rectangles, Labels: win.config.TextLabels, Rasterizer: newRasterizer, + }) + } + if err != nil { + application.fail(err) + return + } + if win.config.SetFrameInterval != nil { + // A FIFO present blocks until the display takes the frame, so the display + // paces the window; the runtime asks for the next frame as soon as the last + // one is shown. + win.config.SetFrameInterval(0) + } + if err := win.resized(false); err != nil { + application.fail(err) + } + case ev.surface != win.native: + // A new surface: the activity was recreated, or came back from behind another. + win.releaseNative() + win.native, win.width, win.height, win.density = ev.surface, uint32(ev.width), uint32(ev.height), density + if err := win.renderer.SetScale(density); err != nil { + application.fail(err) + return + } + if err := win.renderer.ReplaceSurface(win.width, win.height); err != nil { + application.fail(err) + return + } + if err := win.resized(true); err != nil { + application.fail(err) + } + default: + // The same surface at another size (a rotation, a split screen) or density. + C.ANativeWindow_release(ev.surface) // the host's reference to a window we already hold + changedDensity := density != win.density + win.width, win.height, win.density = uint32(ev.width), uint32(ev.height), density + if changedDensity { + if err := win.renderer.SetScale(density); err != nil { + application.fail(err) + return + } + } + if err := win.resized(true); err != nil { + application.fail(err) + } + } +} + +// resized shows the application at the surface's size: it paints for the size and the +// frame it answers with is drawn. A whole frame is what a surface that came back +// needs, and what the application's resize handler answers with. +func (win *window) resized(swapchain bool) error { + defer win.application.guard() + renderer := win.renderer + if renderer == nil || win.native == nil { + return nil + } + if win.config.OnResize != nil { + frame, err := win.config.OnResize(win.size()) + if err != nil { + return err + } + if swapchain { + if _, err := renderer.Stage(frame); err != nil { + return err + } + if err := renderer.Resize(win.width, win.height); err != nil { + return err + } + } else if _, err := renderer.Apply(frame); err != nil { + return err + } + } + if err := renderer.Present(); err != nil { + return err + } + if win.config.FramePresented != nil { + win.config.FramePresented() + } + return nil +} + +// surfaceLost lets go of the surface before the host takes it away. +func (application *application) surfaceLost(ev event) { + if win := application.window; win != nil && !win.closed { + if win.renderer != nil { + win.renderer.ReleaseSurface() + } + win.releaseNative() + } else { + pendingSurface.Lock() + if old := pendingSurface.event; old != nil && old.surface != nil { + C.ANativeWindow_release(old.surface) + } + pendingSurface.event = nil + pendingSurface.Unlock() + } + if ev.ack != nil { + close(ev.ack) + } +} + +// present draws a frame the application answered with. +func (win *window) present(frame platform.Frame) error { + if win.renderer == nil || win.native == nil || !win.visible { + return nil + } + changed, err := win.renderer.Apply(frame) + if err == nil && changed { + err = win.renderer.Present() + } + if err == nil && win.config.FramePresented != nil { + win.config.FramePresented() + } + return err +} + +// redrawNow answers the application's request for a frame. +func (application *application) redrawNow() { + application.redraw.Store(false) + win := application.window + if win == nil || win.closed || win.config.OnRedraw == nil || win.renderer == nil || win.native == nil || !win.visible { + return + } + defer application.guard() + frame, err := win.config.OnRedraw() + if err == nil { + err = win.present(frame) + } + if err != nil { + application.fail(err) + } +} + +// visibility follows the activity going behind another and coming back. +func (application *application) visibility(visible bool) { + win := application.window + if win == nil || win.closed { + return + } + defer application.guard() + was := win.visible + win.visible = visible + if win.config.OnVisibility != nil && visible != was { + win.config.OnVisibility(visible) + } + if visible && !was && win.renderer != nil && win.native != nil { + // What was drawn last may have gone with the surface: the application + // paints for the size again. + if err := win.resized(true); err != nil { + application.fail(err) + } + } +} + +// closeRequested is the user's back gesture at the root: the application may keep the +// window, as it may a window's close button. +func (application *application) closeRequested() { + win := application.window + if win == nil || win.closed { + return + } + defer application.guard() + if win.config.OnCloseRequest != nil { + win.config.OnCloseRequest(func() { application.Post(application.closeWindow) }) + return + } + application.closeWindow() +} + +// setTitle names the task in the system's list of recent apps. +func setTitle(title string) { + units := utf16Units(title) + if len(units) == 0 { + return + } + C.viva_host_set_title((*C.uint16_t)(unsafe.Pointer(&units[0])), C.int(len(units))) +} diff --git a/internal/platform/android/exports_android.go b/internal/platform/android/exports_android.go new file mode 100644 index 000000000..c431b30df --- /dev/null +++ b/internal/platform/android/exports_android.go @@ -0,0 +1,97 @@ +//go:build android + +package android + +/* +#include +#include +#include +#include "jni_android.h" +*/ +import "C" + +import ( + "os" + "sync" + "unsafe" + _ "unsafe" // for go:linkname +) + +// The host's calls, made on the UI thread by dev.viva.host.Native. They queue what +// happened for the program's own thread, and return. + +//go:linkname applicationMain main.main +func applicationMain() + +var started sync.Once + +//export Java_dev_viva_host_Native_start +func Java_dev_viva_host_Native_start(env *C.JNIEnv, _ C.jclass, filesDir, cacheDir C.jstring) { + started.Do(func() { + if dir := goString(env, filesDir); dir != "" { + // What a program looks for under the home directory is the app's own. + os.Setenv("HOME", dir) + } + if dir := goString(env, cacheDir); dir != "" { + os.Setenv("TMPDIR", dir) + } + go func() { + applicationMain() + // The program's main returned: its window is gone, and so is the activity. + C.viva_host_finish() + }() + }) +} + +func goString(env *C.JNIEnv, value C.jstring) string { + chars := C.viva_string_chars(env, value) + if chars == nil { + return "" + } + defer C.free(unsafe.Pointer(chars)) + return C.GoString(chars) +} + +//export Java_dev_viva_host_Native_surfaceChanged +func Java_dev_viva_host_Native_surfaceChanged(env *C.JNIEnv, _ C.jclass, surface C.jobject, width, height C.jint, density C.jfloat) { + native := C.ANativeWindow_fromSurface(env, surface) + if native == nil { + return + } + send(event{kind: eventSurface, surface: native, width: int32(width), height: int32(height), density: float32(density)}) +} + +//export Java_dev_viva_host_Native_surfaceDestroyed +func Java_dev_viva_host_Native_surfaceDestroyed(env *C.JNIEnv, _ C.jclass) { + // The host takes the surface back when this returns, so the program must have let + // go of it by then. + ack := make(chan struct{}) + send(event{kind: eventSurfaceLost, ack: ack}) + <-ack +} + +//export Java_dev_viva_host_Native_touch +func Java_dev_viva_host_Native_touch(env *C.JNIEnv, _ C.jclass, action, pointer C.jint, x, y C.jfloat, tool, buttons, modifiers C.jint, uptime C.jlong) { + ev := event{kind: eventTouch, action: int32(action), pointer: int32(pointer), x: float32(x), y: float32(y), + tool: int32(tool), buttons: int32(buttons), modifiers: int32(modifiers), time: int64(uptime)} + if ev.action == actionMove { + sendMove(ev) + return + } + send(ev) +} + +//export Java_dev_viva_host_Native_visible +func Java_dev_viva_host_Native_visible(env *C.JNIEnv, _ C.jclass, visible C.jboolean) { + send(event{kind: eventVisible, visible: visible != 0}) +} + +//export Java_dev_viva_host_Native_lowMemory +func Java_dev_viva_host_Native_lowMemory(env *C.JNIEnv, _ C.jclass) { + send(event{kind: eventLowMemory}) +} + +//export Java_dev_viva_host_Native_closeRequested +func Java_dev_viva_host_Native_closeRequested(env *C.JNIEnv, _ C.jclass) { + send(event{kind: eventClose}) +} diff --git a/internal/platform/android/hostsrc/embed.go b/internal/platform/android/hostsrc/embed.go new file mode 100644 index 000000000..0d578bb47 --- /dev/null +++ b/internal/platform/android/hostsrc/embed.go @@ -0,0 +1,12 @@ +// Package hostsrc holds the Java sources of the Android host: the Activity and the +// SurfaceView that give the Go program a window, and what it asks of the system's +// text drawing. viva build compiles them with the application, so the host needs +// no Gradle project. +package hostsrc + +import "embed" + +// Java is the host's source tree, rooted at java/. +// +//go:embed java +var Java embed.FS diff --git a/internal/platform/android/hostsrc/java/dev/viva/host/Host.java b/internal/platform/android/hostsrc/java/dev/viva/host/Host.java new file mode 100644 index 000000000..ad76b8dc4 --- /dev/null +++ b/internal/platform/android/hostsrc/java/dev/viva/host/Host.java @@ -0,0 +1,38 @@ +package dev.viva.host; + +import android.app.Activity; +import android.view.Surface; + +/** What the Go program asks of the host, on any thread. */ +public final class Host { + private Host() {} + + private static volatile Activity activity; + + static void attach(Activity current) { + activity = current; + } + + /** Ends the activity; the program's window is gone with it. */ + public static void finish() { + final Activity current = activity; + if (current != null) { + current.runOnUiThread(current::finishAndRemoveTask); + } + } + + /** Names the task in the system's list of recent apps. */ + public static void setTitle(final String title) { + final Activity current = activity; + if (current != null) { + current.runOnUiThread(() -> current.setTitle(title)); + } + } + + /** Asks the display for the rate the program's frames take, the highest it has. */ + public static void preferHighRefresh(Surface surface) { + if (surface != null && surface.isValid() && android.os.Build.VERSION.SDK_INT >= 30) { + surface.setFrameRate(120f, Surface.FRAME_RATE_COMPATIBILITY_DEFAULT); + } + } +} diff --git a/internal/platform/android/hostsrc/java/dev/viva/host/Native.java b/internal/platform/android/hostsrc/java/dev/viva/host/Native.java new file mode 100644 index 000000000..0d2bcb5e1 --- /dev/null +++ b/internal/platform/android/hostsrc/java/dev/viva/host/Native.java @@ -0,0 +1,37 @@ +package dev.viva.host; + +import android.view.Surface; + +/** + * The calls the host makes into the Go program, which runs in this process as a + * shared library. They are made on the UI thread and only queue what happened: the + * program works on a thread of its own. + */ +public final class Native { + private Native() {} + + static { + System.loadLibrary("viva"); + } + + /** Starts the program once for the process; later calls change nothing. */ + public static native void start(String filesDir, String cacheDir); + + /** The surface of the window has a size (and the display a density), or a new one. */ + public static native void surfaceChanged(Surface surface, int width, int height, float density); + + /** The surface is going away; the program must stop drawing to it before this returns. */ + public static native void surfaceDestroyed(); + + /** One finger or pen: its action, and where, in the surface's pixels. */ + public static native void touch(int action, int pointer, float x, float y, int toolType, int buttons, int modifiers, long uptimeMillis); + + /** The activity is in front (true) or has gone behind another (false). */ + public static native void visible(boolean visible); + + /** The system is short of memory. */ + public static native void lowMemory(); + + /** The user asked to close the window (the back gesture at the root). */ + public static native void closeRequested(); +} diff --git a/internal/platform/android/hostsrc/java/dev/viva/host/Text.java b/internal/platform/android/hostsrc/java/dev/viva/host/Text.java new file mode 100644 index 000000000..a70768274 --- /dev/null +++ b/internal/platform/android/hostsrc/java/dev/viva/host/Text.java @@ -0,0 +1,162 @@ +package dev.viva.host; + +import android.graphics.Bitmap; +import android.graphics.Canvas; +import android.graphics.Color; +import android.graphics.Paint; +import android.graphics.Path; +import android.graphics.RectF; +import android.graphics.Typeface; +import android.os.Build; +import android.text.Layout; +import android.text.StaticLayout; +import android.text.TextPaint; + +import java.nio.ByteBuffer; + +/** + * What the Go program asks of the system's text drawing: the width of a line, the + * extent of each of its grapheme clusters, and its pixels. The system shapes with + * Minikin and HarfBuzz and draws with Skia, so what the program measures is what is + * drawn. The program asks on one thread and caches what it learns; none of this is + * called for a line it has seen. + */ +public final class Text { + private Text() {} + + private static final TextPaint paint = new TextPaint(Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG); + private static final Path path = new Path(); + private static final RectF bounds = new RectF(); + private static final float[] advances = new float[256]; + + /** The family the interface's proportional text is shaped in; null for the system's. */ + private static volatile String family; + + /** Moves on every change after which the same line shapes differently. */ + public static void setFamily(String name) { + family = (name == null || name.isEmpty()) ? null : name; + } + + private static Typeface face(int weight, boolean italic, boolean mono) { + Typeface base = mono ? Typeface.MONOSPACE : null; + if (base == null) { + String name = family; + base = name == null ? Typeface.DEFAULT : Typeface.create(name, Typeface.NORMAL); + } + if (Build.VERSION.SDK_INT >= 28) { + return Typeface.create(base, weight, italic); + } + int style = (weight >= 600 ? Typeface.BOLD : Typeface.NORMAL) | (italic ? Typeface.ITALIC : 0); + return Typeface.create(base, style); + } + + private static TextPaint set(float size, int weight, boolean italic, boolean mono) { + paint.setTypeface(face(weight, italic, mono)); + paint.setTextSize(size); + return paint; + } + + /** The advance of the whole line. */ + public static float width(String value, float size, int weight, boolean italic, boolean mono) { + return set(size, weight, italic, mono).measureText(value); + } + + /** The ascent and descent of the font at size, and the gap it asks between lines, in out. */ + public static void metrics(float size, int weight, boolean italic, boolean mono, float[] out) { + Paint.FontMetrics fm = set(size, weight, italic, mono).getFontMetrics(); + out[0] = -fm.ascent; + out[1] = fm.descent; + out[2] = fm.leading; + } + + /** + * The horizontal extent, from the left end of the line, of each range + * [bounds[i], bounds[i+1]) of value, in UTF-16 units: left to right in lefts and + * rights. A line that is all left-to-right adds up the advances the font gives; + * one with right-to-left text asks the layout, which orders the runs. + */ + public static void rects(String value, float size, int weight, boolean italic, boolean mono, boolean rtl, + int[] boundaries, float[] lefts, float[] rights) { + TextPaint p = set(size, weight, italic, mono); + int n = value.length(); + int count = boundaries.length - 1; + if (!rtl && !hasRightToLeft(value)) { + char[] chars = value.toCharArray(); + float[] advance = n <= advances.length ? advances : new float[n]; + p.getTextRunAdvances(chars, 0, n, 0, n, false, advance, 0); + float x = 0; + int unit = 0; + for (int i = 0; i < count; i++) { + float start = x; + // Ligatures give the first unit the whole advance and the rest none, + // so summing the units of a cluster is the cluster's width. + for (; unit < boundaries[i + 1]; unit++) { + x += advance[unit]; + } + lefts[i] = start; + rights[i] = x; + } + return; + } + StaticLayout layout = StaticLayout.Builder.obtain(value, 0, n, p, 1 << 24) + .setIncludePad(false) + .setAlignment(Layout.Alignment.ALIGN_NORMAL) + .setTextDirection(rtl ? android.text.TextDirectionHeuristics.RTL : android.text.TextDirectionHeuristics.LTR) + .build(); + for (int i = 0; i < count; i++) { + path.rewind(); + layout.getSelectionPath(boundaries[i], boundaries[i + 1], path); + path.computeBounds(bounds, true); + lefts[i] = bounds.left; + rights[i] = bounds.right; + } + } + + private static boolean hasRightToLeft(String value) { + for (int i = 0; i < value.length(); i++) { + byte d = Character.getDirectionality(value.charAt(i)); + if (d == Character.DIRECTIONALITY_RIGHT_TO_LEFT || d == Character.DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC + || d == Character.DIRECTIONALITY_RIGHT_TO_LEFT_EMBEDDING || d == Character.DIRECTIONALITY_RIGHT_TO_LEFT_OVERRIDE + || d == Character.DIRECTIONALITY_ARABIC_NUMBER) { + return true; + } + } + return false; + } + + private static Bitmap bitmap; + private static Canvas canvas; + + /** Starts a transparent bitmap of width x height pixels that draw adds runs to. */ + public static void begin(int width, int height) { + if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { + if (bitmap != null) { + bitmap.recycle(); + } + bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); + canvas = new Canvas(bitmap); + } + bitmap.eraseColor(Color.TRANSPARENT); + } + + /** Draws a run of text with its left end at x and its baseline at baseline, in pixels. */ + public static void draw(String value, float x, float baseline, float size, int weight, boolean italic, boolean mono, + int argb, boolean underline, boolean rtl) { + TextPaint p = set(size, weight, italic, mono); + p.setColor(argb); + p.setUnderlineText(underline); + if (rtl) { + // Draw from the right end: the run's own direction lays its glyphs out. + canvas.drawText(value, 0, value.length(), x, baseline, p); + } else { + canvas.drawText(value, 0, value.length(), x, baseline, p); + } + p.setUnderlineText(false); + } + + /** Copies the pixels, premultiplied, in the order of Bitmap's ARGB_8888 (RGBA bytes), to out. */ + public static void end(ByteBuffer out) { + out.clear(); + bitmap.copyPixelsToBuffer(out); + } +} diff --git a/internal/platform/android/hostsrc/java/dev/viva/host/VivaActivity.java b/internal/platform/android/hostsrc/java/dev/viva/host/VivaActivity.java new file mode 100644 index 000000000..e640735c7 --- /dev/null +++ b/internal/platform/android/hostsrc/java/dev/viva/host/VivaActivity.java @@ -0,0 +1,122 @@ +package dev.viva.host; + +import android.app.Activity; +import android.content.res.Configuration; +import android.os.Bundle; +import android.view.MotionEvent; +import android.view.SurfaceHolder; +import android.view.SurfaceView; +import android.view.View; +import android.view.Window; +import android.view.WindowInsets; +import android.widget.FrameLayout; + +/** + * The window of a Viva program: one SurfaceView that fills the screen, which the + * program draws on with Vulkan. Everything the user does reaches the program as + * what happened; nothing here lays anything out. + */ +public class VivaActivity extends Activity implements SurfaceHolder.Callback { + private SurfaceView view; + + @Override + protected void onCreate(Bundle state) { + super.onCreate(state); + requestWindowFeature(Window.FEATURE_NO_TITLE); + Host.attach(this); + view = new SurfaceView(this); + view.getHolder().addCallback(this); + view.setOnTouchListener(this::onTouch); + // The surface lies inside what the system covers: its bars, the display cutout + // and the keyboard. A program that wants the whole screen asks for it. + FrameLayout root = new FrameLayout(this); + root.addView(view, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT)); + root.setOnApplyWindowInsetsListener(VivaActivity::applyInsets); + setContentView(root); + Native.start(getFilesDir().getAbsolutePath(), getCacheDir().getAbsolutePath()); + } + + @Override + protected void onStart() { + super.onStart(); + Native.visible(true); + } + + @Override + protected void onStop() { + Native.visible(false); + super.onStop(); + } + + @Override + public void onLowMemory() { + super.onLowMemory(); + Native.lowMemory(); + } + + @Override + public void onConfigurationChanged(Configuration config) { + super.onConfigurationChanged(config); + } + + @Override + public void onBackPressed() { + Native.closeRequested(); + } + + @Override + public void surfaceCreated(SurfaceHolder holder) {} + + @Override + public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { + Host.preferHighRefresh(holder.getSurface()); + Native.surfaceChanged(holder.getSurface(), width, height, getResources().getDisplayMetrics().density); + } + + @Override + public void surfaceDestroyed(SurfaceHolder holder) { + Native.surfaceDestroyed(); + } + + private static WindowInsets applyInsets(View root, WindowInsets insets) { + if (android.os.Build.VERSION.SDK_INT >= 30) { + android.graphics.Insets bars = insets.getInsets( + WindowInsets.Type.systemBars() | WindowInsets.Type.displayCutout() | WindowInsets.Type.ime()); + root.setPadding(bars.left, bars.top, bars.right, bars.bottom); + return WindowInsets.CONSUMED; + } + root.setPadding(insets.getSystemWindowInsetLeft(), insets.getSystemWindowInsetTop(), + insets.getSystemWindowInsetRight(), insets.getSystemWindowInsetBottom()); + return insets.consumeSystemWindowInsets(); + } + + private boolean onTouch(View v, MotionEvent event) { + int action = event.getActionMasked(); + long time = event.getEventTime(); + int buttons = event.getButtonState(); + int modifiers = event.getMetaState(); + switch (action) { + case MotionEvent.ACTION_MOVE: + for (int i = 0; i < event.getPointerCount(); i++) { + Native.touch(action, event.getPointerId(i), event.getX(i), event.getY(i), event.getToolType(i), buttons, modifiers, time); + } + break; + case MotionEvent.ACTION_DOWN: + case MotionEvent.ACTION_POINTER_DOWN: + case MotionEvent.ACTION_UP: + case MotionEvent.ACTION_POINTER_UP: { + int i = event.getActionIndex(); + Native.touch(action, event.getPointerId(i), event.getX(i), event.getY(i), event.getToolType(i), buttons, modifiers, time); + break; + } + case MotionEvent.ACTION_CANCEL: + for (int i = 0; i < event.getPointerCount(); i++) { + Native.touch(action, event.getPointerId(i), event.getX(i), event.getY(i), event.getToolType(i), buttons, modifiers, time); + } + break; + default: + return false; + } + return true; + } +} diff --git a/internal/platform/android/jni_android.c b/internal/platform/android/jni_android.c new file mode 100644 index 000000000..070d1e59e --- /dev/null +++ b/internal/platform/android/jni_android.c @@ -0,0 +1,210 @@ +#include "jni_android.h" + +#include +#include +#include +#include + +static JavaVM *vm; +static jclass hostClass, textClass; +static jmethodID hostFinish, hostSetTitle; +static jmethodID textWidth, textMetrics, textRects, textSetFamily, textBegin, textDraw, textEnd; + +/* A JNI_OnLoad finds the host's classes while the loader that holds them is the caller's. */ +JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *jvm, void *reserved) { + JNIEnv *env; + vm = jvm; + if ((*jvm)->GetEnv(jvm, (void **)&env, JNI_VERSION_1_6) != JNI_OK) { + return JNI_ERR; + } + jclass host = (*env)->FindClass(env, "dev/viva/host/Host"); + jclass text = (*env)->FindClass(env, "dev/viva/host/Text"); + if (host == NULL || text == NULL) { + return JNI_ERR; + } + hostClass = (*env)->NewGlobalRef(env, host); + textClass = (*env)->NewGlobalRef(env, text); + hostFinish = (*env)->GetStaticMethodID(env, hostClass, "finish", "()V"); + hostSetTitle = (*env)->GetStaticMethodID(env, hostClass, "setTitle", "(Ljava/lang/String;)V"); + textWidth = (*env)->GetStaticMethodID(env, textClass, "width", "(Ljava/lang/String;FIZZ)F"); + textMetrics = (*env)->GetStaticMethodID(env, textClass, "metrics", "(FIZZ[F)V"); + textRects = (*env)->GetStaticMethodID(env, textClass, "rects", "(Ljava/lang/String;FIZZZ[I[F[F)V"); + textSetFamily = (*env)->GetStaticMethodID(env, textClass, "setFamily", "(Ljava/lang/String;)V"); + textBegin = (*env)->GetStaticMethodID(env, textClass, "begin", "(II)V"); + textDraw = (*env)->GetStaticMethodID(env, textClass, "draw", "(Ljava/lang/String;FFFIZZIZZ)V"); + textEnd = (*env)->GetStaticMethodID(env, textClass, "end", "(Ljava/nio/ByteBuffer;)V"); + return JNI_VERSION_1_6; +} + +/* A thread that attached itself must detach before it exits, or the runtime aborts: + * a key whose destructor does it as the thread ends. */ +static pthread_key_t detachKey; +static pthread_once_t detachOnce = PTHREAD_ONCE_INIT; + +static void detach(void *unused) { + if (vm != NULL) { + (*vm)->DetachCurrentThread(vm); + } +} + +static void makeDetachKey(void) { pthread_key_create(&detachKey, detach); } + +static JNIEnv *env(void) { + JNIEnv *e = NULL; + if (vm == NULL) { + return NULL; + } + if ((*vm)->GetEnv(vm, (void **)&e, JNI_VERSION_1_6) == JNI_EDETACHED) { + if ((*vm)->AttachCurrentThread(vm, &e, NULL) != JNI_OK) { + return NULL; + } + pthread_once(&detachOnce, makeDetachKey); + pthread_setspecific(detachKey, e); + } + return e; +} + +int viva_attach_thread(void) { return env() != NULL; } + +char *viva_string_chars(JNIEnv *e, jstring value) { + if (value == NULL) { + return NULL; + } + const char *chars = (*e)->GetStringUTFChars(e, value, NULL); + if (chars == NULL) { + return NULL; + } + char *copy = strdup(chars); + (*e)->ReleaseStringUTFChars(e, value, chars); + return copy; +} + +/* clear drops a pending Java exception: a call into the host must not leave one behind. */ +static int failed(JNIEnv *e) { + if ((*e)->ExceptionCheck(e)) { + (*e)->ExceptionClear(e); + return 1; + } + return 0; +} + +float viva_text_width(const uint16_t *value, int length, float size, int weight, int italic, int mono) { + JNIEnv *e = env(); + if (e == NULL) { + return -1; + } + jstring s = (*e)->NewString(e, (const jchar *)value, length); + jfloat width = (*e)->CallStaticFloatMethod(e, textClass, textWidth, s, size, weight, italic != 0, mono != 0); + (*e)->DeleteLocalRef(e, s); + return failed(e) ? -1 : width; +} + +void viva_text_metrics(float size, int weight, int italic, int mono, float *out) { + JNIEnv *e = env(); + out[0] = out[1] = out[2] = 0; + if (e == NULL) { + return; + } + jfloatArray array = (*e)->NewFloatArray(e, 3); + (*e)->CallStaticVoidMethod(e, textClass, textMetrics, size, weight, italic != 0, mono != 0, array); + if (!failed(e)) { + (*e)->GetFloatArrayRegion(e, array, 0, 3, out); + } + (*e)->DeleteLocalRef(e, array); +} + +int viva_text_rects(const uint16_t *value, int length, float size, int weight, int italic, int mono, int rtl, + const int32_t *bounds, int boundCount, float *lefts, float *rights) { + JNIEnv *e = env(); + if (e == NULL) { + return 0; + } + int count = boundCount - 1; + jstring s = (*e)->NewString(e, (const jchar *)value, length); + jintArray b = (*e)->NewIntArray(e, boundCount); + jfloatArray l = (*e)->NewFloatArray(e, count); + jfloatArray r = (*e)->NewFloatArray(e, count); + (*e)->SetIntArrayRegion(e, b, 0, boundCount, (const jint *)bounds); + (*e)->CallStaticVoidMethod(e, textClass, textRects, s, size, weight, italic != 0, mono != 0, rtl != 0, b, l, r); + int ok = !failed(e); + if (ok) { + (*e)->GetFloatArrayRegion(e, l, 0, count, lefts); + (*e)->GetFloatArrayRegion(e, r, 0, count, rights); + } + (*e)->DeleteLocalRef(e, s); + (*e)->DeleteLocalRef(e, b); + (*e)->DeleteLocalRef(e, l); + (*e)->DeleteLocalRef(e, r); + return ok; +} + +void viva_text_set_family(const uint16_t *name, int length) { + JNIEnv *e = env(); + if (e == NULL) { + return; + } + jstring s = length > 0 ? (*e)->NewString(e, (const jchar *)name, length) : NULL; + (*e)->CallStaticVoidMethod(e, textClass, textSetFamily, s); + failed(e); + if (s != NULL) { + (*e)->DeleteLocalRef(e, s); + } +} + +int viva_text_begin(int width, int height) { + JNIEnv *e = env(); + if (e == NULL) { + return 0; + } + (*e)->CallStaticVoidMethod(e, textClass, textBegin, width, height); + return !failed(e); +} + +void viva_text_draw(const uint16_t *value, int length, float x, float baseline, float size, int weight, int italic, + int mono, int argb, int underline, int rtl) { + JNIEnv *e = env(); + if (e == NULL) { + return; + } + jstring s = (*e)->NewString(e, (const jchar *)value, length); + (*e)->CallStaticVoidMethod(e, textClass, textDraw, s, x, baseline, size, weight, italic != 0, mono != 0, argb, + underline != 0, rtl != 0); + failed(e); + (*e)->DeleteLocalRef(e, s); +} + +int viva_text_end(void *out, int64_t capacity) { + JNIEnv *e = env(); + if (e == NULL) { + return 0; + } + jobject buffer = (*e)->NewDirectByteBuffer(e, out, capacity); + if (buffer == NULL) { + failed(e); + return 0; + } + (*e)->CallStaticVoidMethod(e, textClass, textEnd, buffer); + (*e)->DeleteLocalRef(e, buffer); + return !failed(e); +} + +void viva_host_finish(void) { + JNIEnv *e = env(); + if (e != NULL) { + (*e)->CallStaticVoidMethod(e, hostClass, hostFinish); + failed(e); + } +} + +void viva_host_set_title(const uint16_t *title, int length) { + JNIEnv *e = env(); + if (e == NULL) { + return; + } + jstring s = (*e)->NewString(e, (const jchar *)title, length); + (*e)->CallStaticVoidMethod(e, hostClass, hostSetTitle, s); + failed(e); + (*e)->DeleteLocalRef(e, s); +} + +void viva_log(int priority, const char *line) { __android_log_write(priority, "viva", line); } diff --git a/internal/platform/android/jni_android.h b/internal/platform/android/jni_android.h new file mode 100644 index 000000000..a5a22e8a8 --- /dev/null +++ b/internal/platform/android/jni_android.h @@ -0,0 +1,28 @@ +// The host's calls, from the Go program's threads. + +#include +#include + +/* log writes a line to the system log under the tag "viva". */ +void viva_log(int priority, const char *line); + +/* attach_thread makes the calling OS thread known to the JVM; it stays attached. */ +int viva_attach_thread(void); + +/* string_chars copies a Java string to malloc memory as modified UTF-8; free it. */ +char *viva_string_chars(JNIEnv *env, jstring value); + +/* The text helpers (dev.viva.host.Text), over UTF-16. */ +float viva_text_width(const uint16_t *value, int length, float size, int weight, int italic, int mono); +void viva_text_metrics(float size, int weight, int italic, int mono, float *out); +int viva_text_rects(const uint16_t *value, int length, float size, int weight, int italic, int mono, int rtl, + const int32_t *bounds, int boundCount, float *lefts, float *rights); +void viva_text_set_family(const uint16_t *name, int length); +int viva_text_begin(int width, int height); +void viva_text_draw(const uint16_t *value, int length, float x, float baseline, float size, int weight, int italic, + int mono, int argb, int underline, int rtl); +int viva_text_end(void *out, int64_t capacity); + +/* The host (dev.viva.host.Host). */ +void viva_host_finish(void); +void viva_host_set_title(const uint16_t *title, int length); diff --git a/internal/platform/android/link_android.s b/internal/platform/android/link_android.s new file mode 100644 index 000000000..9823b839c --- /dev/null +++ b/internal/platform/android/link_android.s @@ -0,0 +1,3 @@ +//go:build android +// An empty assembly file lets applicationMain be declared without a body, which +// go:linkname to the program's main needs. diff --git a/internal/platform/android/log_android.go b/internal/platform/android/log_android.go new file mode 100644 index 000000000..805bbccdb --- /dev/null +++ b/internal/platform/android/log_android.go @@ -0,0 +1,28 @@ +//go:build android + +package android + +/* +#cgo LDFLAGS: -llog +#include +#include "jni_android.h" +*/ +import "C" + +import ( + "fmt" + "unsafe" +) + +// Priorities of the system log. +const ( + logInfo = 4 + logError = 6 +) + +// logf writes a line to the system log (adb logcat -s viva). +func logf(priority int, format string, args ...any) { + line := C.CString(fmt.Sprintf(format, args...)) + defer C.free(unsafe.Pointer(line)) + C.viva_log(C.int(priority), line) +} diff --git a/internal/platform/android/surface_android.go b/internal/platform/android/surface_android.go new file mode 100644 index 000000000..6e5be7733 --- /dev/null +++ b/internal/platform/android/surface_android.go @@ -0,0 +1,54 @@ +//go:build android + +package android + +/* +#cgo LDFLAGS: -landroid +#include +*/ +import "C" + +import ( + "errors" + "unsafe" + + "github.com/vivaui/viva/internal/platform/vulkan" +) + +const ( + vkStructureAndroidSurfaceCreateInfo = 1000008000 +) + +type vkAndroidSurfaceCreateInfo struct { + SType uint32 + _ uint32 + Next uintptr + Flags uint32 + _ uint32 + Window uintptr +} + +// surfaceSource makes the Vulkan surface of the ANativeWindow the window holds now: +// the renderer asks again whenever it has to make its surface again, and the window +// then is the one the host last gave. +func (win *window) surfaceSource() (vulkan.SurfaceSource, error) { + var create func(uintptr, *vkAndroidSurfaceCreateInfo, unsafe.Pointer, *uintptr) int32 + if err := vulkan.Bind(&create, "vkCreateAndroidSurfaceKHR"); err != nil { + return vulkan.SurfaceSource{}, err + } + return vulkan.SurfaceSource{ + Extension: "VK_KHR_android_surface", + Create: func(instance uintptr) (uintptr, error) { + native := win.native + if native == nil { + return 0, errors.New("android: the window has no surface") + } + info := vkAndroidSurfaceCreateInfo{SType: vkStructureAndroidSurfaceCreateInfo, Window: uintptr(unsafe.Pointer(native))} + var surface uintptr + if err := vulkan.Check(create(instance, &info, nil, &surface), "create Android surface"); err != nil { + return 0, err + } + return surface, nil + }, + }, nil +} diff --git a/internal/platform/android/text_android.go b/internal/platform/android/text_android.go new file mode 100644 index 000000000..210fd09c1 --- /dev/null +++ b/internal/platform/android/text_android.go @@ -0,0 +1,304 @@ +//go:build android + +package android + +/* +#include +#include "jni_android.h" +*/ +import "C" + +import ( + "errors" + "math" + "sync" + "unicode/utf16" + "unsafe" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/bidi" + "github.com/vivaui/viva/internal/lineengine" + "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/internal/platform/vulkan" + "github.com/vivaui/viva/internal/textmetrics" +) + +// The Android text engine is the shared line engine over the system's own text +// drawing (dev.viva.host.Text): the width of a line and the extent of each of its +// grapheme clusters come from the font Android draws it with, shaped by Minikin, so +// what is measured is what is on screen. A line that has been measured is answered +// from the engine's tables and crosses into Java no more. + +// measurer is the line engine's view of the system's text drawing. The Java side +// keeps one Paint and one bitmap, so every call is made under mu. +type measurer struct { + mu sync.Mutex + units []uint16 + pixels unsafe.Pointer + capacity int + invalidate func() +} + +var _ lineengine.Measurer = (*measurer)(nil) +var _ lineengine.StyledMeasurer = (*measurer)(nil) +var _ lineengine.Rasterizer = (*measurer)(nil) + +// shared is the one measurer of the process: the engine and the Vulkan renderer's +// label drawing read the same fonts. +var shared = &measurer{} + +// encode puts value in UTF-16 in the measurer's scratch, which is valid until the +// next call. The caller holds mu. +func (m *measurer) encode(value string) (*C.uint16_t, C.int) { + m.units = m.units[:0] + for _, r := range value { + if r >= 0x10000 { + high, low := utf16.EncodeRune(r) + m.units = append(m.units, uint16(high), uint16(low)) + } else { + m.units = append(m.units, uint16(r)) + } + } + if len(m.units) == 0 { + return nil, 0 + } + return (*C.uint16_t)(unsafe.Pointer(&m.units[0])), C.int(len(m.units)) +} + +// weightClass is the CSS weight of a gfx weight: the steps the platforms' own +// engines take. +func weightClass(weight float32) int { + switch { + case weight >= 0.34: + return 700 + case weight >= 0.20: + return 600 + case weight >= 0.10: + return 500 + } + return 400 +} + +func cBool(value bool) C.int { + if value { + return 1 + } + return 0 +} + +func (m *measurer) SetInvalidate(invalidate func()) { m.invalidate = invalidate } + +func (m *measurer) Width(value string, size, weight float32, rtl bool) float32 { + return m.WidthStyle(value, size, weight, false, rtl) +} + +func (m *measurer) WidthStyle(value string, size, weight float32, italic, rtl bool) float32 { + if value == "" { + return 0 + } + m.mu.Lock() + defer m.mu.Unlock() + units, length := m.encode(value) + width := float32(C.viva_text_width(units, length, C.float(size), C.int(weightClass(weight)), cBool(italic), 0)) + if width < 0 { + return 0 + } + return width +} + +func (m *measurer) Rects(value string, size, weight float32, rtl bool, bounds []int32, lefts, rights []float32) { + m.RectsStyle(value, size, weight, false, rtl, bounds, lefts, rights) +} + +func (m *measurer) RectsStyle(value string, size, weight float32, italic, rtl bool, bounds []int32, lefts, rights []float32) { + count := len(bounds) - 1 + if count <= 0 { + return + } + m.mu.Lock() + defer m.mu.Unlock() + units, length := m.encode(value) + if C.viva_text_rects(units, length, C.float(size), C.int(weightClass(weight)), cBool(italic), 0, cBool(rtl), + (*C.int32_t)(unsafe.Pointer(&bounds[0])), C.int(len(bounds)), (*C.float)(unsafe.Pointer(&lefts[0])), (*C.float)(unsafe.Pointer(&rights[0]))) == 0 { + // The host could not answer: the line is drawn with no extent rather than not at all. + clear(lefts[:count]) + clear(rights[:count]) + } +} + +// argb is a color as Android's Canvas takes it. +func argb(red, green, blue, alpha float64) C.int { + component := func(v float64) uint32 { return uint32(math.Round(min(max(v, 0), 1) * 255)) } + return C.int(int32(component(alpha)<<24 | component(red)<<16 | component(green)<<8 | component(blue))) +} + +// bitmap is the pixels of the Java bitmap, as BGRA premultiplied: Android's own +// order is RGBA, and the renderers' textures are BGRA. +func (m *measurer) bitmap(width, height int) ([]byte, error) { + size := width * height * 4 + if size > m.capacity { + if m.pixels != nil { + C.free(m.pixels) + } + m.pixels, m.capacity = C.malloc(C.size_t(size)), size + if m.pixels == nil { + m.capacity = 0 + return nil, errors.New("android: no memory for a text bitmap") + } + } + if C.viva_text_end(m.pixels, C.int64_t(size)) == 0 { + return nil, errors.New("android: the host could not copy the text bitmap") + } + rgba := unsafe.Slice((*byte)(m.pixels), size) + pixels := make([]byte, size) + for i := 0; i < size; i += 4 { + pixels[i], pixels[i+1], pixels[i+2], pixels[i+3] = rgba[i+2], rgba[i+1], rgba[i], rgba[i+3] + } + return pixels, nil +} + +// RasterizeText draws one proportional line, as a gfx.TextRasterizer. +func (m *measurer) RasterizeText(value string, style gfx.TextStyle, scale float32, width, height int) (gfx.Bitmap, error) { + if width <= 0 || height <= 0 || width > 16384 || height > 16384 || width*height > 16*1024*1024 || scale <= 0 || !platform.ValidFontSize(style.Size) { + return gfx.Bitmap{}, errors.New("android: invalid text bitmap size or scale") + } + m.mu.Lock() + defer m.mu.Unlock() + if C.viva_text_begin(C.int(width), C.int(height)) == 0 { + return gfx.Bitmap{}, errors.New("android: the host could not start a text bitmap") + } + if value != "" { + units, length := m.encode(value) + baseline := float32(textmetrics.LabelBaseline(height, float64(style.Size*scale))) + color := style.Color + C.viva_text_draw(units, length, 0, C.float(baseline), C.float(style.Size*scale), C.int(weightClass(style.Weight)), cBool(style.Italic), + cBool(style.Mono), argb(float64(color.Red), float64(color.Green), float64(color.Blue), float64(color.Alpha)), 0, + cBool(bidi.BaseDirection(value) == bidi.RTL)) + } + pixels, err := m.bitmap(width, height) + if err != nil { + return gfx.Bitmap{}, err + } + return gfx.Bitmap{Pix: pixels, Width: width, Height: height, Stride: width * 4}, nil +} + +// Rasterize draws the glyphs of a label into the coverage of its texture, as the +// Vulkan renderer's text rasterizer: the device columns from skip to skip+width of the +// line. It is the grayscale text Android draws; LCD text is not offered. +func (m *measurer) Rasterize(label platform.TextLabel, scale float32, skip, width, height int, allowLCD bool) ([]byte, bool, error) { + if !platform.LabelTextureFits(width, height) || skip < 0 { + return nil, false, errors.New("android: label texture exceeds bounded size") + } + if !platform.ValidFontSize(label.FontSize) || scale <= 0 || math.IsNaN(float64(scale)) || math.IsInf(float64(scale), 0) { + return nil, false, errors.New("android: invalid label font size or scale") + } + pixels := make([]byte, width*height*4) + if label.Value == "" || (label.Color.Alpha <= 0 && len(label.Runs) == 0) { + return pixels, false, nil + } + m.mu.Lock() + defer m.mu.Unlock() + if C.viva_text_begin(C.int(width), C.int(height)) == 0 { + return nil, false, errors.New("android: the host could not start a text bitmap") + } + size := C.float(label.FontSize * scale) + baseline := C.float(platform.TextBaseline(label, height, scale)) + rtl := cBool(bidi.BaseDirection(label.Value) == bidi.RTL) + if len(label.Runs) == 0 { + units, length := m.encode(label.Value) + C.viva_text_draw(units, length, C.float(-skip), baseline, size, C.int(weightClass(label.Weight)), cBool(label.Italic), cBool(label.Mono), + argb(label.Color.Red, label.Color.Green, label.Color.Blue, label.Color.Alpha), 0, rtl) + } else { + pitch := float64(label.CellWidth * scale) + if pitch <= 0 || math.IsNaN(pitch) || math.IsInf(pitch, 0) { + return nil, false, errors.New("android: invalid fixed-pitch cell width") + } + offset := 0 + for _, run := range label.Runs { + end := min(offset+int(run.Bytes), len(label.Value)) + text := label.Value[offset:end] + offset = end + if text == "" { + continue + } + weight := run.Weight + if weight == 0 { + weight = label.Weight + } + x := float64(run.Column)*pitch - float64(skip) + units, length := m.encode(text) + C.viva_text_draw(units, length, C.float(x), baseline, size, C.int(weightClass(weight)), cBool(run.Italic || label.Italic), 1, + argb(float64(run.Color.Red), float64(run.Color.Green), float64(run.Color.Blue), float64(run.Color.Alpha)), cBool(run.Underline), 0) + } + } + drawn, err := m.bitmap(width, height) + if err != nil { + return nil, false, err + } + return drawn, false, nil +} + +func (m *measurer) Spans() []vulkan.ColorSpan { return nil } +func (m *measurer) Close() {} + +// newRasterizer makes what the Vulkan renderer draws label glyphs with. +func newRasterizer() (vulkan.TextRasterizer, error) { return shared, nil } + +// engine is the text engine the application measures with: the shared line engine +// over the system's text drawing, with the fixed-pitch cell of the system's own +// monospace font. +type engine struct { + *lineengine.Engine +} + +var _ gfx.TextEngine = engine{} +var _ gfx.StyledTextEngine = engine{} +var _ gfx.TextRasterizer = engine{} +var _ gfx.FontFamilyAware = engine{} +var _ gfx.MonoCellEngine = engine{} + +var sharedEngine = struct { + once sync.Once + engine engine +}{} + +// TextEngine is the gfx.TextEngine over the system's text, shared by every window. +func TextEngine() gfx.TextEngine { + sharedEngine.once.Do(func() { + sharedEngine.engine = engine{lineengine.New(shared)} + }) + return sharedEngine.engine +} + +// SetFontFamily names the family the interface's proportional text is shaped in. +func (e engine) SetFontFamily(family string) { + e.Engine.SetFontFamily(family) + shared.mu.Lock() + defer shared.mu.Unlock() + if family == "" { + C.viva_text_set_family(nil, 0) + return + } + units, length := shared.encode(family) + C.viva_text_set_family(units, length) +} + +// MonoCell is the cell of the system's monospace font at a logical size. +func (e engine) MonoCell(size float32, face gfx.MonoFace) gfx.MonoCellMetrics { + if !platform.ValidFontSize(size) { + return gfx.MonoCellMetrics{} + } + shared.mu.Lock() + defer shared.mu.Unlock() + var out [3]C.float + C.viva_text_metrics(C.float(size), 400, 0, 1, &out[0]) + units, length := shared.encode("0") + advance := float32(C.viva_text_width(units, length, C.float(size), 400, 0, 1)) + if advance <= 0 || out[0]+out[1] <= 0 { + return gfx.MonoCellMetrics{} + } + return gfx.MonoCellMetrics{Advance: advance, Ascent: float32(out[0]), Descent: float32(out[1]), LineGap: float32(out[2])} +} + +// utf16Units is value in UTF-16. +func utf16Units(value string) []uint16 { return utf16.Encode([]rune(value)) } diff --git a/internal/platform/android/touch_android.go b/internal/platform/android/touch_android.go new file mode 100644 index 000000000..1d89c6cdb --- /dev/null +++ b/internal/platform/android/touch_android.go @@ -0,0 +1,120 @@ +//go:build android + +package android + +import ( + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/input" + "github.com/vivaui/viva/internal/platform" +) + +// MotionEvent's actions, tools, buttons and meta state, as the host sends them. +const ( + actionDown = 0 + actionUp = 1 + actionMove = 2 + actionCancel = 3 + actionPointerDown = 5 + actionPointerUp = 6 + + toolFinger = 1 + toolStylus = 2 + toolMouse = 3 + toolEraser = 4 + + buttonSecondary = 2 + buttonTertiary = 4 + + metaShift = 0x1 + metaAlt = 0x2 + metaCtrl = 0x1000 + metaMeta = 0x10000 +) + +// pointerKind is what an Android action is to the application, false for one the +// application has no use for. +func pointerKind(action int32) (platform.PointerEventKind, bool) { + switch action { + case actionDown, actionPointerDown: + return platform.PointerDown, true + case actionMove: + return platform.PointerMove, true + case actionUp, actionPointerUp: + return platform.PointerUp, true + case actionCancel: + return platform.PointerCancel, true + } + return 0, false +} + +func pointerDevice(tool int32) gfx.PointerDevice { + switch tool { + case toolMouse: + return gfx.PointerMouse + case toolStylus, toolEraser: + return gfx.PointerPen + } + return gfx.PointerTouch +} + +// pointerButton is the button a press of the tool is: a finger and a pen's tip press the +// primary one, a mouse the one it holds. +func pointerButton(tool, buttons int32) gfx.PointerButton { + if tool == toolMouse { + switch { + case buttons&buttonSecondary != 0: + return gfx.PointerButtonSecondary + case buttons&buttonTertiary != 0: + return gfx.PointerButtonMiddle + } + } + return gfx.PointerButtonPrimary +} + +func modifiers(meta int32) input.Modifiers { + var result input.Modifiers + if meta&metaShift != 0 { + result |= input.ModifierShift + } + if meta&metaCtrl != 0 { + result |= input.ModifierControl + } + if meta&metaAlt != 0 { + result |= input.ModifierAlt + } + if meta&metaMeta != 0 { + result |= input.ModifierMeta + } + return result +} + +// touch gives the application one finger's event, and shows what it answers with. +func (application *application) touch(ev event) { + win := application.window + if win == nil || win.closed || win.config.OnPointer == nil || win.renderer == nil || win.native == nil || win.density <= 0 { + return + } + kind, ok := pointerKind(ev.action) + if !ok { + return + } + defer application.guard() + // The surface fills the window and starts at the screen's corner: the surface's + // pixels over the density are the window's and the screen's logical ones. + x, y := ev.x/win.density, ev.y/win.density + event := platform.PointerEvent{ + Kind: kind, Modifiers: modifiers(ev.modifiers), X: x, Y: y, ScreenX: x, ScreenY: y, + Device: pointerDevice(ev.tool), PointerID: ev.pointer, + } + if kind == platform.PointerDown || kind == platform.PointerUp { + event.Button = pointerButton(ev.tool, ev.buttons) + event.ClickCount = 1 + } + frame, err := win.config.OnPointer(event) + if err == nil { + err = win.present(frame) + } + if err != nil { + application.fail(err) + } +} diff --git a/internal/platform/linux/always_on_top_linux.go b/internal/platform/linux/always_on_top_linux.go index 549a99c97..74823dba6 100644 --- a/internal/platform/linux/always_on_top_linux.go +++ b/internal/platform/linux/always_on_top_linux.go @@ -1,4 +1,4 @@ -//go:build linux +//go:build linux && !android package linux diff --git a/internal/platform/linux/always_on_top_linux_test.go b/internal/platform/linux/always_on_top_linux_test.go index b892a25e0..f4c63e4c8 100644 --- a/internal/platform/linux/always_on_top_linux_test.go +++ b/internal/platform/linux/always_on_top_linux_test.go @@ -1,4 +1,4 @@ -//go:build linux +//go:build linux && !android package linux diff --git a/internal/platform/linux/api_linux_test.go b/internal/platform/linux/api_linux_test.go index f826d6973..46e938bed 100644 --- a/internal/platform/linux/api_linux_test.go +++ b/internal/platform/linux/api_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/atspi_host_linux_test.go b/internal/platform/linux/atspi_host_linux_test.go index 8063232a5..32f95eb5c 100644 --- a/internal/platform/linux/atspi_host_linux_test.go +++ b/internal/platform/linux/atspi_host_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/atspi_linux.go b/internal/platform/linux/atspi_linux.go index 46f8c7155..cbcb29996 100644 --- a/internal/platform/linux/atspi_linux.go +++ b/internal/platform/linux/atspi_linux.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/atspi_native_linux_test.go b/internal/platform/linux/atspi_native_linux_test.go index 2e936076b..2d602294b 100644 --- a/internal/platform/linux/atspi_native_linux_test.go +++ b/internal/platform/linux/atspi_native_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/atspi_resize_native_linux_test.go b/internal/platform/linux/atspi_resize_native_linux_test.go index 42621011f..5416faad2 100644 --- a/internal/platform/linux/atspi_resize_native_linux_test.go +++ b/internal/platform/linux/atspi_resize_native_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/clipboard_files_linux_test.go b/internal/platform/linux/clipboard_files_linux_test.go index f5f898592..85140d8ee 100644 --- a/internal/platform/linux/clipboard_files_linux_test.go +++ b/internal/platform/linux/clipboard_files_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/clipboard_files_write_linux.go b/internal/platform/linux/clipboard_files_write_linux.go index 9d6019457..4ebb8585a 100644 --- a/internal/platform/linux/clipboard_files_write_linux.go +++ b/internal/platform/linux/clipboard_files_write_linux.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/clipboard_html_linux_test.go b/internal/platform/linux/clipboard_html_linux_test.go index 7576ad37a..337e3e1c5 100644 --- a/internal/platform/linux/clipboard_html_linux_test.go +++ b/internal/platform/linux/clipboard_html_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/clipboard_html_write_linux.go b/internal/platform/linux/clipboard_html_write_linux.go index 8fe296b14..01730dc3f 100644 --- a/internal/platform/linux/clipboard_html_write_linux.go +++ b/internal/platform/linux/clipboard_html_write_linux.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/clipboard_image_linux_test.go b/internal/platform/linux/clipboard_image_linux_test.go index d89081225..d45939b50 100644 --- a/internal/platform/linux/clipboard_image_linux_test.go +++ b/internal/platform/linux/clipboard_image_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/clipboard_image_write_linux.go b/internal/platform/linux/clipboard_image_write_linux.go index fc705d96a..28a950643 100644 --- a/internal/platform/linux/clipboard_image_write_linux.go +++ b/internal/platform/linux/clipboard_image_write_linux.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/clipboard_image_write_linux_test.go b/internal/platform/linux/clipboard_image_write_linux_test.go index 83fd3e130..a421262b8 100644 --- a/internal/platform/linux/clipboard_image_write_linux_test.go +++ b/internal/platform/linux/clipboard_image_write_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/cpu_lcd_linux_test.go b/internal/platform/linux/cpu_lcd_linux_test.go index 51ac9ef70..350ca7193 100644 --- a/internal/platform/linux/cpu_lcd_linux_test.go +++ b/internal/platform/linux/cpu_lcd_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/cpu_offscreen_linux.go b/internal/platform/linux/cpu_offscreen_linux.go index 4c9f717df..1a055d820 100644 --- a/internal/platform/linux/cpu_offscreen_linux.go +++ b/internal/platform/linux/cpu_offscreen_linux.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/cpu_offscreen_linux_test.go b/internal/platform/linux/cpu_offscreen_linux_test.go index 2cb11af1d..fec33e354 100644 --- a/internal/platform/linux/cpu_offscreen_linux_test.go +++ b/internal/platform/linux/cpu_offscreen_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/cpu_window_linux.go b/internal/platform/linux/cpu_window_linux.go index 8e989e112..85f93c27d 100644 --- a/internal/platform/linux/cpu_window_linux.go +++ b/internal/platform/linux/cpu_window_linux.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/cpu_window_linux_test.go b/internal/platform/linux/cpu_window_linux_test.go index bf0b6699c..07ed00e42 100644 --- a/internal/platform/linux/cpu_window_linux_test.go +++ b/internal/platform/linux/cpu_window_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/cpu_window_live_linux_test.go b/internal/platform/linux/cpu_window_live_linux_test.go index e9b230426..36824cc15 100644 --- a/internal/platform/linux/cpu_window_live_linux_test.go +++ b/internal/platform/linux/cpu_window_live_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/cursor_image_linux.go b/internal/platform/linux/cursor_image_linux.go index f7f0190a6..49828a5b1 100644 --- a/internal/platform/linux/cursor_image_linux.go +++ b/internal/platform/linux/cursor_image_linux.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/cursor_image_linux_test.go b/internal/platform/linux/cursor_image_linux_test.go index 08ee7da4f..8e1541050 100644 --- a/internal/platform/linux/cursor_image_linux_test.go +++ b/internal/platform/linux/cursor_image_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/cursor_linux.go b/internal/platform/linux/cursor_linux.go index 8232710f3..05ed53cd1 100644 --- a/internal/platform/linux/cursor_linux.go +++ b/internal/platform/linux/cursor_linux.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/desktop_bus_linux.go b/internal/platform/linux/desktop_bus_linux.go index d362567a9..f0d98654f 100644 --- a/internal/platform/linux/desktop_bus_linux.go +++ b/internal/platform/linux/desktop_bus_linux.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/desktop_fonts_linux_test.go b/internal/platform/linux/desktop_fonts_linux_test.go index a64874b8a..3857ec633 100644 --- a/internal/platform/linux/desktop_fonts_linux_test.go +++ b/internal/platform/linux/desktop_fonts_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/desktop_live_linux_test.go b/internal/platform/linux/desktop_live_linux_test.go index 1e0860714..80248121c 100644 --- a/internal/platform/linux/desktop_live_linux_test.go +++ b/internal/platform/linux/desktop_live_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/desktop_retry_linux_test.go b/internal/platform/linux/desktop_retry_linux_test.go index 321787116..9839dc830 100644 --- a/internal/platform/linux/desktop_retry_linux_test.go +++ b/internal/platform/linux/desktop_retry_linux_test.go @@ -1,4 +1,4 @@ -//go:build linux +//go:build linux && !android package linux diff --git a/internal/platform/linux/desktop_services_linux.go b/internal/platform/linux/desktop_services_linux.go index 23e03eb2e..cc8e39565 100644 --- a/internal/platform/linux/desktop_services_linux.go +++ b/internal/platform/linux/desktop_services_linux.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/dock_badge_linux.go b/internal/platform/linux/dock_badge_linux.go index 5629ca28b..f40a19ae6 100644 --- a/internal/platform/linux/dock_badge_linux.go +++ b/internal/platform/linux/dock_badge_linux.go @@ -1,4 +1,4 @@ -//go:build linux +//go:build linux && !android package linux diff --git a/internal/platform/linux/dock_progress_linux.go b/internal/platform/linux/dock_progress_linux.go index 875b14d0e..d8b0a9cd5 100644 --- a/internal/platform/linux/dock_progress_linux.go +++ b/internal/platform/linux/dock_progress_linux.go @@ -1,4 +1,4 @@ -//go:build linux +//go:build linux && !android package linux diff --git a/internal/platform/linux/dock_progress_linux_test.go b/internal/platform/linux/dock_progress_linux_test.go index 70f74f2c6..326278e11 100644 --- a/internal/platform/linux/dock_progress_linux_test.go +++ b/internal/platform/linux/dock_progress_linux_test.go @@ -1,4 +1,4 @@ -//go:build linux +//go:build linux && !android package linux diff --git a/internal/platform/linux/drag_linux.go b/internal/platform/linux/drag_linux.go index 5c77760f6..a5ef05150 100644 --- a/internal/platform/linux/drag_linux.go +++ b/internal/platform/linux/drag_linux.go @@ -1,4 +1,4 @@ -//go:build linux +//go:build linux && !android package linux diff --git a/internal/platform/linux/drop_linux.go b/internal/platform/linux/drop_linux.go index 3b56856d8..4f33c9c08 100644 --- a/internal/platform/linux/drop_linux.go +++ b/internal/platform/linux/drop_linux.go @@ -1,4 +1,4 @@ -//go:build linux +//go:build linux && !android package linux diff --git a/internal/platform/linux/drop_linux_test.go b/internal/platform/linux/drop_linux_test.go index 0e152698a..af843665a 100644 --- a/internal/platform/linux/drop_linux_test.go +++ b/internal/platform/linux/drop_linux_test.go @@ -1,4 +1,4 @@ -//go:build linux +//go:build linux && !android package linux diff --git a/internal/platform/linux/engine_fake_linux_test.go b/internal/platform/linux/engine_fake_linux_test.go index 2e0727e5b..4413dab5d 100644 --- a/internal/platform/linux/engine_fake_linux_test.go +++ b/internal/platform/linux/engine_fake_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/fidelity_linux_test.go b/internal/platform/linux/fidelity_linux_test.go index 95fc356c9..9d7cd92ba 100644 --- a/internal/platform/linux/fidelity_linux_test.go +++ b/internal/platform/linux/fidelity_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/font_register_linux.go b/internal/platform/linux/font_register_linux.go index b41255b0d..2284a6f8a 100644 --- a/internal/platform/linux/font_register_linux.go +++ b/internal/platform/linux/font_register_linux.go @@ -1,4 +1,4 @@ -//go:build linux +//go:build linux && !android package linux diff --git a/internal/platform/linux/font_settings_linux.go b/internal/platform/linux/font_settings_linux.go index 2d22f7316..bc106f390 100644 --- a/internal/platform/linux/font_settings_linux.go +++ b/internal/platform/linux/font_settings_linux.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import "sync" diff --git a/internal/platform/linux/font_settings_linux_test.go b/internal/platform/linux/font_settings_linux_test.go index 4d329973e..b4e5fbc91 100644 --- a/internal/platform/linux/font_settings_linux_test.go +++ b/internal/platform/linux/font_settings_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/fonts_linux.go b/internal/platform/linux/fonts_linux.go index 53060daa9..0e9f7df47 100644 --- a/internal/platform/linux/fonts_linux.go +++ b/internal/platform/linux/fonts_linux.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/fractional_scale_linux_test.go b/internal/platform/linux/fractional_scale_linux_test.go index 78882ae2c..94066a3bb 100644 --- a/internal/platform/linux/fractional_scale_linux_test.go +++ b/internal/platform/linux/fractional_scale_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/fullscreen_linux.go b/internal/platform/linux/fullscreen_linux.go index 72aed3284..ebbccfbf0 100644 --- a/internal/platform/linux/fullscreen_linux.go +++ b/internal/platform/linux/fullscreen_linux.go @@ -1,4 +1,4 @@ -//go:build linux +//go:build linux && !android package linux diff --git a/internal/platform/linux/fullscreen_linux_test.go b/internal/platform/linux/fullscreen_linux_test.go index bcfaf3f3b..1d907d930 100644 --- a/internal/platform/linux/fullscreen_linux_test.go +++ b/internal/platform/linux/fullscreen_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/global_shortcut_linux.go b/internal/platform/linux/global_shortcut_linux.go index 43604cfa3..c54b52ce7 100644 --- a/internal/platform/linux/global_shortcut_linux.go +++ b/internal/platform/linux/global_shortcut_linux.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/global_shortcut_linux_test.go b/internal/platform/linux/global_shortcut_linux_test.go index aea2ae7e6..183f04ea4 100644 --- a/internal/platform/linux/global_shortcut_linux_test.go +++ b/internal/platform/linux/global_shortcut_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/image_shading_linux_test.go b/internal/platform/linux/image_shading_linux_test.go index 0fe90e946..062dd8cca 100644 --- a/internal/platform/linux/image_shading_linux_test.go +++ b/internal/platform/linux/image_shading_linux_test.go @@ -1,4 +1,4 @@ -//go:build linux +//go:build linux && !android package linux diff --git a/internal/platform/linux/ime_bench_linux_test.go b/internal/platform/linux/ime_bench_linux_test.go index c2f7e5a35..45f6ea574 100644 --- a/internal/platform/linux/ime_bench_linux_test.go +++ b/internal/platform/linux/ime_bench_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/ime_composition_linux.go b/internal/platform/linux/ime_composition_linux.go index eb60f12e3..404f6e0ee 100644 --- a/internal/platform/linux/ime_composition_linux.go +++ b/internal/platform/linux/ime_composition_linux.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/ime_daemon_linux.go b/internal/platform/linux/ime_daemon_linux.go index d266c049c..3727aa382 100644 --- a/internal/platform/linux/ime_daemon_linux.go +++ b/internal/platform/linux/ime_daemon_linux.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/ime_daemon_linux_test.go b/internal/platform/linux/ime_daemon_linux_test.go index b15f263de..f4bba8f27 100644 --- a/internal/platform/linux/ime_daemon_linux_test.go +++ b/internal/platform/linux/ime_daemon_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/ime_linux.go b/internal/platform/linux/ime_linux.go index c823063e5..0757c7743 100644 --- a/internal/platform/linux/ime_linux.go +++ b/internal/platform/linux/ime_linux.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/ime_linux_test.go b/internal/platform/linux/ime_linux_test.go index faadaab2a..c9a1297c3 100644 --- a/internal/platform/linux/ime_linux_test.go +++ b/internal/platform/linux/ime_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/ime_native_linux_test.go b/internal/platform/linux/ime_native_linux_test.go index 108d9f663..349e5fc2e 100644 --- a/internal/platform/linux/ime_native_linux_test.go +++ b/internal/platform/linux/ime_native_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/ime_retirement_linux_test.go b/internal/platform/linux/ime_retirement_linux_test.go index 684e98444..c790b3343 100644 --- a/internal/platform/linux/ime_retirement_linux_test.go +++ b/internal/platform/linux/ime_retirement_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/ime_tentative_linux_test.go b/internal/platform/linux/ime_tentative_linux_test.go index 1191ac003..56ae0d576 100644 --- a/internal/platform/linux/ime_tentative_linux_test.go +++ b/internal/platform/linux/ime_tentative_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/ink_overflow_linux_test.go b/internal/platform/linux/ink_overflow_linux_test.go index f5baec1df..f5e0589a2 100644 --- a/internal/platform/linux/ink_overflow_linux_test.go +++ b/internal/platform/linux/ink_overflow_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/input_linux.go b/internal/platform/linux/input_linux.go index e096d9352..f1c8b8c69 100644 --- a/internal/platform/linux/input_linux.go +++ b/internal/platform/linux/input_linux.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/input_linux_test.go b/internal/platform/linux/input_linux_test.go index 117049051..65bb66686 100644 --- a/internal/platform/linux/input_linux_test.go +++ b/internal/platform/linux/input_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/interface_font_linux_test.go b/internal/platform/linux/interface_font_linux_test.go index 081eb7167..6d2d2660f 100644 --- a/internal/platform/linux/interface_font_linux_test.go +++ b/internal/platform/linux/interface_font_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/ligature_linux_test.go b/internal/platform/linux/ligature_linux_test.go index c5135eaca..db6055bda 100644 --- a/internal/platform/linux/ligature_linux_test.go +++ b/internal/platform/linux/ligature_linux_test.go @@ -1,4 +1,4 @@ -//go:build linux +//go:build linux && !android package linux diff --git a/internal/platform/linux/memfd_linux_amd64.go b/internal/platform/linux/memfd_linux_amd64.go index 649e365f3..3b6547cf1 100644 --- a/internal/platform/linux/memfd_linux_amd64.go +++ b/internal/platform/linux/memfd_linux_amd64.go @@ -1,3 +1,5 @@ +//go:build !android + package linux // sysMemfdCreate is the number of the memfd_create system call. diff --git a/internal/platform/linux/memfd_linux_arm64.go b/internal/platform/linux/memfd_linux_arm64.go index 4ad561fd5..94d26359e 100644 --- a/internal/platform/linux/memfd_linux_arm64.go +++ b/internal/platform/linux/memfd_linux_arm64.go @@ -1,3 +1,5 @@ +//go:build !android + package linux // sysMemfdCreate is the number of the memfd_create system call. diff --git a/internal/platform/linux/mono_family_linux_test.go b/internal/platform/linux/mono_family_linux_test.go index 42c02ced8..c8f3c27a2 100644 --- a/internal/platform/linux/mono_family_linux_test.go +++ b/internal/platform/linux/mono_family_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/offscreen_linux.go b/internal/platform/linux/offscreen_linux.go index 54e8649a2..ab38b01ee 100644 --- a/internal/platform/linux/offscreen_linux.go +++ b/internal/platform/linux/offscreen_linux.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/offscreen_linux_test.go b/internal/platform/linux/offscreen_linux_test.go index 925c60fe3..614d81f46 100644 --- a/internal/platform/linux/offscreen_linux_test.go +++ b/internal/platform/linux/offscreen_linux_test.go @@ -1,4 +1,4 @@ -//go:build linux +//go:build linux && !android package linux diff --git a/internal/platform/linux/open_in_browser_linux.go b/internal/platform/linux/open_in_browser_linux.go index 02b927b5b..bf8d1cf2d 100644 --- a/internal/platform/linux/open_in_browser_linux.go +++ b/internal/platform/linux/open_in_browser_linux.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/open_with_linux.go b/internal/platform/linux/open_with_linux.go index a0ba1ce4e..11bc6e1c6 100644 --- a/internal/platform/linux/open_with_linux.go +++ b/internal/platform/linux/open_with_linux.go @@ -1,4 +1,4 @@ -//go:build linux +//go:build linux && !android package linux diff --git a/internal/platform/linux/open_with_linux_test.go b/internal/platform/linux/open_with_linux_test.go index b85d83964..bf2fdf0b7 100644 --- a/internal/platform/linux/open_with_linux_test.go +++ b/internal/platform/linux/open_with_linux_test.go @@ -1,4 +1,4 @@ -//go:build linux +//go:build linux && !android package linux diff --git a/internal/platform/linux/placement_linux.go b/internal/platform/linux/placement_linux.go index 33535b079..72cc9805c 100644 --- a/internal/platform/linux/placement_linux.go +++ b/internal/platform/linux/placement_linux.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/post_linux.go b/internal/platform/linux/post_linux.go index d47f147e0..87fc354cc 100644 --- a/internal/platform/linux/post_linux.go +++ b/internal/platform/linux/post_linux.go @@ -1,4 +1,4 @@ -//go:build linux +//go:build linux && !android package linux diff --git a/internal/platform/linux/post_linux_test.go b/internal/platform/linux/post_linux_test.go index f79dc8e56..3124133a6 100644 --- a/internal/platform/linux/post_linux_test.go +++ b/internal/platform/linux/post_linux_test.go @@ -1,4 +1,4 @@ -//go:build linux +//go:build linux && !android package linux diff --git a/internal/platform/linux/raster_parity_linux_test.go b/internal/platform/linux/raster_parity_linux_test.go index e7e9c63fc..5d3740dfd 100644 --- a/internal/platform/linux/raster_parity_linux_test.go +++ b/internal/platform/linux/raster_parity_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/rasterize_bench_linux_test.go b/internal/platform/linux/rasterize_bench_linux_test.go index 4d20de255..100dda631 100644 --- a/internal/platform/linux/rasterize_bench_linux_test.go +++ b/internal/platform/linux/rasterize_bench_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/reveal_path_linux.go b/internal/platform/linux/reveal_path_linux.go index 10fe07fa2..9fc7d8989 100644 --- a/internal/platform/linux/reveal_path_linux.go +++ b/internal/platform/linux/reveal_path_linux.go @@ -1,4 +1,4 @@ -//go:build linux +//go:build linux && !android package linux diff --git a/internal/platform/linux/reveal_path_linux_test.go b/internal/platform/linux/reveal_path_linux_test.go index 972a4b8b6..ef862fd55 100644 --- a/internal/platform/linux/reveal_path_linux_test.go +++ b/internal/platform/linux/reveal_path_linux_test.go @@ -1,4 +1,4 @@ -//go:build linux +//go:build linux && !android package linux diff --git a/internal/platform/linux/scale_x11_linux.go b/internal/platform/linux/scale_x11_linux.go index d15e2ae19..d9cbbeef6 100644 --- a/internal/platform/linux/scale_x11_linux.go +++ b/internal/platform/linux/scale_x11_linux.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/scheme_linux.go b/internal/platform/linux/scheme_linux.go index 0ec5f9628..0d0aa2fe7 100644 --- a/internal/platform/linux/scheme_linux.go +++ b/internal/platform/linux/scheme_linux.go @@ -1,4 +1,4 @@ -//go:build linux +//go:build linux && !android package linux diff --git a/internal/platform/linux/scheme_linux_test.go b/internal/platform/linux/scheme_linux_test.go index 2e8d5d21d..c6ee2c210 100644 --- a/internal/platform/linux/scheme_linux_test.go +++ b/internal/platform/linux/scheme_linux_test.go @@ -1,4 +1,4 @@ -//go:build linux +//go:build linux && !android package linux diff --git a/internal/platform/linux/secret_linux.go b/internal/platform/linux/secret_linux.go index 277acd434..0a01f9e5d 100644 --- a/internal/platform/linux/secret_linux.go +++ b/internal/platform/linux/secret_linux.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/selection_linux.go b/internal/platform/linux/selection_linux.go index 770c80a2a..f0de4e2cf 100644 --- a/internal/platform/linux/selection_linux.go +++ b/internal/platform/linux/selection_linux.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/selection_linux_test.go b/internal/platform/linux/selection_linux_test.go index 601c85861..0c967d265 100644 --- a/internal/platform/linux/selection_linux_test.go +++ b/internal/platform/linux/selection_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/selection_live_linux_test.go b/internal/platform/linux/selection_live_linux_test.go index 7c3a7e8ce..943b89cc1 100644 --- a/internal/platform/linux/selection_live_linux_test.go +++ b/internal/platform/linux/selection_live_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/shared_api_linux_test.go b/internal/platform/linux/shared_api_linux_test.go index c7d72a510..cec1ae995 100644 --- a/internal/platform/linux/shared_api_linux_test.go +++ b/internal/platform/linux/shared_api_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import "testing" diff --git a/internal/platform/linux/sharpness_linux_test.go b/internal/platform/linux/sharpness_linux_test.go index 8508a074c..c41991975 100644 --- a/internal/platform/linux/sharpness_linux_test.go +++ b/internal/platform/linux/sharpness_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/shell_hooks_linux.go b/internal/platform/linux/shell_hooks_linux.go index bba8a6062..4538bf146 100644 --- a/internal/platform/linux/shell_hooks_linux.go +++ b/internal/platform/linux/shell_hooks_linux.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/sleep_linux.go b/internal/platform/linux/sleep_linux.go index 0c077bf03..437a46f8a 100644 --- a/internal/platform/linux/sleep_linux.go +++ b/internal/platform/linux/sleep_linux.go @@ -1,4 +1,4 @@ -//go:build linux +//go:build linux && !android package linux diff --git a/internal/platform/linux/sleep_linux_test.go b/internal/platform/linux/sleep_linux_test.go index aabf6352c..ec554863e 100644 --- a/internal/platform/linux/sleep_linux_test.go +++ b/internal/platform/linux/sleep_linux_test.go @@ -1,4 +1,4 @@ -//go:build linux +//go:build linux && !android package linux diff --git a/internal/platform/linux/soft_scene_linux.go b/internal/platform/linux/soft_scene_linux.go index a29e5fe2b..4fb46138b 100644 --- a/internal/platform/linux/soft_scene_linux.go +++ b/internal/platform/linux/soft_scene_linux.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/soft_scene_linux_test.go b/internal/platform/linux/soft_scene_linux_test.go index 452120af4..098156018 100644 --- a/internal/platform/linux/soft_scene_linux_test.go +++ b/internal/platform/linux/soft_scene_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/status_item_linux.go b/internal/platform/linux/status_item_linux.go index 857e09061..34f46c295 100644 --- a/internal/platform/linux/status_item_linux.go +++ b/internal/platform/linux/status_item_linux.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/status_item_linux_test.go b/internal/platform/linux/status_item_linux_test.go index 53e487a39..409c64eda 100644 --- a/internal/platform/linux/status_item_linux_test.go +++ b/internal/platform/linux/status_item_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/status_item_registration_linux_test.go b/internal/platform/linux/status_item_registration_linux_test.go index 0c8442a72..9d0e1e6a2 100644 --- a/internal/platform/linux/status_item_registration_linux_test.go +++ b/internal/platform/linux/status_item_registration_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/system_linux.go b/internal/platform/linux/system_linux.go index 7000efb9e..e4795ca9e 100644 --- a/internal/platform/linux/system_linux.go +++ b/internal/platform/linux/system_linux.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/system_linux_test.go b/internal/platform/linux/system_linux_test.go index 5662311b2..5c181aadd 100644 --- a/internal/platform/linux/system_linux_test.go +++ b/internal/platform/linux/system_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/text_callback_linux_test.go b/internal/platform/linux/text_callback_linux_test.go index 77c47ca8f..c5bd274d3 100644 --- a/internal/platform/linux/text_callback_linux_test.go +++ b/internal/platform/linux/text_callback_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/text_engine_linux.go b/internal/platform/linux/text_engine_linux.go index 494437da3..f3aa88b38 100644 --- a/internal/platform/linux/text_engine_linux.go +++ b/internal/platform/linux/text_engine_linux.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/text_engine_linux_test.go b/internal/platform/linux/text_engine_linux_test.go index e1129d963..251acca81 100644 --- a/internal/platform/linux/text_engine_linux_test.go +++ b/internal/platform/linux/text_engine_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/text_engine_scale_linux_test.go b/internal/platform/linux/text_engine_scale_linux_test.go index 3730dc559..8b04e4e3c 100644 --- a/internal/platform/linux/text_engine_scale_linux_test.go +++ b/internal/platform/linux/text_engine_scale_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/text_ink_linux.go b/internal/platform/linux/text_ink_linux.go index 003ca9b0f..e795ace20 100644 --- a/internal/platform/linux/text_ink_linux.go +++ b/internal/platform/linux/text_ink_linux.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/text_input_linux.go b/internal/platform/linux/text_input_linux.go index c021d3ae5..e3bbb1443 100644 --- a/internal/platform/linux/text_input_linux.go +++ b/internal/platform/linux/text_input_linux.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/text_input_linux_test.go b/internal/platform/linux/text_input_linux_test.go index 315363d96..70d1dd419 100644 --- a/internal/platform/linux/text_input_linux_test.go +++ b/internal/platform/linux/text_input_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/text_linux.go b/internal/platform/linux/text_linux.go index a0f9593e0..5fd98fa4d 100644 --- a/internal/platform/linux/text_linux.go +++ b/internal/platform/linux/text_linux.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/text_linux_test.go b/internal/platform/linux/text_linux_test.go index b3ceb5293..c68fc58a0 100644 --- a/internal/platform/linux/text_linux_test.go +++ b/internal/platform/linux/text_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/text_resize_linux_test.go b/internal/platform/linux/text_resize_linux_test.go index 6ba3d8330..8f6db668e 100644 --- a/internal/platform/linux/text_resize_linux_test.go +++ b/internal/platform/linux/text_resize_linux_test.go @@ -1,4 +1,4 @@ -//go:build linux +//go:build linux && !android package linux diff --git a/internal/platform/linux/vulkan_window_linux.go b/internal/platform/linux/vulkan_window_linux.go index eb5dd9993..e09495af1 100644 --- a/internal/platform/linux/vulkan_window_linux.go +++ b/internal/platform/linux/vulkan_window_linux.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/wide_label_linux_test.go b/internal/platform/linux/wide_label_linux_test.go index 17b6bbdd6..61b720a5b 100644 --- a/internal/platform/linux/wide_label_linux_test.go +++ b/internal/platform/linux/wide_label_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/window_activation_linux_test.go b/internal/platform/linux/window_activation_linux_test.go index ce0e7ad23..e15d922aa 100644 --- a/internal/platform/linux/window_activation_linux_test.go +++ b/internal/platform/linux/window_activation_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/window_close_linux_test.go b/internal/platform/linux/window_close_linux_test.go index a14add54d..557e7f8a0 100644 --- a/internal/platform/linux/window_close_linux_test.go +++ b/internal/platform/linux/window_close_linux_test.go @@ -1,4 +1,4 @@ -//go:build linux +//go:build linux && !android package linux diff --git a/internal/platform/linux/window_controls_linux.go b/internal/platform/linux/window_controls_linux.go index 8a9629067..9f19a6b85 100644 --- a/internal/platform/linux/window_controls_linux.go +++ b/internal/platform/linux/window_controls_linux.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/window_controls_linux_test.go b/internal/platform/linux/window_controls_linux_test.go index 78a274a94..5b946d900 100644 --- a/internal/platform/linux/window_controls_linux_test.go +++ b/internal/platform/linux/window_controls_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/window_frame_linux_test.go b/internal/platform/linux/window_frame_linux_test.go index 68d5347d6..e32d55377 100644 --- a/internal/platform/linux/window_frame_linux_test.go +++ b/internal/platform/linux/window_frame_linux_test.go @@ -1,4 +1,4 @@ -//go:build linux +//go:build linux && !android package linux diff --git a/internal/platform/linux/window_icon_linux.go b/internal/platform/linux/window_icon_linux.go index d93ae4fb9..775e2563b 100644 --- a/internal/platform/linux/window_icon_linux.go +++ b/internal/platform/linux/window_icon_linux.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/window_icon_linux_test.go b/internal/platform/linux/window_icon_linux_test.go index 9ded6f7e2..320de0018 100644 --- a/internal/platform/linux/window_icon_linux_test.go +++ b/internal/platform/linux/window_icon_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/window_icon_update_linux_test.go b/internal/platform/linux/window_icon_update_linux_test.go index 1896cca33..288f25279 100644 --- a/internal/platform/linux/window_icon_update_linux_test.go +++ b/internal/platform/linux/window_icon_update_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/window_identity_linux.go b/internal/platform/linux/window_identity_linux.go index 9f48bcf7d..72697d99a 100644 --- a/internal/platform/linux/window_identity_linux.go +++ b/internal/platform/linux/window_identity_linux.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/window_linux.go b/internal/platform/linux/window_linux.go index 4bdde0dea..f6716773a 100644 --- a/internal/platform/linux/window_linux.go +++ b/internal/platform/linux/window_linux.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/window_margin_linux.go b/internal/platform/linux/window_margin_linux.go index f114f36c6..6e18d38d3 100644 --- a/internal/platform/linux/window_margin_linux.go +++ b/internal/platform/linux/window_margin_linux.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/window_minimum_linux.go b/internal/platform/linux/window_minimum_linux.go index 8bcd56966..6cfc8136e 100644 --- a/internal/platform/linux/window_minimum_linux.go +++ b/internal/platform/linux/window_minimum_linux.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/window_minimum_linux_test.go b/internal/platform/linux/window_minimum_linux_test.go index 634347244..513d5bd8e 100644 --- a/internal/platform/linux/window_minimum_linux_test.go +++ b/internal/platform/linux/window_minimum_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/window_motion_linux_test.go b/internal/platform/linux/window_motion_linux_test.go index ed0f50cf3..8ff2f12de 100644 --- a/internal/platform/linux/window_motion_linux_test.go +++ b/internal/platform/linux/window_motion_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/window_notification_linux_test.go b/internal/platform/linux/window_notification_linux_test.go index b6c8ad522..6d7b821e8 100644 --- a/internal/platform/linux/window_notification_linux_test.go +++ b/internal/platform/linux/window_notification_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/window_preview_linux.go b/internal/platform/linux/window_preview_linux.go index b8f5dee42..e1fd9c665 100644 --- a/internal/platform/linux/window_preview_linux.go +++ b/internal/platform/linux/window_preview_linux.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/window_preview_linux_test.go b/internal/platform/linux/window_preview_linux_test.go index 4cd7e8dc8..95decb15a 100644 --- a/internal/platform/linux/window_preview_linux_test.go +++ b/internal/platform/linux/window_preview_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/window_protocols_linux_test.go b/internal/platform/linux/window_protocols_linux_test.go index 66c0ea238..439cbd40d 100644 --- a/internal/platform/linux/window_protocols_linux_test.go +++ b/internal/platform/linux/window_protocols_linux_test.go @@ -1,4 +1,4 @@ -//go:build linux +//go:build linux && !android package linux diff --git a/internal/platform/linux/window_readahead_linux_test.go b/internal/platform/linux/window_readahead_linux_test.go index 104ef4be8..58584c173 100644 --- a/internal/platform/linux/window_readahead_linux_test.go +++ b/internal/platform/linux/window_readahead_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/window_renderer_fake_linux_test.go b/internal/platform/linux/window_renderer_fake_linux_test.go index 29e738c42..9e1ea2fbc 100644 --- a/internal/platform/linux/window_renderer_fake_linux_test.go +++ b/internal/platform/linux/window_renderer_fake_linux_test.go @@ -1,4 +1,4 @@ -//go:build linux +//go:build linux && !android package linux diff --git a/internal/platform/linux/window_renderer_linux.go b/internal/platform/linux/window_renderer_linux.go index 544d99d0e..16bf34dbf 100644 --- a/internal/platform/linux/window_renderer_linux.go +++ b/internal/platform/linux/window_renderer_linux.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/window_resize_bench_linux_test.go b/internal/platform/linux/window_resize_bench_linux_test.go index ecd3ca0c9..cad16eba8 100644 --- a/internal/platform/linux/window_resize_bench_linux_test.go +++ b/internal/platform/linux/window_resize_bench_linux_test.go @@ -1,4 +1,4 @@ -//go:build linux +//go:build linux && !android package linux diff --git a/internal/platform/linux/window_resize_linux_test.go b/internal/platform/linux/window_resize_linux_test.go index 508e99d22..931086c22 100644 --- a/internal/platform/linux/window_resize_linux_test.go +++ b/internal/platform/linux/window_resize_linux_test.go @@ -1,4 +1,4 @@ -//go:build linux +//go:build linux && !android package linux diff --git a/internal/platform/linux/window_size_linux.go b/internal/platform/linux/window_size_linux.go index 3b89aef7e..8bccd1830 100644 --- a/internal/platform/linux/window_size_linux.go +++ b/internal/platform/linux/window_size_linux.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import "fmt" diff --git a/internal/platform/linux/window_size_linux_test.go b/internal/platform/linux/window_size_linux_test.go index b62d1f6cc..0f0273267 100644 --- a/internal/platform/linux/window_size_linux_test.go +++ b/internal/platform/linux/window_size_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/window_sync_linux.go b/internal/platform/linux/window_sync_linux.go index 6d8b4db05..86079211b 100644 --- a/internal/platform/linux/window_sync_linux.go +++ b/internal/platform/linux/window_sync_linux.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/window_sync_resize_linux_test.go b/internal/platform/linux/window_sync_resize_linux_test.go index 054b8e172..201078fba 100644 --- a/internal/platform/linux/window_sync_resize_linux_test.go +++ b/internal/platform/linux/window_sync_resize_linux_test.go @@ -1,4 +1,4 @@ -//go:build linux +//go:build linux && !android package linux diff --git a/internal/platform/linux/window_title_linux.go b/internal/platform/linux/window_title_linux.go index abfdf22f9..74845d599 100644 --- a/internal/platform/linux/window_title_linux.go +++ b/internal/platform/linux/window_title_linux.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import "fmt" diff --git a/internal/platform/linux/window_title_linux_test.go b/internal/platform/linux/window_title_linux_test.go index 706c08146..af29e2e9b 100644 --- a/internal/platform/linux/window_title_linux_test.go +++ b/internal/platform/linux/window_title_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/wm_class_linux.go b/internal/platform/linux/wm_class_linux.go index 3b500c630..88b1de0ba 100644 --- a/internal/platform/linux/wm_class_linux.go +++ b/internal/platform/linux/wm_class_linux.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/wm_class_linux_test.go b/internal/platform/linux/wm_class_linux_test.go index 9573b0670..29a31f92d 100644 --- a/internal/platform/linux/wm_class_linux_test.go +++ b/internal/platform/linux/wm_class_linux_test.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/linux/xcb_linux.go b/internal/platform/linux/xcb_linux.go index c6bdf30fc..aadafebac 100644 --- a/internal/platform/linux/xcb_linux.go +++ b/internal/platform/linux/xcb_linux.go @@ -1,3 +1,5 @@ +//go:build !android + package linux import ( diff --git a/internal/platform/vulkan/api_vulkan_test.go b/internal/platform/vulkan/api_vulkan_test.go index afb9f0b0d..c50438984 100644 --- a/internal/platform/vulkan/api_vulkan_test.go +++ b/internal/platform/vulkan/api_vulkan_test.go @@ -6,8 +6,6 @@ import ( "bytes" "errors" "fmt" - "os" - "path/filepath" "slices" "strings" "testing" @@ -298,120 +296,6 @@ func TestMissingVulkanIsNamedAndSaysWhatToInstall(t *testing.T) { } } -func TestVulkanDriverManifestDetection(t *testing.T) { - dir := t.TempDir() - if err := os.WriteFile(filepath.Join(dir, "notes.txt"), []byte("not a driver"), 0o600); err != nil { - t.Fatal(err) - } - if vulkanDriverManifestsExist([]string{dir}) { - t.Fatal("a directory without an ICD manifest counts as a Vulkan driver") - } - manifest := filepath.Join(dir, "driver.json") - if err := os.WriteFile(manifest, []byte("{}"), 0o600); err != nil { - t.Fatal(err) - } - if !vulkanDriverManifestsExist([]string{dir}) || !vulkanDriverManifestsExist([]string{manifest}) { - t.Fatal("an ICD manifest was not detected") - } -} - -func TestVulkanWithoutDriverManifestDoesNotLoadDriver(t *testing.T) { - t.Setenv("VK_DRIVER_FILES", filepath.Join(t.TempDir(), "missing.json")) - t.Setenv("VK_ICD_FILENAMES", "") - t.Setenv("VK_ADD_DRIVER_FILES", "") - if vulkanDriverConfigured() { - t.Fatal("a missing ICD manifest counts as a Vulkan driver") - } - _, err := openVulkan() - if !errors.Is(err, platform.ErrNoGraphics) { - t.Fatalf("openVulkan error = %v, want platform.ErrNoGraphics", err) - } -} - -func TestVulkanEmptyICDOverrideDoesNotUseDefaultManifests(t *testing.T) { - root := t.TempDir() - t.Setenv("HOME", root) - t.Setenv("XDG_DATA_HOME", root) - writeVulkanManifest(t, filepath.Join(root, "vulkan", "icd.d")) - t.Setenv("VK_DRIVER_FILES", "") - t.Setenv("VK_ICD_FILENAMES", "") - unsetTestEnv(t, "VK_ADD_DRIVER_FILES") - if vulkanDriverConfigured() { - t.Fatal("an empty ICD override falls back to the default driver manifests") - } -} - -// The default search reads each XDG base the loader reads. Only positive cases are -// checked: the system's /etc/vulkan/icd.d is always searched, so an empty result -// cannot be asserted on a machine that has a driver installed. -func TestVulkanDefaultManifestSearchFindsEachXDGDirectory(t *testing.T) { - cases := []struct { - name string - // env sets the search variables under root, and returns the base whose - // vulkan/icd.d holds the manifest. - env func(t *testing.T, root string) string - }{ - {"config home", func(t *testing.T, root string) string { - t.Setenv("XDG_CONFIG_HOME", filepath.Join(root, "config")) - return filepath.Join(root, "config") - }}, - {"home default config", func(t *testing.T, root string) string { - t.Setenv("HOME", root) - return filepath.Join(root, ".config") - }}, - {"config dirs", func(t *testing.T, root string) string { - t.Setenv("XDG_CONFIG_DIRS", filepath.Join(root, "missing")+":"+filepath.Join(root, "xdg")) - return filepath.Join(root, "xdg") - }}, - {"data home", func(t *testing.T, root string) string { - t.Setenv("XDG_DATA_HOME", filepath.Join(root, "data")) - return filepath.Join(root, "data") - }}, - {"data dirs", func(t *testing.T, root string) string { - t.Setenv("XDG_DATA_DIRS", filepath.Join(root, "share")) - return filepath.Join(root, "share") - }}, - } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - root := t.TempDir() - t.Setenv("HOME", filepath.Join(root, "home")) - t.Setenv("XDG_CONFIG_DIRS", "") - t.Setenv("XDG_DATA_DIRS", "") - unsetTestEnv(t, "XDG_CONFIG_HOME") - unsetTestEnv(t, "XDG_DATA_HOME") - unsetTestEnv(t, "VK_DRIVER_FILES") - unsetTestEnv(t, "VK_ICD_FILENAMES") - unsetTestEnv(t, "VK_ADD_DRIVER_FILES") - base := tc.env(t, root) - writeVulkanManifest(t, filepath.Join(base, "vulkan", "icd.d")) - if !vulkanDriverConfigured() { - t.Fatalf("a manifest under the %s was not found", tc.name) - } - }) - } -} - -// unsetTestEnv removes name for the rest of the test. t.Setenv restores the original -// value at cleanup, which the bare os.Unsetenv alone would not. -func unsetTestEnv(t *testing.T, name string) { - t.Helper() - t.Setenv(name, "") - if err := os.Unsetenv(name); err != nil { - t.Fatal(err) - } -} - -func writeVulkanManifest(t *testing.T, dir string) { - t.Helper() - if err := os.MkdirAll(dir, 0o700); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(filepath.Join(dir, "driver.json"), []byte("{}"), 0o600); err != nil { - t.Fatal(err) - } -} - // A loader whose installed drivers fail to initialize fails enumeration with // VK_ERROR_INITIALIZATION_FAILED (a driver-less loader gives // VK_ERROR_INCOMPATIBLE_DRIVER). That is still a machine that cannot draw, not a diff --git a/internal/platform/vulkan/driver_desktop_linux_test.go b/internal/platform/vulkan/driver_desktop_linux_test.go new file mode 100644 index 000000000..a4fc94b9d --- /dev/null +++ b/internal/platform/vulkan/driver_desktop_linux_test.go @@ -0,0 +1,126 @@ +//go:build linux && !android + +package vulkan + +import ( + "errors" + "os" + "path/filepath" + "testing" + + "github.com/vivaui/viva/internal/platform" +) + +func TestVulkanDriverManifestDetection(t *testing.T) { + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "notes.txt"), []byte("not a driver"), 0o600); err != nil { + t.Fatal(err) + } + if vulkanDriverManifestsExist([]string{dir}) { + t.Fatal("a directory without an ICD manifest counts as a Vulkan driver") + } + manifest := filepath.Join(dir, "driver.json") + if err := os.WriteFile(manifest, []byte("{}"), 0o600); err != nil { + t.Fatal(err) + } + if !vulkanDriverManifestsExist([]string{dir}) || !vulkanDriverManifestsExist([]string{manifest}) { + t.Fatal("an ICD manifest was not detected") + } +} + +func TestVulkanWithoutDriverManifestDoesNotLoadDriver(t *testing.T) { + t.Setenv("VK_DRIVER_FILES", filepath.Join(t.TempDir(), "missing.json")) + t.Setenv("VK_ICD_FILENAMES", "") + t.Setenv("VK_ADD_DRIVER_FILES", "") + if vulkanDriverConfigured() { + t.Fatal("a missing ICD manifest counts as a Vulkan driver") + } + _, err := openVulkan() + if !errors.Is(err, platform.ErrNoGraphics) { + t.Fatalf("openVulkan error = %v, want platform.ErrNoGraphics", err) + } +} + +func TestVulkanEmptyICDOverrideDoesNotUseDefaultManifests(t *testing.T) { + root := t.TempDir() + t.Setenv("HOME", root) + t.Setenv("XDG_DATA_HOME", root) + writeVulkanManifest(t, filepath.Join(root, "vulkan", "icd.d")) + t.Setenv("VK_DRIVER_FILES", "") + t.Setenv("VK_ICD_FILENAMES", "") + unsetTestEnv(t, "VK_ADD_DRIVER_FILES") + if vulkanDriverConfigured() { + t.Fatal("an empty ICD override falls back to the default driver manifests") + } +} + +// The default search reads each XDG base the loader reads. Only positive cases are +// checked: the system's /etc/vulkan/icd.d is always searched, so an empty result +// cannot be asserted on a machine that has a driver installed. +func TestVulkanDefaultManifestSearchFindsEachXDGDirectory(t *testing.T) { + cases := []struct { + name string + // env sets the search variables under root, and returns the base whose + // vulkan/icd.d holds the manifest. + env func(t *testing.T, root string) string + }{ + {"config home", func(t *testing.T, root string) string { + t.Setenv("XDG_CONFIG_HOME", filepath.Join(root, "config")) + return filepath.Join(root, "config") + }}, + {"home default config", func(t *testing.T, root string) string { + t.Setenv("HOME", root) + return filepath.Join(root, ".config") + }}, + {"config dirs", func(t *testing.T, root string) string { + t.Setenv("XDG_CONFIG_DIRS", filepath.Join(root, "missing")+":"+filepath.Join(root, "xdg")) + return filepath.Join(root, "xdg") + }}, + {"data home", func(t *testing.T, root string) string { + t.Setenv("XDG_DATA_HOME", filepath.Join(root, "data")) + return filepath.Join(root, "data") + }}, + {"data dirs", func(t *testing.T, root string) string { + t.Setenv("XDG_DATA_DIRS", filepath.Join(root, "share")) + return filepath.Join(root, "share") + }}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + root := t.TempDir() + t.Setenv("HOME", filepath.Join(root, "home")) + t.Setenv("XDG_CONFIG_DIRS", "") + t.Setenv("XDG_DATA_DIRS", "") + unsetTestEnv(t, "XDG_CONFIG_HOME") + unsetTestEnv(t, "XDG_DATA_HOME") + unsetTestEnv(t, "VK_DRIVER_FILES") + unsetTestEnv(t, "VK_ICD_FILENAMES") + unsetTestEnv(t, "VK_ADD_DRIVER_FILES") + base := tc.env(t, root) + writeVulkanManifest(t, filepath.Join(base, "vulkan", "icd.d")) + if !vulkanDriverConfigured() { + t.Fatalf("a manifest under the %s was not found", tc.name) + } + }) + } +} + +// unsetTestEnv removes name for the rest of the test. t.Setenv restores the original +// value at cleanup, which the bare os.Unsetenv alone would not. +func unsetTestEnv(t *testing.T, name string) { + t.Helper() + t.Setenv(name, "") + if err := os.Unsetenv(name); err != nil { + t.Fatal(err) + } +} + +func writeVulkanManifest(t *testing.T, dir string) { + t.Helper() + if err := os.MkdirAll(dir, 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "driver.json"), []byte("{}"), 0o600); err != nil { + t.Fatal(err) + } +} diff --git a/internal/platform/vulkan/surface_lifecycle_linux.go b/internal/platform/vulkan/surface_lifecycle_linux.go new file mode 100644 index 000000000..4c66ab23c --- /dev/null +++ b/internal/platform/vulkan/surface_lifecycle_linux.go @@ -0,0 +1,57 @@ +package vulkan + +import "fmt" + +// A window system can take a surface back while the application lives on: Android +// destroys the surface of a window that goes behind another and gives it a new one +// when it returns. ReleaseSurface and ReplaceSurface keep the device, the scene and +// the label textures through that; only what hangs on the surface is made again. + +// ReleaseSurface lets go of the swapchain and the surface, and everything made for +// the swapchain's images, before the window system takes the surface away. The device +// is kept, so is what the renderer would draw. Nothing is drawn until ReplaceSurface. +func (renderer *Renderer) ReleaseSurface() { + if renderer == nil || renderer.api == nil || renderer.device == 0 { + return + } + renderer.api.deviceWaitIdle(renderer.device) + renderer.destroySwapchain() + if renderer.surface != 0 && renderer.instance != 0 { + renderer.api.destroySurface(renderer.instance, renderer.surface, nil) + } + renderer.surface = 0 + renderer.hasSurfaceFormat = false + renderer.hasPresentMode = false + renderer.hasPendingCapabilities = false + renderer.recorded = nil +} + +// ReplaceSurface makes the surface again from the window system's current one, which +// is width x height device pixels, and a swapchain on it. The scene and the label +// textures the renderer kept are drawn on it; the application should apply a whole +// frame next, as the one it applied last may have been before the surface went. +func (renderer *Renderer) ReplaceSurface(width, height uint32) error { + for losses := 0; ; losses++ { + retry, err := renderer.recoverFrom(renderer.replaceSurfaceOnce(width, height), losses) + if !retry { + return err + } + } +} + +func (renderer *Renderer) replaceSurfaceOnce(width, height uint32) error { + if renderer.source.Create == nil || renderer.shared == nil { + return fmt.Errorf("vulkan: only a window renderer has a surface to replace") + } + renderer.ReleaseSurface() + surface, err := renderer.source.Create(renderer.instance) + if err != nil { + return err + } + renderer.surface = surface + if err := renderer.shared.attach(surface); err != nil { + return err + } + renderer.width, renderer.height = width, height + return renderer.createSwapchain() +} diff --git a/tools/visualparity/measure_linux.go b/tools/visualparity/measure_linux.go index 5501c569d..3b010a3ee 100644 --- a/tools/visualparity/measure_linux.go +++ b/tools/visualparity/measure_linux.go @@ -1,4 +1,4 @@ -//go:build linux +//go:build linux && !android package main diff --git a/update/install_linux.go b/update/install_linux.go index 59c5d8056..2ff346de9 100644 --- a/update/install_linux.go +++ b/update/install_linux.go @@ -1,4 +1,4 @@ -//go:build linux +//go:build linux && !android package update diff --git a/update/install_linux_test.go b/update/install_linux_test.go index c74b63f4e..de8c33e3d 100644 --- a/update/install_linux_test.go +++ b/update/install_linux_test.go @@ -1,4 +1,4 @@ -//go:build linux +//go:build linux && !android package update diff --git a/update/payload_linux.go b/update/payload_linux.go index 3e556399d..f5737f128 100644 --- a/update/payload_linux.go +++ b/update/payload_linux.go @@ -1,4 +1,4 @@ -//go:build linux +//go:build linux && !android package update From 9fafb6279d140d29d86de3ec49502319f12e608e Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 22 Nov 2026 22:13:27 +0800 Subject: [PATCH 30/64] fix(ci): follow the Vulkan shaders and layers tests, and detach the whole disk image The Vulkan renderer's shaders and compositing-layer tests moved to internal/platform/vulkan; the shader generator, the vector coverage job and the text input job still looked under internal/platform/linux. The disk image test failed on macOS runners with the image still attached after detaching: the device node detach was given is the volume's partition, which unmounts the volume and leaves the image attached. It is given the whole disk. --- .github/workflows/text-input.yml | 4 +++- .github/workflows/vector-coverage.yml | 6 +++--- tools/dmg/build.go | 14 ++++++++++++++ tools/dmg/busy_test.go | 10 ++++++++++ tools/generate_linux_shaders.sh | 2 +- 5 files changed, 31 insertions(+), 5 deletions(-) diff --git a/.github/workflows/text-input.yml b/.github/workflows/text-input.yml index 55face264..c4c35f253 100644 --- a/.github/workflows/text-input.yml +++ b/.github/workflows/text-input.yml @@ -194,7 +194,9 @@ jobs: run: go test -tags vivagtk ./internal/platform/linux -run '^TestGTKDestroyDetachesInputMethodBeforeNativeWidget$' -count=1 -v - name: Linux clipboard, compositing and icon contracts if: runner.os == 'Linux' - run: go test -tags vivagtk ./internal/platform/linux -run '^Test(AClipboardHTML|SetClipboardHTML|GTKClipboardHTML|CompositingLayers|NetWMIcon)' -count=1 -v + run: | + go test -tags vivagtk ./internal/platform/linux -run '^Test(AClipboardHTML|SetClipboardHTML|GTKClipboardHTML|NetWMIcon)' -count=1 -v + go test ./internal/platform/vulkan -run '^TestCompositingLayers' -count=1 -v # A terminal input is a preedit surface with a cursor of its own: the native # editor must draw no caret or selection over it, and blink none. - name: Windows terminal preedit draws no native caret diff --git a/.github/workflows/vector-coverage.yml b/.github/workflows/vector-coverage.yml index 4dc3694bf..dd33eef6d 100644 --- a/.github/workflows/vector-coverage.yml +++ b/.github/workflows/vector-coverage.yml @@ -62,11 +62,11 @@ jobs: # bash on every runner: the Windows default shell is PowerShell. shell: bash run: | - if git diff --quiet -- internal/platform/darwin/shaders internal/platform/linux/shaders internal/platform/windows/shaders; then + if git diff --quiet -- internal/platform/darwin/shaders internal/platform/vulkan/shaders internal/platform/windows/shaders; then echo "the shipped shaders are what the sources compile to" echo changed=false >> "$GITHUB_OUTPUT" else - git diff --stat -- internal/platform/darwin/shaders internal/platform/linux/shaders internal/platform/windows/shaders + git diff --stat -- internal/platform/darwin/shaders internal/platform/vulkan/shaders internal/platform/windows/shaders echo changed=true >> "$GITHUB_OUTPUT" fi - name: Native pixel coverage with the rebuilt shaders @@ -82,6 +82,6 @@ jobs: name: vector-shaders-${{ runner.os }} path: | internal/platform/darwin/shaders/scene.metallib - internal/platform/linux/shaders/*.spv + internal/platform/vulkan/shaders/*.spv internal/platform/windows/shaders/*.dxbc internal/platform/windows/shaders/manifest.json diff --git a/tools/dmg/build.go b/tools/dmg/build.go index 1a74f2f91..09835a5b9 100644 --- a/tools/dmg/build.go +++ b/tools/dmg/build.go @@ -8,6 +8,7 @@ import ( "os" "os/exec" "path/filepath" + "regexp" "strings" "time" ) @@ -197,6 +198,9 @@ func attachedDevice(output, mount string) (string, error) { // detach unmounts the image, retrying while the system still holds it, and // forcing it as the last resort. func detach(mount, device string) error { + // Detaching a partition's node unmounts that volume and leaves the image attached, + // which the disk image service then holds: the whole disk is what goes. + device = wholeDisk(device) mounted, err := volumeMounted(mount) if err != nil { return err @@ -226,6 +230,16 @@ func detach(mount, device string) error { return err } +var partitionNode = regexp.MustCompile(`^(/dev/disk\d+)s\d+$`) + +// wholeDisk is the device node of the disk a node is on: /dev/disk7 for /dev/disk7s1. +func wholeDisk(device string) string { + if match := partitionNode.FindStringSubmatch(device); match != nil { + return match[1] + } + return device +} + // releaseAttempts and releaseWait bound how long released waits for the disk // image service: up to two minutes. const ( diff --git a/tools/dmg/busy_test.go b/tools/dmg/busy_test.go index f8021b8a9..85bee54c9 100644 --- a/tools/dmg/busy_test.go +++ b/tools/dmg/busy_test.go @@ -117,3 +117,13 @@ func TestReleasedWaitsUntilTheImageIsNoLongerAttached(t *testing.T) { t.Fatalf("an image that stays attached gave %v", err) } } + +// A volume's node is a slice of a disk, and detaching the slice leaves the image +// attached: detach is given the disk. +func TestDetachTargetsTheWholeDisk(t *testing.T) { + for node, want := range map[string]string{"/dev/disk7s1": "/dev/disk7", "/dev/disk12s3": "/dev/disk12", "/dev/disk7": "/dev/disk7", "/dev/diskimage": "/dev/diskimage"} { + if got := wholeDisk(node); got != want { + t.Errorf("wholeDisk(%q) = %q, want %q", node, got, want) + } + } +} diff --git a/tools/generate_linux_shaders.sh b/tools/generate_linux_shaders.sh index 35a7cd41f..169433cf0 100755 --- a/tools/generate_linux_shaders.sh +++ b/tools/generate_linux_shaders.sh @@ -3,7 +3,7 @@ set -eu root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) -shader_dir="$root/internal/platform/linux/shaders" +shader_dir="$root/internal/platform/vulkan/shaders" glslc --target-env=vulkan1.0 -O "$shader_dir/scene.vert" -o "$shader_dir/scene.vert.spv" glslc --target-env=vulkan1.0 -O "$shader_dir/scene.frag" -o "$shader_dir/scene.frag.spv" From b214e5a5ce8969aa77af305faddb33af51f0fce1 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 22 Nov 2026 23:14:40 +0800 Subject: [PATCH 31/64] feat(ios): keep the surface inside the safe area and the keyboard, follow the lifecycle The window's view lives in a container whose controller puts the Metal surface inside the safe area (status bar, sensor housing, home indicator) and above the keyboard, in the keyboard's own animation. Going to the background tells the application it is not visible and stops GPU work, which the system kills an application for; coming back tells it and draws the scene again. A connected keyboard's keys that are not text arrive as key events (from the USB HID usage UIKey reports) and chords with Control or Command are offered as shortcuts first. The iPhone's text engine is Core Text, as the labels already were. --- internal/platform/darwin/ios_host.m | 116 ++++++++++++++++++++++-- internal/platform/darwin/ios_keys.go | 128 +++++++++++++++++++++++++++ 2 files changed, 236 insertions(+), 8 deletions(-) create mode 100644 internal/platform/darwin/ios_keys.go diff --git a/internal/platform/darwin/ios_host.m b/internal/platform/darwin/ios_host.m index 8bfc3c13c..b4dcb6a6b 100644 --- a/internal/platform/darwin/ios_host.m +++ b/internal/platform/darwin/ios_host.m @@ -13,10 +13,13 @@ /* The callbacks into Go. */ extern void vivaIOSLaunched(void); extern void vivaViewResized(uintptr_t callbackHandle, void *view, double width, double height); -extern void vivaRedrawRequested(uintptr_t callbackHandle, void *view); extern void vivaWindowClosed(uintptr_t callbackHandle); extern void vivaTouchEvent(uintptr_t callbackHandle, void *view, int kind, int identifier, double x, double y, double screenX, double screenY); +extern void vivaIOSKeyEvent(uintptr_t callbackHandle, void *view, int usage, int modifiers, int repeat, + const unsigned char *utf8, size_t utf8Length); +extern void vivaIOSVisibility(uintptr_t callbackHandle, void *view, int visible); +extern void vivaRedrawRequested(uintptr_t callbackHandle, void *view); /* The pointer kinds, as platform.PointerEventKind numbers them. */ enum { @@ -156,7 +159,8 @@ - (void)render { } - (void)renderWaitingForSchedule:(BOOL)wait { - if (_closed) { + // The system kills an application that submits GPU work from the background. + if (_closed || UIApplication.sharedApplication.applicationState == UIApplicationStateBackground) { return; } @autoreleasepool { @@ -251,13 +255,94 @@ - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event [self emitTouches:touches kind:VIVA_IOS_POINTER_CANCEL]; } +#pragma mark Hardware keyboard + +- (BOOL)canBecomeFirstResponder { + return YES; +} + +- (void)didMoveToWindow { + [super didMoveToWindow]; + if (self.window != nil) { + [self becomeFirstResponder]; + } +} + +// pressesBegan reports the keys of a connected keyboard. The keys that are not +// text arrive as key events and the chords with Control or Command as shortcut +// offers; what is typed is the text input's (see UITextInput). +- (void)pressesBegan:(NSSet *)presses withEvent:(UIPressesEvent *)event { + BOOL handled = NO; + for (UIPress *press in presses) { + UIKey *key = press.key; + if (key == nil || _closed) { + continue; + } + const char *chars = key.charactersIgnoringModifiers.UTF8String; + size_t length = chars != NULL ? strlen(chars) : 0; + vivaIOSKeyEvent(_callbackHandle, self, (int)key.keyCode, (int)key.modifierFlags, 0, (const unsigned char *)chars, length); + handled = YES; + } + if (!handled) { + [super pressesBegan:presses withEvent:event]; + } +} + @end -@interface VivaIOSViewController : UIViewController +@interface VivaIOSViewController : UIViewController { + VivaIOSView *_surface; +} +- (void)setSurface:(VivaIOSView *)surface; @end @implementation VivaIOSViewController +- (void)loadView { + UIView *root = [[UIView alloc] init]; + root.backgroundColor = UIColor.systemBackgroundColor; + self.view = root; + [root release]; +} + +- (void)setSurface:(VivaIOSView *)surface { + _surface = surface; + [self.view addSubview:surface]; + [[NSNotificationCenter defaultCenter] addObserver:self + selector:@selector(keyboardWillChange:) + name:UIKeyboardWillChangeFrameNotification + object:nil]; +} + +- (void)dealloc { + [[NSNotificationCenter defaultCenter] removeObserver:self]; + [super dealloc]; +} + +// keyboardWillChange moves the surface with the keyboard, in the keyboard's own +// animation. +- (void)keyboardWillChange:(NSNotification *)notification { + NSTimeInterval duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue]; + UIViewAnimationOptions curve = [notification.userInfo[UIKeyboardAnimationCurveUserInfoKey] unsignedIntegerValue] << 16; + [self.view setNeedsLayout]; + [UIView animateWithDuration:duration delay:0 options:curve animations:^{ + [self.view layoutIfNeeded]; + } completion:nil]; +} + +// viewDidLayoutSubviews puts the surface inside what the system covers: the status +// bar and the sensor housing, the home indicator, and the keyboard. A program that +// wants the whole screen asks for it (ADR 0095). +- (void)viewDidLayoutSubviews { + [super viewDidLayoutSubviews]; + CGRect bounds = UIEdgeInsetsInsetRect(self.view.bounds, self.view.safeAreaInsets); + CGFloat keyboardTop = CGRectGetMinY(self.view.keyboardLayoutGuide.layoutFrame); + if (keyboardTop < CGRectGetMaxY(bounds)) { + bounds.size.height = MAX(keyboardTop - bounds.origin.y, 0); + } + _surface.frame = bounds; +} + - (UIInterfaceOrientationMask)supportedInterfaceOrientations { return UIInterfaceOrientationMaskAll; } @@ -267,6 +352,10 @@ - (UIInterfaceOrientationMask)supportedInterfaceOrientations { @interface VivaIOSAppDelegate : UIResponder @end +/* The one window an iPhone application shows (see viva_application_open_window). */ +static UIWindow *viva_ios_window; +static VivaIOSView *viva_ios_view; + @implementation VivaIOSAppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { @@ -274,11 +363,21 @@ - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:( return YES; } -@end +// The application goes behind another and comes back: it is told, and on the way +// back asks for a frame, since what the layer shows may not be what it should. +- (void)applicationDidEnterBackground:(UIApplication *)application { + if (viva_ios_view != nil && !viva_ios_view.closed) { + vivaIOSVisibility(viva_ios_view.callbackHandle, viva_ios_view, 0); + } +} -/* The one window an iPhone application shows (see viva_application_open_window). */ -static UIWindow *viva_ios_window; -static VivaIOSView *viva_ios_view; +- (void)applicationWillEnterForeground:(UIApplication *)application { + if (viva_ios_view != nil && !viva_ios_view.closed) { + vivaIOSVisibility(viva_ios_view.callbackHandle, viva_ios_view, 1); + } +} + +@end int viva_ios_main(void) { @autoreleasepool { @@ -343,7 +442,8 @@ int viva_application_last_status(void) { return NULL; } VivaIOSViewController *controller = [[VivaIOSViewController alloc] init]; - controller.view = view; + [controller loadViewIfNeeded]; + [controller setSurface:view]; UIWindow *window = [[UIWindow alloc] initWithFrame:screen]; window.rootViewController = controller; [window makeKeyAndVisible]; diff --git a/internal/platform/darwin/ios_keys.go b/internal/platform/darwin/ios_keys.go new file mode 100644 index 000000000..3d3c36544 --- /dev/null +++ b/internal/platform/darwin/ios_keys.go @@ -0,0 +1,128 @@ +//go:build ios + +package darwin + +/* +#include "native.h" +*/ +import "C" + +import ( + "fmt" + "unsafe" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/input" +) + +// UIKeyModifierFlags, as UIKey reports them. +const ( + uiKeyModifierShift = 1 << 17 + uiKeyModifierControl = 1 << 18 + uiKeyModifierAlt = 1 << 19 + uiKeyModifierCommand = 1 << 20 +) + +// keyOfUsage is the key a USB HID usage of the keyboard page names, for the keys that +// are not text: what a connected keyboard reports in UIKey.keyCode. +func keyOfUsage(usage int) gfx.Key { + switch { + case usage >= 0x3A && usage <= 0x45: // F1 to F12 + return gfx.KeyF1 + gfx.Key(usage-0x3A) + } + switch usage { + case 0x28, 0x58: // Return, keypad Enter + return gfx.KeyEnter + case 0x29: + return gfx.KeyEscape + case 0x2A: + return gfx.KeyBackspace + case 0x2B: + return gfx.KeyTab + case 0x2C: + return gfx.KeySpace + case 0x49: + return gfx.KeyInsert + case 0x4A: + return gfx.KeyHome + case 0x4B: + return gfx.KeyPageUp + case 0x4C: + return gfx.KeyDelete + case 0x4D: + return gfx.KeyEnd + case 0x4E: + return gfx.KeyPageDown + case 0x4F: + return gfx.KeyRight + case 0x50: + return gfx.KeyLeft + case 0x51: + return gfx.KeyDown + case 0x52: + return gfx.KeyUp + } + return gfx.KeyUnknown +} + +func keyModifiers(flags int) input.Modifiers { + var modifiers input.Modifiers + if flags&uiKeyModifierShift != 0 { + modifiers |= input.ModifierShift + } + if flags&uiKeyModifierControl != 0 { + modifiers |= input.ModifierControl + } + if flags&uiKeyModifierAlt != 0 { + modifiers |= input.ModifierAlt + } + if flags&uiKeyModifierCommand != 0 { + modifiers |= input.ModifierMeta + } + return modifiers +} + +// vivaIOSKeyEvent is a key of a connected keyboard. A key that is not text is a key +// event; a chord with Control or Command and a character is offered as a shortcut, +// and is a key event only if nothing took it. What a key types is the text input's. +// +//export vivaIOSKeyEvent +func vivaIOSKeyEvent(handle C.uintptr_t, view unsafe.Pointer, usage C.int, flags C.int, repeat C.int, utf8 *C.uchar, utf8Length C.size_t) { + state, ok := runStateFor(handle) + if !ok || state.closed { + return + } + modifiers := keyModifiers(int(flags)) + key := keyOfUsage(int(usage)) + chord := modifiers&(input.ModifierControl|input.ModifierMeta) != 0 && utf8Length > 0 + if chord && vivaShortcutEvent(handle, view, C.int(key), C.int(modifiers), repeat, utf8, utf8Length) != 0 { + return + } + if key == gfx.KeyUnknown && !chord { + return + } + deliverKey(handle, view, KeyEvent{Key: key, Modifiers: modifiers, Repeat: repeat != 0}, utf8, utf8Length) +} + +// vivaIOSVisibility follows the application going behind another and coming back. +// Coming back, the window is drawn again: what the layer holds may not be the scene. +// +//export vivaIOSVisibility +func vivaIOSVisibility(handle C.uintptr_t, view unsafe.Pointer, visible C.int) { + state, ok := runStateFor(handle) + if !ok || state.closed { + return + } + vivaWindowOccluded(handle, view, visible) + if visible == 0 || state.redrawHandler == nil { + return + } + frame, err := state.redrawHandler() + if err == nil { + err = presentFrame(state, view, frame, false) + } + if err != nil { + state.err = fmt.Errorf("darwin: drawing after the application returned: %w", err) + C.viva_view_close(view) + } +} From 9d8c9cc63bb865e5154295fd112c2d6f517ec609 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 22 Nov 2026 23:14:41 +0800 Subject: [PATCH 32/64] feat(android): the input method, keyboards, mouse and the surface's size A focused text input is the input method's: the host's view is a text editor while the application has one, an InputConnection sends every edit to the program and returns when it has been applied and the editor's state is sent back, because keyboards read what surrounds the cursor as soon as they type. internal/platform/imebridge turns what Android and UIKit do in UTF-16 ranges (commit, compose, replace, delete around the cursor, reopen a word) into the text events the editor takes, and the keys of a hardware keyboard into typing or editing as the desktops' text services do; it is tested on the host against the real editor. A hardware keyboard's named keys, a mouse's hover and wheel reach the application. The swapchain is made at the size the host reported for the surface (SurfaceSource.HostSize), since Android tells the swapchain a surface's new size a frame later than the program. viva run waits for a device that has just started. --- cmd/viva/android.go | 28 ++ cmd/viva/android_test.go | 36 +++ internal/platform/android/android.go | 30 +- internal/platform/android/exports_android.go | 63 +++++ .../hostsrc/java/dev/viva/host/Editor.java | 60 ++++ .../hostsrc/java/dev/viva/host/Host.java | 24 +- .../hostsrc/java/dev/viva/host/Native.java | 28 ++ .../java/dev/viva/host/VivaActivity.java | 7 +- .../dev/viva/host/VivaInputConnection.java | 121 ++++++++ .../hostsrc/java/dev/viva/host/VivaView.java | 116 ++++++++ internal/platform/android/input_android.go | 254 +++++++++++++++++ internal/platform/android/jni_android.c | 24 +- internal/platform/android/jni_android.h | 2 + internal/platform/android/surface_android.go | 1 + internal/platform/android/touch_android.go | 49 ++++ internal/platform/imebridge/imebridge.go | 259 ++++++++++++++++++ internal/platform/imebridge/imebridge_test.go | 210 ++++++++++++++ internal/platform/vulkan/vulkan_linux.go | 7 +- 18 files changed, 1311 insertions(+), 8 deletions(-) create mode 100644 internal/platform/android/hostsrc/java/dev/viva/host/Editor.java create mode 100644 internal/platform/android/hostsrc/java/dev/viva/host/VivaInputConnection.java create mode 100644 internal/platform/android/hostsrc/java/dev/viva/host/VivaView.java create mode 100644 internal/platform/android/input_android.go create mode 100644 internal/platform/imebridge/imebridge.go create mode 100644 internal/platform/imebridge/imebridge_test.go diff --git a/cmd/viva/android.go b/cmd/viva/android.go index 421ac1d41..475a1be1e 100644 --- a/cmd/viva/android.go +++ b/cmd/viva/android.go @@ -571,6 +571,9 @@ func runOnAndroid(plan buildPlan, requested string, output io.Writer) error { if err != nil { return err } + if err := waitForPackageService(sdk, device.Serial, output); err != nil { + return err + } if _, err := adb(sdk, device.Serial, "install", "-r", plan.out); err != nil { return err } @@ -581,3 +584,28 @@ func runOnAndroid(plan buildPlan, requested string, output io.Writer) error { fmt.Fprintf(output, "started %s on %s\n", id, device.Serial) return nil } + +// bootWait bounds how long run waits for a device that has just started. +const ( + bootAttempts = 90 + bootPause = 2 * time.Second +) + +// pause waits between boot checks; tests replace it. +var pause = time.Sleep + +// waitForPackageService waits for the device to have its package service: an emulator +// that is still starting is a device adb already lists, and answers an install with +// "Can't find service: package". +func waitForPackageService(sdk androidSDK, serial string, output io.Writer) error { + for attempt := 0; attempt < bootAttempts; attempt++ { + if _, err := adb(sdk, serial, "shell", "pm", "path", "android"); err == nil { + return nil + } + if attempt == 0 { + fmt.Fprintf(output, "waiting for %s to finish starting\n", serial) + } + pause(bootPause) + } + return fmt.Errorf("%s did not finish starting in %v", serial, bootAttempts*bootPause) +} diff --git a/cmd/viva/android_test.go b/cmd/viva/android_test.go index 16388b5aa..6e42913e6 100644 --- a/cmd/viva/android_test.go +++ b/cmd/viva/android_test.go @@ -3,11 +3,13 @@ package main import ( "archive/zip" "encoding/xml" + "errors" "io" "os" "path/filepath" "strings" "testing" + "time" ) // Releases are ordered by a number: a later version is never a smaller one, and a @@ -230,3 +232,37 @@ func TestAddToAPKStoresTheLibraryAndKeepsTheBase(t *testing.T) { t.Errorf("library entry %q method %d, want it stored", contents[name], methods[name]) } } + +// A device adb lists while it is still starting answers nothing yet: run waits for it +// and then installs, instead of failing on the first try. +func TestRunWaitsForADeviceThatIsStillStarting(t *testing.T) { + asked := 0 + previous, previousPause := adb, pause + t.Cleanup(func() { adb, pause = previous, previousPause }) + adb = func(sdk androidSDK, serial string, arguments ...string) (string, error) { + asked++ + if asked < 4 { + return "", errors.New("cmd: Can't find service: package") + } + return "package:/system/framework/framework-res.apk", nil + } + pauses := 0 + pause = func(time.Duration) { pauses++ } + var output strings.Builder + if err := waitForPackageService(androidSDK{}, "emulator-5554", &output); err != nil { + t.Fatal(err) + } + if asked != 4 || pauses != 3 || !strings.Contains(output.String(), "waiting") { + t.Fatalf("asked %d times, paused %d, said %q", asked, pauses, output.String()) + } +} + +func TestRunGivesUpOnADeviceThatNeverStarts(t *testing.T) { + previous, previousPause := adb, pause + t.Cleanup(func() { adb, pause = previous, previousPause }) + adb = func(androidSDK, string, ...string) (string, error) { return "", errors.New("no service") } + pause = func(time.Duration) {} + if err := waitForPackageService(androidSDK{}, "emulator-5554", io.Discard); err == nil { + t.Fatal("a device that never started was waited for forever") + } +} diff --git a/internal/platform/android/android.go b/internal/platform/android/android.go index befc36f50..3b969b97f 100644 --- a/internal/platform/android/android.go +++ b/internal/platform/android/android.go @@ -38,6 +38,11 @@ const ( eventClose // the user asked to close the window eventWake // something was posted eventRedraw // the application asked for a frame + eventText // the input method edits the text input + eventKey // a key of a keyboard + eventHover // a mouse over the surface + eventHoverExit // the mouse left it + eventScroll // a wheel ) // event is one thing that happened, small enough to queue by value. @@ -52,8 +57,16 @@ type event struct { action, pointer, tool, buttons, modifiers int32 x, y float32 time int64 - // ack is answered once the program no longer uses the surface it is told to let go of. + // ack is answered once the program no longer uses the surface it is told to let go of, + // or has applied the edit it was sent. ack chan struct{} + // edit is eventText's operation. + edit edit + // A key: its Android code, the character it types and whether it repeats; the modifiers + // are modifiers above. A scroll's distances are dx and dy. + keyCode, unicode int32 + repeat bool + dx, dy float32 // visible is eventVisible's state. visible bool } @@ -192,6 +205,14 @@ func (application *application) handle(ev event) { application.runPosts() case eventRedraw: application.redrawNow() + case eventText: + application.textEdit(ev) + case eventKey: + application.keyEvent(ev) + case eventHover, eventHoverExit: + application.hover(ev) + case eventScroll: + application.scroll(ev) case eventLowMemory: } } @@ -237,6 +258,8 @@ type window struct { height uint32 density float32 // device pixels per logical pixel renderer *vulkan.Renderer + text *textInput // the application's focused text input, if it has one + hovering bool // a mouse is over the surface } func (win *window) Close() { @@ -275,6 +298,7 @@ func (application *application) closeWindow() { win.renderer.Close() win.renderer = nil } + win.setTextInput(platform.TextInputUpdate{Changed: true}) win.releaseNative() application.done = true if win.config.OnClosed != nil { @@ -401,6 +425,7 @@ func (win *window) resized(swapchain bool) error { } else if _, err := renderer.Apply(frame); err != nil { return err } + win.setTextInput(frame.TextInput) } if err := renderer.Present(); err != nil { return err @@ -440,6 +465,9 @@ func (win *window) present(frame platform.Frame) error { if err == nil && changed { err = win.renderer.Present() } + if err == nil { + win.setTextInput(frame.TextInput) + } if err == nil && win.config.FramePresented != nil { win.config.FramePresented() } diff --git a/internal/platform/android/exports_android.go b/internal/platform/android/exports_android.go index c431b30df..50dda97e6 100644 --- a/internal/platform/android/exports_android.go +++ b/internal/platform/android/exports_android.go @@ -95,3 +95,66 @@ func Java_dev_viva_host_Native_lowMemory(env *C.JNIEnv, _ C.jclass) { func Java_dev_viva_host_Native_closeRequested(env *C.JNIEnv, _ C.jclass) { send(event{kind: eventClose}) } + +// edit queues an input method's edit and returns when the program has applied it: the +// input method asks what is around the cursor as soon as it has typed. +func queueEdit(operation textOperation, text string, first, last int32, codePoints bool) { + ack := make(chan struct{}) + send(event{kind: eventText, ack: ack, edit: edit{operation: operation, text: text, first: first, last: last, codePoints: codePoints}}) + <-ack +} + +//export Java_dev_viva_host_Native_commitText +func Java_dev_viva_host_Native_commitText(env *C.JNIEnv, _ C.jclass, text C.jstring, newCursor C.jint) { + queueEdit(opCommit, goString(env, text), int32(newCursor), 0, false) +} + +//export Java_dev_viva_host_Native_setComposingText +func Java_dev_viva_host_Native_setComposingText(env *C.JNIEnv, _ C.jclass, text C.jstring, newCursor C.jint) { + queueEdit(opSetComposing, goString(env, text), int32(newCursor), 0, false) +} + +//export Java_dev_viva_host_Native_finishComposing +func Java_dev_viva_host_Native_finishComposing(env *C.JNIEnv, _ C.jclass) { + queueEdit(opFinish, "", 0, 0, false) +} + +//export Java_dev_viva_host_Native_deleteSurrounding +func Java_dev_viva_host_Native_deleteSurrounding(env *C.JNIEnv, _ C.jclass, before, after C.jint, codePoints C.jboolean) { + queueEdit(opDeleteSurrounding, "", int32(before), int32(after), codePoints != 0) +} + +//export Java_dev_viva_host_Native_setSelection +func Java_dev_viva_host_Native_setSelection(env *C.JNIEnv, _ C.jclass, start, end C.jint) { + queueEdit(opSelect, "", int32(start), int32(end), false) +} + +//export Java_dev_viva_host_Native_setComposingRegion +func Java_dev_viva_host_Native_setComposingRegion(env *C.JNIEnv, _ C.jclass, start, end C.jint) { + queueEdit(opMarkRange, "", int32(start), int32(end), false) +} + +//export Java_dev_viva_host_Native_editorAction +func Java_dev_viva_host_Native_editorAction(env *C.JNIEnv, _ C.jclass, action C.jint) { + send(event{kind: eventText, edit: edit{operation: opAction, editorAction: int32(action)}}) +} + +//export Java_dev_viva_host_Native_key +func Java_dev_viva_host_Native_key(env *C.JNIEnv, _ C.jclass, keyCode, meta, unicode C.jint, repeat C.jboolean) { + send(event{kind: eventKey, keyCode: int32(keyCode), modifiers: int32(meta), unicode: int32(unicode), repeat: repeat != 0}) +} + +//export Java_dev_viva_host_Native_hover +func Java_dev_viva_host_Native_hover(env *C.JNIEnv, _ C.jclass, x, y C.jfloat, meta C.jint, uptime C.jlong) { + sendMove(event{kind: eventHover, x: float32(x), y: float32(y), modifiers: int32(meta), time: int64(uptime)}) +} + +//export Java_dev_viva_host_Native_hoverExit +func Java_dev_viva_host_Native_hoverExit(env *C.JNIEnv, _ C.jclass) { + send(event{kind: eventHoverExit}) +} + +//export Java_dev_viva_host_Native_scroll +func Java_dev_viva_host_Native_scroll(env *C.JNIEnv, _ C.jclass, x, y, dx, dy C.jfloat, meta C.jint) { + send(event{kind: eventScroll, x: float32(x), y: float32(y), dx: float32(dx), dy: float32(dy), modifiers: int32(meta)}) +} diff --git a/internal/platform/android/hostsrc/java/dev/viva/host/Editor.java b/internal/platform/android/hostsrc/java/dev/viva/host/Editor.java new file mode 100644 index 000000000..2222bd5d3 --- /dev/null +++ b/internal/platform/android/hostsrc/java/dev/viva/host/Editor.java @@ -0,0 +1,60 @@ +package dev.viva.host; + +/** + * The text input the program has focused, as the input method reads it: the text and + * where the selection and the composing text are, in UTF-16 units. The program is the + * owner of it and sends it whole after every change; the input method only reads. + */ +final class Editor { + private Editor() {} + + private static String text = ""; + private static int selectionStart; + private static int selectionEnd; + private static int compositionStart = -1; + private static int compositionEnd = -1; + + static synchronized void set(String value, int start, int end, int compStart, int compEnd) { + text = value; + selectionStart = start; + selectionEnd = end; + compositionStart = compStart; + compositionEnd = compEnd; + } + + static synchronized String text() { + return text; + } + + static synchronized int selectionStart() { + return Math.min(selectionStart, selectionEnd); + } + + static synchronized int selectionEnd() { + return Math.max(selectionStart, selectionEnd); + } + + static synchronized int compositionStart() { + return compositionStart; + } + + static synchronized int compositionEnd() { + return compositionEnd; + } + + static synchronized CharSequence before(int length) { + int end = selectionStart(); + return text.substring(Math.max(0, end - length), end); + } + + static synchronized CharSequence after(int length) { + int start = selectionEnd(); + return text.substring(start, Math.min(text.length(), start + length)); + } + + static synchronized CharSequence selected() { + int start = selectionStart(); + int end = selectionEnd(); + return start == end ? null : text.substring(start, end); + } +} diff --git a/internal/platform/android/hostsrc/java/dev/viva/host/Host.java b/internal/platform/android/hostsrc/java/dev/viva/host/Host.java index ad76b8dc4..d3a0c4c98 100644 --- a/internal/platform/android/hostsrc/java/dev/viva/host/Host.java +++ b/internal/platform/android/hostsrc/java/dev/viva/host/Host.java @@ -8,9 +8,31 @@ public final class Host { private Host() {} private static volatile Activity activity; + private static volatile VivaView view; - static void attach(Activity current) { + static void attach(Activity current, VivaView surface) { activity = current; + view = surface; + } + + /** + * The program's focused text input has this text: the input method reads it from + * here, and is told when it changes under it. + */ + public static void editor(String text, int selectionStart, int selectionEnd, int compositionStart, int compositionEnd) { + Editor.set(text, selectionStart, selectionEnd, compositionStart, compositionEnd); + final VivaView current = view; + if (current != null) { + current.post(current::editorChanged); + } + } + + /** Shows the keyboard for a text input, or takes it away when editing is false. */ + public static void keyboard(final boolean editing, final boolean multiline, final boolean secure) { + final VivaView current = view; + if (current != null) { + current.post(() -> current.configure(editing, multiline, secure)); + } } /** Ends the activity; the program's window is gone with it. */ diff --git a/internal/platform/android/hostsrc/java/dev/viva/host/Native.java b/internal/platform/android/hostsrc/java/dev/viva/host/Native.java index 0d2bcb5e1..c527ca932 100644 --- a/internal/platform/android/hostsrc/java/dev/viva/host/Native.java +++ b/internal/platform/android/hostsrc/java/dev/viva/host/Native.java @@ -34,4 +34,32 @@ private Native() {} /** The user asked to close the window (the back gesture at the root). */ public static native void closeRequested(); + + // The input method's edits of the program's focused text input, in UTF-16 units. Each + // returns when the program has applied it and sent the editor's state (Host.editor). + + public static native void commitText(String text, int newCursorPosition); + + public static native void setComposingText(String text, int newCursorPosition); + + public static native void finishComposing(); + + public static native void deleteSurrounding(int before, int after, boolean codePoints); + + public static native void setSelection(int start, int end); + + public static native void setComposingRegion(int start, int end); + + public static native void editorAction(int action); + + /** A key of a keyboard: its Android key code, the meta state and the character it types. */ + public static native void key(int keyCode, int meta, int unicode, boolean repeat); + + /** A mouse over the surface. */ + public static native void hover(float x, float y, int meta, long uptimeMillis); + + public static native void hoverExit(); + + /** A wheel, in pixels. */ + public static native void scroll(float x, float y, float dx, float dy, int meta); } diff --git a/internal/platform/android/hostsrc/java/dev/viva/host/VivaActivity.java b/internal/platform/android/hostsrc/java/dev/viva/host/VivaActivity.java index e640735c7..bcb3eeea6 100644 --- a/internal/platform/android/hostsrc/java/dev/viva/host/VivaActivity.java +++ b/internal/platform/android/hostsrc/java/dev/viva/host/VivaActivity.java @@ -5,7 +5,6 @@ import android.os.Bundle; import android.view.MotionEvent; import android.view.SurfaceHolder; -import android.view.SurfaceView; import android.view.View; import android.view.Window; import android.view.WindowInsets; @@ -17,14 +16,14 @@ * what happened; nothing here lays anything out. */ public class VivaActivity extends Activity implements SurfaceHolder.Callback { - private SurfaceView view; + private VivaView view; @Override protected void onCreate(Bundle state) { super.onCreate(state); requestWindowFeature(Window.FEATURE_NO_TITLE); - Host.attach(this); - view = new SurfaceView(this); + view = new VivaView(this); + Host.attach(this, view); view.getHolder().addCallback(this); view.setOnTouchListener(this::onTouch); // The surface lies inside what the system covers: its bars, the display cutout diff --git a/internal/platform/android/hostsrc/java/dev/viva/host/VivaInputConnection.java b/internal/platform/android/hostsrc/java/dev/viva/host/VivaInputConnection.java new file mode 100644 index 000000000..efbd13184 --- /dev/null +++ b/internal/platform/android/hostsrc/java/dev/viva/host/VivaInputConnection.java @@ -0,0 +1,121 @@ +package dev.viva.host; + +import android.view.KeyEvent; +import android.view.View; +import android.view.inputmethod.BaseInputConnection; +import android.view.inputmethod.CompletionInfo; +import android.view.inputmethod.ExtractedText; +import android.view.inputmethod.ExtractedTextRequest; + +/** + * What an input method says to the program's focused text input. Each edit is sent to + * the program and answered when it has been applied, with the editor's state (Editor) + * as it is after, because a keyboard asks what is around the cursor as soon as it has + * typed. + */ +final class VivaInputConnection extends BaseInputConnection { + VivaInputConnection(View view) { + super(view, false); + } + + @Override + public boolean commitText(CharSequence text, int newCursorPosition) { + Native.commitText(text.toString(), newCursorPosition); + return true; + } + + @Override + public boolean setComposingText(CharSequence text, int newCursorPosition) { + Native.setComposingText(text.toString(), newCursorPosition); + return true; + } + + @Override + public boolean finishComposingText() { + Native.finishComposing(); + return true; + } + + @Override + public boolean deleteSurroundingText(int before, int after) { + Native.deleteSurrounding(before, after, false); + return true; + } + + @Override + public boolean deleteSurroundingTextInCodePoints(int before, int after) { + Native.deleteSurrounding(before, after, true); + return true; + } + + @Override + public boolean setSelection(int start, int end) { + Native.setSelection(start, end); + return true; + } + + @Override + public boolean setComposingRegion(int start, int end) { + Native.setComposingRegion(start, end); + return true; + } + + @Override + public boolean performEditorAction(int action) { + Native.editorAction(action); + return true; + } + + @Override + public boolean sendKeyEvent(KeyEvent event) { + // A soft keyboard's Delete and Enter come as keys. + if (event.getAction() == KeyEvent.ACTION_DOWN) { + Native.key(event.getKeyCode(), event.getMetaState(), event.getUnicodeChar(event.getMetaState()), event.getRepeatCount() > 0); + } + return true; + } + + @Override + public CharSequence getTextBeforeCursor(int length, int flags) { + return Editor.before(length); + } + + @Override + public CharSequence getTextAfterCursor(int length, int flags) { + return Editor.after(length); + } + + @Override + public CharSequence getSelectedText(int flags) { + return Editor.selected(); + } + + @Override + public int getCursorCapsMode(int reqModes) { + return 0; + } + + @Override + public ExtractedText getExtractedText(ExtractedTextRequest request, int flags) { + ExtractedText extracted = new ExtractedText(); + extracted.text = Editor.text(); + extracted.selectionStart = Editor.selectionStart(); + extracted.selectionEnd = Editor.selectionEnd(); + return extracted; + } + + @Override + public boolean commitCompletion(CompletionInfo text) { + return false; + } + + @Override + public boolean beginBatchEdit() { + return true; + } + + @Override + public boolean endBatchEdit() { + return true; + } +} diff --git a/internal/platform/android/hostsrc/java/dev/viva/host/VivaView.java b/internal/platform/android/hostsrc/java/dev/viva/host/VivaView.java new file mode 100644 index 000000000..12d985f9d --- /dev/null +++ b/internal/platform/android/hostsrc/java/dev/viva/host/VivaView.java @@ -0,0 +1,116 @@ +package dev.viva.host; + +import android.content.Context; +import android.text.InputType; +import android.view.KeyEvent; +import android.view.MotionEvent; +import android.view.SurfaceView; +import android.view.ViewConfiguration; +import android.view.inputmethod.EditorInfo; +import android.view.inputmethod.InputConnection; +import android.view.inputmethod.InputMethodManager; + +/** + * The surface the program draws on, which is also what the keyboard types into when + * the program has a text input focused. + */ +final class VivaView extends SurfaceView { + private boolean editing; + private boolean multiline; + private boolean secure; + + VivaView(Context context) { + super(context); + setFocusable(true); + setFocusableInTouchMode(true); + } + + /** Makes the view a text editor, or not, and restarts the input method on it. */ + void configure(boolean editing, boolean multiline, boolean secure) { + boolean restart = this.editing != editing || this.multiline != multiline || this.secure != secure; + this.editing = editing; + this.multiline = multiline; + this.secure = secure; + InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE); + if (imm == null) { + return; + } + if (!editing) { + imm.hideSoftInputFromWindow(getWindowToken(), 0); + if (restart) { + imm.restartInput(this); + } + return; + } + requestFocus(); + if (restart) { + imm.restartInput(this); + } + imm.showSoftInput(this, 0); + } + + /** The program changed the text under the input method. */ + void editorChanged() { + InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE); + if (imm != null && editing) { + imm.updateSelection(this, Editor.selectionStart(), Editor.selectionEnd(), Editor.compositionStart(), Editor.compositionEnd()); + } + } + + @Override + public boolean onCheckIsTextEditor() { + return editing; + } + + @Override + public InputConnection onCreateInputConnection(EditorInfo info) { + if (!editing) { + return null; + } + int type = InputType.TYPE_CLASS_TEXT; + if (multiline) { + type |= InputType.TYPE_TEXT_FLAG_MULTI_LINE; + } + if (secure) { + type |= InputType.TYPE_TEXT_VARIATION_PASSWORD; + } + info.inputType = type; + info.imeOptions = EditorInfo.IME_FLAG_NO_FULLSCREEN | EditorInfo.IME_FLAG_NO_EXTRACT_UI + | (multiline ? EditorInfo.IME_ACTION_NONE : EditorInfo.IME_ACTION_DONE); + info.initialSelStart = Editor.selectionStart(); + info.initialSelEnd = Editor.selectionEnd(); + return new VivaInputConnection(this); + } + + @Override + public boolean onKeyDown(int keyCode, KeyEvent event) { + if (keyCode == KeyEvent.KEYCODE_BACK) { + return super.onKeyDown(keyCode, event); + } + Native.key(keyCode, event.getMetaState(), event.getUnicodeChar(event.getMetaState()), event.getRepeatCount() > 0); + return true; + } + + @Override + public boolean onGenericMotionEvent(MotionEvent event) { + long time = event.getEventTime(); + switch (event.getActionMasked()) { + case MotionEvent.ACTION_HOVER_MOVE: + case MotionEvent.ACTION_HOVER_ENTER: + Native.hover(event.getX(), event.getY(), event.getMetaState(), time); + return true; + case MotionEvent.ACTION_HOVER_EXIT: + Native.hoverExit(); + return true; + case MotionEvent.ACTION_SCROLL: { + ViewConfiguration configuration = ViewConfiguration.get(getContext()); + float horizontal = event.getAxisValue(MotionEvent.AXIS_HSCROLL) * configuration.getScaledHorizontalScrollFactor(); + float vertical = event.getAxisValue(MotionEvent.AXIS_VSCROLL) * configuration.getScaledVerticalScrollFactor(); + Native.scroll(event.getX(), event.getY(), horizontal, vertical, event.getMetaState()); + return true; + } + default: + return super.onGenericMotionEvent(event); + } + } +} diff --git a/internal/platform/android/input_android.go b/internal/platform/android/input_android.go new file mode 100644 index 000000000..1ca1366e7 --- /dev/null +++ b/internal/platform/android/input_android.go @@ -0,0 +1,254 @@ +//go:build android + +package android + +/* +#include "jni_android.h" +*/ +import "C" + +import ( + "unsafe" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/input" + "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/internal/platform/imebridge" +) + +// Android's key codes of the keys that are not text, and its meta state. +const ( + keycodeBack = 4 + keycodeDpadUp = 19 + keycodeDpadDown = 20 + keycodeDpadLeft = 21 + keycodeDpadRight = 22 + keycodeTab = 61 + keycodeSpace = 62 + keycodeEnter = 66 + keycodeDelete = 67 // the key that deletes backward + keycodeEscape = 111 + keycodeForwardDel = 112 + keycodeMoveHome = 122 + keycodeMoveEnd = 123 + keycodeInsert = 124 + keycodePageUp = 92 + keycodePageDown = 93 + keycodeF1 = 131 + keycodeF12 = 142 + keycodeNumpadEnter = 160 +) + +// keyOfCode is the key an Android key code names, for the keys that are not text. +func keyOfCode(code int32) gfx.Key { + if code >= keycodeF1 && code <= keycodeF12 { + return gfx.KeyF1 + gfx.Key(code-keycodeF1) + } + switch code { + case keycodeDpadUp: + return gfx.KeyUp + case keycodeDpadDown: + return gfx.KeyDown + case keycodeDpadLeft: + return gfx.KeyLeft + case keycodeDpadRight: + return gfx.KeyRight + case keycodeTab: + return gfx.KeyTab + case keycodeSpace: + return gfx.KeySpace + case keycodeEnter, keycodeNumpadEnter: + return gfx.KeyEnter + case keycodeDelete: + return gfx.KeyBackspace + case keycodeEscape: + return gfx.KeyEscape + case keycodeForwardDel: + return gfx.KeyDelete + case keycodeMoveHome: + return gfx.KeyHome + case keycodeMoveEnd: + return gfx.KeyEnd + case keycodeInsert: + return gfx.KeyInsert + case keycodePageUp: + return gfx.KeyPageUp + case keycodePageDown: + return gfx.KeyPageDown + } + return gfx.KeyUnknown +} + +// textOperation is what the input method does to the text input. +type textOperation uint8 + +const ( + opCommit textOperation = iota + 1 + opSetComposing + opFinish + opDeleteSurrounding + opSelect + opMarkRange + opAction + opKey +) + +// textInput is the text input the application has focused. +type textInput struct { + session imebridge.Session + input *platform.TextInput +} + +// setTextInput follows the application's wish for its text input: another one, the +// same one with other text, or none (platform.TextInputUpdate). +func (win *window) setTextInput(update platform.TextInputUpdate) { + if !update.Changed { + return + } + if update.Input == nil { + if win.text != nil { + win.text = nil + C.viva_host_keyboard(0, 0, 0) + } + return + } + input := update.Input + restart := win.text == nil || win.text.input.Target != input.Target || win.text.input.Multiline != input.Multiline || win.text.input.Secure != input.Secure + win.text = &textInput{session: imebridge.Session{Handler: input.OnEvent, State: input.State}, input: input} + win.pushEditor() + if restart { + C.viva_host_keyboard(1, boolInt(input.Multiline), boolInt(input.Secure)) + } +} + +func boolInt(value bool) C.int { + if value { + return 1 + } + return 0 +} + +// pushEditor gives the host the text input's state, for the input method to read. +func (win *window) pushEditor() { + mirror := win.text.session.Mirror() + units := utf16Units(mirror.Text) + var data *C.uint16_t + if len(units) > 0 { + data = (*C.uint16_t)(unsafe.Pointer(&units[0])) + } + C.viva_host_editor(data, C.int(len(units)), C.int(mirror.SelStart), C.int(mirror.SelEnd), C.int(mirror.CompStart), C.int(mirror.CompEnd)) +} + +// edit is one edit of the input method. +type edit struct { + operation textOperation + text string + first, last int32 // newCursor, the range, or what to delete before and after + codePoints bool + editorAction int32 + action imebridge.KeyAction +} + +// textEdit applies an input method's edit to the application's text input, sends the state +// after it back, and shows what the application painted for it. +func (application *application) textEdit(ev event) { + if ev.ack != nil { + defer close(ev.ack) + } + win := application.window + if win == nil || win.closed || win.text == nil { + return + } + defer application.guard() + text, session := win.text, &win.text.session + var err error + switch ev.edit.operation { + case opCommit: + err = session.Commit(ev.edit.text, int(ev.edit.first)) + case opSetComposing: + err = session.SetComposing(ev.edit.text, int(ev.edit.first)) + case opFinish: + err = session.Finish() + case opDeleteSurrounding: + err = session.DeleteSurrounding(int(ev.edit.first), int(ev.edit.last), ev.edit.codePoints) + case opSelect: + err = session.Select(int(ev.edit.first), int(ev.edit.last)) + case opMarkRange: + err = session.MarkRange(int(ev.edit.first), int(ev.edit.last)) + case opKey: + err = ev.edit.action.Apply(session) + case opAction: + application.editorAction(ev.edit.editorAction) + return + } + if err != nil { + application.fail(err) + return + } + text.input.State = session.State + win.pushEditor() + if win.config.OnRedraw != nil { + frame, err := win.config.OnRedraw() + if err == nil { + err = win.present(frame) + } + if err != nil { + application.fail(err) + } + } +} + +// editorAction is the action key of a keyboard (Done, Go, Search): it is Enter. +func (application *application) editorAction(int32) { + application.keyEvent(event{keyCode: keycodeEnter}) +} + +// keyEvent gives the application a key of a keyboard. A key that is not text is a key +// event; a character, in a window with a text input, is typed into it; a chord with +// Control or Meta and a character is offered as a shortcut first. +func (application *application) keyEvent(ev event) { + win := application.window + if win == nil || win.closed || win.renderer == nil { + return + } + defer application.guard() + modifiers := modifiers(ev.modifiers) + key := keyOfCode(ev.keyCode) + character := "" + if ev.unicode > 0 { + character = string(rune(ev.unicode)) + } + chord := modifiers&(input.ModifierControl|input.ModifierMeta) != 0 && character != "" + if chord && win.config.OnShortcut != nil { + frame, handled, err := win.config.OnShortcut(platform.KeyEvent{Key: key, Modifiers: modifiers, Repeat: ev.repeat, Text: character}) + if err == nil { + err = win.present(frame) + } + if err != nil { + application.fail(err) + return + } + if handled { + return + } + } + if win.text != nil && !chord { + if action, ok := imebridge.KeyEdit(key, modifiers, character, win.text.input); ok { + application.textEdit(event{edit: edit{operation: opKey, action: action}}) + return + } + } + if key == gfx.KeyUnknown && !chord { + return + } + if win.config.OnKey == nil { + return + } + frame, err := win.config.OnKey(platform.KeyEvent{Key: key, Modifiers: modifiers, Repeat: ev.repeat, Text: character}) + if err == nil { + err = win.present(frame) + } + if err != nil { + application.fail(err) + } +} diff --git a/internal/platform/android/jni_android.c b/internal/platform/android/jni_android.c index 070d1e59e..da4c1e203 100644 --- a/internal/platform/android/jni_android.c +++ b/internal/platform/android/jni_android.c @@ -7,7 +7,7 @@ static JavaVM *vm; static jclass hostClass, textClass; -static jmethodID hostFinish, hostSetTitle; +static jmethodID hostFinish, hostSetTitle, hostEditor, hostKeyboard; static jmethodID textWidth, textMetrics, textRects, textSetFamily, textBegin, textDraw, textEnd; /* A JNI_OnLoad finds the host's classes while the loader that holds them is the caller's. */ @@ -26,6 +26,8 @@ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *jvm, void *reserved) { textClass = (*env)->NewGlobalRef(env, text); hostFinish = (*env)->GetStaticMethodID(env, hostClass, "finish", "()V"); hostSetTitle = (*env)->GetStaticMethodID(env, hostClass, "setTitle", "(Ljava/lang/String;)V"); + hostEditor = (*env)->GetStaticMethodID(env, hostClass, "editor", "(Ljava/lang/String;IIII)V"); + hostKeyboard = (*env)->GetStaticMethodID(env, hostClass, "keyboard", "(ZZZ)V"); textWidth = (*env)->GetStaticMethodID(env, textClass, "width", "(Ljava/lang/String;FIZZ)F"); textMetrics = (*env)->GetStaticMethodID(env, textClass, "metrics", "(FIZZ[F)V"); textRects = (*env)->GetStaticMethodID(env, textClass, "rects", "(Ljava/lang/String;FIZZZ[I[F[F)V"); @@ -208,3 +210,23 @@ void viva_host_set_title(const uint16_t *title, int length) { } void viva_log(int priority, const char *line) { __android_log_write(priority, "viva", line); } + +void viva_host_editor(const uint16_t *text, int length, int selectionStart, int selectionEnd, int compositionStart, int compositionEnd) { + JNIEnv *e = env(); + if (e == NULL) { + return; + } + jstring s = (*e)->NewString(e, (const jchar *)text, length); + (*e)->CallStaticVoidMethod(e, hostClass, hostEditor, s, selectionStart, selectionEnd, compositionStart, compositionEnd); + failed(e); + (*e)->DeleteLocalRef(e, s); +} + +void viva_host_keyboard(int editing, int multiline, int secure) { + JNIEnv *e = env(); + if (e != NULL) { + (*e)->CallStaticVoidMethod(e, hostClass, hostKeyboard, editing != 0, multiline != 0, secure != 0); + failed(e); + } +} + diff --git a/internal/platform/android/jni_android.h b/internal/platform/android/jni_android.h index a5a22e8a8..b1d587081 100644 --- a/internal/platform/android/jni_android.h +++ b/internal/platform/android/jni_android.h @@ -24,5 +24,7 @@ void viva_text_draw(const uint16_t *value, int length, float x, float baseline, int viva_text_end(void *out, int64_t capacity); /* The host (dev.viva.host.Host). */ +void viva_host_editor(const uint16_t *text, int length, int selectionStart, int selectionEnd, int compositionStart, int compositionEnd); +void viva_host_keyboard(int editing, int multiline, int secure); void viva_host_finish(void); void viva_host_set_title(const uint16_t *title, int length); diff --git a/internal/platform/android/surface_android.go b/internal/platform/android/surface_android.go index 6e5be7733..3fa640d53 100644 --- a/internal/platform/android/surface_android.go +++ b/internal/platform/android/surface_android.go @@ -38,6 +38,7 @@ func (win *window) surfaceSource() (vulkan.SurfaceSource, error) { } return vulkan.SurfaceSource{ Extension: "VK_KHR_android_surface", + HostSize: true, Create: func(instance uintptr) (uintptr, error) { native := win.native if native == nil { diff --git a/internal/platform/android/touch_android.go b/internal/platform/android/touch_android.go index 1d89c6cdb..f2223642d 100644 --- a/internal/platform/android/touch_android.go +++ b/internal/platform/android/touch_android.go @@ -118,3 +118,52 @@ func (application *application) touch(ev event) { application.fail(err) } } + +// hover gives the application a mouse over the surface, as a pointer that moves with no +// button, and its leaving. +func (application *application) hover(ev event) { + win := application.window + if win == nil || win.closed || win.config.OnPointer == nil || win.renderer == nil || win.native == nil || win.density <= 0 { + return + } + defer application.guard() + event := platform.PointerEvent{Kind: platform.PointerMove, Device: gfx.PointerMouse} + if ev.kind == eventHoverExit { + if !win.hovering { + return + } + win.hovering = false + event.Kind = platform.PointerExit + } else { + win.hovering = true + x, y := ev.x/win.density, ev.y/win.density + event.X, event.Y, event.ScreenX, event.ScreenY, event.Modifiers = x, y, x, y, modifiers(ev.modifiers) + } + frame, err := win.config.OnPointer(event) + if err == nil { + err = win.present(frame) + } + if err != nil { + application.fail(err) + } +} + +// scroll gives the application a wheel. Android reports a wheel up as positive; a scroll +// that moves the content up is a positive distance here, as on the other platforms. +func (application *application) scroll(ev event) { + win := application.window + if win == nil || win.closed || win.config.OnScroll == nil || win.renderer == nil || win.native == nil || win.density <= 0 { + return + } + defer application.guard() + x, y := ev.x/win.density, ev.y/win.density + frame, err := win.config.OnScroll(platform.ScrollEvent{ + Modifiers: modifiers(ev.modifiers), X: x, Y: y, DeltaX: ev.dx / win.density, DeltaY: -ev.dy / win.density, + }) + if err == nil { + err = win.present(frame) + } + if err != nil { + application.fail(err) + } +} diff --git a/internal/platform/imebridge/imebridge.go b/internal/platform/imebridge/imebridge.go new file mode 100644 index 000000000..5ed555e43 --- /dev/null +++ b/internal/platform/imebridge/imebridge.go @@ -0,0 +1,259 @@ +// Package imebridge turns what a phone's input method does into the text events +// the application's editor takes. Android's InputConnection and iOS's UITextInput +// both speak in UTF-16 ranges of a copy of the text, and commit, mark, replace and +// select in ways that differ from a desktop's; the bridge reads each operation +// against the editor's state as it stands, so an operation that follows another sees +// what the first did. It has no system call in it and is tested on the host. +package imebridge + +import ( + "unicode/utf16" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/input" + "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/text" +) + +// Session is one focused editor as the input method edits it: the state the +// application last gave, and the handler that applies an event and answers with the +// state after it. +type Session struct { + Handler platform.TextHandler + State platform.TextState +} + +// Mirror is the text and the ranges an input method reads, in UTF-16 units. +type Mirror struct { + Text string + SelStart, SelEnd int + CompStart, CompEnd int + Composing bool + SelectionEndIsCaret bool + TentativeComposition bool +} + +// Mirror is the state as the input method counts it. +func (session *Session) Mirror() Mirror { return MirrorOf(session.State) } + +// MirrorOf is state counted in UTF-16 units. +func MirrorOf(state platform.TextState) Mirror { + mirror := Mirror{ + Text: state.Value, + SelStart: text.UTF16Offset(state.Value, state.Selection.Start), + SelEnd: text.UTF16Offset(state.Value, state.Selection.End), + SelectionEndIsCaret: !state.SelectionReversed, + Composing: state.Composing, + } + if state.Composing { + mirror.CompStart = text.UTF16Offset(state.Value, state.Composition.Start) + mirror.CompEnd = text.UTF16Offset(state.Value, state.Composition.End) + } else { + mirror.CompStart, mirror.CompEnd = -1, -1 + } + return mirror +} + +// apply sends one event and takes the state after it. +func (session *Session) apply(event platform.TextEvent) error { + next, err := session.Handler(event) + if err != nil { + return err + } + session.State = next + return nil +} + +// units is the number of UTF-16 units of value. +func units(value string) int { return len(utf16.Encode([]rune(value))) } + +// runeRange is the rune range of the UTF-16 range [start, end) of value, clamped to the +// text and ordered. +func runeRange(value string, start, end int) text.Range { + length := units(value) + start, end = min(max(start, 0), length), min(max(end, 0), length) + if end < start { + start, end = end, start + } + return text.Range{Start: text.RuneIndexAtUTF16(value, start), End: text.RuneIndexAtUTF16(value, end)} +} + +// Commit puts value in place of the composing text, or of the selection when nothing is +// composing, and ends the composition: InputConnection.commitText and UIKeyInput's +// insertText. newCursor places the caret as commitText does: above zero, after the text +// counted from its end (1 is just after); zero or below, before it counted from its start. +func (session *Session) Commit(value string, newCursor int) error { + event := platform.TextEvent{Kind: platform.TextInsert, Text: value} + if session.State.Composing { + event.Replacement, event.HasReplacement = session.State.Composition, true + } + if err := session.apply(event); err != nil { + return err + } + if newCursor == 1 { + return nil + } + after := MirrorOf(session.State) + end := after.SelEnd + target := end + newCursor - 1 + if newCursor <= 0 { + target = end - units(value) + newCursor + } + target = min(max(target, 0), units(after.Text)) + if target == end { + return nil + } + return session.apply(platform.TextEvent{Kind: platform.TextSetSelection, Selection: runeRange(after.Text, target, target)}) +} + +// SetComposing replaces the composing text, or the selection when nothing is composing, +// with value, which stays composing: InputConnection.setComposingText. The caret is +// placed inside it as commitText's newCursor does. +func (session *Session) SetComposing(value string, newCursor int) error { + length := units(value) + caret := newCursor + if newCursor > 0 { + caret = length + newCursor - 1 + } + return session.SetMarked(value, caret, caret) +} + +// SetMarked replaces the composing text, or the selection, with value, composing, and +// selects [start, end) of it in UTF-16 units: UITextInput's setMarkedText. +func (session *Session) SetMarked(value string, start, end int) error { + event := platform.TextEvent{Kind: platform.TextSetMarked, Text: value, MarkedSelection: runeRange(value, start, end)} + if session.State.Composing { + event.Replacement, event.HasReplacement = session.State.Composition, true + } + return session.apply(event) +} + +// Finish ends the composition, keeping what is composed: finishComposingText and +// unmarkText. +func (session *Session) Finish() error { + if !session.State.Composing { + return nil + } + return session.apply(platform.TextEvent{Kind: platform.TextUnmark}) +} + +// DeleteSurrounding deletes before units before the selection and after units after it, +// counting UTF-16 units, or code points when codePoints says so. +func (session *Session) DeleteSurrounding(before, after int, codePoints bool) error { + mirror := MirrorOf(session.State) + start, end := mirror.SelStart, mirror.SelEnd + if start > end { + start, end = end, start + } + if codePoints { + runes := []rune(mirror.Text) + first := text.RuneIndexAtUTF16(mirror.Text, start) + last := text.RuneIndexAtUTF16(mirror.Text, end) + first = max(first-before, 0) + last = min(last+after, len(runes)) + return session.replace(text.Range{Start: first, End: last}, "") + } + return session.replace(runeRange(mirror.Text, start-before, end+after), "") +} + +// Replace puts value in place of the UTF-16 range [start, end): UITextInput's +// replaceRange, an autocorrection or a suggestion taken. +func (session *Session) Replace(start, end int, value string) error { + return session.replace(runeRange(session.State.Value, start, end), value) +} + +func (session *Session) replace(replacement text.Range, value string) error { + if replacement.Start == replacement.End && value == "" { + return nil + } + return session.apply(platform.TextEvent{Kind: platform.TextInsert, Text: value, Replacement: replacement, HasReplacement: true}) +} + +// Select selects [start, end) in UTF-16 units: setSelection and selectedTextRange. +func (session *Session) Select(start, end int) error { + return session.apply(platform.TextEvent{Kind: platform.TextSetSelection, Selection: runeRange(session.State.Value, start, end)}) +} + +// MarkRange makes text that is already there the composing text: setComposingRegion, +// which a keyboard uses to reopen a word it is about to correct. +func (session *Session) MarkRange(start, end int) error { + value := session.State.Value + rng := runeRange(value, start, end) + if rng.Start == rng.End { + return nil + } + marked := string([]rune(value)[rng.Start:rng.End]) + size := rng.End - rng.Start + return session.apply(platform.TextEvent{ + Kind: platform.TextSetMarked, Text: marked, MarkedSelection: text.Range{Start: size, End: size}, + Replacement: rng, HasReplacement: true, + }) +} + +// Command applies an editing command: deleteBackward of a hardware or software key. +func (session *Session) Command(command platform.TextCommand) error { + return session.apply(platform.TextEvent{Kind: platform.TextCommandEvent, Command: command}) +} + +// KeyEdit is what a key of a hardware keyboard does in a focused text input: type its +// character, or edit as the key says, which is how the desktops' native text services +// take the keys of a text field. A key it does not answer for, such as Enter in a field of +// one line, is for the application, and so are all the keys of a terminal. +func KeyEdit(key gfx.Key, modifiers input.Modifiers, character string, field *platform.TextInput) (KeyAction, bool) { + if field.Terminal { + return KeyAction{}, false + } + word := modifiers&(input.ModifierControl|input.ModifierAlt) != 0 + shift := modifiers&input.ModifierShift != 0 + choose := func(plain, selecting, byWord, selectingByWord platform.TextCommand) (KeyAction, bool) { + command := plain + switch { + case shift && word: + command = selectingByWord + case word: + command = byWord + case shift: + command = selecting + } + return KeyAction{Command: command}, command != 0 + } + switch key { + case gfx.KeyBackspace: + return choose(platform.TextDeleteBackward, platform.TextDeleteBackward, platform.TextDeleteWordBackward, platform.TextDeleteWordBackward) + case gfx.KeyDelete: + return choose(platform.TextDeleteForward, platform.TextDeleteForward, platform.TextDeleteWordForward, platform.TextDeleteWordForward) + case gfx.KeyLeft: + return choose(platform.TextMoveLeft, platform.TextMoveLeftAndModifySelection, platform.TextMoveWordLeft, platform.TextMoveWordLeftAndModifySelection) + case gfx.KeyRight: + return choose(platform.TextMoveRight, platform.TextMoveRightAndModifySelection, platform.TextMoveWordRight, platform.TextMoveWordRightAndModifySelection) + case gfx.KeyHome: + return choose(platform.TextMoveLineStart, platform.TextMoveLineStartAndModifySelection, platform.TextMoveLineStart, platform.TextMoveLineStartAndModifySelection) + case gfx.KeyEnd: + return choose(platform.TextMoveLineEnd, platform.TextMoveLineEndAndModifySelection, platform.TextMoveLineEnd, platform.TextMoveLineEndAndModifySelection) + case gfx.KeyEnter: + if field.Multiline { + return KeyAction{Command: platform.TextInsertNewline}, true + } + case gfx.KeySpace: + return KeyAction{Text: " "}, true + case gfx.KeyUnknown: + if character != "" { + return KeyAction{Text: character}, true + } + } + return KeyAction{}, false +} + +// KeyAction is what KeyEdit decided: a command to apply, or text to commit. +type KeyAction struct { + Command platform.TextCommand + Text string +} + +// Apply does the action to the session. +func (action KeyAction) Apply(session *Session) error { + if action.Command != 0 { + return session.Command(action.Command) + } + return session.Commit(action.Text, 1) +} diff --git a/internal/platform/imebridge/imebridge_test.go b/internal/platform/imebridge/imebridge_test.go new file mode 100644 index 000000000..5bf37cb75 --- /dev/null +++ b/internal/platform/imebridge/imebridge_test.go @@ -0,0 +1,210 @@ +package imebridge + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/input" + "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/text" +) + +// newSession is an editor holding initial, with the caret at its end, behind a session. +func newSession(initial string) (*Session, *text.Editor) { + editor := text.NewEditor(initial) + editor.SetSelection(text.Range{Start: editor.RuneCount(), End: editor.RuneCount()}) + session := &Session{ + Handler: func(event platform.TextEvent) (platform.TextState, error) { + event.Apply(editor) + return platform.EditorState(editor), nil + }, + State: platform.EditorState(editor), + } + return session, editor +} + +func must(t *testing.T, err error) { + t.Helper() + if err != nil { + t.Fatal(err) + } +} + +func TestCommitTypesAtTheCaretAndLeavesItAfter(t *testing.T) { + session, editor := newSession("ab") + must(t, session.Commit("cd", 1)) + if editor.String() != "abcd" || editor.Caret() != 4 { + t.Fatalf("text %q caret %d", editor.String(), editor.Caret()) + } +} + +// A keyboard that commits with a cursor before the text, or past it, moves the caret +// as commitText says. +func TestCommitPlacesTheCaretByItsNewCursorPosition(t *testing.T) { + for _, test := range []struct{ newCursor, caret int }{{1, 7}, {0, 4}, {-1, 3}, {2, 7}, {-9, 0}, {9, 7}} { + session, editor := newSession("abcd") + must(t, session.Commit("xyz", test.newCursor)) + if editor.String() != "abcdxyz" || editor.Caret() != test.caret { + t.Errorf("newCursor %d: text %q caret %d, want caret %d", test.newCursor, editor.String(), editor.Caret(), test.caret) + } + } +} + +// Composing, as a pinyin keyboard does: the letters are marked, replaced by the +// candidate, and committed over the composition, which ends it. +func TestAComposedWordIsMarkedReplacedAndCommitted(t *testing.T) { + session, editor := newSession("") + must(t, session.SetComposing("ni", 1)) + if composition, composing := editor.Composition(); !composing || editor.String() != "ni" || composition != (text.Range{Start: 0, End: 2}) { + t.Fatalf("after the first letters: %q composing=%v %v", editor.String(), composing, composition) + } + must(t, session.SetComposing("你", 1)) + if composition, composing := editor.Composition(); !composing || editor.String() != "你" || composition != (text.Range{Start: 0, End: 1}) { + t.Fatalf("after the candidate: %q composing=%v %v", editor.String(), composing, composition) + } + must(t, session.Commit("你好", 1)) + if _, composing := editor.Composition(); composing || editor.String() != "你好" || editor.Caret() != 2 { + t.Fatalf("after the commit: %q composing=%v caret %d", editor.String(), composing, editor.Caret()) + } +} + +func TestFinishKeepsWhatIsComposed(t *testing.T) { + session, editor := newSession("a") + must(t, session.SetComposing("bc", 1)) + must(t, session.Finish()) + if _, composing := editor.Composition(); composing || editor.String() != "abc" { + t.Fatalf("text %q composing=%v", editor.String(), composing) + } + must(t, session.Finish()) // nothing composing: nothing happens +} + +// Ranges count UTF-16 units, so an emoji is two, and a range may not end in the middle +// of a character. +func TestRangesCountUTF16UnitsOverSurrogatePairs(t *testing.T) { + session, editor := newSession("a😀b") + mirror := session.Mirror() + if mirror.Text != "a😀b" || mirror.SelStart != 4 || mirror.SelEnd != 4 { + t.Fatalf("mirror %+v", mirror) + } + must(t, session.Select(1, 3)) // the emoji + if selection := editor.Selection(); selection != (text.Range{Start: 1, End: 2}) { + t.Fatalf("selection %v", selection) + } + must(t, session.Replace(1, 3, "x")) + if editor.String() != "axb" { + t.Fatalf("text %q", editor.String()) + } +} + +func TestDeleteSurroundingCountsUnitsOrCodePoints(t *testing.T) { + session, editor := newSession("a😀b") + must(t, session.Select(3, 3)) + must(t, session.DeleteSurrounding(2, 0, false)) // the emoji is two units + if editor.String() != "ab" { + t.Fatalf("by units: %q", editor.String()) + } + session, editor = newSession("a😀b") + must(t, session.Select(3, 3)) + must(t, session.DeleteSurrounding(1, 1, true)) // one code point either side + if editor.String() != "a" { + t.Fatalf("by code points: %q", editor.String()) + } + must(t, session.DeleteSurrounding(0, 0, false)) // nothing to delete +} + +func TestMarkRangeReopensAWordForCorrection(t *testing.T) { + session, editor := newSession("hello wrld") + must(t, session.MarkRange(6, 10)) + composition, composing := editor.Composition() + if !composing || composition != (text.Range{Start: 6, End: 10}) { + t.Fatalf("composition %v %v", composition, composing) + } + must(t, session.SetComposing("world", 1)) + must(t, session.Commit("world", 1)) + if editor.String() != "hello world" { + t.Fatalf("text %q", editor.String()) + } +} + +func TestSetMarkedSelectsInsideTheMarkedText(t *testing.T) { + session, editor := newSession("") + must(t, session.SetMarked("abc", 1, 1)) + if editor.Caret() != 1 { + t.Fatalf("caret %d, want it inside the marked text", editor.Caret()) + } +} + +func TestMirrorOfAComposingEditorNamesItsComposition(t *testing.T) { + session, _ := newSession("") + must(t, session.SetComposing("😀a", 1)) + mirror := session.Mirror() + if !mirror.Composing || mirror.CompStart != 0 || mirror.CompEnd != 3 { + t.Fatalf("mirror %+v", mirror) + } + must(t, session.Finish()) + if mirror := session.Mirror(); mirror.Composing || mirror.CompStart != -1 || mirror.CompEnd != -1 { + t.Fatalf("mirror %+v after finishing", mirror) + } +} + +func keyInto(t *testing.T, session *Session, key gfx.Key, modifiers input.Modifiers, character string, field *platform.TextInput) bool { + t.Helper() + action, ok := KeyEdit(key, modifiers, character, field) + if !ok { + return false + } + must(t, action.Apply(session)) + return true +} + +// A hardware keyboard types into a field and edits it as a desktop's does: characters and +// the space are typed, Backspace deletes, the arrows move, and a word's worth with Control. +func TestKeysTypeAndEditAFocusedField(t *testing.T) { + session, editor := newSession("") + field := &platform.TextInput{} + for _, step := range []struct { + key gfx.Key + modifiers input.Modifiers + character string + }{ + {gfx.KeyUnknown, 0, "h"}, {gfx.KeyUnknown, 0, "i"}, {gfx.KeySpace, 0, " "}, {gfx.KeyUnknown, 0, "x"}, {gfx.KeyBackspace, 0, ""}, + } { + if !keyInto(t, session, step.key, step.modifiers, step.character, field) { + t.Fatalf("key %v was not taken", step.key) + } + } + if editor.String() != "hi " { + t.Fatalf("text %q", editor.String()) + } + keyInto(t, session, gfx.KeyLeft, 0, "", field) + if editor.Caret() != 2 { + t.Fatalf("caret %d after Left", editor.Caret()) + } + keyInto(t, session, gfx.KeyLeft, input.ModifierShift, "", field) + if selection := editor.Selection(); selection.End-selection.Start != 1 { + t.Fatalf("selection %v after Shift+Left", selection) + } + keyInto(t, session, gfx.KeyBackspace, input.ModifierControl, "", field) + if editor.String() != "h " { + t.Fatalf("text %q after deleting the selection", editor.String()) + } +} + +// Enter is a newline in a field of several lines and the application's in one of a line; +// a terminal's keys are all the application's. +func TestEnterAndTerminalKeysBelongToTheApplicationWhereTheyShould(t *testing.T) { + if _, ok := KeyEdit(gfx.KeyEnter, 0, "", &platform.TextInput{}); ok { + t.Error("Enter in a one-line field was taken") + } + if action, ok := KeyEdit(gfx.KeyEnter, 0, "", &platform.TextInput{Multiline: true}); !ok || action.Command != platform.TextInsertNewline { + t.Errorf("Enter in a multiline field: %+v %v", action, ok) + } + for _, key := range []gfx.Key{gfx.KeyBackspace, gfx.KeyLeft, gfx.KeySpace, gfx.KeyUnknown} { + if _, ok := KeyEdit(key, 0, "x", &platform.TextInput{Terminal: true}); ok { + t.Errorf("key %v of a terminal was taken", key) + } + } + if _, ok := KeyEdit(gfx.KeyUp, 0, "", &platform.TextInput{}); ok { + t.Error("Up was taken: moving between rows is the application's") + } +} diff --git a/internal/platform/vulkan/vulkan_linux.go b/internal/platform/vulkan/vulkan_linux.go index ea85721f2..7c5828ff2 100644 --- a/internal/platform/vulkan/vulkan_linux.go +++ b/internal/platform/vulkan/vulkan_linux.go @@ -554,6 +554,11 @@ type SurfaceSource struct { // Create makes the surface on instance. The renderer calls it again after the // device or the surface was lost. Create func(instance uintptr) (surface uintptr, err error) + // HostSize says the window system gives the surface's size with its events, which is + // truer than what the surface reports while it changes: Android learns the new size + // of a surface a frame after it told the program. The swapchain is then made at the + // size the renderer was given, and the compositor fits it to the window. + HostSize bool } // Config is what a window's renderer is made from. @@ -693,7 +698,7 @@ func (renderer *Renderer) createSwapchain() (err error) { renderer.hasSurfaceFormat = true } extent := capabilities.Current - if extent.Width == math.MaxUint32 { + if extent.Width == math.MaxUint32 || renderer.source.HostSize { extent.Width = clamp(renderer.width, capabilities.Minimum.Width, capabilities.Maximum.Width) extent.Height = clamp(renderer.height, capabilities.Minimum.Height, capabilities.Maximum.Height) } From cfab9e233c24ac5cdbe672a124c3390271641178 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 22 Nov 2026 23:36:18 +0800 Subject: [PATCH 33/64] feat(android,ios): the system's clipboard, links, theme and screen reader; the iPhone's keyboard Android answers the application with the system's services: the clipboard, opening a link, the user's languages, the dark theme (and its changes) and whether animations are off. The program's accessibility tree is shown to TalkBack and the other services as virtual views of the surface, and their requests (press, focus, set a value or text) go back to the application's accessibility handler. Frames carry the tree only when it changes, so a screen reader that starts late asks for it (Config.AccessibilityTree). iOS gets the keyboard: an invisible UITextInput view holds a copy of the focused text input, becomes the first responder while the application has one, and sends what the keyboard does (commit, compose, replace, select, delete) through the same imebridge the Android input method uses and the text events the other platforms' text services make, so the editor and its composition behave the same everywhere. --- app/ios_unsupported.go | 12 + app/mobile_unsupported.go | 8 - app/run_canvas.go | 61 +-- app/system_android.go | 47 ++ .../platform/android/accessibility_android.go | 123 +++++ internal/platform/android/android.go | 51 ++- internal/platform/android/exports_android.go | 15 + .../java/dev/viva/host/Accessibility.java | 248 ++++++++++ .../hostsrc/java/dev/viva/host/Host.java | 89 ++++ .../hostsrc/java/dev/viva/host/Native.java | 9 + .../java/dev/viva/host/VivaActivity.java | 1 + .../hostsrc/java/dev/viva/host/VivaView.java | 24 + internal/platform/android/jni_android.c | 87 ++++ internal/platform/android/jni_android.h | 11 + internal/platform/android/system_android.go | 64 +++ internal/platform/contract.go | 6 +- internal/platform/darwin/ios_host.m | 426 +++++++++++++++++- internal/platform/darwin/ios_text.go | 68 +++ 18 files changed, 1296 insertions(+), 54 deletions(-) create mode 100644 internal/platform/android/accessibility_android.go create mode 100644 internal/platform/android/hostsrc/java/dev/viva/host/Accessibility.java create mode 100644 internal/platform/android/system_android.go create mode 100644 internal/platform/darwin/ios_text.go diff --git a/app/ios_unsupported.go b/app/ios_unsupported.go index 6356e3dd1..2097323fc 100644 --- a/app/ios_unsupported.go +++ b/app/ios_unsupported.go @@ -2,8 +2,20 @@ package app +import "os" + // What a phone has no use for, and Android answers with its common fallbacks: // an iPhone has no file icons for the application to ask for, and no reopening. func nativeFileIcon(string, int) ([]byte, error) { return nil, ErrUnsupported } func setReopenHandler(*Config, *Window) {} + +// What the system answers an iPhone application with, until its backend does: + +func nativeClipboardText() (string, error) { return "", ErrUnsupported } +func nativeSetClipboardText(string) error { return ErrUnsupported } +func nativeOpenURL(string) error { return ErrUnsupported } +func nativePreferredLanguages() []string { return languagesFromEnvironment(os.Getenv) } +func nativeReduceMotion() bool { return false } +func nativeAppearance() Appearance { return AppearanceUnknown } +func nativeWatchAppearance() {} diff --git a/app/mobile_unsupported.go b/app/mobile_unsupported.go index c6c4be1c2..7f77ae94a 100644 --- a/app/mobile_unsupported.go +++ b/app/mobile_unsupported.go @@ -4,7 +4,6 @@ package app import ( "fmt" - "os" "github.com/vivaui/viva/gfx" ) @@ -16,10 +15,6 @@ import ( func currentPlatform() Platform { return PlatformUnknown } -func nativeReduceMotion() bool { return false } -func nativePreferredLanguages() []string { return languagesFromEnvironment(os.Getenv) } -func nativeClipboardText() (string, error) { return "", ErrUnsupported } -func nativeSetClipboardText(string) error { return ErrUnsupported } func nativeHasClipboardImage() bool { return false } func nativeClipboardImagePNG() ([]byte, error) { return nil, ErrUnsupported } func nativeSetClipboardImage([]byte) error { return ErrUnsupported } @@ -35,7 +30,6 @@ func nativeSaveFile(SaveFileOptions) (string, error) { return "", ErrU func nativeSaveFileWithCheckbox(SaveFileOptions, SaveFileCheckbox) (SaveFileSelection, error) { return SaveFileSelection{}, ErrUnsupported } -func nativeOpenURL(string) error { return ErrUnsupported } func nativeRevealPath(string) error { return ErrUnsupported } func nativePlaySystemSound(SystemSound) error { return ErrUnsupported } func nativeSendNotification(Notification) error { return ErrUnsupported } @@ -50,8 +44,6 @@ func nativeMonospaceFamilies() []string { return nil } func nativeFontFamilies() []string { return nil } func nativeFontWeights(string) []int { return nil } -func nativeAppearance() Appearance { return AppearanceUnknown } -func nativeWatchAppearance() {} func nativeSetAppearance(Appearance) {} func nativeStartFileDrag([]string, FileDragEffect) (FileDragEffect, error) { diff --git a/app/run_canvas.go b/app/run_canvas.go index 9d68e883f..93d1e940d 100644 --- a/app/run_canvas.go +++ b/app/run_canvas.go @@ -178,36 +178,37 @@ func nativeWindowConfig(normalized *Config, painter *painter) (platform.Config, Red: normalized.ClearColor.Red, Green: normalized.ClearColor.Green, Blue: normalized.ClearColor.Blue, Alpha: normalized.ClearColor.Alpha, }, - Web: normalized.Web.bind(), - NativeViews: slices.Clone(painter.lastViews), - Rectangles: painter.frame.Rectangles(), - TextLabels: painter.frame.Labels(), - Accessibility: painter.accessibility, - OnResize: resizeHandler, - OnFrameChange: frameChangeHandler(normalized.OnFrameChange), - OnMinimize: minimizeHandler(normalized.OnMinimize), - OnVisibility: gate.handler(), - OnMaximize: maximizeHandler(normalized.OnMaximize), - OnFullscreen: painter.fullscreenHandler(normalized.OnFullscreen), - OnReopen: normalized.onReopen, - OnPointer: pointerHandler, - PressAt: painter.pressAt, - OnKey: keyHandler, - ModifierTaps: normalized.OnModifierTap != nil, - OnShortcut: painter.shortcutHandler(normalized), - OnAccessibility: painter.accessibilityHandler(normalized), - OnFocusLost: painter.focusLostHandler(), - OnActivate: normalized.OnActivate, - OnDeactivate: painter.deactivateHandler(), - OnScroll: scrollHandler, - OnFileDrop: dropHandler, - OnRedraw: redrawHandler, - SetFrameInterval: setFrameInterval, - FramePresented: framePresented, - Waker: waker, - OnCloseRequest: closeHandler, - OnClosed: normalized.OnClosed, - DynamicTextInput: normalized.TextInput != nil, + Web: normalized.Web.bind(), + NativeViews: slices.Clone(painter.lastViews), + Rectangles: painter.frame.Rectangles(), + TextLabels: painter.frame.Labels(), + Accessibility: painter.accessibility, + OnResize: resizeHandler, + OnFrameChange: frameChangeHandler(normalized.OnFrameChange), + OnMinimize: minimizeHandler(normalized.OnMinimize), + OnVisibility: gate.handler(), + OnMaximize: maximizeHandler(normalized.OnMaximize), + OnFullscreen: painter.fullscreenHandler(normalized.OnFullscreen), + OnReopen: normalized.onReopen, + OnPointer: pointerHandler, + PressAt: painter.pressAt, + OnKey: keyHandler, + ModifierTaps: normalized.OnModifierTap != nil, + OnShortcut: painter.shortcutHandler(normalized), + OnAccessibility: painter.accessibilityHandler(normalized), + AccessibilityTree: func() []platform.AccessibilityNode { return painter.accessibility }, + OnFocusLost: painter.focusLostHandler(), + OnActivate: normalized.OnActivate, + OnDeactivate: painter.deactivateHandler(), + OnScroll: scrollHandler, + OnFileDrop: dropHandler, + OnRedraw: redrawHandler, + SetFrameInterval: setFrameInterval, + FramePresented: framePresented, + Waker: waker, + OnCloseRequest: closeHandler, + OnClosed: normalized.OnClosed, + DynamicTextInput: normalized.TextInput != nil, } if normalized.TextInput != nil { config.ReadOnlyTextFocused = func() bool { diff --git a/app/system_android.go b/app/system_android.go index dd2a57a53..43daea339 100644 --- a/app/system_android.go +++ b/app/system_android.go @@ -3,6 +3,8 @@ package app import ( + "os" + "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/internal/platform/android" ) @@ -11,3 +13,48 @@ import ( // rest is answered in mobile_unsupported.go. func nativeTextEngine() gfx.TextEngine { return android.TextEngine() } + +func nativeClipboardText() (string, error) { + text, ok := android.ClipboardText() + if !ok { + return "", nil + } + return text, nil +} + +func nativeSetClipboardText(text string) error { + if !android.SetClipboardText(text) { + return ErrUnsupported + } + return nil +} + +func nativeOpenURL(url string) error { + if !android.OpenURL(url) { + return ErrUnsupported + } + return nil +} + +func nativePreferredLanguages() []string { + if languages := android.PreferredLanguages(); len(languages) > 0 { + return languages + } + return languagesFromEnvironment(os.Getenv) +} + +func nativeReduceMotion() bool { return android.AnimationsOff() } + +func nativeAppearance() Appearance { + switch android.DarkTheme() { + case 1: + return AppearanceDark + case 0: + return AppearanceLight + } + return AppearanceUnknown +} + +// The host tells the application when the theme changes (Activity.onConfigurationChanged), +// whether or not anyone watches. +func nativeWatchAppearance() {} diff --git a/internal/platform/android/accessibility_android.go b/internal/platform/android/accessibility_android.go new file mode 100644 index 000000000..e9001b4e9 --- /dev/null +++ b/internal/platform/android/accessibility_android.go @@ -0,0 +1,123 @@ +//go:build android + +package android + +/* +#include "jni_android.h" +*/ +import "C" + +import ( + "unsafe" + + "github.com/vivaui/viva/internal/platform" +) + +// The flags of a node, as the host's Accessibility reads them. +const ( + a11yFocused = 1 << iota + a11yDisabled + a11yChecked + a11yMixed + a11ySelected + a11yExpanded + a11yMultiline + a11yReadOnly + a11yInvalid + a11ySecure + a11yFocusable + a11yExpandable + a11yHasRange +) + +func a11yFlags(node platform.AccessibilityNode) int32 { + var flags int32 + for _, flag := range []struct { + on bool + bit int32 + }{ + {node.Focused, a11yFocused}, {node.Disabled, a11yDisabled}, {node.Checked, a11yChecked}, {node.Mixed, a11yMixed}, + {node.Selected, a11ySelected}, {node.Expanded, a11yExpanded}, {node.Multiline, a11yMultiline}, {node.ReadOnly, a11yReadOnly}, + {node.Invalid, a11yInvalid}, {node.Secure, a11ySecure}, {node.Focusable, a11yFocusable}, {node.Expandable, a11yExpandable}, + {node.Range.Set, a11yHasRange}, + } { + if flag.on { + flags |= flag.bit + } + } + return flags +} + +// pushTree gives the host the accessibility tree a screen reader reads, in the window's +// pixels. The nodes are the application's to reuse after this returns, so what is kept is +// the place of each in the tree, which is what a request of the screen reader names. +func (win *window) pushTree(nodes []platform.AccessibilityNode) { + count := len(nodes) + win.treeIDs = win.treeIDs[:0] + bounds := make([]float32, 0, 4*count) + ints := make([]int32, 0, 5*count) + ranges := make([]float32, 0, 3*count) + offsets := make([]int32, 0, 4*count+1) + var chars []uint16 + scale := win.density + for _, node := range nodes { + win.treeIDs = append(win.treeIDs, node.ID) + bounds = append(bounds, node.X*scale, node.Y*scale, node.Width*scale, node.Height*scale) + ints = append(ints, int32(node.Role), a11yFlags(node), int32(node.Level), node.PosInSet, node.SetSize) + ranges = append(ranges, float32(node.Range.Min), float32(node.Range.Max), float32(node.Range.Now)) + for _, text := range [4]string{node.Label, node.Value, node.Hint, node.Description} { + offsets = append(offsets, int32(len(chars))) + chars = append(chars, utf16Units(text)...) + } + } + offsets = append(offsets, int32(len(chars))) + var boundsPointer, rangesPointer *C.float + var intsPointer *C.int32_t + var charsPointer *C.uint16_t + if count > 0 { + boundsPointer = (*C.float)(unsafe.Pointer(&bounds[0])) + intsPointer = (*C.int32_t)(unsafe.Pointer(&ints[0])) + rangesPointer = (*C.float)(unsafe.Pointer(&ranges[0])) + } + if len(chars) > 0 { + charsPointer = (*C.uint16_t)(unsafe.Pointer(&chars[0])) + } + C.viva_host_tree(C.int(count), boundsPointer, intsPointer, rangesPointer, charsPointer, C.int(len(chars)), (*C.int32_t)(unsafe.Pointer(&offsets[0]))) +} + +// accessibilityState follows a screen reader starting or stopping. Starting, the program +// asks the application for the tree it has, as frames carry it only when it changes. +func (application *application) accessibilityState(on bool) { + win := application.window + if win == nil || win.closed { + return + } + win.a11y = on + if on && win.config.AccessibilityTree != nil { + win.pushTree(win.config.AccessibilityTree()) + } +} + +// accessible carries out a screen reader's request of the node at index in the tree last +// sent, and shows what the application paints for it. +func (application *application) accessible(ev event) { + win := application.window + if win == nil || win.closed || win.config.OnAccessibility == nil || ev.index < 0 || int(ev.index) >= len(win.treeIDs) { + return + } + defer application.guard() + action := [...]platform.AccessibilityAction{ + 1: platform.AccessibilityPress, 2: platform.AccessibilityFocus, 3: platform.AccessibilityIncrement, + 4: platform.AccessibilityDecrement, 5: platform.AccessibilitySetNumber, 6: platform.AccessibilitySetText, + 7: platform.AccessibilitySetSelection, + } + if ev.action < 1 || int(ev.action) >= len(action) { + return + } + request := platform.AccessibilityRequest{ + Node: win.treeIDs[ev.index], Action: action[ev.action], Number: float64(ev.dx), Text: ev.text, Start: ev.start, End: ev.end, + } + if _, err := win.config.OnAccessibility(request, win.present); err != nil { + application.fail(err) + } +} diff --git a/internal/platform/android/android.go b/internal/platform/android/android.go index 3b969b97f..d755e8c39 100644 --- a/internal/platform/android/android.go +++ b/internal/platform/android/android.go @@ -30,19 +30,22 @@ import ( type eventKind uint8 const ( - eventSurface eventKind = iota + 1 // a surface, of a size, on a display of a density - eventSurfaceLost // the surface is going away: let go of it, then answer - eventTouch // a finger, a pen or a mouse - eventVisible // the activity is in front or behind - eventLowMemory // the system is short of memory - eventClose // the user asked to close the window - eventWake // something was posted - eventRedraw // the application asked for a frame - eventText // the input method edits the text input - eventKey // a key of a keyboard - eventHover // a mouse over the surface - eventHoverExit // the mouse left it - eventScroll // a wheel + eventSurface eventKind = iota + 1 // a surface, of a size, on a display of a density + eventSurfaceLost // the surface is going away: let go of it, then answer + eventTouch // a finger, a pen or a mouse + eventVisible // the activity is in front or behind + eventLowMemory // the system is short of memory + eventClose // the user asked to close the window + eventWake // something was posted + eventRedraw // the application asked for a frame + eventText // the input method edits the text input + eventKey // a key of a keyboard + eventHover // a mouse over the surface + eventHoverExit // the mouse left it + eventScroll // a wheel + eventAppearance // the theme, the language or the animation setting may have changed + eventAccessibility // a screen reader started or stopped + eventAccessible // a screen reader asks something of a node ) // event is one thing that happened, small enough to queue by value. @@ -67,6 +70,11 @@ type event struct { keyCode, unicode int32 repeat bool dx, dy float32 + // An accessibility request: the node (an index of the tree last sent), the action (above), the + // text and the span; the number is dx. + index int32 + text string + start, end int32 // visible is eventVisible's state. visible bool } @@ -213,6 +221,12 @@ func (application *application) handle(ev event) { application.hover(ev) case eventScroll: application.scroll(ev) + case eventAppearance: + platform.NotifyAppearanceChanged() + case eventAccessibility: + application.accessibilityState(ev.visible) + case eventAccessible: + application.accessible(ev) case eventLowMemory: } } @@ -260,6 +274,8 @@ type window struct { renderer *vulkan.Renderer text *textInput // the application's focused text input, if it has one hovering bool // a mouse is over the surface + a11y bool // a screen reader reads the window + treeIDs []gfx.ID // the nodes of the tree last sent to the host, by place } func (win *window) Close() { @@ -426,6 +442,7 @@ func (win *window) resized(swapchain bool) error { return err } win.setTextInput(frame.TextInput) + win.syncTree(frame) } if err := renderer.Present(); err != nil { return err @@ -467,6 +484,7 @@ func (win *window) present(frame platform.Frame) error { } if err == nil { win.setTextInput(frame.TextInput) + win.syncTree(frame) } if err == nil && win.config.FramePresented != nil { win.config.FramePresented() @@ -535,3 +553,10 @@ func setTitle(title string) { } C.viva_host_set_title((*C.uint16_t)(unsafe.Pointer(&units[0])), C.int(len(units))) } + +// syncTree gives the host the accessibility tree a frame carries, when a screen reader reads. +func (win *window) syncTree(frame platform.Frame) { + if win.a11y && frame.Accessibility != nil { + win.pushTree(frame.Accessibility) + } +} diff --git a/internal/platform/android/exports_android.go b/internal/platform/android/exports_android.go index 50dda97e6..192108363 100644 --- a/internal/platform/android/exports_android.go +++ b/internal/platform/android/exports_android.go @@ -158,3 +158,18 @@ func Java_dev_viva_host_Native_hoverExit(env *C.JNIEnv, _ C.jclass) { func Java_dev_viva_host_Native_scroll(env *C.JNIEnv, _ C.jclass, x, y, dx, dy C.jfloat, meta C.jint) { send(event{kind: eventScroll, x: float32(x), y: float32(y), dx: float32(dx), dy: float32(dy), modifiers: int32(meta)}) } + +//export Java_dev_viva_host_Native_appearanceChanged +func Java_dev_viva_host_Native_appearanceChanged(env *C.JNIEnv, _ C.jclass) { + send(event{kind: eventAppearance}) +} + +//export Java_dev_viva_host_Native_accessibility +func Java_dev_viva_host_Native_accessibility(env *C.JNIEnv, _ C.jclass, on C.jboolean) { + send(event{kind: eventAccessibility, visible: on != 0}) +} + +//export Java_dev_viva_host_Native_accessible +func Java_dev_viva_host_Native_accessible(env *C.JNIEnv, _ C.jclass, node C.jint, action C.jint, number C.jfloat, text C.jstring, start, end C.jint) { + send(event{kind: eventAccessible, index: int32(node), action: int32(action), dx: float32(number), text: goString(env, text), start: int32(start), end: int32(end)}) +} diff --git a/internal/platform/android/hostsrc/java/dev/viva/host/Accessibility.java b/internal/platform/android/hostsrc/java/dev/viva/host/Accessibility.java new file mode 100644 index 000000000..1bbcdb207 --- /dev/null +++ b/internal/platform/android/hostsrc/java/dev/viva/host/Accessibility.java @@ -0,0 +1,248 @@ +package dev.viva.host; + +import android.graphics.Rect; +import android.os.Bundle; +import android.view.View; +import android.view.accessibility.AccessibilityEvent; +import android.view.accessibility.AccessibilityNodeInfo; +import android.view.accessibility.AccessibilityNodeProvider; + +import java.util.ArrayList; +import java.util.List; + +/** + * The program's accessibility tree, shown to TalkBack and the other services as virtual + * views of the surface. The program sends the tree whole whenever it changes (Host.tree), + * and a service's requests go back to it as what to do to which node (Native.accessible). + */ +final class Accessibility extends AccessibilityNodeProvider { + // The roles, in the program's numbering (platform.A11yRole*). + private static final int BUTTON = 3, TEXT = 4, TEXT_FIELD = 5, CHECKBOX = 6, SLIDER = 7, IMAGE = 8, LINK = 9, RADIO = 10, + TAB = 11, SWITCH = 14, LIST_BOX = 17, OPTION = 18, HEADING = 21, STATUS = 22, PROGRESS = 24; + // The flags of a node. + private static final int FOCUSED = 1, DISABLED = 2, CHECKED = 4, MIXED = 8, SELECTED = 16, EXPANDED = 32, MULTILINE = 64, + READ_ONLY = 128, INVALID = 256, SECURE = 512, FOCUSABLE = 1024, EXPANDABLE = 2048, HAS_RANGE = 4096; + // What a service asks of a node (platform.Accessibility*). + static final int PRESS = 1, FOCUS = 2, INCREMENT = 3, DECREMENT = 4, SET_NUMBER = 5, SET_TEXT = 6, SET_SELECTION = 7; + + private static final class Node { + int role, flags, level, position, size; + float x, y, width, height; + float min, max, value; + String label, text, hint, description; + } + + private final View view; + private volatile Node[] nodes = new Node[0]; + private volatile boolean enabled; + + Accessibility(View view) { + this.view = view; + } + + boolean enabled() { + return enabled; + } + + void setEnabled(boolean on) { + enabled = on; + } + + /** The tree the program has now. */ + void set(float[] bounds, int[] ints, float[] ranges, char[] chars, int[] offsets) { + int count = bounds.length / 4; + Node[] next = new Node[count]; + for (int i = 0; i < count; i++) { + Node node = new Node(); + node.x = bounds[4 * i]; + node.y = bounds[4 * i + 1]; + node.width = bounds[4 * i + 2]; + node.height = bounds[4 * i + 3]; + node.role = ints[5 * i]; + node.flags = ints[5 * i + 1]; + node.level = ints[5 * i + 2]; + node.position = ints[5 * i + 3]; + node.size = ints[5 * i + 4]; + node.min = ranges[3 * i]; + node.max = ranges[3 * i + 1]; + node.value = ranges[3 * i + 2]; + node.label = text(chars, offsets, 4 * i); + node.text = text(chars, offsets, 4 * i + 1); + node.hint = text(chars, offsets, 4 * i + 2); + node.description = text(chars, offsets, 4 * i + 3); + next[i] = node; + } + nodes = next; + view.post(() -> view.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED)); + } + + private static String text(char[] chars, int[] offsets, int index) { + return new String(chars, offsets[index], offsets[index + 1] - offsets[index]); + } + + private static String className(Node node) { + switch (node.role) { + case BUTTON: + case LINK: + return "android.widget.Button"; + case TEXT_FIELD: + return "android.widget.EditText"; + case CHECKBOX: + return "android.widget.CheckBox"; + case SWITCH: + return "android.widget.Switch"; + case RADIO: + return "android.widget.RadioButton"; + case SLIDER: + return "android.widget.SeekBar"; + case PROGRESS: + return "android.widget.ProgressBar"; + case IMAGE: + return "android.widget.ImageView"; + case LIST_BOX: + return "android.widget.ListView"; + case TEXT: + case HEADING: + case STATUS: + return "android.widget.TextView"; + default: + return "android.view.View"; + } + } + + @Override + public AccessibilityNodeInfo createAccessibilityNodeInfo(int virtualViewId) { + Node[] tree = nodes; + if (virtualViewId == View.NO_ID) { + AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(view); + view.onInitializeAccessibilityNodeInfo(info); + for (int i = 0; i < tree.length; i++) { + info.addChild(view, i); + } + return info; + } + if (virtualViewId < 0 || virtualViewId >= tree.length) { + return null; + } + Node node = tree[virtualViewId]; + AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(view, virtualViewId); + info.setPackageName(view.getContext().getPackageName()); + info.setClassName(className(node)); + info.setParent(view); + info.setEnabled((node.flags & DISABLED) == 0); + info.setFocusable((node.flags & FOCUSABLE) != 0); + info.setVisibleToUser(true); + info.setContentDescription(node.label.isEmpty() ? null : node.label); + if (!node.text.isEmpty()) { + info.setText(node.text); + } else if (node.role == TEXT || node.role == HEADING || node.role == STATUS) { + info.setText(node.label); + } + if (!node.hint.isEmpty() && android.os.Build.VERSION.SDK_INT >= 26) { + info.setHintText(node.hint); + } + if (!node.description.isEmpty() && android.os.Build.VERSION.SDK_INT >= 30) { + info.setStateDescription(node.description); + } + if (node.role == HEADING) { + info.setHeading(true); + } + if (node.role == CHECKBOX || node.role == SWITCH || node.role == RADIO) { + info.setCheckable(true); + info.setChecked((node.flags & CHECKED) != 0); + } + if ((node.flags & SELECTED) != 0) { + info.setSelected(true); + } + if ((node.flags & INVALID) != 0) { + info.setContentInvalid(true); + } + if (node.role == TEXT_FIELD) { + info.setEditable((node.flags & READ_ONLY) == 0); + info.setMultiLine((node.flags & MULTILINE) != 0); + info.setPassword((node.flags & SECURE) != 0); + if ((node.flags & READ_ONLY) == 0) { + info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_SET_TEXT); + } + } + if ((node.flags & HAS_RANGE) != 0) { + info.setRangeInfo(AccessibilityNodeInfo.RangeInfo.obtain(AccessibilityNodeInfo.RangeInfo.RANGE_TYPE_FLOAT, node.min, node.max, node.value)); + if (node.role == SLIDER) { + info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_SCROLL_FORWARD); + info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_SCROLL_BACKWARD); + if (android.os.Build.VERSION.SDK_INT >= 24) { + info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_SET_PROGRESS); + } + } + } + if (node.size > 0 && (node.role == TAB || node.role == OPTION || node.role == RADIO)) { + info.setCollectionItemInfo(AccessibilityNodeInfo.CollectionItemInfo.obtain(Math.max(node.position - 1, 0), 1, 0, 1, false, (node.flags & SELECTED) != 0)); + } + boolean operable = (node.flags & DISABLED) == 0; + if (operable && (node.role == BUTTON || node.role == LINK || node.role == CHECKBOX || node.role == SWITCH || node.role == RADIO + || node.role == TAB || node.role == OPTION || node.role == 12 || node.role == 20)) { + info.setClickable(true); + info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_CLICK); + } + if ((node.flags & EXPANDABLE) != 0 && operable) { + info.addAction((node.flags & EXPANDED) != 0 ? AccessibilityNodeInfo.AccessibilityAction.ACTION_COLLAPSE : AccessibilityNodeInfo.AccessibilityAction.ACTION_EXPAND); + } + if ((node.flags & FOCUSABLE) != 0) { + info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_FOCUS); + } + info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_ACCESSIBILITY_FOCUS); + int[] origin = new int[2]; + view.getLocationOnScreen(origin); + Rect screen = new Rect(origin[0] + Math.round(node.x), origin[1] + Math.round(node.y), + origin[0] + Math.round(node.x + node.width), origin[1] + Math.round(node.y + node.height)); + info.setBoundsInScreen(screen); + Rect parent = new Rect(Math.round(node.x), Math.round(node.y), Math.round(node.x + node.width), Math.round(node.y + node.height)); + info.setBoundsInParent(parent); + return info; + } + + @Override + public boolean performAction(int virtualViewId, int action, Bundle arguments) { + Node[] tree = nodes; + if (virtualViewId == View.NO_ID) { + return view.performAccessibilityAction(action, arguments); + } + if (virtualViewId < 0 || virtualViewId >= tree.length) { + return false; + } + Node node = tree[virtualViewId]; + switch (action) { + case AccessibilityNodeInfo.ACTION_CLICK: + case AccessibilityNodeInfo.ACTION_EXPAND: + case AccessibilityNodeInfo.ACTION_COLLAPSE: + Native.accessible(virtualViewId, PRESS, 0, null, 0, 0); + return true; + case AccessibilityNodeInfo.ACTION_FOCUS: + Native.accessible(virtualViewId, FOCUS, 0, null, 0, 0); + return true; + case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { + AccessibilityEvent event = AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); + event.setSource(view, virtualViewId); + view.getParent().requestSendAccessibilityEvent(view, event); + return true; + } + case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: + Native.accessible(virtualViewId, INCREMENT, 0, null, 0, 0); + return true; + case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: + Native.accessible(virtualViewId, DECREMENT, 0, null, 0, 0); + return true; + case AccessibilityNodeInfo.ACTION_SET_TEXT: { + CharSequence text = arguments == null ? null : arguments.getCharSequence(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE); + Native.accessible(virtualViewId, SET_TEXT, 0, text == null ? "" : text.toString(), 0, 0); + return true; + } + default: + if (android.os.Build.VERSION.SDK_INT >= 24 && action == android.R.id.accessibilityActionSetProgress && arguments != null) { + Native.accessible(virtualViewId, SET_NUMBER, arguments.getFloat(AccessibilityNodeInfo.ACTION_ARGUMENT_PROGRESS_VALUE), null, 0, 0); + return true; + } + return false; + } + } +} diff --git a/internal/platform/android/hostsrc/java/dev/viva/host/Host.java b/internal/platform/android/hostsrc/java/dev/viva/host/Host.java index d3a0c4c98..f0f1025d0 100644 --- a/internal/platform/android/hostsrc/java/dev/viva/host/Host.java +++ b/internal/platform/android/hostsrc/java/dev/viva/host/Host.java @@ -1,6 +1,14 @@ package dev.viva.host; import android.app.Activity; +import android.content.ClipData; +import android.content.ClipboardManager; +import android.content.Context; +import android.content.Intent; +import android.content.res.Configuration; +import android.net.Uri; +import android.os.LocaleList; +import android.provider.Settings; import android.view.Surface; /** What the Go program asks of the host, on any thread. */ @@ -27,6 +35,14 @@ public static void editor(String text, int selectionStart, int selectionEnd, int } } + /** The program's accessibility tree, whole: its nodes and what a screen reader reads of them. */ + public static void tree(float[] bounds, int[] ints, float[] ranges, char[] chars, int[] offsets) { + VivaView current = view; + if (current != null) { + current.accessibility().set(bounds, ints, ranges, chars, offsets); + } + } + /** Shows the keyboard for a text input, or takes it away when editing is false. */ public static void keyboard(final boolean editing, final boolean multiline, final boolean secure) { final VivaView current = view; @@ -57,4 +73,77 @@ public static void preferHighRefresh(Surface surface) { surface.setFrameRate(120f, Surface.FRAME_RATE_COMPATIBILITY_DEFAULT); } } + + /** The text on the clipboard, or null when there is none or the system will not say. */ + public static String clipboardText() { + Activity current = activity; + if (current == null) { + return null; + } + ClipboardManager clipboard = (ClipboardManager) current.getSystemService(Context.CLIPBOARD_SERVICE); + if (clipboard == null || !clipboard.hasPrimaryClip() || clipboard.getPrimaryClip().getItemCount() == 0) { + return null; + } + CharSequence text = clipboard.getPrimaryClip().getItemAt(0).coerceToText(current); + return text == null ? null : text.toString(); + } + + public static boolean setClipboardText(String text) { + Activity current = activity; + if (current == null) { + return false; + } + ClipboardManager clipboard = (ClipboardManager) current.getSystemService(Context.CLIPBOARD_SERVICE); + if (clipboard == null) { + return false; + } + clipboard.setPrimaryClip(ClipData.newPlainText(null, text)); + return true; + } + + /** Opens a link in the app that takes it. */ + public static boolean openURL(String url) { + Activity current = activity; + if (current == null) { + return false; + } + try { + current.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); + return true; + } catch (RuntimeException e) { + return false; + } + } + + /** The user's languages, most preferred first, as BCP 47 tags separated by newlines. */ + public static String languages() { + LocaleList list = LocaleList.getAdjustedDefault(); + StringBuilder tags = new StringBuilder(); + for (int i = 0; i < list.size(); i++) { + if (i > 0) { + tags.append('\n'); + } + tags.append(list.get(i).toLanguageTag()); + } + return tags.toString(); + } + + /** 1 when the system shows the dark theme, 0 for the light one. */ + public static int darkTheme() { + Activity current = activity; + if (current == null) { + return -1; + } + int night = current.getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK; + return night == Configuration.UI_MODE_NIGHT_YES ? 1 : 0; + } + + /** True when the user turned animations off. */ + public static boolean animationsOff() { + Activity current = activity; + if (current == null) { + return false; + } + return Settings.Global.getFloat(current.getContentResolver(), Settings.Global.ANIMATOR_DURATION_SCALE, 1f) == 0f; + } } diff --git a/internal/platform/android/hostsrc/java/dev/viva/host/Native.java b/internal/platform/android/hostsrc/java/dev/viva/host/Native.java index c527ca932..06196cfe8 100644 --- a/internal/platform/android/hostsrc/java/dev/viva/host/Native.java +++ b/internal/platform/android/hostsrc/java/dev/viva/host/Native.java @@ -29,6 +29,9 @@ private Native() {} /** The activity is in front (true) or has gone behind another (false). */ public static native void visible(boolean visible); + /** The theme, the language or the animation setting may have changed. */ + public static native void appearanceChanged(); + /** The system is short of memory. */ public static native void lowMemory(); @@ -55,6 +58,12 @@ private Native() {} /** A key of a keyboard: its Android key code, the meta state and the character it types. */ public static native void key(int keyCode, int meta, int unicode, boolean repeat); + /** A screen reader is reading the window, or has stopped. */ + public static native void accessibility(boolean on); + + /** A screen reader's request of a node: its place in the tree last sent, what to do, and the value of it. */ + public static native void accessible(int node, int action, float number, String text, int start, int end); + /** A mouse over the surface. */ public static native void hover(float x, float y, int meta, long uptimeMillis); diff --git a/internal/platform/android/hostsrc/java/dev/viva/host/VivaActivity.java b/internal/platform/android/hostsrc/java/dev/viva/host/VivaActivity.java index bcb3eeea6..588a821ed 100644 --- a/internal/platform/android/hostsrc/java/dev/viva/host/VivaActivity.java +++ b/internal/platform/android/hostsrc/java/dev/viva/host/VivaActivity.java @@ -56,6 +56,7 @@ public void onLowMemory() { @Override public void onConfigurationChanged(Configuration config) { super.onConfigurationChanged(config); + Native.appearanceChanged(); } @Override diff --git a/internal/platform/android/hostsrc/java/dev/viva/host/VivaView.java b/internal/platform/android/hostsrc/java/dev/viva/host/VivaView.java index 12d985f9d..b71d00de0 100644 --- a/internal/platform/android/hostsrc/java/dev/viva/host/VivaView.java +++ b/internal/platform/android/hostsrc/java/dev/viva/host/VivaView.java @@ -6,6 +6,8 @@ import android.view.MotionEvent; import android.view.SurfaceView; import android.view.ViewConfiguration; +import android.view.accessibility.AccessibilityManager; +import android.view.accessibility.AccessibilityNodeProvider; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputConnection; import android.view.inputmethod.InputMethodManager; @@ -19,10 +21,32 @@ final class VivaView extends SurfaceView { private boolean multiline; private boolean secure; + private final Accessibility accessibility = new Accessibility(this); + VivaView(Context context) { super(context); setFocusable(true); setFocusableInTouchMode(true); + setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); + } + + Accessibility accessibility() { + return accessibility; + } + + @Override + public AccessibilityNodeProvider getAccessibilityNodeProvider() { + return accessibility; + } + + @Override + protected void onAttachedToWindow() { + super.onAttachedToWindow(); + AccessibilityManager manager = (AccessibilityManager) getContext().getSystemService(Context.ACCESSIBILITY_SERVICE); + if (manager != null) { + Native.accessibility(manager.isEnabled()); + manager.addAccessibilityStateChangeListener(Native::accessibility); + } } /** Makes the view a text editor, or not, and restarts the input method on it. */ diff --git a/internal/platform/android/jni_android.c b/internal/platform/android/jni_android.c index da4c1e203..c213dfa57 100644 --- a/internal/platform/android/jni_android.c +++ b/internal/platform/android/jni_android.c @@ -8,6 +8,7 @@ static JavaVM *vm; static jclass hostClass, textClass; static jmethodID hostFinish, hostSetTitle, hostEditor, hostKeyboard; +static jmethodID hostTree, hostClipboardText, hostSetClipboardText, hostOpenURL, hostLanguages, hostDarkTheme, hostAnimationsOff; static jmethodID textWidth, textMetrics, textRects, textSetFamily, textBegin, textDraw, textEnd; /* A JNI_OnLoad finds the host's classes while the loader that holds them is the caller's. */ @@ -28,6 +29,13 @@ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *jvm, void *reserved) { hostSetTitle = (*env)->GetStaticMethodID(env, hostClass, "setTitle", "(Ljava/lang/String;)V"); hostEditor = (*env)->GetStaticMethodID(env, hostClass, "editor", "(Ljava/lang/String;IIII)V"); hostKeyboard = (*env)->GetStaticMethodID(env, hostClass, "keyboard", "(ZZZ)V"); + hostTree = (*env)->GetStaticMethodID(env, hostClass, "tree", "([F[I[F[C[I)V"); + hostClipboardText = (*env)->GetStaticMethodID(env, hostClass, "clipboardText", "()Ljava/lang/String;"); + hostSetClipboardText = (*env)->GetStaticMethodID(env, hostClass, "setClipboardText", "(Ljava/lang/String;)Z"); + hostOpenURL = (*env)->GetStaticMethodID(env, hostClass, "openURL", "(Ljava/lang/String;)Z"); + hostLanguages = (*env)->GetStaticMethodID(env, hostClass, "languages", "()Ljava/lang/String;"); + hostDarkTheme = (*env)->GetStaticMethodID(env, hostClass, "darkTheme", "()I"); + hostAnimationsOff = (*env)->GetStaticMethodID(env, hostClass, "animationsOff", "()Z"); textWidth = (*env)->GetStaticMethodID(env, textClass, "width", "(Ljava/lang/String;FIZZ)F"); textMetrics = (*env)->GetStaticMethodID(env, textClass, "metrics", "(FIZZ[F)V"); textRects = (*env)->GetStaticMethodID(env, textClass, "rects", "(Ljava/lang/String;FIZZZ[I[F[F)V"); @@ -230,3 +238,82 @@ void viva_host_keyboard(int editing, int multiline, int secure) { } } + +static char *host_string(jmethodID method) { + JNIEnv *e = env(); + if (e == NULL) { + return NULL; + } + jstring s = (jstring)(*e)->CallStaticObjectMethod(e, hostClass, method); + if (failed(e) || s == NULL) { + return NULL; + } + char *copy = viva_string_chars(e, s); + (*e)->DeleteLocalRef(e, s); + return copy; +} + +char *viva_host_clipboard_text(void) { return host_string(hostClipboardText); } + +char *viva_host_languages(void) { return host_string(hostLanguages); } + +static int host_text_call(jmethodID method, const uint16_t *text, int length) { + JNIEnv *e = env(); + if (e == NULL) { + return 0; + } + jstring s = (*e)->NewString(e, (const jchar *)text, length); + jboolean ok = (*e)->CallStaticBooleanMethod(e, hostClass, method, s); + (*e)->DeleteLocalRef(e, s); + return !failed(e) && ok; +} + +int viva_host_set_clipboard_text(const uint16_t *text, int length) { return host_text_call(hostSetClipboardText, text, length); } + +int viva_host_open_url(const uint16_t *url, int length) { return host_text_call(hostOpenURL, url, length); } + +int viva_host_dark_theme(void) { + JNIEnv *e = env(); + if (e == NULL) { + return -1; + } + jint theme = (*e)->CallStaticIntMethod(e, hostClass, hostDarkTheme); + return failed(e) ? -1 : theme; +} + +int viva_host_animations_off(void) { + JNIEnv *e = env(); + if (e == NULL) { + return 0; + } + jboolean off = (*e)->CallStaticBooleanMethod(e, hostClass, hostAnimationsOff); + return !failed(e) && off; +} + +void viva_host_tree(int count, const float *bounds, const int32_t *ints, const float *ranges, const uint16_t *chars, int charCount, const int32_t *offsets) { + JNIEnv *e = env(); + if (e == NULL) { + return; + } + jfloatArray b = (*e)->NewFloatArray(e, 4 * count); + jintArray i = (*e)->NewIntArray(e, 5 * count); + jfloatArray r = (*e)->NewFloatArray(e, 3 * count); + jcharArray c = (*e)->NewCharArray(e, charCount); + jintArray o = (*e)->NewIntArray(e, 4 * count + 1); + if (count > 0) { + (*e)->SetFloatArrayRegion(e, b, 0, 4 * count, bounds); + (*e)->SetIntArrayRegion(e, i, 0, 5 * count, (const jint *)ints); + (*e)->SetFloatArrayRegion(e, r, 0, 3 * count, ranges); + } + if (charCount > 0) { + (*e)->SetCharArrayRegion(e, c, 0, charCount, (const jchar *)chars); + } + (*e)->SetIntArrayRegion(e, o, 0, 4 * count + 1, (const jint *)offsets); + (*e)->CallStaticVoidMethod(e, hostClass, hostTree, b, i, r, c, o); + failed(e); + (*e)->DeleteLocalRef(e, b); + (*e)->DeleteLocalRef(e, i); + (*e)->DeleteLocalRef(e, r); + (*e)->DeleteLocalRef(e, c); + (*e)->DeleteLocalRef(e, o); +} diff --git a/internal/platform/android/jni_android.h b/internal/platform/android/jni_android.h index b1d587081..a107b53a6 100644 --- a/internal/platform/android/jni_android.h +++ b/internal/platform/android/jni_android.h @@ -27,4 +27,15 @@ int viva_text_end(void *out, int64_t capacity); void viva_host_editor(const uint16_t *text, int length, int selectionStart, int selectionEnd, int compositionStart, int compositionEnd); void viva_host_keyboard(int editing, int multiline, int secure); void viva_host_finish(void); +/* viva_host_tree gives the host the accessibility tree: per node four floats of bounds, five ints + * (role, flags, level, position, size) and three of range (min, max, now), and four strings + * (label, value, hint, description) in one UTF-16 buffer cut by offsets, four per node plus one. */ +void viva_host_tree(int count, const float *bounds, const int32_t *ints, const float *ranges, const uint16_t *chars, int charCount, const int32_t *offsets); +/* The strings the system answers with, malloc memory the caller frees; NULL for none. */ +char *viva_host_clipboard_text(void); +int viva_host_set_clipboard_text(const uint16_t *text, int length); +int viva_host_open_url(const uint16_t *url, int length); +char *viva_host_languages(void); +int viva_host_dark_theme(void); +int viva_host_animations_off(void); void viva_host_set_title(const uint16_t *title, int length); diff --git a/internal/platform/android/system_android.go b/internal/platform/android/system_android.go new file mode 100644 index 000000000..3189fe268 --- /dev/null +++ b/internal/platform/android/system_android.go @@ -0,0 +1,64 @@ +//go:build android + +package android + +/* +#include +#include "jni_android.h" +*/ +import "C" + +import ( + "strings" + "unsafe" +) + +// What the system answers an application with, from the host's calls into Android's +// services. They are safe from any goroutine. + +func hostString(chars *C.char) (string, bool) { + if chars == nil { + return "", false + } + defer C.free(unsafe.Pointer(chars)) + return C.GoString(chars), true +} + +// ClipboardText is the text on the clipboard, false when there is none or the system will +// not say (Android lets only the application in front read it). +func ClipboardText() (string, bool) { return hostString(C.viva_host_clipboard_text()) } + +// SetClipboardText puts text on the clipboard. +func SetClipboardText(text string) bool { + units := utf16Units(text) + var data *C.uint16_t + if len(units) > 0 { + data = (*C.uint16_t)(unsafe.Pointer(&units[0])) + } + return C.viva_host_set_clipboard_text(data, C.int(len(units))) != 0 +} + +// OpenURL opens a link in the app that takes it. +func OpenURL(url string) bool { + units := utf16Units(url) + if len(units) == 0 { + return false + } + return C.viva_host_open_url((*C.uint16_t)(unsafe.Pointer(&units[0])), C.int(len(units))) != 0 +} + +// PreferredLanguages are the user's languages, most preferred first, as BCP 47 tags. +func PreferredLanguages() []string { + tags, ok := hostString(C.viva_host_languages()) + if !ok || tags == "" { + return nil + } + return strings.Split(tags, "\n") +} + +// DarkTheme is 1 when the system shows the dark theme, 0 for the light one and -1 when it +// does not say. +func DarkTheme() int { return int(C.viva_host_dark_theme()) } + +// AnimationsOff reports whether the user turned animations off. +func AnimationsOff() bool { return C.viva_host_animations_off() != 0 } diff --git a/internal/platform/contract.go b/internal/platform/contract.go index 6925a6ad9..91da6ef4d 100644 --- a/internal/platform/contract.go +++ b/internal/platform/contract.go @@ -124,7 +124,11 @@ type Config struct { // node: press it, focus it, set its value. The adapter calls it on the // event-loop thread and presents the frames it hands back. OnAccessibility AccessibilityHandler - OnRedraw RedrawHandler + // AccessibilityTree, when set, answers with the tree the window has now, for an adapter + // whose assistive technology starts after the window opened: frames carry the tree only + // when it changes. The slice is the application's, read at once and not kept. + AccessibilityTree func() []AccessibilityNode + OnRedraw RedrawHandler // SetFrameInterval, when set, is called by the adapter on the window thread // once it knows how the window's frames are paced: the interval between // display frames, or zero when presenting a frame blocks until the display diff --git a/internal/platform/darwin/ios_host.m b/internal/platform/darwin/ios_host.m index b4dcb6a6b..f81535302 100644 --- a/internal/platform/darwin/ios_host.m +++ b/internal/platform/darwin/ios_host.m @@ -19,6 +19,8 @@ extern void vivaTouchEvent(uintptr_t callbackHandle, void *view, int kind, int i extern void vivaIOSKeyEvent(uintptr_t callbackHandle, void *view, int usage, int modifiers, int repeat, const unsigned char *utf8, size_t utf8Length); extern void vivaIOSVisibility(uintptr_t callbackHandle, void *view, int visible); +extern void vivaIOSTextOp(uintptr_t callbackHandle, void *view, int operation, const unsigned char *utf8, size_t utf8Length, + int64_t first, int64_t last); extern void vivaRedrawRequested(uintptr_t callbackHandle, void *view); /* The pointer kinds, as platform.PointerEventKind numbers them. */ @@ -38,7 +40,95 @@ extern void vivaIOSKeyEvent(uintptr_t callbackHandle, void *view, int usage, int static int viva_application_status = 0; +/* What the keyboard does to the text input, as vivaIOSTextOp takes it. */ +enum { + VIVA_IOS_TEXT_COMMIT = 1, + VIVA_IOS_TEXT_SET_MARKED = 2, + VIVA_IOS_TEXT_FINISH = 3, + VIVA_IOS_TEXT_REPLACE = 4, + VIVA_IOS_TEXT_SELECT = 5, + VIVA_IOS_TEXT_DELETE_BACKWARD = 6, + VIVA_IOS_TEXT_ENTER = 7, +}; + +@class VivaIOSView; + +/* A position in the text, as a number of UTF-16 units from its start. */ +@interface VivaIOSTextPosition : UITextPosition { +@public + NSInteger _offset; +} ++ (instancetype)positionAt:(NSInteger)offset; +@end + +@implementation VivaIOSTextPosition ++ (instancetype)positionAt:(NSInteger)offset { + VivaIOSTextPosition *position = [[VivaIOSTextPosition alloc] init]; + position->_offset = offset; + return [position autorelease]; +} +@end + +@interface VivaIOSTextRange : UITextRange { + VivaIOSTextPosition *_start; + VivaIOSTextPosition *_end; +} ++ (instancetype)rangeFrom:(NSInteger)start to:(NSInteger)end; +@end + +@implementation VivaIOSTextRange ++ (instancetype)rangeFrom:(NSInteger)start to:(NSInteger)end { + VivaIOSTextRange *range = [[VivaIOSTextRange alloc] init]; + range->_start = [[VivaIOSTextPosition positionAt:MIN(start, end)] retain]; + range->_end = [[VivaIOSTextPosition positionAt:MAX(start, end)] retain]; + return [range autorelease]; +} +- (void)dealloc { + [_start release]; + [_end release]; + [super dealloc]; +} +- (UITextPosition *)start { + return _start; +} +- (UITextPosition *)end { + return _end; +} +- (BOOL)isEmpty { + return _start->_offset == _end->_offset; +} +@end + +/* VivaIOSEditor is what the keyboard types into: an invisible view that holds a copy of + * the application's focused text input and passes what the keyboard does to it back, as + * ranges of UTF-16 units. The application owns the text; this is only read by UIKit. */ +@interface VivaIOSEditor : UIView { + NSMutableString *_text; + NSRange _selected; + NSRange _marked; + BOOL _hasMarked; + BOOL _enabled; + BOOL _multiline; + BOOL _secure; + uintptr_t _callbackHandle; + VivaIOSView *_surface; + CGRect _caret; + id _inputDelegate; + UITextInputStringTokenizer *_tokenizer; + UITextInputAssistantItem *_assistant; +} +@property(nonatomic, assign) VivaIOSView *surface; +@property(nonatomic, assign) uintptr_t callbackHandle; +@property(nonatomic, readonly) BOOL enabled; +- (void)setState:(const unsigned char *)utf8 length:(size_t)length selection:(NSRange)selection marked:(NSRange)marked hasMarked:(BOOL)hasMarked; +- (void)setEnabled:(BOOL)enabled multiline:(BOOL)multiline secure:(BOOL)secure; +- (void)setCaret:(CGRect)caret; ++ (BOOL)textSystemTakes:(UIKey *)key; +@end + + @interface VivaIOSView : UIView { + VivaIOSEditor *_editor; VivaRenderer *_renderer; uintptr_t _callbackHandle; BOOL _resizeEventsEnabled; @@ -48,6 +138,7 @@ @interface VivaIOSView : UIView { } @property(nonatomic, readonly) uintptr_t callbackHandle; @property(nonatomic, readonly) BOOL closed; +@property(nonatomic, readonly) VivaIOSEditor *editor; - (instancetype)initWithFrame:(CGRect)frame device:(id)device commandQueue:(id)commandQueue @@ -73,6 +164,7 @@ @implementation VivaIOSView @synthesize callbackHandle = _callbackHandle; @synthesize closed = _closed; +@synthesize editor = _editor; + (Class)layerClass { return [CAMetalLayer class]; @@ -90,6 +182,10 @@ - (instancetype)initWithFrame:(CGRect)frame return nil; } _callbackHandle = config->callback_handle; + _editor = [[VivaIOSEditor alloc] initWithFrame:CGRectMake(0, 0, 1, 1)]; + _editor.surface = self; + _editor.callbackHandle = _callbackHandle; + [self addSubview:_editor]; _resizeEventsEnabled = config->resize_events_enabled != 0; // Fingers are separate pointers: a second one ends what the first was doing. self.multipleTouchEnabled = YES; @@ -124,6 +220,7 @@ - (instancetype)initWithFrame:(CGRect)frame } - (void)dealloc { + [_editor release]; [_renderer release]; [super dealloc]; } @@ -278,6 +375,9 @@ - (void)pressesBegan:(NSSet *)presses withEvent:(UIPressesEvent *)eve if (key == nil || _closed) { continue; } + if (_editor.enabled && [VivaIOSEditor textSystemTakes:key]) { + continue; + } const char *chars = key.charactersIgnoringModifiers.UTF8String; size_t length = chars != NULL ? strlen(chars) : 0; vivaIOSKeyEvent(_callbackHandle, self, (int)key.keyCode, (int)key.modifierFlags, 0, (const unsigned char *)chars, length); @@ -290,6 +390,297 @@ - (void)pressesBegan:(NSSet *)presses withEvent:(UIPressesEvent *)eve @end + +@implementation VivaIOSEditor + +@synthesize surface = _surface; +@synthesize callbackHandle = _callbackHandle; +@synthesize enabled = _enabled; +@synthesize markedTextStyle; +@synthesize inputDelegate = _inputDelegate; + +- (instancetype)initWithFrame:(CGRect)frame { + self = [super initWithFrame:frame]; + if (self != nil) { + _text = [[NSMutableString alloc] init]; + _selected = NSMakeRange(0, 0); + _marked = NSMakeRange(NSNotFound, 0); + self.alpha = 0; + self.userInteractionEnabled = NO; + } + return self; +} + +- (void)dealloc { + [_text release]; + [_tokenizer release]; + [markedTextStyle release]; + [super dealloc]; +} + +/* textSystemTakes says a hardware key is the text system's while a field is focused: it + * arrives as insertText, deleteBackward or a change of the selection, not as a key. */ ++ (BOOL)textSystemTakes:(UIKey *)key { + switch (key.keyCode) { + case UIKeyboardHIDUsageKeyboardReturnOrEnter: + case UIKeyboardHIDUsageKeyboardDeleteOrBackspace: + case UIKeyboardHIDUsageKeyboardDeleteForward: + case UIKeyboardHIDUsageKeyboardLeftArrow: + case UIKeyboardHIDUsageKeyboardRightArrow: + case UIKeyboardHIDUsageKeyboardHome: + case UIKeyboardHIDUsageKeyboardEnd: + case UIKeyboardHIDUsageKeyboardSpacebar: + return YES; + default: + return NO; + } +} + +- (BOOL)canBecomeFirstResponder { + return _enabled; +} + +- (void)setEnabled:(BOOL)enabled multiline:(BOOL)multiline secure:(BOOL)secure { + BOOL restart = _enabled != enabled || _multiline != multiline || _secure != secure; + _enabled = enabled; + _multiline = multiline; + _secure = secure; + if (!restart) { + return; + } + if (enabled) { + if (self.isFirstResponder) { + [self reloadInputViews]; + } else { + [self becomeFirstResponder]; + } + } else { + [self resignFirstResponder]; + // The keys of a connected keyboard go on to the surface. + [_surface becomeFirstResponder]; + } +} + +- (void)setState:(const unsigned char *)utf8 length:(size_t)length selection:(NSRange)selection marked:(NSRange)marked hasMarked:(BOOL)hasMarked { + NSString *value = length > 0 ? [[NSString alloc] initWithBytes:utf8 length:length encoding:NSUTF8StringEncoding] : [[NSString alloc] init]; + BOOL textChanged = ![_text isEqualToString:value]; + BOOL selectionChanged = !NSEqualRanges(_selected, selection) || _hasMarked != hasMarked || (hasMarked && !NSEqualRanges(_marked, marked)); + if (textChanged) { + [_inputDelegate textWillChange:self]; + } + if (selectionChanged) { + [_inputDelegate selectionWillChange:self]; + } + [_text setString:value]; + [value release]; + _selected = NSMakeRange(MIN(selection.location, _text.length), MIN(selection.length, _text.length - MIN(selection.location, _text.length))); + _hasMarked = hasMarked; + _marked = hasMarked ? NSMakeRange(MIN(marked.location, _text.length), MIN(marked.length, _text.length - MIN(marked.location, _text.length))) : NSMakeRange(NSNotFound, 0); + if (selectionChanged) { + [_inputDelegate selectionDidChange:self]; + } + if (textChanged) { + [_inputDelegate textDidChange:self]; + } +} + +- (void)setCaret:(CGRect)caret { + _caret = caret; +} + +- (void)sendOperation:(int)operation text:(NSString *)text first:(NSInteger)first last:(NSInteger)last { + NSData *data = [text dataUsingEncoding:NSUTF8StringEncoding]; + vivaIOSTextOp(_callbackHandle, _surface, operation, data.bytes, data.length, first, last); +} + +#pragma mark UIKeyInput + +- (BOOL)hasText { + return _text.length > 0; +} + +- (void)insertText:(NSString *)text { + if ([text isEqualToString:@"\n"] && !_multiline) { + [self sendOperation:VIVA_IOS_TEXT_ENTER text:@"" first:0 last:0]; + return; + } + [self sendOperation:VIVA_IOS_TEXT_COMMIT text:text first:0 last:0]; +} + +- (void)deleteBackward { + [self sendOperation:VIVA_IOS_TEXT_DELETE_BACKWARD text:@"" first:0 last:0]; +} + +#pragma mark UITextInput: text + +- (NSString *)textInRange:(UITextRange *)range { + VivaIOSTextRange *r = (VivaIOSTextRange *)range; + NSInteger start = MIN(((VivaIOSTextPosition *)r.start)->_offset, (NSInteger)_text.length); + NSInteger end = MIN(((VivaIOSTextPosition *)r.end)->_offset, (NSInteger)_text.length); + return [_text substringWithRange:NSMakeRange(start, MAX(end - start, 0))]; +} + +- (void)replaceRange:(UITextRange *)range withText:(NSString *)text { + VivaIOSTextRange *r = (VivaIOSTextRange *)range; + [self sendOperation:VIVA_IOS_TEXT_REPLACE text:text first:((VivaIOSTextPosition *)r.start)->_offset last:((VivaIOSTextPosition *)r.end)->_offset]; +} + +- (UITextRange *)selectedTextRange { + return [VivaIOSTextRange rangeFrom:_selected.location to:_selected.location + _selected.length]; +} + +- (void)setSelectedTextRange:(UITextRange *)range { + VivaIOSTextRange *r = (VivaIOSTextRange *)range; + if (r == nil) { + return; + } + [self sendOperation:VIVA_IOS_TEXT_SELECT text:@"" first:((VivaIOSTextPosition *)r.start)->_offset last:((VivaIOSTextPosition *)r.end)->_offset]; +} + +- (UITextRange *)markedTextRange { + return _hasMarked ? [VivaIOSTextRange rangeFrom:_marked.location to:_marked.location + _marked.length] : nil; +} + +- (void)setMarkedText:(NSString *)markedText selectedRange:(NSRange)selectedRange { + NSInteger start = selectedRange.location == NSNotFound ? (NSInteger)markedText.length : (NSInteger)selectedRange.location; + [self sendOperation:VIVA_IOS_TEXT_SET_MARKED text:markedText ?: @"" first:start last:start + (NSInteger)selectedRange.length]; +} + +- (void)unmarkText { + [self sendOperation:VIVA_IOS_TEXT_FINISH text:@"" first:0 last:0]; +} + +#pragma mark UITextInput: positions + +- (UITextPosition *)beginningOfDocument { + return [VivaIOSTextPosition positionAt:0]; +} + +- (UITextPosition *)endOfDocument { + return [VivaIOSTextPosition positionAt:_text.length]; +} + +- (UITextRange *)textRangeFromPosition:(UITextPosition *)from toPosition:(UITextPosition *)to { + return [VivaIOSTextRange rangeFrom:((VivaIOSTextPosition *)from)->_offset to:((VivaIOSTextPosition *)to)->_offset]; +} + +- (UITextPosition *)positionFromPosition:(UITextPosition *)position offset:(NSInteger)offset { + NSInteger target = ((VivaIOSTextPosition *)position)->_offset + offset; + if (target < 0 || target > (NSInteger)_text.length) { + return nil; + } + return [VivaIOSTextPosition positionAt:target]; +} + +- (UITextPosition *)positionFromPosition:(UITextPosition *)position inDirection:(UITextLayoutDirection)direction offset:(NSInteger)offset { + NSInteger from = ((VivaIOSTextPosition *)position)->_offset; + NSInteger target = from; + switch (direction) { + case UITextLayoutDirectionLeft: + target = from - offset; + break; + case UITextLayoutDirectionRight: + target = from + offset; + break; + case UITextLayoutDirectionUp: + target = 0; + break; + case UITextLayoutDirectionDown: + target = _text.length; + break; + } + return [VivaIOSTextPosition positionAt:MIN(MAX(target, 0), (NSInteger)_text.length)]; +} + +- (NSComparisonResult)comparePosition:(UITextPosition *)position toPosition:(UITextPosition *)other { + NSInteger a = ((VivaIOSTextPosition *)position)->_offset; + NSInteger b = ((VivaIOSTextPosition *)other)->_offset; + return a < b ? NSOrderedAscending : a > b ? NSOrderedDescending : NSOrderedSame; +} + +- (NSInteger)offsetFromPosition:(UITextPosition *)from toPosition:(UITextPosition *)to { + return ((VivaIOSTextPosition *)to)->_offset - ((VivaIOSTextPosition *)from)->_offset; +} + +- (id)tokenizer { + if (_tokenizer == nil) { + _tokenizer = [[UITextInputStringTokenizer alloc] initWithTextInput:self]; + } + return _tokenizer; +} + +- (UITextPosition *)positionWithinRange:(UITextRange *)range farthestInDirection:(UITextLayoutDirection)direction { + BOOL end = direction == UITextLayoutDirectionRight || direction == UITextLayoutDirectionDown; + return end ? range.end : range.start; +} + +- (UITextRange *)characterRangeByExtendingPosition:(UITextPosition *)position inDirection:(UITextLayoutDirection)direction { + NSInteger offset = ((VivaIOSTextPosition *)position)->_offset; + BOOL forward = direction == UITextLayoutDirectionRight || direction == UITextLayoutDirectionDown; + return [VivaIOSTextRange rangeFrom:offset to:forward ? _text.length : 0]; +} + +- (NSWritingDirection)baseWritingDirectionForPosition:(UITextPosition *)position inDirection:(UITextStorageDirection)direction { + return NSWritingDirectionNatural; +} + +- (void)setBaseWritingDirection:(NSWritingDirection)direction forRange:(UITextRange *)range { +} + +#pragma mark UITextInput: geometry + +- (CGRect)firstRectForRange:(UITextRange *)range { + return [self convertRect:_caret fromView:_surface]; +} + +- (CGRect)caretRectForPosition:(UITextPosition *)position { + return [self convertRect:CGRectMake(CGRectGetMinX(_caret), CGRectGetMinY(_caret), 2, CGRectGetHeight(_caret)) fromView:_surface]; +} + +- (NSArray *)selectionRectsForRange:(UITextRange *)range { + return @[]; +} + +- (UITextPosition *)closestPositionToPoint:(CGPoint)point { + return [VivaIOSTextPosition positionAt:_selected.location + _selected.length]; +} + +- (UITextPosition *)closestPositionToPoint:(CGPoint)point withinRange:(UITextRange *)range { + return range.end; +} + +- (UITextRange *)characterRangeAtPoint:(CGPoint)point { + return nil; +} + +#pragma mark UITextInputTraits + +- (UIKeyboardType)keyboardType { + return UIKeyboardTypeDefault; +} + +- (BOOL)isSecureTextEntry { + return _secure; +} + +- (UIReturnKeyType)returnKeyType { + return _multiline ? UIReturnKeyDefault : UIReturnKeyDone; +} + +- (UITextAutocorrectionType)autocorrectionType { + return _secure ? UITextAutocorrectionTypeNo : UITextAutocorrectionTypeDefault; +} + +- (UITextAutocapitalizationType)autocapitalizationType { + return UITextAutocapitalizationTypeNone; +} + +- (UITextSpellCheckingType)spellCheckingType { + return _secure ? UITextSpellCheckingTypeNo : UITextSpellCheckingTypeDefault; +} + +@end + @interface VivaIOSViewController : UIViewController { VivaIOSView *_surface; } @@ -578,18 +969,49 @@ int viva_view_update_text( int ends_composition, int render ) { + VivaIOSView *surface = (VivaIOSView *)view; + if (surface == nil || surface.editor == nil) { + return 1; + } + [surface.editor setState:utf8 + length:utf8_length + selection:NSMakeRange(selected_start, selected_length) + marked:NSMakeRange(marked_start, marked_length) + hasMarked:has_marked_text != 0]; return 0; } +/* viva_view_update_text_input follows the application's wish for its text input: another + * one, the same with other text, or none, which has the keyboard away. */ +static int viva_ios_text_input(void *view, viva_text_input_config text_input) { + VivaIOSView *surface = (VivaIOSView *)view; + if (surface == nil || surface.editor == nil) { + return 1; + } + if (text_input.enabled == 0) { + [surface.editor setEnabled:NO multiline:NO secure:NO]; + return 0; + } + [surface.editor setCaret:CGRectMake(text_input.x, text_input.y, text_input.width, text_input.height)]; + [surface.editor setEnabled:YES multiline:text_input.multiline != 0 secure:text_input.secure != 0]; + return viva_view_update_text(view, text_input.utf8, text_input.utf8_length, text_input.selected_start, text_input.selected_length, + text_input.marked_start, text_input.marked_length, text_input.has_marked_text, 0, 0, 0); +} + int viva_view_update_text_input(void *view, viva_text_input_config text_input) { - return 0; + return viva_ios_text_input(view, text_input); } int viva_view_update_text_input_keeping_composition(void *view, viva_text_input_config text_input) { - return 0; + return viva_ios_text_input(view, text_input); } int viva_view_move_text_input(void *view, float x, float y, float width, float height) { + VivaIOSView *surface = (VivaIOSView *)view; + if (surface == nil || surface.editor == nil) { + return 1; + } + [surface.editor setCaret:CGRectMake(x, y, width, height)]; return 0; } diff --git a/internal/platform/darwin/ios_text.go b/internal/platform/darwin/ios_text.go new file mode 100644 index 000000000..e12fae231 --- /dev/null +++ b/internal/platform/darwin/ios_text.go @@ -0,0 +1,68 @@ +//go:build ios + +package darwin + +/* +#include "native.h" +*/ +import "C" + +import ( + "unsafe" + + "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/internal/platform/imebridge" +) + +// What the keyboard does to the text input, as ios_host.m sends it. +const ( + iosTextCommit = iota + 1 + iosTextSetMarked + iosTextFinish + iosTextReplace + iosTextSelect + iosTextDeleteBackward + iosTextEnter +) + +// vivaIOSTextOp is one thing the keyboard does to the focused text input. The ranges are +// UTF-16 units of the text the keyboard sees, which is the application's: each operation +// is read against the editor's state as it stands, and delivered as the text events the +// other platforms' text services make (deliverTextInputEvent), so the editor, the +// composition and the repaint are the same on every platform. +// +//export vivaIOSTextOp +func vivaIOSTextOp(handle C.uintptr_t, view unsafe.Pointer, operation C.int, utf8 *C.uchar, utf8Length C.size_t, first, last C.int64_t) { + state, ok := runStateFor(handle) + if !ok || state.closed || state.textHandler == nil { + return + } + value := "" + if utf8Length > 0 { + value = C.GoStringN((*C.char)(unsafe.Pointer(utf8)), C.int(utf8Length)) + } + session := &imebridge.Session{ + State: state.textState, + Handler: func(event platform.TextEvent) (platform.TextState, error) { + err := deliverTextInputEvent(state, view, event, true, false) + return state.textState, err + }, + } + switch operation { + case iosTextCommit: + session.Commit(value, 1) + case iosTextSetMarked: + session.SetMarked(value, int(first), int(last)) + case iosTextFinish: + session.Finish() + case iosTextReplace: + session.Replace(int(first), int(last), value) + case iosTextSelect: + session.Select(int(first), int(last)) + case iosTextDeleteBackward: + session.Command(platform.TextDeleteBackward) + case iosTextEnter: + // Enter in a field of one line is the application's, as a key. + vivaIOSKeyEvent(handle, view, 0x28, 0, 0, nil, 0) + } +} From 5db1b3c000c9422beb6b28d0d3dfe016c0d3ed01 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 22 Nov 2026 23:51:14 +0800 Subject: [PATCH 34/64] fix(ios): hand the keys the text system takes back to it The surface took every key of a connected keyboard as its own, so a focused text field never saw the characters. A key that types is passed on, up the responder chain, to the text system, and the editor is made a view UIKit will route a keyboard to: it can be interacted with, but takes no touch. Verified in the simulator with the system's pinyin input method: the composition, its candidates and the committed text reach the field. --- internal/platform/darwin/ios_host.m | 32 +++++++++++++++++----------- internal/platform/darwin/ios_keys.go | 12 ++++++----- internal/platform/darwin/ios_text.go | 2 +- 3 files changed, 28 insertions(+), 18 deletions(-) diff --git a/internal/platform/darwin/ios_host.m b/internal/platform/darwin/ios_host.m index f81535302..a68f3f401 100644 --- a/internal/platform/darwin/ios_host.m +++ b/internal/platform/darwin/ios_host.m @@ -16,8 +16,8 @@ extern void vivaWindowClosed(uintptr_t callbackHandle); extern void vivaTouchEvent(uintptr_t callbackHandle, void *view, int kind, int identifier, double x, double y, double screenX, double screenY); -extern void vivaIOSKeyEvent(uintptr_t callbackHandle, void *view, int usage, int modifiers, int repeat, - const unsigned char *utf8, size_t utf8Length); +extern int vivaIOSKeyEvent(uintptr_t callbackHandle, void *view, int usage, int modifiers, int repeat, + const unsigned char *utf8, size_t utf8Length); extern void vivaIOSVisibility(uintptr_t callbackHandle, void *view, int visible); extern void vivaIOSTextOp(uintptr_t callbackHandle, void *view, int operation, const unsigned char *utf8, size_t utf8Length, int64_t first, int64_t last); @@ -369,22 +369,21 @@ - (void)didMoveToWindow { // text arrive as key events and the chords with Control or Command as shortcut // offers; what is typed is the text input's (see UITextInput). - (void)pressesBegan:(NSSet *)presses withEvent:(UIPressesEvent *)event { - BOOL handled = NO; + NSMutableSet *others = [NSMutableSet set]; for (UIPress *press in presses) { UIKey *key = press.key; - if (key == nil || _closed) { - continue; - } - if (_editor.enabled && [VivaIOSEditor textSystemTakes:key]) { + if (key == nil || _closed || (_editor.enabled && [VivaIOSEditor textSystemTakes:key])) { + [others addObject:press]; continue; } const char *chars = key.charactersIgnoringModifiers.UTF8String; size_t length = chars != NULL ? strlen(chars) : 0; - vivaIOSKeyEvent(_callbackHandle, self, (int)key.keyCode, (int)key.modifierFlags, 0, (const unsigned char *)chars, length); - handled = YES; + if (vivaIOSKeyEvent(_callbackHandle, self, (int)key.keyCode, (int)key.modifierFlags, 0, (const unsigned char *)chars, length) == 0) { + [others addObject:press]; + } } - if (!handled) { - [super pressesBegan:presses withEvent:event]; + if (others.count > 0) { + [super pressesBegan:others withEvent:event]; } } @@ -406,7 +405,6 @@ - (instancetype)initWithFrame:(CGRect)frame { _selected = NSMakeRange(0, 0); _marked = NSMakeRange(NSNotFound, 0); self.alpha = 0; - self.userInteractionEnabled = NO; } return self; } @@ -440,6 +438,16 @@ - (BOOL)canBecomeFirstResponder { return _enabled; } +/* The editor is not there to be touched: the surface under it is. */ +- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event { + return NO; +} + +- (UIView *)textInputView { + return self; +} + + - (void)setEnabled:(BOOL)enabled multiline:(BOOL)multiline secure:(BOOL)secure { BOOL restart = _enabled != enabled || _multiline != multiline || _secure != secure; _enabled = enabled; diff --git a/internal/platform/darwin/ios_keys.go b/internal/platform/darwin/ios_keys.go index 3d3c36544..33c13be2f 100644 --- a/internal/platform/darwin/ios_keys.go +++ b/internal/platform/darwin/ios_keys.go @@ -82,26 +82,28 @@ func keyModifiers(flags int) input.Modifiers { return modifiers } -// vivaIOSKeyEvent is a key of a connected keyboard. A key that is not text is a key +// vivaIOSKeyEvent is a key of a connected keyboard, answering whether it was taken. A key that is not text is a key // event; a chord with Control or Command and a character is offered as a shortcut, // and is a key event only if nothing took it. What a key types is the text input's. // //export vivaIOSKeyEvent -func vivaIOSKeyEvent(handle C.uintptr_t, view unsafe.Pointer, usage C.int, flags C.int, repeat C.int, utf8 *C.uchar, utf8Length C.size_t) { +func vivaIOSKeyEvent(handle C.uintptr_t, view unsafe.Pointer, usage C.int, flags C.int, repeat C.int, utf8 *C.uchar, utf8Length C.size_t) C.int { state, ok := runStateFor(handle) if !ok || state.closed { - return + return 0 } modifiers := keyModifiers(int(flags)) key := keyOfUsage(int(usage)) chord := modifiers&(input.ModifierControl|input.ModifierMeta) != 0 && utf8Length > 0 if chord && vivaShortcutEvent(handle, view, C.int(key), C.int(modifiers), repeat, utf8, utf8Length) != 0 { - return + return 1 } if key == gfx.KeyUnknown && !chord { - return + // What the key types is the text system's. + return 0 } deliverKey(handle, view, KeyEvent{Key: key, Modifiers: modifiers, Repeat: repeat != 0}, utf8, utf8Length) + return 1 } // vivaIOSVisibility follows the application going behind another and coming back. diff --git a/internal/platform/darwin/ios_text.go b/internal/platform/darwin/ios_text.go index e12fae231..f6d167718 100644 --- a/internal/platform/darwin/ios_text.go +++ b/internal/platform/darwin/ios_text.go @@ -63,6 +63,6 @@ func vivaIOSTextOp(handle C.uintptr_t, view unsafe.Pointer, operation C.int, utf session.Command(platform.TextDeleteBackward) case iosTextEnter: // Enter in a field of one line is the application's, as a key. - vivaIOSKeyEvent(handle, view, 0x28, 0, 0, nil, 0) + _ = vivaIOSKeyEvent(handle, view, 0x28, 0, 0, nil, 0) } } From 9ca247de515e36b40311cdc73d44ec8ec07d3ba6 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 22 Nov 2026 23:56:40 +0800 Subject: [PATCH 35/64] feat(ios): show the program's accessibility tree to VoiceOver The tree is a list of UIAccessibilityElements held by the surface, which is their container and is not read itself: label, value, hint, the traits of the node's role, its frame, and the activate, increment and decrement actions, which go back to the application by the node's identity as on the other platforms. The tree the window opened with is applied, since a frame carries it only when it changes. Verified with the simulator's accessibility listing: the text field and the button of the text field example, with their frames. --- internal/platform/darwin/ios_host.m | 167 +++++++++++++++++++++++++++- 1 file changed, 166 insertions(+), 1 deletion(-) diff --git a/internal/platform/darwin/ios_host.m b/internal/platform/darwin/ios_host.m index a68f3f401..d36e9b201 100644 --- a/internal/platform/darwin/ios_host.m +++ b/internal/platform/darwin/ios_host.m @@ -19,6 +19,8 @@ extern void vivaTouchEvent(uintptr_t callbackHandle, void *view, int kind, int i extern int vivaIOSKeyEvent(uintptr_t callbackHandle, void *view, int usage, int modifiers, int repeat, const unsigned char *utf8, size_t utf8Length); extern void vivaIOSVisibility(uintptr_t callbackHandle, void *view, int visible); +extern int vivaAccessibilityAction(uintptr_t callbackHandle, void *view, uint64_t node, int action, double number, + const unsigned char *utf8, size_t utf8Length, int start, int end); extern void vivaIOSTextOp(uintptr_t callbackHandle, void *view, int operation, const unsigned char *utf8, size_t utf8Length, int64_t first, int64_t last); extern void vivaRedrawRequested(uintptr_t callbackHandle, void *view); @@ -127,7 +129,132 @@ + (BOOL)textSystemTakes:(UIKey *)key; @end +/* The accessibility roles, in the numbering of platform.A11yRole*. */ +enum { + VIVA_A11Y_GROUP = 2, VIVA_A11Y_BUTTON = 3, VIVA_A11Y_TEXT = 4, VIVA_A11Y_TEXT_FIELD = 5, VIVA_A11Y_CHECKBOX = 6, + VIVA_A11Y_SLIDER = 7, VIVA_A11Y_IMAGE = 8, VIVA_A11Y_LINK = 9, VIVA_A11Y_RADIO = 10, VIVA_A11Y_TAB = 11, + VIVA_A11Y_MENU_ITEM = 12, VIVA_A11Y_SWITCH = 14, VIVA_A11Y_OPTION = 18, VIVA_A11Y_GRID_CELL = 20, + VIVA_A11Y_HEADING = 21, VIVA_A11Y_STATUS = 22, VIVA_A11Y_PROGRESS = 24, +}; + +/* One node of the program's accessibility tree, as VoiceOver reads it. It holds what the + * node said when it was last sent; VoiceOver's requests go back to the program by the + * node's identity. */ +@interface VivaIOSAccessibleElement : UIAccessibilityElement { + uint64_t _identity; + int _role; + BOOL _operable; + uintptr_t _callbackHandle; + void *_surface; + double _rangeNow; + double _rangeMin; + double _rangeMax; +} +- (instancetype)initWithNode:(const viva_accessibility_node *)node container:(UIView *)container handle:(uintptr_t)handle; +@end + +@implementation VivaIOSAccessibleElement + +static NSString *viva_string(const char *chars, size_t length) { + if (chars == NULL || length == 0) { + return nil; + } + return [[[NSString alloc] initWithBytes:chars length:length encoding:NSUTF8StringEncoding] autorelease]; +} + +- (instancetype)initWithNode:(const viva_accessibility_node *)node container:(UIView *)container handle:(uintptr_t)handle { + self = [super initWithAccessibilityContainer:container]; + if (self == nil) { + return nil; + } + _identity = node->id; + _role = node->role; + _callbackHandle = handle; + _surface = container; + _rangeNow = node->range_now; + _rangeMin = node->range_min; + _rangeMax = node->range_max; + _operable = !node->disabled; + self.accessibilityLabel = viva_string(node->label, node->label_length); + NSString *value = viva_string(node->value, node->value_length); + if (_role == VIVA_A11Y_CHECKBOX || _role == VIVA_A11Y_SWITCH || _role == VIVA_A11Y_RADIO) { + value = node->mixed ? @"2" : node->checked ? @"1" : @"0"; + } else if (node->range_set && value == nil) { + double span = node->range_max - node->range_min; + value = span > 0 ? [NSString stringWithFormat:@"%.0f%%", (node->range_now - node->range_min) / span * 100] : nil; + } + self.accessibilityValue = value; + NSString *hint = viva_string(node->hint, node->hint_length); + if (hint == nil) { + hint = viva_string(node->description, node->description_length); + } + self.accessibilityHint = hint; + self.accessibilityFrameInContainerSpace = CGRectMake(node->x, node->y, node->width, node->height); + UIAccessibilityTraits traits = UIAccessibilityTraitNone; + switch (_role) { + case VIVA_A11Y_BUTTON: + case VIVA_A11Y_MENU_ITEM: + case VIVA_A11Y_TAB: + case VIVA_A11Y_OPTION: + case VIVA_A11Y_RADIO: + case VIVA_A11Y_GRID_CELL: + case VIVA_A11Y_CHECKBOX: + case VIVA_A11Y_SWITCH: + traits |= UIAccessibilityTraitButton; + break; + case VIVA_A11Y_LINK: + traits |= UIAccessibilityTraitLink; + break; + case VIVA_A11Y_SLIDER: + traits |= UIAccessibilityTraitAdjustable; + break; + case VIVA_A11Y_HEADING: + traits |= UIAccessibilityTraitHeader | UIAccessibilityTraitStaticText; + break; + case VIVA_A11Y_TEXT: + case VIVA_A11Y_STATUS: + traits |= UIAccessibilityTraitStaticText; + break; + case VIVA_A11Y_IMAGE: + traits |= UIAccessibilityTraitImage; + break; + default: + break; + } + if (node->selected) { + traits |= UIAccessibilityTraitSelected; + } + if (node->disabled) { + traits |= UIAccessibilityTraitNotEnabled; + } + if (node->live != 0) { + traits |= UIAccessibilityTraitUpdatesFrequently; + } + self.accessibilityTraits = traits; + // A group only holds others; what it contains is what is read. + self.isAccessibilityElement = _role != 1 && _role != VIVA_A11Y_GROUP && (self.accessibilityLabel != nil || value != nil || traits != UIAccessibilityTraitNone); + return self; +} + +- (BOOL)accessibilityActivate { + if (!_operable) { + return NO; + } + return vivaAccessibilityAction(_callbackHandle, _surface, _identity, 1, 0, NULL, 0, 0, 0) != 0; +} + +- (void)accessibilityIncrement { + vivaAccessibilityAction(_callbackHandle, _surface, _identity, 3, 0, NULL, 0, 0, 0); +} + +- (void)accessibilityDecrement { + vivaAccessibilityAction(_callbackHandle, _surface, _identity, 4, 0, NULL, 0, 0, 0); +} + +@end + @interface VivaIOSView : UIView { + NSMutableArray *_accessibleElements; VivaIOSEditor *_editor; VivaRenderer *_renderer; uintptr_t _callbackHandle; @@ -157,6 +284,7 @@ - (int)updateRectangles:(const viva_rectangle *)rectangles rebuild:(BOOL)rebuild render:(BOOL)render; - (int)updateLabels:(const viva_text_label *)labels count:(NSUInteger)count; +- (int)updateAccessibility:(const viva_accessibility_node *)nodes count:(NSUInteger)count; - (void)closeWindow; @end @@ -220,6 +348,7 @@ - (instancetype)initWithFrame:(CGRect)frame } - (void)dealloc { + [_accessibleElements release]; [_editor release]; [_renderer release]; [super dealloc]; @@ -320,6 +449,33 @@ - (void)closeWindow { vivaWindowClosed(_callbackHandle); } +#pragma mark Accessibility + +// updateAccessibility makes the program's tree what VoiceOver reads. The surface is the +// container of the elements: it is not itself read. +- (int)updateAccessibility:(const viva_accessibility_node *)nodes count:(NSUInteger)count { + NSMutableArray *elements = [[NSMutableArray alloc] initWithCapacity:count]; + for (NSUInteger index = 0; index < count; index++) { + VivaIOSAccessibleElement *element = [[VivaIOSAccessibleElement alloc] initWithNode:&nodes[index] container:self handle:_callbackHandle]; + if (element != nil) { + [elements addObject:element]; + [element release]; + } + } + [_accessibleElements release]; + _accessibleElements = elements; + UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, nil); + return 0; +} + +- (BOOL)isAccessibilityElement { + return NO; +} + +- (NSArray *)accessibilityElements { + return _accessibleElements; +} + #pragma mark Touches // emitTouches reports each finger of a phase. A finger is its UITouch for as long @@ -689,6 +845,7 @@ - (UITextSpellCheckingType)spellCheckingType { @end + @interface VivaIOSViewController : UIViewController { VivaIOSView *_surface; } @@ -840,6 +997,9 @@ int viva_application_last_status(void) { viva_application_status = VIVA_IOS_STATUS_NO_VIEW; return NULL; } + if (config.accessibility_count > 0) { + [view updateAccessibility:config.accessibility count:config.accessibility_count]; + } VivaIOSViewController *controller = [[VivaIOSViewController alloc] init]; [controller loadViewIfNeeded]; [controller setSurface:view]; @@ -961,7 +1121,12 @@ void viva_view_close_confirmed(void *view) { * accessibility tree and the web views come with their own work packages. They * accept what the application sends and show nothing of it. */ int viva_view_update_accessibility(void *view, const viva_accessibility_node *nodes, size_t count) { - return 0; + if (view == NULL) { + return 1; + } + @autoreleasepool { + return [(VivaIOSView *)view updateAccessibility:nodes count:count]; + } } int viva_view_update_text( From 9b57ae2ab75e6509b067f22c1c9e9653c5b3bdac Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Mon, 23 Nov 2026 00:03:33 +0800 Subject: [PATCH 36/64] feat(examples): add a touch example for checking fingers on phones A scrolling list, a button, a slider, a switch, a text field and a long-press row menu, with tests that drive them by touch. --- examples/touch/main.go | 77 ++++++++++++++++++ examples/touch/main_test.go | 158 ++++++++++++++++++++++++++++++++++++ 2 files changed, 235 insertions(+) create mode 100644 examples/touch/main.go create mode 100644 examples/touch/main_test.go diff --git a/examples/touch/main.go b/examples/touch/main.go new file mode 100644 index 000000000..b620901de --- /dev/null +++ b/examples/touch/main.go @@ -0,0 +1,77 @@ +// Touch is the page a phone is checked with: what a finger does to each kind of control. +// A long list scrolls under a finger and keeps going when it lifts; a tap presses; a +// finger held on a row opens its menu; a slider takes a moving finger as a drag; and a +// field brings the keyboard. The same page runs with a mouse on a desktop. +package main + +import ( + "fmt" + "log" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/ui" +) + +const rows = 200 + +type model struct { + taps int + volume ui.SliderState + notify bool + name string + list ui.ListState + menu string +} + +func newModel() *model { + m := &model{volume: ui.SliderState{Value: 40}} + m.list.Label = func(i int) string { return fmt.Sprintf("Row %d", i+1) } + return m +} + +func (m *model) page(c ui.C) { + ui.Column(c).Fill().Pad(16).Gap(12).Items(ui.Stretch).Children(func() { + ui.Row(c).Gap(12).Items(ui.Center).Children(func() { + if ui.Button(c, "Tap me").Clicked() { + m.taps++ + } + ui.Text(c, fmt.Sprintf("Tapped %d times", m.taps)) + }) + ui.Row(c).Gap(12).Items(ui.Center).Children(func() { + ui.Text(c, fmt.Sprintf("Volume %.0f", m.volume.Value)) + ui.Slider(c, &m.volume).Width(220).Step(1) + }) + ui.Switch(c, &m.notify, "Notifications") + ui.TextField(c, &m.name, "Name", "Your name").Width(320) + if m.menu != "" { + ui.Text(c, m.menu).Muted() + } + ui.List(c, &m.list, rows, m.row).Label("Rows").Grow(1) + }) +} + +// row is one row of the list: a finger lifted on it chooses it, a finger held on it +// opens a menu. +func (m *model) row(r ui.ListRow) { + theme := r.C.Theme() + r.Element.Pad(12).PadX(12) + if r.Index == m.list.Selected() { + r.Element.Background(theme.Hover) + } + ui.Text(r.C, fmt.Sprintf("Row %d", r.Index+1)) + ui.ContextMenu(r.C, r.Element, func(menu *ui.MenuItems) { + if menu.Item("Open").Clicked() { + m.menu = fmt.Sprintf("Opened row %d", r.Index+1) + } + if menu.Item("Delete").Clicked() { + m.menu = fmt.Sprintf("Deleted row %d", r.Index+1) + } + }) +} + +func main() { + m := newModel() + if err := ui.Run(app.Config{Title: "Touch", Width: 420, Height: 760}, ui.PageConfig{View: m.page}); err != nil { + log.Fatal(err) + } +} diff --git a/examples/touch/main_test.go b/examples/touch/main_test.go new file mode 100644 index 000000000..0f54295e5 --- /dev/null +++ b/examples/touch/main_test.go @@ -0,0 +1,158 @@ +package main + +import ( + "runtime" + "testing" + "time" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +func open(t *testing.T, m *model) *app.Driver { + t.Helper() + page := ui.NewPage(ui.PageConfig{View: m.page}) + driver, err := app.NewDriver(ui.Configure(page, app.Config{Width: 420, Height: 760}), nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(driver.Close) + return driver +} + +func control(t *testing.T, driver *app.Driver, label string) gfx.Hit { + t.Helper() + hits := driver.Snapshot().Hits + for i := len(hits) - 1; i >= 0; i-- { + hit := hits[i] + if hit.Label == label && !hit.IsLabel { + return hit + } + } + t.Fatalf("no control named %q on screen", label) + return gfx.Hit{} +} + +func centerOf(t *testing.T, driver *app.Driver, label string) (float32, float32) { + t.Helper() + b := control(t, driver, label).Bounds + return b.X + b.Width/2, b.Y + b.Height/2 +} + +func shown(driver *app.Driver, want string) bool { + for _, label := range driver.Snapshot().Labels { + if label.Value == want { + return true + } + } + return false +} + +// A finger lifted on a button presses it once. +func TestATapPressesTheButton(t *testing.T) { + m := newModel() + driver := open(t, m) + x, y := centerOf(t, driver, "Tap me") + if err := driver.TouchDown(1, x, y); err != nil { + t.Fatal(err) + } + if err := driver.TouchUp(1, x, y); err != nil { + t.Fatal(err) + } + if m.taps != 1 || !shown(driver, "Tapped 1 times") { + t.Fatalf("taps = %d", m.taps) + } +} + +// A finger that drags up the list scrolls it, and the rows it started on are not +// chosen by it. +func TestAFingerScrollsTheListAndChoosesNothing(t *testing.T) { + skipWithoutTouchRuntime(t) + m := newModel() + driver := open(t, m) + if shown(driver, "Row 30") { + t.Fatal("the thirtieth row is on screen before the list scrolled") + } + x, y := centerOf(t, driver, "Row 5") + if err := driver.TouchDown(1, x, y+200); err != nil { + t.Fatal(err) + } + for step := float32(1); step <= 20; step++ { + if err := driver.Advance(10 * time.Millisecond); err != nil { + t.Fatal(err) + } + if err := driver.TouchMove(1, x, y+200-step*30); err != nil { + t.Fatal(err) + } + } + if err := driver.TouchUp(1, x, y-400); err != nil { + t.Fatal(err) + } + if err := driver.Advance(2 * time.Second); err != nil { + t.Fatal(err) + } + if m.list.Selected() >= 0 { + t.Fatalf("a drag chose row %d", m.list.Selected()) + } + if shown(driver, "Row 1") { + t.Fatal("the list did not scroll under the finger") + } +} + +// A finger held on a row opens its menu, and choosing from the menu is a tap. +func TestAHeldFingerOpensTheRowMenu(t *testing.T) { + skipWithoutTouchRuntime(t) + m := newModel() + driver := open(t, m) + x, y := centerOf(t, driver, "Row 1") + if err := driver.TouchDown(1, x, y); err != nil { + t.Fatal(err) + } + if err := driver.Advance(700 * time.Millisecond); err != nil { + t.Fatal(err) + } + if err := driver.TouchUp(1, x, y); err != nil { + t.Fatal(err) + } + mx, my := centerOf(t, driver, "Open") + if err := driver.TouchDown(2, mx, my); err != nil { + t.Fatal(err) + } + if err := driver.TouchUp(2, mx, my); err != nil { + t.Fatal(err) + } + if m.menu != "Opened row 1" { + t.Fatalf("menu = %q", m.menu) + } +} + +// A finger on a slider drags it at once, and does not scroll the page. +func TestAFingerDragsTheSlider(t *testing.T) { + m := newModel() + driver := open(t, m) + b := control(t, driver, "Slider").Bounds + y := b.Y + b.Height/2 + before := m.volume.Value + if err := driver.TouchDown(1, b.X+b.Width*0.4, y); err != nil { + t.Fatal(err) + } + if err := driver.TouchMove(1, b.X+b.Width*0.9, y); err != nil { + t.Fatal(err) + } + if err := driver.TouchUp(1, b.X+b.Width*0.9, y); err != nil { + t.Fatal(err) + } + if m.volume.Value <= before { + t.Fatalf("volume %v after dragging right from %v", m.volume.Value, before) + } +} + +// skipWithoutTouchRuntime skips a test that needs the finger gestures: macOS has no touch +// screen, so its windows do not install them and a finger there is only a pointer. +func skipWithoutTouchRuntime(t *testing.T) { + t.Helper() + if runtime.GOOS == "darwin" { + t.Skip("macOS windows do not install the touch gestures") + } +} From 62cc40cde4151c77fbb4317956e1275e84f8b3da Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Mon, 23 Nov 2026 00:07:14 +0800 Subject: [PATCH 37/64] fix(showcase): drop the breadcrumb when the toolbar is too narrow for it On a phone the page title was painted over the density button. --- internal/gallery/gallery.go | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/internal/gallery/gallery.go b/internal/gallery/gallery.go index 900802ea0..9727058b3 100644 --- a/internal/gallery/gallery.go +++ b/internal/gallery/gallery.go @@ -343,16 +343,20 @@ func (state *State) paintToolbar(canvas *gfx.Canvas, theme gfx.Theme, width floa } labelX := float32(148) title := "Components" - if state.page != 0 { - if components.BeginButton(canvas, theme, hitPageCatalog, gfx.Rect{X: labelX, Y: top, Width: 96}).Small().Ghost("Components").Clicked() { - page = 0 + // On a phone there is no room between the page arrows and the density and theme + // buttons for a breadcrumb; the page's own heading already names where you are. + if titleWidth := width - labelX - 210; titleWidth >= 96 { + if state.page != 0 { + if components.BeginButton(canvas, theme, hitPageCatalog, gfx.Rect{X: labelX, Y: top, Width: 96}).Small().Ghost("Components").Clicked() { + page = 0 + } + labelX += 108 + title = catalog[state.page-1].Title } - labelX += 108 - title = catalog[state.page-1].Title + canvas.Label(title, gfx.Rect{ + X: labelX, Y: top, Width: max(width-labelX-210, 0), Height: control, + }, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Weight: gfx.WeightMedium, Color: theme.MutedForeground}) } - canvas.Label(title, gfx.Rect{ - X: labelX, Y: top, Width: width - labelX - 210, Height: control, - }, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Weight: gfx.WeightMedium, Color: theme.MutedForeground}) densityBounds := gfx.Rect{X: width - 190, Y: top, Width: 88} if components.BeginButton(canvas, theme, hitDensityCycle, densityBounds).Small().Ghost(state.densityName()).Clicked() { From 90459cbdea903c7c03c2967f576bf0ce398ae17e Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Mon, 23 Nov 2026 00:13:36 +0800 Subject: [PATCH 38/64] feat(ios): provide the pasteboard, links, languages, motion and appearance Replaces the iOS stubs with UIPasteboard, UIApplication openURL, NSLocale languages, the reduce-motion setting and the system look, which the view controller reports when it changes. --- app/ios_unsupported.go | 12 ---- app/system_ios.go | 42 +++++++++++++ internal/platform/darwin/ios_host.m | 10 +++ internal/platform/darwin/ios_system.go | 61 ++++++++++++++++++ internal/platform/darwin/ios_system.h | 25 ++++++++ internal/platform/darwin/ios_system.m | 86 ++++++++++++++++++++++++++ 6 files changed, 224 insertions(+), 12 deletions(-) create mode 100644 internal/platform/darwin/ios_system.go create mode 100644 internal/platform/darwin/ios_system.h create mode 100644 internal/platform/darwin/ios_system.m diff --git a/app/ios_unsupported.go b/app/ios_unsupported.go index 2097323fc..6356e3dd1 100644 --- a/app/ios_unsupported.go +++ b/app/ios_unsupported.go @@ -2,20 +2,8 @@ package app -import "os" - // What a phone has no use for, and Android answers with its common fallbacks: // an iPhone has no file icons for the application to ask for, and no reopening. func nativeFileIcon(string, int) ([]byte, error) { return nil, ErrUnsupported } func setReopenHandler(*Config, *Window) {} - -// What the system answers an iPhone application with, until its backend does: - -func nativeClipboardText() (string, error) { return "", ErrUnsupported } -func nativeSetClipboardText(string) error { return ErrUnsupported } -func nativeOpenURL(string) error { return ErrUnsupported } -func nativePreferredLanguages() []string { return languagesFromEnvironment(os.Getenv) } -func nativeReduceMotion() bool { return false } -func nativeAppearance() Appearance { return AppearanceUnknown } -func nativeWatchAppearance() {} diff --git a/app/system_ios.go b/app/system_ios.go index 832b55605..a5279d562 100644 --- a/app/system_ios.go +++ b/app/system_ios.go @@ -3,6 +3,8 @@ package app import ( + "os" + "github.com/vivaui/viva/gfx" darwinplatform "github.com/vivaui/viva/internal/platform/darwin" ) @@ -11,3 +13,43 @@ import ( // rest is answered in mobile_unsupported.go. func nativeTextEngine() gfx.TextEngine { return darwinplatform.SharedTextEngine() } + +func nativeClipboardText() (string, error) { + text, _ := darwinplatform.ClipboardText() + return text, nil +} + +func nativeSetClipboardText(text string) error { + darwinplatform.SetClipboardText(text) + return nil +} + +func nativeOpenURL(url string) error { + if !darwinplatform.OpenURL(url) { + return ErrUnsupported + } + return nil +} + +func nativePreferredLanguages() []string { + if languages := darwinplatform.PreferredLanguages(); len(languages) > 0 { + return languages + } + return languagesFromEnvironment(os.Getenv) +} + +func nativeReduceMotion() bool { return darwinplatform.ReduceMotion() } + +func nativeAppearance() Appearance { + switch darwinplatform.DarkTheme() { + case 1: + return AppearanceDark + case 0: + return AppearanceLight + } + return AppearanceUnknown +} + +// The view controller tells the application when the look changes, whether or not +// anyone watches. +func nativeWatchAppearance() {} diff --git a/internal/platform/darwin/ios_host.m b/internal/platform/darwin/ios_host.m index d36e9b201..a5358ca47 100644 --- a/internal/platform/darwin/ios_host.m +++ b/internal/platform/darwin/ios_host.m @@ -19,6 +19,7 @@ extern void vivaTouchEvent(uintptr_t callbackHandle, void *view, int kind, int i extern int vivaIOSKeyEvent(uintptr_t callbackHandle, void *view, int usage, int modifiers, int repeat, const unsigned char *utf8, size_t utf8Length); extern void vivaIOSVisibility(uintptr_t callbackHandle, void *view, int visible); +extern void vivaIOSAppearanceChanged(void); extern int vivaAccessibilityAction(uintptr_t callbackHandle, void *view, uint64_t node, int action, double number, const unsigned char *utf8, size_t utf8Length, int start, int end); extern void vivaIOSTextOp(uintptr_t callbackHandle, void *view, int operation, const unsigned char *utf8, size_t utf8Length, @@ -903,6 +904,15 @@ - (UIInterfaceOrientationMask)supportedInterfaceOrientations { return UIInterfaceOrientationMaskAll; } +// traitCollectionDidChange tells the application when the system switches between +// its light and dark looks. +- (void)traitCollectionDidChange:(UITraitCollection *)previous { + [super traitCollectionDidChange:previous]; + if (previous != nil && previous.userInterfaceStyle != self.traitCollection.userInterfaceStyle) { + vivaIOSAppearanceChanged(); + } +} + @end @interface VivaIOSAppDelegate : UIResponder diff --git a/internal/platform/darwin/ios_system.go b/internal/platform/darwin/ios_system.go new file mode 100644 index 000000000..4e5ef9d29 --- /dev/null +++ b/internal/platform/darwin/ios_system.go @@ -0,0 +1,61 @@ +//go:build ios + +package darwin + +/* +#include +#include "ios_system.h" +*/ +import "C" + +import ( + "strings" + "unsafe" + + "github.com/vivaui/viva/internal/platform" +) + +// fromC copies and frees a string the native side allocated; false for NULL. +func fromC(value *C.char) (string, bool) { + if value == nil { + return "", false + } + defer C.free(unsafe.Pointer(value)) + return C.GoString(value), true +} + +// ClipboardText is the text on the pasteboard, false when there is none. +func ClipboardText() (string, bool) { return fromC(C.viva_ios_clipboard_text()) } + +// SetClipboardText puts text on the pasteboard. +func SetClipboardText(text string) { + native := C.CString(text) + defer C.free(unsafe.Pointer(native)) + C.viva_ios_set_clipboard_text(native) +} + +// OpenURL opens a link in the application that takes it, false when none does. +func OpenURL(url string) bool { + native := C.CString(url) + defer C.free(unsafe.Pointer(native)) + return C.viva_ios_open_url(native) != 0 +} + +// PreferredLanguages are the user's languages, most preferred first, as BCP 47 tags. +func PreferredLanguages() []string { + joined, ok := fromC(C.viva_ios_preferred_languages()) + if !ok || joined == "" { + return nil + } + return strings.Split(joined, "\n") +} + +// ReduceMotion reports whether the user asked for less motion. +func ReduceMotion() bool { return C.viva_ios_reduce_motion() != 0 } + +// DarkTheme is 1 when the system shows the dark look, 0 for the light one and -1 when +// it does not say. +func DarkTheme() int { return int(C.viva_ios_dark_theme()) } + +//export vivaIOSAppearanceChanged +func vivaIOSAppearanceChanged() { platform.NotifyAppearanceChanged() } diff --git a/internal/platform/darwin/ios_system.h b/internal/platform/darwin/ios_system.h new file mode 100644 index 000000000..26f6c96bd --- /dev/null +++ b/internal/platform/darwin/ios_system.h @@ -0,0 +1,25 @@ +//go:build ios + +#ifndef VIVA_IOS_SYSTEM_H +#define VIVA_IOS_SYSTEM_H + +/* What the system gives an application, answered on the main thread whichever + * thread asks. Strings are UTF-8, malloc'ed and freed by the caller. */ + +/* The text on the pasteboard, NULL when there is none. */ +char *viva_ios_clipboard_text(void); +void viva_ios_set_clipboard_text(const char *text); + +/* Opens a link in the application that takes it; nonzero when one was found. */ +int viva_ios_open_url(const char *url); + +/* The user's languages, most preferred first, joined by newlines. */ +char *viva_ios_preferred_languages(void); + +/* Nonzero when the user asked for less motion. */ +int viva_ios_reduce_motion(void); + +/* 1 for the dark look, 0 for the light one, -1 when unknown. */ +int viva_ios_dark_theme(void); + +#endif diff --git a/internal/platform/darwin/ios_system.m b/internal/platform/darwin/ios_system.m new file mode 100644 index 000000000..0e6347923 --- /dev/null +++ b/internal/platform/darwin/ios_system.m @@ -0,0 +1,86 @@ +//go:build ios + +// What the system gives an iPhone application: the pasteboard, links, the user's +// languages and the look they chose. + +#import +#include +#include + +#include "ios_system.h" + +// onMain runs work on the main thread, where UIKit may be used, and waits for it. +static void viva_on_main(dispatch_block_t work) { + if ([NSThread isMainThread]) { + work(); + } else { + dispatch_sync(dispatch_get_main_queue(), work); + } +} + +static char *viva_copy(NSString *value) { + const char *utf8 = value.UTF8String; + return utf8 == NULL ? NULL : strdup(utf8); +} + +char *viva_ios_clipboard_text(void) { + __block char *result = NULL; + viva_on_main(^{ + // hasStrings does not read the contents, so asking is free of the paste prompt. + if (UIPasteboard.generalPasteboard.hasStrings) { + result = viva_copy(UIPasteboard.generalPasteboard.string); + } + }); + return result; +} + +void viva_ios_set_clipboard_text(const char *text) { + NSString *value = [NSString stringWithUTF8String:text]; + viva_on_main(^{ + UIPasteboard.generalPasteboard.string = value; + }); +} + +int viva_ios_open_url(const char *text) { + NSURL *url = [NSURL URLWithString:[NSString stringWithUTF8String:text]]; + if (url == nil) { + return 0; + } + __block int opened = 0; + viva_on_main(^{ + if ([UIApplication.sharedApplication canOpenURL:url] || [url.scheme hasPrefix:@"http"]) { + [UIApplication.sharedApplication openURL:url options:@{} completionHandler:nil]; + opened = 1; + } + }); + return opened; +} + +char *viva_ios_preferred_languages(void) { + return viva_copy([[NSLocale preferredLanguages] componentsJoinedByString:@"\n"]); +} + +int viva_ios_reduce_motion(void) { + __block int reduced = 0; + viva_on_main(^{ + reduced = UIAccessibilityIsReduceMotionEnabled() ? 1 : 0; + }); + return reduced; +} + +int viva_ios_dark_theme(void) { + __block int dark = -1; + viva_on_main(^{ + switch (UIScreen.mainScreen.traitCollection.userInterfaceStyle) { + case UIUserInterfaceStyleDark: + dark = 1; + break; + case UIUserInterfaceStyleLight: + dark = 0; + break; + default: + break; + } + }); + return dark; +} From 847e49e7fa8e0aa506f1301f169a86e8c864ab58 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Mon, 23 Nov 2026 00:22:09 +0800 Subject: [PATCH 39/64] fix(dmg): detach the disk even when its volume is already unmounted An image whose volume the system had unmounted stayed attached, and the disk image service kept holding the file. --- tools/dmg/build.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/tools/dmg/build.go b/tools/dmg/build.go index 09835a5b9..944294261 100644 --- a/tools/dmg/build.go +++ b/tools/dmg/build.go @@ -206,6 +206,11 @@ func detach(mount, device string) error { return err } if !mounted { + // The volume is already unmounted (by the system, say) but the image is still + // attached, and the disk image service holds the file until the disk goes: + // detach it anyway. Failing here is no news when it was already gone, and + // released reports an image that is still attached. + _ = hdiutil("detach", device) return nil } for attempt := 0; attempt < 5; attempt++ { From 353980c4fba18c2a9b83d36f505329165941c1bb Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Mon, 23 Nov 2026 00:55:36 +0800 Subject: [PATCH 40/64] feat(scroll): let a finger carry content past its end and spring it back A finger and the fling it leaves give at the end of scrollable content like the system's bounce: the content follows at a fraction, a fling gives by one step of what it had left, and the content returns when the finger lifts. Wheels and touchpads still stop at the end. --- app/painter.go | 4 +- app/touch.go | 13 ++- base/layout.go | 6 +- base/scroll.go | 151 ++++++++++++++++++++++++++++++++- base/scroll_overscroll_test.go | 98 +++++++++++++++++++++ examples/touch/main_test.go | 40 +++++++++ gfx/input.go | 20 +++++ internal/interaction/touch.go | 16 +++- internal/platform/contract.go | 2 + 9 files changed, 342 insertions(+), 8 deletions(-) create mode 100644 base/scroll_overscroll_test.go diff --git a/app/painter.go b/app/painter.go index 80e649ee1..887d6e21c 100644 --- a/app/painter.go +++ b/app/painter.go @@ -802,7 +802,7 @@ func (painter *painter) scroll(event platform.ScrollEvent) (platform.Frame, erro // the application leaves it, and reports whether anything changed that needs a // repaint. func (painter *painter) applyScroll(event platform.ScrollEvent) bool { - if event.DeltaY == 0 && event.DeltaX == 0 { + if event.DeltaY == 0 && event.DeltaX == 0 && event.Phase != gfx.ScrollPhaseEnd { return false } target := gfx.ID{} @@ -812,7 +812,7 @@ func (painter *painter) applyScroll(event platform.ScrollEvent) bool { response := gfx.EventResult{} if painter.onScroll != nil { response = painter.onScroll(gfx.ScrollEvent{ - Modifiers: gfx.Modifiers(event.Modifiers), X: event.X, Y: event.Y, + Phase: event.Phase, Modifiers: gfx.Modifiers(event.Modifiers), X: event.X, Y: event.Y, DeltaX: event.DeltaX, DeltaY: event.DeltaY, Viewport: painter.size, Target: target, Precise: event.Precise, }) } diff --git a/app/touch.go b/app/touch.go index 69a58a2c9..fdbed59c7 100644 --- a/app/touch.go +++ b/app/touch.go @@ -99,7 +99,11 @@ func (painter *painter) carryTouch(step interaction.TouchStep) (platform.Frame, return platform.Frame{}, err } if step.Scrolls() { - moved := painter.applyScroll(platform.ScrollEvent{X: step.ScrollAtX, Y: step.ScrollAtY, DeltaX: step.ScrollX, DeltaY: step.ScrollY, Precise: true}) + phase := gfx.ScrollPhaseFinger + if step.Momentum { + phase = gfx.ScrollPhaseMomentum + } + moved := painter.applyScroll(platform.ScrollEvent{Phase: phase, X: step.ScrollAtX, Y: step.ScrollAtY, DeltaX: step.ScrollX, DeltaY: step.ScrollY, Precise: true}) if !moved { t.FlingBlocked() // at the end of what it scrolls step.Wake = false @@ -107,6 +111,13 @@ func (painter *painter) carryTouch(step interaction.TouchStep) (platform.Frame, frame, err = painter.repaintAfterInput() } } + if step.ScrollEnds { + // The finger lifted: content held past an end springs back, and the frames + // that does it come from the layout asking for them. + if painter.applyScroll(platform.ScrollEvent{Phase: gfx.ScrollPhaseEnd, X: step.ScrollAtX, Y: step.ScrollAtY}) && !t.advancing { + frame, err = painter.repaintAfterInput() + } + } if step.Wake && painter.scheduleFrame != nil { painter.scheduleFrame(step.WakeAfter) } diff --git a/base/layout.go b/base/layout.go index cb6865200..379e9d018 100644 --- a/base/layout.go +++ b/base/layout.go @@ -517,7 +517,11 @@ func (f *Frame) solveFlow(n *Node, First, stop int32, axis int, start, avail flo if state := f.Exts[n.Ext].scrollState; state != nil && state.pinned() { n.Scroll = max(used-avail, 0) // at the end of what is there now, not of last frame's } - pos -= snapScroll(n.Scroll) + over := float32(0) + if state := f.Exts[n.Ext].scrollState; state != nil { + over = state.overscroll() + } + pos -= snapScroll(n.Scroll + over) } for c := First; c != stop; c = f.Nodes[c].Next { child := &f.Nodes[c] diff --git a/base/scroll.go b/base/scroll.go index c5dcfbc8a..7b264754e 100644 --- a/base/scroll.go +++ b/base/scroll.go @@ -1,6 +1,7 @@ package base import ( + "math" "time" "github.com/vivaui/viva/gfx" @@ -40,6 +41,15 @@ type ScrollState struct { ContentWidth float32 // the width of everything inside, as of the last layout ViewportWidth float32 // the width of the area itself, less its padding + // pull is how far a finger (or a fling that ran into an end) has carried the content + // past an end, in pixels a finger moved: negative past the start, positive past the + // end. The content is drawn overscroll(pull) away from its end, giving like rubber. + // touching says a finger holds the content, so pull stays; otherwise it springs back + // to zero, from pullAt on. + pull float32 + touching bool + pullAt time.Duration + ID gfx.ID // the area's identity, which its scrollbars are named under grab float32 // where along the thumb being dragged the pointer holds it follow bool // Box.Follow: keep the area at its end while the user has not left it @@ -226,6 +236,10 @@ func wheelStep(delta float32, precise bool) float32 { // It is the function to give as Config.OnScroll when one area owns the wheel; a page // with several areas gives view.Wheel instead, which finds the one under the pointer. func (s *ScrollState) Wheel(event gfx.ScrollEvent) gfx.EventResult { + if event.Phase != gfx.ScrollPhaseWheel { + return s.touchScroll(event) + } + s.pull, s.touching = 0, false dx, dy := s.wheelSteps(event) before, beforeX := s.Offset, s.OffsetX s.Offset = min(max(before+dy, 0), s.Max()) @@ -235,6 +249,109 @@ func (s *ScrollState) Wheel(event gfx.ScrollEvent) gfx.EventResult { return gfx.EventResult{Handled: true, Repaint: s.Offset != before || s.OffsetX != beforeX} } +// overscrollGive is how much of a finger's motion past an end the content follows at +// first; it follows less the further it is, up to a fraction of the area's own height: +// the curve UIScrollView draws, so the edge feels like rubber on every platform. +const overscrollGive = 0.55 + +// overscroll is how far the content is drawn past its end: the pull, through the +// rubber curve. It is zero for content at rest, at an end or inside it. +func (s *ScrollState) overscroll() float32 { + if s.pull == 0 || s.Viewport <= 0 { + return 0 + } + distance := s.pull + if distance < 0 { + distance = -distance + } + shown := s.Viewport * (1 - 1/(distance*overscrollGive/s.Viewport+1)) + if s.pull < 0 { + return -shown + } + return shown +} + +// touchScroll applies the scroll of a finger on a touch screen: it moves the content +// as a wheel does and, where the content ends, carries it past the end by the pull. +// A fling that reaches an end gives by what one step of it had left, and springs +// back at once, not carrying its whole speed past the end. +func (s *ScrollState) touchScroll(event gfx.ScrollEvent) gfx.EventResult { + switch event.Phase { + case gfx.ScrollPhaseEnd: + s.touching = false + return gfx.EventResult{Handled: true, Repaint: s.pull != 0} + case gfx.ScrollPhaseMomentum: + s.touching = false + if s.pull != 0 { + return gfx.EventResult{Handled: true} // already springing back + } + default: + s.touching = true + } + _, dy := s.wheelSteps(event) + before, beforePull := s.Offset, s.pull + s.toEnd = false + if s.pull != 0 { + // Past an end: the finger moves the pull first, and what is left once it is + // back at the end scrolls the content. + pulled := s.pull + dy + if (pulled > 0) != (s.pull > 0) || pulled == 0 { + s.pull, dy = 0, pulled + } else { + s.pull, dy = pulled, 0 + } + } + if dy != 0 { + target := s.Offset + dy + s.Offset = min(max(target, 0), s.Max()) + if left := target - s.Offset; left != 0 && s.Max() > 0 { + limit := s.Viewport * 3 + if event.Phase == gfx.ScrollPhaseMomentum { + limit = s.Viewport / 4 + } + s.pull = min(max(left, -limit), limit) + if event.Phase == gfx.ScrollPhaseMomentum { + s.pullAt = 0 + } + } + } + s.settle() + return gfx.EventResult{Handled: true, Repaint: s.Offset != before || s.pull != beforePull} +} + +// relax lets the content held past an end go: it springs back, a fraction of the way +// each frame, and asks for the frames until it is home. With nobody to run the frames +// (no clock) it is home at once. +func (s *ScrollState) relax(canvas *gfx.Canvas) { + if s.pull == 0 { + return + } + if canvas == nil || !canvas.HasClock() { + if !s.touching { + s.pull = 0 + } + return + } + now := canvas.Now() + if s.touching { + s.pullAt = now + return + } + step := 16 * time.Millisecond + if s.pullAt != 0 && now > s.pullAt { + step = min(now-s.pullAt, 50*time.Millisecond) + } + s.pullAt = now + // The time constant of 1/14 s settles a pull of a screen's height in under half + // a second, as the system's bounce does. + s.pull *= float32(math.Exp(-14 * step.Seconds())) + if s.pull > -0.5 && s.pull < 0.5 { + s.pull, s.pullAt = 0, 0 + return + } + canvas.RequestFrame() +} + // Key applies the keyboard's scrolling to the area, from the content and viewport // of its last layout: Left and Right move a Sideways area by step, Up and Down // vertically by step, PageUp and PageDown by a viewport, and Home and End to the @@ -319,6 +436,23 @@ func (View *View) Wheel(event gfx.ScrollEvent) gfx.EventResult { if f.Surface != nil { trap = f.Surface.TrappedFocusScope() } + if event.Phase == gfx.ScrollPhaseEnd { + // The finger lifted wherever it is now: whatever it held lets go. + result := gfx.EventResult{} + for i := range f.Nodes { + n := &f.Nodes[i] + if n.Ext == 0 || f.Exts[n.Ext].scrollState == nil { + continue + } + if s := f.Exts[n.Ext].scrollState; s.touching || s.pull != 0 { + if r := s.Wheel(event); r.Repaint { + result = r + } + } + } + return result + } + finger := event.Phase != gfx.ScrollPhaseWheel for i := len(f.Nodes) - 1; i >= 0; i-- { n := &f.Nodes[i] if n.Ext == 0 || f.Exts[n.Ext].scrollState == nil { @@ -334,11 +468,25 @@ func (View *View) Wheel(event gfx.ScrollEvent) gfx.EventResult { return gfx.EventResult{} } s := f.Exts[n.Ext].scrollState - if !s.canScroll(s.wheelSteps(event)) { + if !s.canScroll(s.wheelSteps(event)) && !(finger && s.pull != 0) { continue } return s.Wheel(event) } + if finger { + // Nothing under the finger can scroll further, so the innermost area that has + // anywhere to scroll gives at its end. + for i := len(f.Nodes) - 1; i >= 0; i-- { + n := &f.Nodes[i] + if n.Ext == 0 || f.Exts[n.Ext].scrollState == nil || f.Exts[n.Ext].scrollManual { + continue + } + if s := f.Exts[n.Ext].scrollState; s.Max() > 0 && f.ContainsPoint(i, event.X, event.Y) && + (trap.IsZero() || s.scope == trap) { + return s.Wheel(event) + } + } + } return gfx.EventResult{} } @@ -538,6 +686,7 @@ func (f *Frame) reportScrolls() { } else { s.Offset = min(max(s.Offset, 0), s.Max()) } + s.relax(f.Surface) xs, xe := n.Inset(AxisX) s.ViewportWidth = max(n.Rect.Width-xs-xe, 0) if !s.sideways { diff --git a/base/scroll_overscroll_test.go b/base/scroll_overscroll_test.go new file mode 100644 index 000000000..7930cc030 --- /dev/null +++ b/base/scroll_overscroll_test.go @@ -0,0 +1,98 @@ +package base + +import ( + "testing" + + "github.com/vivaui/viva/gfx" +) + +func finger(dy float32) gfx.ScrollEvent { + return gfx.ScrollEvent{Phase: gfx.ScrollPhaseFinger, DeltaY: dy, Precise: true} +} + +func tallArea() *ScrollState { return &ScrollState{Content: 2000, Viewport: 500} } + +// A finger that drags content past its start carries it there at a fraction of its +// motion, the further the less, and never a whole viewport. +func TestAFingerGivesAtTheEndOfTheContent(t *testing.T) { + s := tallArea() + var last float32 + for i := 0; i < 40; i++ { + s.Wheel(finger(-20)) // the finger moves down: the content goes down, past its start + shown := -s.overscroll() + if s.Offset != 0 { + t.Fatalf("the offset left the start: %v", s.Offset) + } + if shown <= last && shown < s.Viewport*0.99 { + t.Fatalf("step %d: content shown past the start %v did not grow from %v", i, shown, last) + } + if shown >= s.Viewport { + t.Fatalf("content went a whole viewport past the start: %v", shown) + } + if i == 0 && shown >= 20 { + t.Fatalf("the first 20 px of the finger moved the content %v, want it to give", shown) + } + last = shown + } +} + +// A wheel and a touchpad stop at the end: they never carry content past it. +func TestAWheelStopsAtTheEnd(t *testing.T) { + s := tallArea() + s.Wheel(gfx.ScrollEvent{DeltaY: -80, Precise: true}) + if s.overscroll() != 0 || s.pull != 0 { + t.Fatalf("a touchpad pulled the content past its start: %v", s.pull) + } +} + +// What the finger holds stays held until it lets go; then it is home. +func TestContentHeldPastTheEndSpringsBackWhenReleased(t *testing.T) { + s := tallArea() + s.Wheel(finger(-60)) + s.relax(nil) + if s.pull == 0 { + t.Fatal("content let go while the finger held it") + } + s.Wheel(gfx.ScrollEvent{Phase: gfx.ScrollPhaseEnd}) + s.relax(nil) + if s.pull != 0 || s.overscroll() != 0 { + t.Fatalf("content is still %v past the start after the finger lifted", s.overscroll()) + } +} + +// The finger moving back first takes the content back to its end, then scrolls it. +func TestTheFingerMovingBackReturnsThePullBeforeScrolling(t *testing.T) { + s := tallArea() + s.Wheel(finger(-100)) + s.Wheel(finger(100 + 30)) + if s.pull != 0 { + t.Fatalf("pull = %v after the finger came back past where it began", s.pull) + } + if s.Offset != 30 { + t.Fatalf("offset = %v, want the 30 px the finger went on", s.Offset) + } +} + +// A fling that reaches an end gives a little and springs back at once, however fast it was. +func TestAFlingReachingTheEndGivesALittle(t *testing.T) { + s := tallArea() + s.Offset = s.Max() + s.Wheel(gfx.ScrollEvent{Phase: gfx.ScrollPhaseMomentum, DeltaY: 4000, Precise: true}) + if s.pull <= 0 || s.pull > s.Viewport/4 { + t.Fatalf("pull = %v, want some, and no more than a quarter of the viewport", s.pull) + } + before := s.pull + s.Wheel(gfx.ScrollEvent{Phase: gfx.ScrollPhaseMomentum, DeltaY: 4000, Precise: true}) + if s.pull != before { + t.Fatalf("the rest of the fling carried the content further: %v", s.pull) + } +} + +// Content that fits has no end to give at. +func TestShortContentDoesNotGive(t *testing.T) { + s := &ScrollState{Content: 300, Viewport: 500} + s.Wheel(finger(-80)) + if s.pull != 0 { + t.Fatalf("content shorter than its area gave: %v", s.pull) + } +} diff --git a/examples/touch/main_test.go b/examples/touch/main_test.go index 0f54295e5..e0f38398d 100644 --- a/examples/touch/main_test.go +++ b/examples/touch/main_test.go @@ -156,3 +156,43 @@ func skipWithoutTouchRuntime(t *testing.T) { t.Skip("macOS windows do not install the touch gestures") } } + +// A finger that drags the list down at its start carries it past the start, and it +// springs back to where it began when the finger lifts. +func TestTheListGivesAtItsStartAndSpringsBack(t *testing.T) { + skipWithoutTouchRuntime(t) + m := newModel() + driver := open(t, m) + _, rest := centerOf(t, driver, "Row 1") + x, y := centerOf(t, driver, "Row 5") + if err := driver.TouchDown(1, x, y); err != nil { + t.Fatal(err) + } + for step := float32(1); step <= 10; step++ { + if err := driver.Advance(10 * time.Millisecond); err != nil { + t.Fatal(err) + } + if err := driver.TouchMove(1, x, y+step*15); err != nil { + t.Fatal(err) + } + } + _, held := centerOf(t, driver, "Row 1") + if held <= rest { + t.Fatalf("the first row is at %v while the finger holds the list past its start, want it below %v", held, rest) + } + if held-rest >= 150 { + t.Fatalf("the list followed the finger all %v px past its start, want it to give", held-rest) + } + if err := driver.TouchUp(1, x, y+150); err != nil { + t.Fatal(err) + } + if err := driver.Advance(2 * time.Second); err != nil { + t.Fatal(err) + } + if _, home := centerOf(t, driver, "Row 1"); home != rest { + t.Fatalf("the first row is at %v after the finger lifted, want %v", home, rest) + } + if m.list.Selected() >= 0 { + t.Fatalf("the drag chose row %d", m.list.Selected()) + } +} diff --git a/gfx/input.go b/gfx/input.go index e70ec538b..81170f49e 100644 --- a/gfx/input.go +++ b/gfx/input.go @@ -212,6 +212,8 @@ type ModifierTapEvent struct { // Target is the stable hit ID at X,Y. Viewport is the current logical window // size, allowing coordinate-driven controls to derive their local geometry. type ScrollEvent struct { + // Phase says what moves the content; the zero value is a wheel or a touchpad. + Phase ScrollPhase Modifiers Modifiers X float32 Y float32 @@ -222,6 +224,24 @@ type ScrollEvent struct { Precise bool } +// ScrollPhase is what a scroll event comes from. A wheel or a touchpad is the zero value +// and stops at the ends of what it scrolls; a finger on a touch screen carries the +// content past an end, where it gives like rubber and springs back once the finger lets go. +type ScrollPhase uint8 + +const ( + // ScrollPhaseWheel is a mouse wheel or a touchpad. + ScrollPhaseWheel ScrollPhase = iota + // ScrollPhaseFinger is a finger dragging the content: it follows the finger, and + // past an end it follows at a fraction. + ScrollPhaseFinger + // ScrollPhaseMomentum is the content still moving after the finger lifted. + ScrollPhaseMomentum + // ScrollPhaseEnd says the finger lifted. It moves nothing: content held past an end + // springs back. + ScrollPhaseEnd +) + // StepY is DeltaY for content that moves in steps of unit pixels, such as the // rows of a list or terminal. A classic wheel never moves less than one unit per // event in its direction: macOS reports a slow notch as a fraction of a line, diff --git a/internal/interaction/touch.go b/internal/interaction/touch.go index 2e49a9a53..3febb530a 100644 --- a/internal/interaction/touch.go +++ b/internal/interaction/touch.go @@ -55,9 +55,14 @@ type TouchStep struct { // is, and Clicks the press's count among quick taps (2 for a double tap). X, Y float32 Clicks int - // ScrollX and ScrollY scroll the content under ScrollAtX, ScrollAtY. + // ScrollX and ScrollY scroll the content under ScrollAtX, ScrollAtY: by the + // finger's motion, or, when Momentum, by what is left of a fling. ScrollX, ScrollY float32 ScrollAtX, ScrollAtY float32 + Momentum bool + // ScrollEnds says the finger that was scrolling lifted or was taken: what it held + // past an end of the content is let go. + ScrollEnds bool // Wake asks for a frame after WakeAfter, when Advance has more to do. Wake bool WakeAfter time.Duration @@ -153,10 +158,12 @@ func (t *Touch) Up(id int32, x, y float32, now time.Duration) TouchStep { return TouchStep{Release: true, Lift: true, X: x, Y: y, Clicks: t.clicks} case touchPanning: vx, vy := t.velocity(now) + step := TouchStep{ScrollEnds: true, ScrollAtX: t.startX, ScrollAtY: t.startY} if math.Hypot(float64(vx), float64(vy)) >= flingMinVelocity { t.flinging, t.flingVX, t.flingVY, t.flingAt = true, vx, vy, now - return TouchStep{Wake: true} + step.Wake = true } + return step case touchLong: return TouchStep{Lift: true, X: x, Y: y} } @@ -168,6 +175,9 @@ func (t *Touch) Up(id int32, x, y float32, now time.Duration) TouchStep { func (t *Touch) Cancel() TouchStep { phase := t.phase t.phase, t.pressDue, t.longPressDue, t.flinging = touchIdle, false, false, false + if phase == touchPanning { + return TouchStep{ScrollEnds: true, ScrollAtX: t.startX, ScrollAtY: t.startY} + } if phase != touchPressed { return TouchStep{} } @@ -224,7 +234,7 @@ func (t *Touch) fling(now time.Duration) TouchStep { } t.flingAt = now seconds := float32(elapsed.Seconds()) - step := TouchStep{ScrollX: -t.flingVX * seconds, ScrollY: -t.flingVY * seconds, ScrollAtX: t.startX, ScrollAtY: t.startY} + step := TouchStep{ScrollX: -t.flingVX * seconds, ScrollY: -t.flingVY * seconds, ScrollAtX: t.startX, ScrollAtY: t.startY, Momentum: true} decay := float32(math.Pow(flingDecay, float64(elapsed)/float64(time.Millisecond))) t.flingVX, t.flingVY = t.flingVX*decay, t.flingVY*decay if math.Hypot(float64(t.flingVX), float64(t.flingVY)) < flingStopVelocity { diff --git a/internal/platform/contract.go b/internal/platform/contract.go index 91da6ef4d..be9312d2a 100644 --- a/internal/platform/contract.go +++ b/internal/platform/contract.go @@ -673,6 +673,8 @@ func ShortcutCandidate(event KeyEvent) bool { // system already applied. Precise reports whether the deltas are device pixels // (trackpad) or scaled line approximations (classic mouse wheels). type ScrollEvent struct { + // Phase is what moves the content; the zero value is a wheel or a touchpad. + Phase gfx.ScrollPhase Modifiers input.Modifiers X float32 Y float32 From de5389a674bdf3f5eff92ea2cdcf1f1ea94afc5d Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Mon, 23 Nov 2026 00:59:24 +0800 Subject: [PATCH 41/64] feat(touch): let a fingertip reach controls smaller than 44 px A touch that lands within reach of a small control, not on it, presses the control rather than what is behind it. The control is drawn as before. --- app/touch.go | 15 ++++++- examples/touch/main_test.go | 23 +++++++++++ internal/input/input.go | 77 ++++++++++++++++++++++++++++++++++++ internal/input/input_test.go | 49 +++++++++++++++++++++++ 4 files changed, 163 insertions(+), 1 deletion(-) diff --git a/app/touch.go b/app/touch.go index fdbed59c7..135b438de 100644 --- a/app/touch.go +++ b/app/touch.go @@ -28,18 +28,31 @@ type touchState struct { modifiers input.Modifiers screenDX, screenDY float32 // screen position less window position advancing bool // a timed step is being carried out: repaint must not start another + snapDX, snapDY float32 // how far the touch was moved onto a small control, for all of the finger's events } +// touchTargetSize is the least a control is to a finger, in logical pixels: the +// 44-point minimum of Apple's guidelines (Material's 48 dp, less its padding, is the +// same on a screen). A control drawn smaller reaches out to it for a touch. +const touchTargetSize = 44 + // touchEvent reads one event of a finger. func (painter *painter) touchEvent(event platform.PointerEvent) (platform.Frame, error) { t := &painter.touch now := painter.canvas.Now() var step interaction.TouchStep + if event.Kind == platform.PointerDown && (!t.Active() || event.PointerID == t.id) { + x, y := painter.focus.Router().TouchPoint(event.X, event.Y, touchTargetSize) + t.snapDX, t.snapDY = x-event.X, y-event.Y + } + if event.PointerID == t.id || event.Kind == platform.PointerDown { + event.X, event.Y = event.X+t.snapDX, event.Y+t.snapDY + } switch event.Kind { case platform.PointerDown: if !t.Active() || event.PointerID == t.id { t.id, t.modifiers = event.PointerID, event.Modifiers - t.screenDX, t.screenDY = event.ScreenX-event.X, event.ScreenY-event.Y + t.screenDX, t.screenDY = event.ScreenX-(event.X-t.snapDX), event.ScreenY-(event.Y-t.snapDY) } step = t.Down(event.PointerID, event.X, event.Y, now, painter.claimsDrag(event.X, event.Y)) case platform.PointerMove: diff --git a/examples/touch/main_test.go b/examples/touch/main_test.go index e0f38398d..bd909b7c8 100644 --- a/examples/touch/main_test.go +++ b/examples/touch/main_test.go @@ -196,3 +196,26 @@ func TestTheListGivesAtItsStartAndSpringsBack(t *testing.T) { t.Fatalf("the drag chose row %d", m.list.Selected()) } } + +// A finger that lands a little beside a small control presses it, as a fingertip is +// bigger than the control is drawn. +func TestAFingerBesideASwitchTurnsItOn(t *testing.T) { + skipWithoutTouchRuntime(t) + m := newModel() + driver := open(t, m) + b := control(t, driver, "Notifications").Bounds + if b.Height >= 44 && b.Width >= 44 { + t.Skip("the switch is already as big as a fingertip") + } + // Just above the switch, outside what it is drawn as but within the 44 px a fingertip needs. + x, y := b.X+b.Width/2, b.Y-3 + if err := driver.TouchDown(1, x, y); err != nil { + t.Fatal(err) + } + if err := driver.TouchUp(1, x, y); err != nil { + t.Fatal(err) + } + if !m.notify { + t.Fatal("a finger just beside the switch did not turn it on") + } +} diff --git a/internal/input/input.go b/internal/input/input.go index dbfcef394..f8a17fd61 100644 --- a/internal/input/input.go +++ b/internal/input/input.go @@ -230,6 +230,83 @@ func (router *Router) PointerAt(x float32, y float32, secondaryPress bool) (Regi return Region{}, false, false } +// TouchPoint is where a finger that touched at x, y presses. A fingertip is about 44 +// logical pixels across and a control may be smaller, so a touch that lands near a +// small control, not on it, presses the control rather than what is behind it: the +// control's region reaches out to minSize in each direction it falls short in. The +// point moves only into a control painted in front of whatever the touch is on, and +// only if that is no small control itself (it is the finger's choice), nor a surface that blocks; of several +// controls in reach the nearest wins, the front-most on a tie. Anywhere else the +// point is returned as it is. +func (router *Router) TouchPoint(x, y, minSize float32) (float32, float32) { + floor := -1 // regions at this index and behind are not in reach + for index := len(router.regions) - 1; index >= 0; index-- { + region := router.regions[index] + if !contains(region.Bounds, x, y) { + continue + } + if region.Blocks { + if router.activeScope.IsZero() || region.Scope == router.activeScope { + floor = index + break + } + continue + } + if router.hitAvailable(region) { + if !region.Backdrop && needsReach(region.Bounds, minSize) { + return x, y // on a small control: that is what the finger chose + } + floor = index + break + } + } + best, bestDistance := -1, float32(0) + for index := len(router.regions) - 1; index > floor; index-- { + region := router.regions[index] + if region.Blocks || region.Backdrop || region.Label || region.MovesWindow || !router.hitAvailable(region) || + !needsReach(region.Bounds, minSize) { + continue + } + reach := reached(region.Bounds, minSize) + if !contains(reach, x, y) { + continue + } + if distance := distanceTo(region.Bounds, x, y); best < 0 || distance < bestDistance { + best, bestDistance = index, distance + } + } + if best < 0 { + return x, y + } + bounds := router.regions[best].Bounds + return min(max(x, bounds.X), bounds.X+bounds.Width-0.01), min(max(y, bounds.Y), bounds.Y+bounds.Height-0.01) +} + +// needsReach says a region is smaller than a fingertip in some direction. +func needsReach(bounds Rect, minSize float32) bool { + return bounds.Width < minSize || bounds.Height < minSize +} + +// reached is a region grown, around its centre, to at least minSize each way. +func reached(bounds Rect, minSize float32) Rect { + if bounds.Width < minSize { + bounds.X -= (minSize - bounds.Width) / 2 + bounds.Width = minSize + } + if bounds.Height < minSize { + bounds.Y -= (minSize - bounds.Height) / 2 + bounds.Height = minSize + } + return bounds +} + +// distanceTo is how far a point is from a rectangle, zero inside it. +func distanceTo(bounds Rect, x, y float32) float32 { + dx := max(bounds.X-x, 0, x-(bounds.X+bounds.Width)) + dy := max(bounds.Y-y, 0, y-(bounds.Y+bounds.Height)) + return dx*dx + dy*dy +} + // PressKind is what a press at a point does in a custom-titlebar window. type PressKind uint8 diff --git a/internal/input/input_test.go b/internal/input/input_test.go index 73fa983b8..45f82527c 100644 --- a/internal/input/input_test.go +++ b/internal/input/input_test.go @@ -536,3 +536,52 @@ func TestRepeatedRegionsKeepTheFocusedSlot(t *testing.T) { t.Fatalf("Tab visited %v and never reached the last target", visited) } } + +func TestATouchNearASmallControlPressesIt(t *testing.T) { + var router Router + router.SetRegions([]Region{ + {Target: gfx.Item(1), Bounds: Rect{Width: 300, Height: 300}}, // a panel + {Target: gfx.Item(2), Bounds: Rect{X: 100, Y: 100, Width: 20, Height: 20}}, // a small control + }) + x, y := router.TouchPoint(100+20+8, 110, 44) // 8 px right of the control: within its reach + if region, ok, _ := router.PointerAt(x, y, false); !ok || region.Target != gfx.Item(2) { + t.Fatalf("a touch next to the control pressed %v, want the control", region.Target) + } + x, y = router.TouchPoint(100+20+30, 110, 44) // out of its reach + if region, _, _ := router.PointerAt(x, y, false); region.Target != gfx.Item(1) { + t.Fatalf("a touch far from the control pressed %v, want the panel", region.Target) + } +} + +func TestATouchOnAControlStaysAndNeighboursDoNotStealIt(t *testing.T) { + var router Router + router.SetRegions([]Region{ + {Target: gfx.Item(1), Bounds: Rect{X: 0, Y: 0, Width: 30, Height: 30}}, + {Target: gfx.Item(2), Bounds: Rect{X: 34, Y: 0, Width: 30, Height: 30}}, + }) + if x, y := router.TouchPoint(40, 10, 44); x != 40 || y != 10 { + t.Fatalf("a touch on a control moved to %v, %v", x, y) + } +} + +func TestATouchDoesNotReachThroughAnOpaqueSurface(t *testing.T) { + var router Router + router.SetRegions([]Region{ + {Target: gfx.Item(1), Bounds: Rect{X: 100, Y: 100, Width: 20, Height: 20}}, + {Blocks: true, Bounds: Rect{X: 90, Y: 0, Width: 200, Height: 300}}, + }) + if x, y := router.TouchPoint(125, 110, 44); x != 125 || y != 110 { + t.Fatalf("a touch on a modal surface reached the control behind it: %v, %v", x, y) + } +} + +func TestTouchPointDoesNotAllocate(t *testing.T) { + var router Router + router.SetRegions([]Region{ + {Target: gfx.Item(1), Bounds: Rect{Width: 300, Height: 300}}, + {Target: gfx.Item(2), Bounds: Rect{X: 100, Y: 100, Width: 20, Height: 20}}, + }) + if allocs := testing.AllocsPerRun(100, func() { router.TouchPoint(128, 110, 44) }); allocs != 0 { + t.Fatalf("TouchPoint allocates %v times per call", allocs) + } +} From f85bd1ba8b03ccd6a570b7d62dc79f0e5189962a Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Mon, 23 Nov 2026 01:08:33 +0800 Subject: [PATCH 42/64] fix(dmg): keep detaching until the disk is no longer attached An image whose volume was already unmounted was detached once and left attached when the service was busy; retry and force it like a mounted one. --- tools/dmg/build.go | 45 ++++++++++++++++++++++--------------------- tools/dmg/dmg_test.go | 6 +++--- 2 files changed, 26 insertions(+), 25 deletions(-) diff --git a/tools/dmg/build.go b/tools/dmg/build.go index 944294261..625090f5a 100644 --- a/tools/dmg/build.go +++ b/tools/dmg/build.go @@ -111,7 +111,7 @@ func settle(writable string, options Options, app string) (err error) { return err } defer func() { - if detachErr := detach(mount, device); err == nil { + if detachErr := detach(device); err == nil { err = detachErr } }() @@ -195,46 +195,47 @@ func attachedDevice(output, mount string) (string, error) { return "", fmt.Errorf("dmg: attached image has no device at %s", mount) } -// detach unmounts the image, retrying while the system still holds it, and -// forcing it as the last resort. -func detach(mount, device string) error { +// detach unmounts the image and detaches its disk, retrying while the system still +// holds it, and forcing it as the last resort. The volume being unmounted already +// (by the system, or by an earlier try) is not the end of it: the image stays +// attached, and the disk image service keeps holding the file, until its disk is +// detached. What ends it is the disk no longer being attached. +func detach(device string) error { // Detaching a partition's node unmounts that volume and leaves the image attached, // which the disk image service then holds: the whole disk is what goes. device = wholeDisk(device) - mounted, err := volumeMounted(mount) - if err != nil { - return err - } - if !mounted { - // The volume is already unmounted (by the system, say) but the image is still - // attached, and the disk image service holds the file until the disk goes: - // detach it anyway. Failing here is no news when it was already gone, and - // released reports an image that is still attached. - _ = hdiutil("detach", device) - return nil - } + var err error for attempt := 0; attempt < 5; attempt++ { if err = hdiutil("detach", device); err == nil { return nil } - if mounted, checkErr := volumeMounted(mount); checkErr == nil && !mounted { + if gone, checkErr := diskGone(device); checkErr != nil { + return fmt.Errorf("%w; checking the disk: %v", err, checkErr) + } else if gone { return nil - } else if checkErr != nil { - return fmt.Errorf("%w; checking mount: %v", err, checkErr) } - time.Sleep(time.Duration(attempt+1) * 500 * time.Millisecond) + pause(time.Duration(attempt+1) * 500 * time.Millisecond) } if forced := hdiutil("detach", "-force", device); forced == nil { return nil } - if mounted, checkErr := volumeMounted(mount); checkErr == nil && !mounted { + if gone, checkErr := diskGone(device); checkErr == nil && gone { return nil } else if checkErr != nil { - return fmt.Errorf("%w; checking mount: %v", err, checkErr) + return fmt.Errorf("%w; checking the disk: %v", err, checkErr) } return err } +// diskGone says no attached image has this disk, as hdiutil info lists them. +func diskGone(device string) (bool, error) { + out, err := hdiutilOutput("info", "-plist") + if err != nil { + return false, err + } + return !strings.Contains(out, ""+device+""), nil +} + var partitionNode = regexp.MustCompile(`^(/dev/disk\d+)s\d+$`) // wholeDisk is the device node of the disk a node is on: /dev/disk7 for /dev/disk7s1. diff --git a/tools/dmg/dmg_test.go b/tools/dmg/dmg_test.go index 65e38918b..3f70e8ba5 100644 --- a/tools/dmg/dmg_test.go +++ b/tools/dmg/dmg_test.go @@ -139,7 +139,7 @@ func TestBuiltImageHoldsTheLayoutTheFinderReads(t *testing.T) { _ = hdiutil("detach", "-force", mount) t.Fatal(err) } - t.Cleanup(func() { _ = detach(mount, device) }) + t.Cleanup(func() { _ = detach(device) }) if mounted, err := volumeMounted(mount); err != nil || !mounted { t.Fatalf("attached image is not mounted: %v", err) } @@ -168,7 +168,7 @@ func TestBuiltImageHoldsTheLayoutTheFinderReads(t *testing.T) { t.Errorf(".DS_Store has no position for %s", name) } } - if err := detach(mount, device); err != nil { + if err := detach(device); err != nil { t.Fatal(err) } } @@ -181,7 +181,7 @@ func TestDetachAcceptsAnAlreadyUnmountedImage(t *testing.T) { if err := os.Mkdir(mount, 0o755); err != nil { t.Fatal(err) } - if err := detach(mount, "/dev/disk-not-attached"); err != nil { + if err := detach("/dev/disk-not-attached"); err != nil { t.Fatal(err) } } From 2fd1447dab1de755fc887e3ac8ee86762afcf9ac Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Mon, 23 Nov 2026 01:28:14 +0800 Subject: [PATCH 43/64] feat(windows): read a finger as a touch pointer, not as a mouse WM_POINTER messages of touch pointers reach the window as touch events, so pan, fling, long press and the other gestures work. Mouse and pen are left to the default procedure as before. --- internal/platform/windows/touch_windows.go | 88 +++++++++++++++++++++ internal/platform/windows/window_windows.go | 4 + 2 files changed, 92 insertions(+) create mode 100644 internal/platform/windows/touch_windows.go diff --git a/internal/platform/windows/touch_windows.go b/internal/platform/windows/touch_windows.go new file mode 100644 index 000000000..a0bbf61da --- /dev/null +++ b/internal/platform/windows/touch_windows.go @@ -0,0 +1,88 @@ +package windows + +import ( + "unsafe" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/platform" +) + +// A finger on a touch screen reaches the window as WM_POINTER messages. A window that +// leaves them to the default procedure gets the finger as a mouse: one press at the +// fingertip, no second finger, no way to tell a tap from a click, so the gestures +// (pan, fling, long press) could not be read from it. The window takes a touch pointer +// itself and leaves the mouse and the pen to the default, which turns them into the +// mouse messages the window already reads. +const ( + wmPointerUpdate = 0x0245 + wmPointerDown = 0x0246 + wmPointerUp = 0x0247 + wmPointerCaptureChanged = 0x024c + pointerTypeTouch = 2 + pointerFlagInContact = 0x4 +) + +var ( + getPointerType = user.NewProc("GetPointerType") + getPointerInfo = user.NewProc("GetPointerInfo") +) + +// pointerInfo is POINTER_INFO. +type pointerInfo struct { + Type, ID, Frame, Flags uint32 + SourceDevice, Target uintptr + Pixel, Himetric point + PixelRaw, HimetricRaw point + Time, History uint32 + InputData int32 + KeyStates uint32 + PerformanceCount uint64 + ButtonChange uint32 +} + +// touchPointer reads a WM_POINTER message for a finger and reports whether it did: a +// pointer that is not a finger is left to the default procedure. +func (state *windowState) touchPointer(kind, first uintptr) bool { + id := uint32(first & 0xffff) + var pointerType uint32 + if ok, _, _ := getPointerType.Call(uintptr(id), uintptr(unsafe.Pointer(&pointerType))); ok == 0 || pointerType != pointerTypeTouch { + return false + } + var eventKind platform.PointerEventKind + switch kind { + case wmPointerDown: + eventKind = platform.PointerDown + case wmPointerUp: + eventKind = platform.PointerUp + case wmPointerUpdate: + eventKind = platform.PointerMove + default: // the system took the finger away, as for a gesture of its own + eventKind = platform.PointerCancel + } + event := platform.PointerEvent{Kind: eventKind, Device: gfx.PointerTouch, PointerID: int32(id), Modifiers: modifiers()} + if eventKind != platform.PointerCancel { + var info pointerInfo + if ok, _, _ := getPointerInfo.Call(uintptr(id), uintptr(unsafe.Pointer(&info))); ok == 0 { + return true + } + if eventKind == platform.PointerMove && info.Flags&pointerFlagInContact == 0 { + return true // a finger hovering over a pen-capable digitizer is no touch + } + client := info.Pixel + screenToClient.Call(state.window, uintptr(unsafe.Pointer(&client))) + event.X, event.Y = float32(client.X)/state.scale, float32(client.Y)/state.scale + event.ScreenX, event.ScreenY = float32(info.Pixel.X)/state.scale, float32(info.Pixel.Y)/state.scale + if eventKind == platform.PointerDown || eventKind == platform.PointerUp { + event.Button = gfx.PointerButtonPrimary + } + } + if eventKind == platform.PointerDown && state.config.WindowMode != platform.WindowNotification { + setFocus.Call(state.window) + } + if state.config.OnPointer != nil { + state.pointerEvents++ + frame, err := state.config.OnPointer(event) + state.frame(frame, err) + } + return true +} diff --git a/internal/platform/windows/window_windows.go b/internal/platform/windows/window_windows.go index 56204e497..4388833c8 100644 --- a/internal/platform/windows/window_windows.go +++ b/internal/platform/windows/window_windows.go @@ -961,6 +961,10 @@ func windowProc(window, kind, first, second uintptr) (result uintptr) { return 1 // the side-button messages ask for TRUE, unlike the others } return 0 + case wmPointerDown, wmPointerUpdate, wmPointerUp, wmPointerCaptureChanged: + if state.touchPointer(kind, first) { + return 0 + } case wmMouseLeave, wmKillFocus: state.tracking = false if kind == wmMouseLeave && state.web != nil && state.web.pointerOverCover() { From 44f0e98473dae6955c40f47a79a636ab71ff2ca2 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Mon, 23 Nov 2026 01:43:46 +0800 Subject: [PATCH 44/64] feat(linux): read a finger as X Input touch events on X11 A window selects the touch events of X Input 2.2 and reads touch begin, update and end as touch pointers, so pan, fling and long press work. A server or machine without the extension keeps the finger as the pointer. --- .../linux/touch_x11_fake_linux_test.go | 168 +++++++++++++++++ internal/platform/linux/touch_x11_linux.go | 172 ++++++++++++++++++ .../platform/linux/touch_x11_linux_test.go | 99 ++++++++++ internal/platform/linux/window_linux.go | 13 ++ 4 files changed, 452 insertions(+) create mode 100644 internal/platform/linux/touch_x11_fake_linux_test.go create mode 100644 internal/platform/linux/touch_x11_linux.go create mode 100644 internal/platform/linux/touch_x11_linux_test.go diff --git a/internal/platform/linux/touch_x11_fake_linux_test.go b/internal/platform/linux/touch_x11_fake_linux_test.go new file mode 100644 index 000000000..6b68d3e19 --- /dev/null +++ b/internal/platform/linux/touch_x11_fake_linux_test.go @@ -0,0 +1,168 @@ +//go:build !android + +package linux + +import ( + "encoding/binary" + "io" + "net" + "strconv" + "testing" + "time" + "unsafe" + + "github.com/vivaui/viva/internal/platform" +) + +// A server that speaks just enough of the X protocol, over the abstract socket libxcb +// tries first, for a client to look the X Input extension up, negotiate version 2.2 and +// select touch events, and that then sends a touch event as a real server does: a +// generic event of 32 bytes and the words its length says follow. What the test reads +// back is what libxcb makes of that, which is what the window reads, so the offsets the +// backend uses are tested against the library and not against this file's idea of them. +const fakeXInputOpcode = 131 + +type fakeXServer struct { + selected chan []byte // the body of the client's XISelectEvents + event []byte // the wire event to send once the client has selected +} + +func startFakeXServer(t *testing.T, display int, event []byte) *fakeXServer { + t.Helper() + listener, err := net.Listen("unix", "@/tmp/.X11-unix/X"+strconv.Itoa(display)) + if err != nil { + t.Skipf("no abstract socket for a fake X server: %v", err) + } + server := &fakeXServer{selected: make(chan []byte, 1), event: event} + t.Cleanup(func() { listener.Close() }) + go func() { + connection, err := listener.Accept() + if err != nil { + return + } + defer connection.Close() + server.serve(connection) + }() + return server +} + +func (server *fakeXServer) serve(connection net.Conn) { + if _, err := io.ReadFull(connection, make([]byte, 12)); err != nil { + return + } + // Setup success: one bare screen, no pixmap formats and a four-byte vendor. + body := make([]byte, 32+4+40) + binary.LittleEndian.PutUint32(body[0:], 1) // release + binary.LittleEndian.PutUint32(body[4:], 0x00200000) // resource id base + binary.LittleEndian.PutUint32(body[8:], 0x001fffff) // resource id mask + binary.LittleEndian.PutUint32(body[12:], 256) // motion buffer + binary.LittleEndian.PutUint16(body[16:], 4) // vendor length + binary.LittleEndian.PutUint16(body[18:], 65535) // maximum request length + body[20] = 1 // one screen + copy(body[32:], "fake") + binary.LittleEndian.PutUint32(body[36:], 0x100) // its root window + reply := make([]byte, 8) + reply[0] = 1 + binary.LittleEndian.PutUint16(reply[2:], 11) + binary.LittleEndian.PutUint16(reply[6:], uint16(len(body)/4)) + connection.Write(append(reply, body...)) + var sequence uint16 + for { + header := make([]byte, 4) + if _, err := io.ReadFull(connection, header); err != nil { + return + } + rest := make([]byte, int(binary.LittleEndian.Uint16(header[2:]))*4-4) + if _, err := io.ReadFull(connection, rest); err != nil { + return + } + sequence++ + answer := func(fill func(r []byte)) { + r := make([]byte, 32) + r[0] = 1 + binary.LittleEndian.PutUint16(r[2:], sequence) + fill(r) + connection.Write(r) + } + switch { + case header[0] == 98: // QueryExtension + answer(func(r []byte) { r[8], r[9], r[10] = 1, fakeXInputOpcode, 64 }) + case header[0] == fakeXInputOpcode && header[1] == 47: // XIQueryVersion + answer(func(r []byte) { + binary.LittleEndian.PutUint16(r[8:], 2) + binary.LittleEndian.PutUint16(r[10:], 4) + }) + case header[0] == fakeXInputOpcode && header[1] == 46: // XISelectEvents + server.selected <- rest + binary.LittleEndian.PutUint16(server.event[2:], sequence) + connection.Write(server.event) + } + } +} + +// wireTouchEvent is an XI_TouchBegin as the X Input protocol puts it on the wire. +func wireTouchEvent(eventType uint16, id uint32, x, y float32, effectiveMods uint32) []byte { + event := make([]byte, 80) + event[0], event[1] = xcbGenericEventType, fakeXInputOpcode + binary.LittleEndian.PutUint32(event[4:], 12) // the words after the first 32 bytes + binary.LittleEndian.PutUint16(event[8:], eventType) + binary.LittleEndian.PutUint16(event[10:], 2) + binary.LittleEndian.PutUint32(event[12:], 4242) + binary.LittleEndian.PutUint32(event[16:], id) + fixed := func(offset int, value float32) { + binary.LittleEndian.PutUint32(event[offset:], uint32(int32(value*65536))) + } + fixed(32, x+100) // root_x + fixed(36, y+200) + fixed(40, x) // event_x + fixed(44, y) + binary.LittleEndian.PutUint32(event[72:], effectiveMods) + return event +} + +func TestATouchEventFromTheWireIsReadAsLibxcbDeliversIt(t *testing.T) { + const display = 89 + server := startFakeXServer(t, display, wireTouchEvent(xiTouchBegin, 7, 12.5, -3.25, 0x5)) + t.Setenv("DISPLAY", ":"+strconv.Itoa(display)) + api, err := loadXCB() + if err != nil { + t.Skip(err) + } + var screen int32 + connection := api.connect(nil, &screen) + if connection == 0 || api.connectionHasError(connection) != 0 { + t.Skip("libxcb could not talk to the fake server") + } + defer api.disconnect(connection) + touch := loadXInputTouch(api, connection, 0x200001) + if touch == nil { + t.Skip("libxcb-xinput is not installed") + } + if touch.opcode != fakeXInputOpcode { + t.Fatalf("opcode = %d, want the one the server gave", touch.opcode) + } + select { + case mask := <-server.selected: + // The window, the number of masks, then the mask: the device, its length, the bits. + if binary.LittleEndian.Uint32(mask[0:]) != 0x200001 || binary.LittleEndian.Uint16(mask[4:]) != 1 || + binary.LittleEndian.Uint16(mask[8:]) != xiAllMasterDevices || binary.LittleEndian.Uint16(mask[10:]) != 1 || + binary.LittleEndian.Uint32(mask[12:]) != xiTouchMask { + t.Fatalf("the selection the server got = % x, want the touch events of all master devices", mask) + } + case <-time.After(2 * time.Second): + t.Fatal("the server never got the selection") + } + var event unsafe.Pointer + for deadline := time.Now().Add(2 * time.Second); event == nil && time.Now().Before(deadline); time.Sleep(5 * time.Millisecond) { + event = api.pollForEvent(connection) + } + if event == nil { + t.Fatal("libxcb delivered no event") + } + defer api.free(event) + got, ok := touch.read(event) + if !ok || got.kind != platform.PointerDown || got.id != 7 || got.x != 12.5 || got.y != -3.25 || + got.rootX != 112.5 || got.rootY != 196.75 || got.modifiers != 0x5 || got.timestamp != 4242 { + t.Fatalf("read %+v, %v; want a touch begin of touch 7 at 12.5, -3.25 (112.5, 196.75 on the screen) with modifiers 0x5 at time 4242", got, ok) + } +} diff --git a/internal/platform/linux/touch_x11_linux.go b/internal/platform/linux/touch_x11_linux.go new file mode 100644 index 000000000..b0688ed57 --- /dev/null +++ b/internal/platform/linux/touch_x11_linux.go @@ -0,0 +1,172 @@ +//go:build !android + +package linux + +import ( + "encoding/binary" + "unsafe" + + "github.com/ebitengine/purego" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/platform" +) + +// A finger on a touch screen reaches an X11 window through the X Input extension, version +// 2.2 or later. Without it the server turns a finger into the pointer: one press at the +// fingertip, no second finger, and no telling a tap from a click, so the gestures (pan, +// fling, long press) could not be read from it. A window that selects the touch events +// gets the finger as touch events and none of that emulated pointer. The extension and +// its library are optional: a machine without them keeps the finger as a pointer. +const ( + xcbGenericEventType = 35 // XCB_GE_GENERIC: the events of extensions, which are more than 32 bytes + xiAllMasterDevices = 1 + xiTouchBegin = 18 + xiTouchUpdate = 19 + xiTouchEnd = 20 + xiTouchMask = 1< 2 || version.Major == 2 && version.Minor >= 2 + api.free(unsafe.Pointer(version)) + if !supported { + return fail() + } + // xcb_input_event_mask_t: the device, the mask's length in words, and the mask. + var mask [8]byte + binary.LittleEndian.PutUint16(mask[0:], xiAllMasterDevices) + binary.LittleEndian.PutUint16(mask[2:], 1) + binary.LittleEndian.PutUint32(mask[4:], xiTouchMask) + selectEvents(connection, window, 1, unsafe.Pointer(&mask[0])) + api.flush(connection) + return &xinputTouch{library: library, opcode: opcode} +} + +// xinputTouchEvent is the part of an XI2 touch event this backend reads, from the event +// as the server sent it. +type xinputTouchEvent struct { + kind platform.PointerEventKind + id int32 + x, y, rootX, rootY float32 // device pixels + modifiers, timestamp uint32 +} + +// read decodes event when it is a touch event of the extension, and says whether it was. +// The positions are 16.16 fixed point; the touch id is the event's detail. +func (touch *xinputTouch) read(event unsafe.Pointer) (xinputTouchEvent, bool) { + generic := (*xcbGenericEvent)(event) + if generic.ResponseType&0x7f != xcbGenericEventType { + return xinputTouchEvent{}, false + } + header := unsafe.Slice((*byte)(event), xiEventMinimumLength) + if header[1] != touch.opcode { + return xinputTouchEvent{}, false + } + word := func(offset int) uint32 { return binary.LittleEndian.Uint32(header[offset:]) } + fixed := func(offset int) float32 { return float32(int32(word(offset))) / 65536 } + result := xinputTouchEvent{ + id: int32(word(xiEventOffsetDetail)), timestamp: word(xiEventOffsetTime), + x: fixed(xiEventOffsetEventX), y: fixed(xiEventOffsetEventX + 4), + rootX: fixed(xiEventOffsetRootX), rootY: fixed(xiEventOffsetRootX + 4), + modifiers: word(xiEventOffsetMods), + } + switch binary.LittleEndian.Uint16(header[8:]) { + case xiTouchBegin: + result.kind = platform.PointerDown + case xiTouchUpdate: + result.kind = platform.PointerMove + case xiTouchEnd: + result.kind = platform.PointerUp + if word(xiEventOffsetFlags)&xiTouchPendingEnd != 0 { + result.kind = platform.PointerCancel + } + default: + return xinputTouchEvent{}, false + } + return result, true +} + +// touch tells the application about a finger. The application's touch runtime reads +// the gestures from these; the text input is not told, as a drag on a text field +// scrolls what it is in rather than selecting. +func (router eventRouter) touch(event xinputTouchEvent, margin float32) error { + if router.config.OnPointer == nil { + return nil + } + scale := router.displayScale() + pointerEvent := platform.PointerEvent{ + Kind: event.kind, Device: gfx.PointerTouch, PointerID: event.id, + Modifiers: xcbModifiers(uint16(event.modifiers)), + X: (event.x - margin) / scale, Y: (event.y - margin) / scale, + ScreenX: event.rootX / scale, ScreenY: event.rootY / scale, + } + if event.kind == platform.PointerDown || event.kind == platform.PointerUp { + pointerEvent.Button = gfx.PointerButtonPrimary + } + frame, err := router.config.OnPointer(pointerEvent) + return router.presentFrame(frame, err) +} diff --git a/internal/platform/linux/touch_x11_linux_test.go b/internal/platform/linux/touch_x11_linux_test.go new file mode 100644 index 000000000..0af1dcb1e --- /dev/null +++ b/internal/platform/linux/touch_x11_linux_test.go @@ -0,0 +1,99 @@ +//go:build !android + +package linux + +import ( + "encoding/binary" + "os" + "testing" + "unsafe" + + "github.com/vivaui/viva/internal/platform" +) + +// xiTouchEventBytes is a touch event as the server sends it: a generic event of the +// extension, the touch's id in the detail, 16.16 fixed point positions. +func xiTouchEventBytes(opcode uint8, eventType uint16, id uint32, x, y float32, flags uint32) []byte { + event := make([]byte, 96) + event[0], event[1] = xcbGenericEventType, opcode + binary.LittleEndian.PutUint16(event[8:], eventType) + binary.LittleEndian.PutUint32(event[xiEventOffsetTime:], 4242) + binary.LittleEndian.PutUint32(event[xiEventOffsetDetail:], id) + put := func(offset int, value float32) { + binary.LittleEndian.PutUint32(event[offset:], uint32(int32(value*65536))) + } + put(xiEventOffsetRootX, x+100) + put(xiEventOffsetRootX+4, y+200) + put(xiEventOffsetEventX, x) + put(xiEventOffsetEventX+4, y) + binary.LittleEndian.PutUint32(event[xiEventOffsetFlags:], flags) + return event +} + +func TestATouchEventIsReadFromTheServersBytes(t *testing.T) { + touch := &xinputTouch{opcode: 131} + for _, c := range []struct { + eventType uint16 + flags uint32 + want platform.PointerEventKind + }{ + {xiTouchBegin, 0, platform.PointerDown}, + {xiTouchUpdate, 0, platform.PointerMove}, + {xiTouchEnd, 0, platform.PointerUp}, + {xiTouchEnd, xiTouchPendingEnd, platform.PointerCancel}, + } { + bytes := xiTouchEventBytes(131, c.eventType, 7, 12.5, -3.25, c.flags) + event, ok := touch.read(unsafe.Pointer(&bytes[0])) + if !ok || event.kind != c.want || event.id != 7 || event.x != 12.5 || event.y != -3.25 || event.rootX != 112.5 || event.rootY != 196.75 { + t.Errorf("type %d flags %#x: read %+v, %v; want kind %v at 12.5, -3.25 as touch 7", c.eventType, c.flags, event, ok, c.want) + } + } +} + +func TestOtherEventsAreNotTouches(t *testing.T) { + touch := &xinputTouch{opcode: 131} + other := xiTouchEventBytes(130, xiTouchBegin, 1, 0, 0, 0) // another extension's + if _, ok := touch.read(unsafe.Pointer(&other[0])); ok { + t.Error("an event of another extension was read as a touch") + } + ownership := xiTouchEventBytes(131, 21, 1, 0, 0, 0) // XI_TouchOwnership is not selected, and not a finger moving + if _, ok := touch.read(unsafe.Pointer(&ownership[0])); ok { + t.Error("a touch ownership event was read as a touch") + } + core := make([]byte, 96) + core[0] = xcbButtonPress + if _, ok := touch.read(unsafe.Pointer(&core[0])); ok { + t.Error("a core event was read as a touch") + } +} + +// Selecting the touch events must be accepted by a real server: a mistake in the request +// would shut the connection down or answer with an error. +func TestTheServerAcceptsTheTouchSelection(t *testing.T) { + if testing.Short() || os.Getenv("VIVA_LINUX_XCB_SMOKE") == "" { + t.Skip("set VIVA_LINUX_XCB_SMOKE=1 with an X11 display") + } + win, err := openWindow(platform.Config{Title: "Viva touch smoke", Width: 160, Height: 100, WindowMode: platform.WindowTitled}) + if err != nil { + t.Fatal(err) + } + defer win.close() + touch := loadXInputTouch(win.api, win.connection, win.id) + if touch == nil { + t.Skip("the server has no X Input 2.2 or libxcb-xinput is missing") + } + // A round trip makes the server answer every request before it, an error included. + win.api.flush(win.connection) + if _, err := win.readMaximized(); err != nil { + t.Fatalf("a round trip after selecting touch events: %v", err) + } + if win.api.connectionHasError(win.connection) != 0 { + t.Fatal("the connection failed after selecting touch events") + } + for event := win.api.pollForEvent(win.connection); event != nil; event = win.api.pollForEvent(win.connection) { + if (*xcbGenericEvent)(event).ResponseType == 0 { + t.Errorf("the server answered the touch selection with an X error: code %d", unsafe.Slice((*byte)(event), 32)[1]) + } + win.api.free(event) + } +} diff --git a/internal/platform/linux/window_linux.go b/internal/platform/linux/window_linux.go index f6716773a..8ac4d03d7 100644 --- a/internal/platform/linux/window_linux.go +++ b/internal/platform/linux/window_linux.go @@ -172,6 +172,9 @@ type linuxWindowState struct { exposed bool // visible is the last visibility reported to OnVisibility; a window starts as visible. visible bool + // touch is the window's touch events through the X Input extension; nil where the + // server or the library lacks it, and the finger then reaches the window as a pointer. + touch *xinputTouch } type linuxApplication struct { @@ -338,6 +341,7 @@ func (application *linuxApplication) OpenWindow(config platform.Config) (platfor return nil, err } state.win = win + state.touch = loadXInputTouch(win.api, win.connection, win.id) textInput, err := newLinuxTextInput(&config) if err != nil { win.close() @@ -899,6 +903,15 @@ func (state *linuxWindowState) handleEvent(event unsafe.Pointer) (bool, error) { activeWindow.Store(win) } kind := (*xcbGenericEvent)(event).ResponseType & 0x7f + if state.touch != nil && kind == xcbGenericEventType { + if touch, ok := state.touch.read(event); ok { + if touch.kind == platform.PointerDown { + state.application.lastUserTime = touch.timestamp + win.setUserTime(touch.timestamp) + } + return false, router.touch(touch, float32(win.margin)) + } + } if kind == xcbButtonPress || kind == xcbKeyPress { if timestamp := (*xcbInputEvent)(event).Time; timestamp != 0 { state.application.lastUserTime = timestamp From dbb487f40c072a9749f6972a1d68064efcab40cd Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Mon, 23 Nov 2026 01:52:34 +0800 Subject: [PATCH 45/64] fix(dmg): run hdiutil create again when the service loses the staged folder On a loaded runner create answers No such file or directory with the folder there, as the disk image service starts; wait it out like a busy service. --- tools/dmg/build.go | 12 ++++++++++-- tools/dmg/busy_test.go | 14 ++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/tools/dmg/build.go b/tools/dmg/build.go index 625090f5a..29e60c147 100644 --- a/tools/dmg/build.go +++ b/tools/dmg/build.go @@ -296,6 +296,15 @@ var ( // resources beyond the previous ten-second window after detaching its volume. const busyAttempts = 10 +// transient says a failure of hdiutil is the disk image service being unready rather +// than a mistake of ours: it is busy or unavailable, or, for create, it lost the staged +// folder it was just given ("No such file or directory" with the folder there), which +// is how it answers while the service starts under load. Another run takes. +func transient(command, output string) bool { + return strings.Contains(output, "Resource busy") || strings.Contains(output, "Resource temporarily unavailable") || + command == "create" && strings.Contains(output, "create failed - No such file or directory") +} + func hdiutilOutput(arguments ...string) (string, error) { for attempt := 1; ; attempt++ { out, err := runHdiutil(arguments...) @@ -306,8 +315,7 @@ func hdiutilOutput(arguments ...string) (string, error) { return "", errors.New("a .dmg needs hdiutil, which ships with macOS") } // detach has its own way of waiting, which checks whether the volume is gone. - if arguments[0] != "detach" && attempt < busyAttempts && - (strings.Contains(string(out), "Resource busy") || strings.Contains(string(out), "Resource temporarily unavailable")) { + if arguments[0] != "detach" && attempt < busyAttempts && transient(arguments[0], string(out)) { pause(time.Duration(attempt) * time.Second) continue } diff --git a/tools/dmg/busy_test.go b/tools/dmg/busy_test.go index 85bee54c9..6c8c0d64b 100644 --- a/tools/dmg/busy_test.go +++ b/tools/dmg/busy_test.go @@ -58,6 +58,20 @@ func TestHdiutilWaitsOutABusySystem(t *testing.T) { } } +// create answers "No such file or directory" while the disk image service starts under +// load, with the folder it was given there: that is waited out too, but only for create. +func TestHdiutilCreateRetriesALostFolder(t *testing.T) { + lost := reply{"hdiutil: create failed - No such file or directory", errExit} + runs, _ := stub(t, []reply{lost, {"ready", nil}}) + if out, err := hdiutilOutput("create", "image"); err != nil || out != "ready" || len(*runs) != 2 { + t.Fatalf("output %q, error %v, %d runs", out, err, len(*runs)) + } + runs, _ = stub(t, []reply{{"hdiutil: attach failed - No such file or directory", errExit}}) + if _, err := hdiutilOutput("attach", "image"); err == nil || len(*runs) != 1 { + t.Fatalf("a missing image was retried: %v, %d runs", err, len(*runs)) + } +} + // It does not wait for ever, and the error says what the tool said. func TestHdiutilGivesUpOnAStaysBusySystem(t *testing.T) { for _, message := range []string{"Resource busy", "Resource temporarily unavailable"} { From 2d473fb5607ab082ef9b1913dfcaa9fb513f0a44 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Mon, 23 Nov 2026 02:03:24 +0800 Subject: [PATCH 46/64] fix(dmg): detach the disk again while its image stays attached A detach that reported success could leave the image attached and the file held for minutes on a loaded runner; release now detaches the disk again at intervals. --- tools/dmg/build.go | 29 +++++++++++++++++++++++++++++ tools/dmg/busy_test.go | 24 ++++++++++++++++++++++++ 2 files changed, 53 insertions(+) diff --git a/tools/dmg/build.go b/tools/dmg/build.go index 29e60c147..239f96566 100644 --- a/tools/dmg/build.go +++ b/tools/dmg/build.go @@ -270,11 +270,40 @@ func released(image string) error { return nil } attached = out + if redetachAt[attempt] { + // The service can keep an image attached, and hold the file, after a detach + // that reported success: take its disk away again. + if device := diskOf(out, path, image); device != "" { + _ = hdiutil("detach", "-force", device) + } + } pause(releaseWait) } return fmt.Errorf("the disk image service still holds %s after detaching it:\n%s", image, attached) } +// redetachAt are the attempts of released at which an image still attached has its disk +// detached again. +var redetachAt = map[int]bool{5: true, 20: true, 50: true, 90: true} + +var diskNode = regexp.MustCompile(`(/dev/disk\d+)`) + +// diskOf is the disk of the attached image at one of the paths, from hdiutil info's +// list: the first disk its entry names, since an entry lists its image's path before +// its system entities. +func diskOf(info string, paths ...string) string { + for _, path := range paths { + at := strings.Index(info, ""+path+"") + if at < 0 { + continue + } + if match := diskNode.FindStringSubmatch(info[at:]); match != nil { + return match[1] + } + } + return "" +} + func hdiutil(arguments ...string) error { _, err := hdiutilOutput(arguments...) return err diff --git a/tools/dmg/busy_test.go b/tools/dmg/busy_test.go index 6c8c0d64b..c6107b129 100644 --- a/tools/dmg/busy_test.go +++ b/tools/dmg/busy_test.go @@ -115,6 +115,30 @@ func TestHdiutilReportsOtherFailuresAtOnce(t *testing.T) { // The image is converted only once the disk image service has let go of it: // released waits while hdiutil info still lists it, and says so if it never // does. +func TestReleasedDetachesTheDiskAgainWhileTheImageStaysAttached(t *testing.T) { + const image = "/tmp/viva-release-test/writable.dmg" + held := reply{"image-path" + image + "dev-entry/dev/disk7", nil} + free := reply{"", nil} + replies := []reply{} + for i := 0; i < 7; i++ { // attempts 0 to 5 find it held, and the force detach of attempt 5 is one more run + replies = append(replies, held) + } + replies = append(replies, free) + runs, _ := stub(t, replies) + if err := released(image); err != nil { + t.Fatal(err) + } + forced := false + for _, arguments := range *runs { + if len(arguments) == 3 && arguments[0] == "detach" && arguments[1] == "-force" && arguments[2] == "/dev/disk7" { + forced = true + } + } + if !forced { + t.Fatalf("the disk was never detached again: %v", *runs) + } +} + func TestReleasedWaitsUntilTheImageIsNoLongerAttached(t *testing.T) { const image = "/tmp/viva-release-test/writable.dmg" held := reply{"image-path" + image + "", nil} From 148d6dcbe67a21728c18e5f1c3d646cdfb18a8f3 Mon Sep 17 00:00:00 2001 From: muchen <145200703+Mucheen@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:07:59 +0800 Subject: [PATCH 47/64] fix(markdown): decode inline character references --- markdown/inline.go | 97 +++++++++++++++++++++++++++++++++++---- markdown/markdown.go | 7 ++- markdown/markdown_test.go | 22 +++++++++ 3 files changed, 113 insertions(+), 13 deletions(-) diff --git a/markdown/inline.go b/markdown/inline.go index 3da7a8fc0..25295a7a5 100644 --- a/markdown/inline.go +++ b/markdown/inline.go @@ -1,6 +1,11 @@ package markdown -import "strings" +import ( + "html" + "strconv" + "strings" + "unicode/utf8" +) // inline parses the inline formatting of s and appends its spans. style and // link are what the surrounding text already has. @@ -11,19 +16,39 @@ func (d *Document) inline(s string, style Style, link string, depth int) { d.work = 32*len(s) + 4096 } text := 0 // where the plain text not yet emitted begins + var decoded strings.Builder + flush := func(end int) { + value := s[text:end] + if decoded.Len() != 0 { + decoded.WriteString(value) + value = decoded.String() + decoded.Reset() + } + d.emit(value, style, link) + } for i := 0; i < len(s); { switch c := s[i]; c { case '\\': if i+1 < len(s) && isPunct(s[i+1]) { - d.emit(s[text:i], style, link) + flush(i) text = i + 1 i += 2 continue } + case '&': + if value, size := characterReference(s[i:]); size != 0 { + // Keep the decoded text in the same span so it shapes and wraps + // together with the surrounding word. + decoded.WriteString(s[text:i]) + decoded.WriteString(value) + i += size + text = i + continue + } case '`': n := run(s, i, '`') if end := d.findCodeEnd(s, i+n, n); end >= 0 { - d.emit(s[text:i], style, link) + flush(i) code := s[i+n : end] if len(code) >= 2 && code[0] == ' ' && code[len(code)-1] == ' ' && strings.Trim(code, " ") != "" { code = code[1 : len(code)-1] @@ -41,7 +66,7 @@ func (d *Document) inline(s string, style Style, link string, depth int) { n := run(s, i, c) if n <= 3 && depth < maxNesting { if end := d.findEmphasisEnd(s, i, n, c); end >= 0 { - d.emit(s[text:i], style, link) + flush(i) d.inline(s[i+n:end], style|emphasisStyle(n), link, depth+1) i = end + n text = i @@ -54,7 +79,7 @@ func (d *Document) inline(s string, style Style, link string, depth int) { n := run(s, i, '~') if n == 2 && depth < maxNesting { if end := d.findEmphasisEnd(s, i, n, c); end >= 0 { - d.emit(s[text:i], style, link) + flush(i) d.inline(s[i+2:end], style|Strike, link, depth+1) i = end + 2 text = i @@ -66,7 +91,7 @@ func (d *Document) inline(s string, style Style, link string, depth int) { case '!': if i+1 < len(s) && s[i+1] == '[' { if labelEnd, dest, end := d.findLink(s, i+1); end >= 0 { - d.emit(s[text:i], style, link) + flush(i) d.spans = append(d.spans, Span{Text: s[i+2 : labelEnd], Style: style, Link: link, Image: dest}) i = end text = i @@ -76,7 +101,7 @@ func (d *Document) inline(s string, style Style, link string, depth int) { case '[': if link == "" && depth < maxNesting { if labelEnd, dest, end := d.findLink(s, i); end >= 0 { - d.emit(s[text:i], style, link) + flush(i) if safeLink(dest) { d.inline(s[i+1:labelEnd], style, dest, depth+1) } else { @@ -90,7 +115,7 @@ func (d *Document) inline(s string, style Style, link string, depth int) { case 'h': if link == "" && (i == 0 || !isWord(s[i-1])) { if end := autolinkEnd(s, i); end > 0 { - d.emit(s[text:i], style, link) + flush(i) d.spans = append(d.spans, Span{Text: s[i:end], Style: style, Link: s[i:end]}) i = end text = i @@ -100,7 +125,61 @@ func (d *Document) inline(s string, style Style, link string, depth int) { } i++ } - d.emit(s[text:], style, link) + flush(len(s)) +} + +// characterReference recognizes a complete reference starting at an ampersand. +// The longest named reference bounds the lookahead even in unfinished text. +func characterReference(s string) (string, int) { + const maxLength = len("∳") + end := strings.IndexByte(s[:min(len(s), maxLength)], ';') + if end < 2 { + return "", 0 + } + if s[1] == '#' { + digits := s[2:end] + base, limit := 10, 7 + if strings.HasPrefix(digits, "x") || strings.HasPrefix(digits, "X") { + base, limit = 16, 6 + digits = digits[1:] + } + if len(digits) > limit { + return "", 0 + } + value, err := strconv.ParseUint(digits, base, 32) + if err != nil { + return "", 0 + } + r := rune(value) + if r == 0 || !utf8.ValidRune(r) { + r = utf8.RuneError + } + return string(r), end + 1 + } + for i := 1; i < end; i++ { + if !isWord(s[i]) { + return "", 0 + } + } + ref := s[:end+1] + switch ref { + case " ": + return "\u00a0", end + 1 + // Go's decoder omits these two names because their UTF-8 expansions + // are longer than the input and cannot be decoded in place. + case "≪⃒": + return "\u226a\u20d2", end + 1 + case "≫⃒": + return "\u226b\u20d2", end + 1 + } + value := html.UnescapeString(ref) + // A complete named reference decodes to at most two runes. HTML also + // accepts some prefixes without a semicolon, leaving a suffix of at + // least one letter and the semicolon (for example, ¬i; -> ¬i;). + if value == ref || utf8.RuneCountInString(value) > 2 { + return "", 0 + } + return value, end + 1 } func (d *Document) emit(text string, style Style, link string) { diff --git a/markdown/markdown.go b/markdown/markdown.go index 4412a0b64..c9dfa7ad7 100644 --- a/markdown/markdown.go +++ b/markdown/markdown.go @@ -5,10 +5,9 @@ // // It is a reader for display, not a CommonMark implementation. The result is a // flat list of blocks (lists and quotes are a depth on a block, not a tree) -// whose text is sliced from the source, so parsing builds no strings except for -// the rare fenced block that sits inside a list or a quote. A Document keeps its -// storage between calls to Parse: re-parsing a message that grows by a few -// words allocates nothing once the Document is warm. +// whose text is normally sliced from the source. Parsing builds strings when +// decoding inline character references or collecting fenced code inside a list +// or quote. A Document reuses its storage between calls to Parse. // // A newline inside a paragraph is a line break, as it is in chat. Text that is // not closed (a "**" with no partner, a fence nobody ended yet) stays as typed, diff --git a/markdown/markdown_test.go b/markdown/markdown_test.go index 276d29b91..c65ab2abd 100644 --- a/markdown/markdown_test.go +++ b/markdown/markdown_test.go @@ -127,6 +127,28 @@ func TestTextThatIsNotClosedStaysAsTyped(t *testing.T) { } } +func TestInlineCharacterReferences(t *testing.T) { + for _, tc := range []struct { + name, source, want string + }{ + {"documentation indent", "    (...) Matches the expression.", "P0 {\u00a0\u00a0\u00a0\u00a0(...) Matches the expression.}\n"}, + {"number and name", "A B 🚀 ≂̸ ;", "P0 {A\u00a0B 🚀 ≂̸ ;}\n"}, + {"expanding names", "≪⃒≫⃒", "P0 {\u226a\u20d2\u226b\u20d2}\n"}, + {"malformed references", "¬it; ¬i; ©   � &;", "P0 {¬it; ¬i; ©   � &;}\n"}, + {"invalid code points", "� � �", "P0 {� � �}\n"}, + {"decoded once as text", "&nbsp; *word*", "P0 {  *word*}\n"}, + {"escaped ampersand", `\ `, "P0 { }\n"}, + {"link text and emphasis", "[a & b](https://example.com) **A B**", "P0 {a & b -> https://example.com}{ }{A\u00a0B:b}\n"}, + {"code", "` `\n\n```\n \n```", "P0 { :m}\nCODE[] \" \"\n"}, + } { + t.Run(tc.name, func(t *testing.T) { + if got := parse(tc.source); got != tc.want { + t.Errorf("got %q, want %q", got, tc.want) + } + }) + } +} + func TestOnlyWebAndMailLinksAreKept(t *testing.T) { for _, dest := range []string{"javascript:alert(1)", "file:///etc/passwd", "ssh://host", "./local.md", "data:text/html,x"} { got := parse("[click me](" + dest + ")") From 54468610e60f563a2527696fb15fab7ca8a13d5f Mon Sep 17 00:00:00 2001 From: ccq <76206374+caichangqing1120@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:10:08 +0800 Subject: [PATCH 48/64] docs(guides): name c.TitlebarInsets in the Windows guide --- website/content/guides/en/windows.md | 4 ++-- website/content/guides/zh/windows.md | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/website/content/guides/en/windows.md b/website/content/guides/en/windows.md index e56047b53..154666ea4 100644 --- a/website/content/guides/en/windows.md +++ b/website/content/guides/en/windows.md @@ -23,7 +23,7 @@ Every window has its own canvas, paint callback, focus, input state and close ha | `WindowPanel` | A transient popup with no chrome, above other windows, meant to open beside a status icon. | | `WindowNotification` | A desktop popup that accepts pointer input without taking keyboard focus, meant for the outcome of background work. On Wayland the compositor decides its placement, stacking and focus. | -With a custom title bar the window buttons are the system's on macOS and are drawn by Viva on Windows and Linux. Either way they cover part of the strip, so ask `app.TitlebarInsets` how much and keep your own content clear of it. `Config.TitlebarHeight` sets the strip's height (where Viva puts its buttons and the traffic lights); the window moves from the row you mark `MovesWindow`, controls inside it keep their own clicks, and a menu or dialog open over it is dismissed by a click there, with the window moving once the pointer drags. `Config.WindowControls` styles the buttons Viva draws so they follow your theme. +With a custom title bar the window buttons are the system's on macOS and are drawn by Viva on Windows and Linux. Either way they cover part of the strip, so ask `c.TitlebarInsets()` how much and keep your own content clear of it. `Config.TitlebarHeight` sets the strip's height (where Viva puts its buttons and the traffic lights); the window moves from the row you mark `MovesWindow`, controls inside it keep their own clicks, and a menu or dialog open over it is dismissed by a click there, with the window moving once the pointer drags. `Config.WindowControls` styles the buttons Viva draws so they follow your theme. ## Fullscreen @@ -79,7 +79,7 @@ Hosts without the capability return an error wrapping `app.ErrUnsupported`. ## A complete example -The program below opens a custom-title-bar window with a Settings button that opens a second window, and refuses to close while a note is unsaved. The strip along the top is an ordinary `ui.Row` padded by `app.TitlebarInsets`, so the title never runs under the window buttons, and the confirmation is a `ui.ModalWith` declared only while a close is pending: +The program below opens a custom-title-bar window with a Settings button that opens a second window, and refuses to close while a note is unsaved. The strip along the top is an ordinary `ui.Row` padded by `c.TitlebarInsets()`, so the title never runs under the window buttons, and the confirmation is a `ui.ModalWith` declared only while a close is pending: ```go diff --git a/website/content/guides/zh/windows.md b/website/content/guides/zh/windows.md index eb2b53f0c..81f13ee09 100644 --- a/website/content/guides/zh/windows.md +++ b/website/content/guides/zh/windows.md @@ -23,7 +23,7 @@ group: guides | `WindowPanel` | 无外框的临时弹出窗口,位于其他窗口之上,用来在状态栏图标旁边打开。 | | `WindowNotification` | 接受鼠标操作但不抢键盘焦点的桌面浮窗,用于后台任务的结果提示;Wayland 下位置、层级与焦点由合成器决定。 | -使用自定义标题栏时,窗口按钮在 macOS 上由系统绘制,在 Windows 和 Linux 上由 Viva 绘制。无论哪种,它们都会盖住条带的一部分,所以用 `app.TitlebarInsets` 询问盖住多少,让自己的内容避开。`Config.TitlebarHeight` 设置条带高度(Viva 放置自绘按钮和 macOS 红绿灯的位置);窗口从你标记了 `MovesWindow` 的那一行移动,行内的控件仍然接收自己的点击,行上方打开的菜单或对话框会被那里的点击关闭,指针拖动后窗口才移动。`Config.WindowControls` 给 Viva 绘制的按钮定样式,使它们跟随你的主题。 +使用自定义标题栏时,窗口按钮在 macOS 上由系统绘制,在 Windows 和 Linux 上由 Viva 绘制。无论哪种,它们都会盖住条带的一部分,所以用 `c.TitlebarInsets()` 询问盖住多少,让自己的内容避开。`Config.TitlebarHeight` 设置条带高度(Viva 放置自绘按钮和 macOS 红绿灯的位置);窗口从你标记了 `MovesWindow` 的那一行移动,行内的控件仍然接收自己的点击,行上方打开的菜单或对话框会被那里的点击关闭,指针拖动后窗口才移动。`Config.WindowControls` 给 Viva 绘制的按钮定样式,使它们跟随你的主题。 ## 全屏 @@ -45,7 +45,7 @@ Windows 使用整个显示器而不是任务栏工作区,并保存之前的位 ## 完整示例 -下面的程序打开一个自定义标题栏窗口,其中的“Settings”按钮会打开第二个窗口,并且在有未保存的笔记时拒绝关闭。顶部条带是一个普通的 `ui.Row`,用 `app.TitlebarInsets` 留出内边距,所以标题不会压到窗口按钮下面;确认框是 `ui.ModalWith`,只在有关闭请求挂起时才声明: +下面的程序打开一个自定义标题栏窗口,其中的“Settings”按钮会打开第二个窗口,并且在有未保存的笔记时拒绝关闭。顶部条带是一个普通的 `ui.Row`,用 `c.TitlebarInsets()` 留出内边距,所以标题不会压到窗口按钮下面;确认框是 `ui.ModalWith`,只在有关闭请求挂起时才声明: ```go From cb5b31f52cfb7b9aa7364c0c5c229f34b5dfca92 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Mon, 23 Nov 2026 02:20:19 +0800 Subject: [PATCH 49/64] feat(tooltip): open a control's tooltip when a finger holds it A long press on a control that has a tooltip and takes no context menu shows the tooltip for a moment, as Material and Android's tooltipText do on touch. --- components/tooltip.go | 49 ++++++++++++++++++++++++++++-- examples/touch/main.go | 2 +- examples/touch/main_test.go | 59 +++++++++++++++++++++++++++++++++++++ gfx/canvas.go | 11 +++++++ ui/tooltip_paint.go | 12 +++++++- 5 files changed, 129 insertions(+), 4 deletions(-) diff --git a/components/tooltip.go b/components/tooltip.go index edd26967a..e4d4cbff7 100644 --- a/components/tooltip.go +++ b/components/tooltip.go @@ -286,8 +286,20 @@ type HoverTooltip struct { // shown is the control whose tooltip the last Paint drew, so a press or an // explicit Dismiss can suppress that control until the pointer leaves. shown gfx.ID + // held is the control a finger held and whose tooltip the hold opened, from heldSince + // until TouchTooltipTime has passed or another finger touches. + held gfx.ID + heldSince time.Duration } +// TouchTooltipTime is how long the tooltip a held finger opened stays: a touch screen has +// no pointer to rest on a control, so a long press shows the hint, as Android's +// tooltipText and Material's long-press tooltip do, and it goes away by itself. +const TouchTooltipTime = 1500 * time.Millisecond + +// Holding returns the control whose tooltip a held finger opened and that is still open, or zero. +func (hover *HoverTooltip) Holding() gfx.ID { return hover.held } + // Showing returns the control whose tooltip the last Paint drew, or zero. func (hover *HoverTooltip) Showing() gfx.ID { return hover.shown } @@ -314,7 +326,8 @@ func (hover *HoverTooltip) ShowOnFocus() { hover.focus = true } // for hits without a Hint. func (hover *HoverTooltip) Paint(canvas *gfx.Canvas, theme gfx.Theme, viewport gfx.Rect, options TooltipOptions, delay time.Duration) bool { hovered := canvas.Hovered() - if !canvas.Pressed().IsZero() { + hover.holdByFinger(canvas) + if !canvas.Pressed().IsZero() && hover.held.IsZero() { if !hover.shown.IsZero() { hover.suppressed = hover.shown } @@ -330,7 +343,16 @@ func (hover *HoverTooltip) Paint(canvas *gfx.Canvas, theme gfx.Theme, viewport g } id := hovered immediate := false - if hover.focus { + if !hover.held.IsZero() { + id, immediate = hover.held, true + if remaining := TouchTooltipTime - (canvas.Now() - hover.heldSince); remaining > 0 { + canvas.RequestFrameIn(remaining) + } else { + hover.held = gfx.ID{} + id, immediate = hovered, false + } + } + if hover.focus && hover.held.IsZero() { if focused := canvas.FocusVisible(); !focused.IsZero() { id, immediate = focused, true } @@ -374,6 +396,29 @@ func (hover *HoverTooltip) Paint(canvas *gfx.Canvas, theme gfx.Theme, viewport g return true } +// holdByFinger opens the tooltip of a control a finger held long enough to press it as a +// right click, when nothing took that press (a control with a context menu takes it, as +// on Android a long-click listener keeps the tooltip from showing). +func (hover *HoverTooltip) holdByFinger(canvas *gfx.Canvas) { + event, consumed, ok := canvas.PointerPass() + if !ok || event.Kind != gfx.PointerDown { + return + } + if event.Button == gfx.PointerButtonPrimary { + hover.held = gfx.ID{} // another touch: what a held finger opened is closed + return + } + if consumed || event.Device != gfx.PointerTouch || event.Button != gfx.PointerButtonSecondary || event.Target.IsZero() { + return + } + for _, hit := range canvas.Hits() { + if hit.ID == event.Target && !hit.Block && hit.Hint != "" { + hover.held, hover.heldSince = event.Target, canvas.Now() + return + } + } +} + // Aliases into the style vocabulary, kept for callers of this component. type TooltipSide = style.TooltipSide diff --git a/examples/touch/main.go b/examples/touch/main.go index b620901de..ddf0b5b19 100644 --- a/examples/touch/main.go +++ b/examples/touch/main.go @@ -32,7 +32,7 @@ func newModel() *model { func (m *model) page(c ui.C) { ui.Column(c).Fill().Pad(16).Gap(12).Items(ui.Stretch).Children(func() { ui.Row(c).Gap(12).Items(ui.Center).Children(func() { - if ui.Button(c, "Tap me").Clicked() { + if ui.Button(c, "Tap me").Tooltip("Counts your taps").Clicked() { m.taps++ } ui.Text(c, fmt.Sprintf("Tapped %d times", m.taps)) diff --git a/examples/touch/main_test.go b/examples/touch/main_test.go index bd909b7c8..c86592b3a 100644 --- a/examples/touch/main_test.go +++ b/examples/touch/main_test.go @@ -219,3 +219,62 @@ func TestAFingerBesideASwitchTurnsItOn(t *testing.T) { t.Fatal("a finger just beside the switch did not turn it on") } } + +// A finger held on a control that has a tooltip and no menu shows it, and it goes away +// by itself. +func TestAHeldFingerShowsTheTooltipAndItGoesAway(t *testing.T) { + skipWithoutTouchRuntime(t) + m := newModel() + driver := open(t, m) + x, y := centerOf(t, driver, "Tap me") + if err := driver.TouchDown(1, x, y); err != nil { + t.Fatal(err) + } + if err := driver.Advance(700 * time.Millisecond); err != nil { + t.Fatal(err) + } + if !shown(driver, "Counts your taps") { + t.Fatal("the tooltip did not open under a held finger") + } + if err := driver.TouchUp(1, x, y); err != nil { + t.Fatal(err) + } + if m.taps != 0 { + t.Fatalf("a long press also tapped: %d", m.taps) + } + if !shown(driver, "Counts your taps") { + t.Fatal("the tooltip went away at once when the finger lifted") + } + if err := driver.Advance(300 * time.Millisecond); err != nil { + t.Fatal(err) + } + if !shown(driver, "Counts your taps") { + t.Fatal("the tooltip went away as soon as the finger lifted") + } + if err := driver.Advance(2 * time.Second); err != nil { + t.Fatal(err) + } + if shown(driver, "Counts your taps") { + t.Fatal("the tooltip stayed") + } +} + +// A row with a menu opens the menu, not a tooltip. +func TestAHeldFingerOnAControlWithAMenuShowsNoTooltip(t *testing.T) { + skipWithoutTouchRuntime(t) + m := newModel() + driver := open(t, m) + x, y := centerOf(t, driver, "Row 1") + if err := driver.TouchDown(1, x, y); err != nil { + t.Fatal(err) + } + if err := driver.Advance(700 * time.Millisecond); err != nil { + t.Fatal(err) + } + if err := driver.TouchUp(1, x, y); err != nil { + t.Fatal(err) + } + if !shown(driver, "Open") { + t.Fatal("the long press did not open the row's menu") + } +} diff --git a/gfx/canvas.go b/gfx/canvas.go index dfc6a22b1..bc03cfc3f 100644 --- a/gfx/canvas.go +++ b/gfx/canvas.go @@ -2350,6 +2350,17 @@ func (canvas *Canvas) Consume() { } } +// PointerPass is the pointer event being delivered in this paint, whoever it is aimed at, and +// whether a control has already consumed it; ok is false outside an event pass. A control +// that comes last in the paint, as a tooltip does, reads what the others left of the event. +func (canvas *Canvas) PointerPass() (event PointerEvent, consumed, ok bool) { + canvas.listensForPointer = true + if !canvas.hasPointer { + return PointerEvent{}, false, false + } + return canvas.pointer, canvas.consumed, true +} + // ListensForPointer reports whether the last paint asked PointerOn or PointerIn: // whether a pointer event needs the event pass. func (canvas *Canvas) ListensForPointer() bool { return canvas.listensForPointer } diff --git a/ui/tooltip_paint.go b/ui/tooltip_paint.go index 0f82abf51..49e265fc5 100644 --- a/ui/tooltip_paint.go +++ b/ui/tooltip_paint.go @@ -2,6 +2,7 @@ package ui import ( "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" ) // paintTooltip paints the Tooltip of the element the pointer rests on, over @@ -10,7 +11,16 @@ func paintTooltip(f *Frame) { if f.Surface == nil { return } - if !f.HasTooltip(f.Surface.Hovered()) { + // The element a tooltip belongs to: the one the pointer rests on, or the one a finger + // held (the press that opens it, then the element it stays for). + target := f.Surface.Hovered() + if event, _, ok := f.Surface.PointerPass(); ok && event.Device == gfx.PointerTouch && event.Kind == gfx.PointerDown && + event.Button == gfx.PointerButtonSecondary { + target = event.Target + } else if held := frameTooltipState(f).Holding(); !held.IsZero() { + target = held + } + if !f.HasTooltip(target) { // The pointer is on another frame's element (a page in a pane of this one), // whose frame paints its tip, or on none. f.SetTooltipValue(nil) From 1ded51e1097cb464b8d5cbbd3012f8276c3e1414 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Mon, 23 Nov 2026 03:07:31 +0800 Subject: [PATCH 50/64] feat(mobile): draw under the system bars and report lifecycle events Phone windows now fill the screen; Size.SafeArea, Canvas.SafeArea and ui.SafeArea keep content inside the bars. app.Config.OnLifecycle reports Background, Foreground and MemoryWarning on iOS and Android. Also fixes the screen staying stale after returning to the app (iOS redraws when active; Android presents again after the surface is replaced) and an allocation in the tooltip paint. --- app/app.go | 19 ++++ app/driver.go | 19 ++++ app/painter.go | 5 +- app/run_canvas.go | 9 ++ base/elements.go | 15 +++ examples/touch/main.go | 57 ++++++++---- examples/touch/main_test.go | 39 ++++++++ gfx/canvas.go | 11 +++ internal/gallery/gallery.go | 38 ++++---- internal/platform/android/android.go | 71 +++++++++++++- internal/platform/android/exports_android.go | 10 ++ .../hostsrc/java/dev/viva/host/Native.java | 10 ++ .../java/dev/viva/host/VivaActivity.java | 93 +++++++++++++++++-- internal/platform/contract.go | 20 ++++ internal/platform/darwin/callback.go | 2 +- internal/platform/darwin/ios_callback.go | 12 +++ internal/platform/darwin/ios_host.m | 56 +++++++++-- internal/platform/darwin/ios_keys.go | 20 ++++ internal/platform/darwin/platform.go | 5 +- ui/facade.go | 2 + ui/tooltip_paint.go | 4 +- 21 files changed, 463 insertions(+), 54 deletions(-) diff --git a/app/app.go b/app/app.go index 7f4fc62fa..1dbbd20af 100644 --- a/app/app.go +++ b/app/app.go @@ -208,6 +208,12 @@ type Config struct { // application stop work nobody can see, such as a remote desktop stream. // Hide is the application's own request and is not reported here. OnMinimize func(minimized bool) + // OnLifecycle runs on the window thread when the system moves a phone application + // between the foreground and the background, or asks it for memory. A desktop window + // never gets one. A phone may end a backgrounded application without further notice, so + // Background is when to save what the user would miss; a MemoryWarning is when to drop + // caches that can be rebuilt. + OnLifecycle func(LifecycleEvent) // OnActivate runs on the window thread when the top-level window becomes // the active window, including when the user switches back from another // application. Moving focus between editors inside the window does not @@ -336,3 +342,16 @@ func (config Config) originPoint() gfx.Point { } return *config.Origin } + +// LifecycleEvent is a change the system makes to the state of a phone application (see +// Config.OnLifecycle). +type LifecycleEvent uint8 + +const ( + // LifecycleBackground says the application went behind another. + LifecycleBackground LifecycleEvent = iota + 1 + // LifecycleForeground says it came back to the front. + LifecycleForeground + // LifecycleMemoryWarning says the system wants memory back. + LifecycleMemoryWarning +) diff --git a/app/driver.go b/app/driver.go index e0ee01339..7931d39b8 100644 --- a/app/driver.go +++ b/app/driver.go @@ -291,6 +291,25 @@ func (driver *Driver) Resize(width, height int) error { return err } +// Lifecycle tells the application the system did something to it, as a phone does when it +// moves the application to the background or asks it for memory. +func (driver *Driver) Lifecycle(event LifecycleEvent) { + if driver.config.OnLifecycle != nil { + driver.config.OnLifecycle(event) + } +} + +// SetSafeArea says the system covers the window's edges by insets, as a phone's status bar, +// sensor housing and home indicator do, and lets the page lay out again inside what is left. +func (driver *Driver) SetSafeArea(insets gfx.Insets) error { + if err := driver.Pump(); err != nil { + return err + } + size := driver.painter.size + _, err := driver.painter.resize(platform.Size{Width: size.Width, Height: size.Height, Scale: driver.painter.scale, SafeArea: insets}) + return err +} + func (driver *Driver) pointer(kind platform.PointerEventKind, x, y float32, button gfx.PointerButton, clicks int) error { if err := driver.Pump(); err != nil { return err diff --git a/app/painter.go b/app/painter.go index 887d6e21c..08c48a010 100644 --- a/app/painter.go +++ b/app/painter.go @@ -23,6 +23,8 @@ import ( // native label list, so an unchanged repaint performs no renderer work. type painter struct { fullscreen bool + // safeArea is how far the system covers the window's edges, as the platform last said. + safeArea gfx.Insets // touch reads a finger's presses, pans and flings (touch.go). touch touchState // customTitlebar says the page draws the window's titlebar strip itself @@ -207,7 +209,7 @@ func newPainterWithClock(canvas *gfx.Canvas, config *Config, clock func() time.D func (painter *painter) resize(size platform.Size) (platform.Frame, error) { next := gfx.Size{Width: size.Width, Height: size.Height} changed := next != painter.size - painter.size, painter.scale = next, size.Scale + painter.size, painter.scale, painter.safeArea = next, size.Scale, size.SafeArea if changed && painter.onResize != nil { painter.onResize(next) } @@ -1006,6 +1008,7 @@ func (painter *painter) paintCanvas() { painter.canvas.SetHoveredRole(painter.pointer.HoveredRole()) painter.canvas.SetPointerOnSurface(painter.onSurface) painter.canvas.SetTitlebarInsets(painter.titlebarInsets()) + painter.canvas.SetSafeArea(painter.safeArea) painter.canvas.SetScroll(painter.scrollX, painter.scrollY) painter.canvas.BeginFrame() painter.paint(painter.canvas, painter.size) diff --git a/app/run_canvas.go b/app/run_canvas.go index 93d1e940d..8d2c9fedc 100644 --- a/app/run_canvas.go +++ b/app/run_canvas.go @@ -187,6 +187,7 @@ func nativeWindowConfig(normalized *Config, painter *painter) (platform.Config, OnFrameChange: frameChangeHandler(normalized.OnFrameChange), OnMinimize: minimizeHandler(normalized.OnMinimize), OnVisibility: gate.handler(), + OnLifecycle: lifecycleHandler(normalized.OnLifecycle), OnMaximize: maximizeHandler(normalized.OnMaximize), OnFullscreen: painter.fullscreenHandler(normalized.OnFullscreen), OnReopen: normalized.onReopen, @@ -260,3 +261,11 @@ func prepareNativeWindow(config Config, canvas *gfx.Canvas) (platform.Config, *p stopWatchingDesktop := watchDesktopSettings(canvas, native.Waker) return native, painter, func() { stopWatchingDesktop(); cleanup() }, nil } + +// lifecycleHandler is the application's OnLifecycle as the platform's, or nil without one. +func lifecycleHandler(handler func(LifecycleEvent)) func(platform.Lifecycle) { + if handler == nil { + return nil + } + return func(event platform.Lifecycle) { handler(LifecycleEvent(event)) } +} diff --git a/base/elements.go b/base/elements.go index eba7ccac2..d852157b9 100644 --- a/base/elements.go +++ b/base/elements.go @@ -14,6 +14,21 @@ func Row(c C) Box { return c.page.container(c.f.Row()) } func Column(c C) Box { return c.page.container(c.f.Column()) } func Stack(c C) Box { return c.page.container(c.f.Stack()) } +// SafeArea is a column that fills its container and keeps what it holds inside what the +// system draws over the window's edges: the status bar and the sensor housing, the home +// indicator or navigation bar, a cutout. A phone's window runs under them, so the page's +// background reaches the screen's edges while its content stays readable and tappable. It is +// padded by the window's SafeArea as the last layout left it, and not at all on a desktop +// window. Put it once at the root of a page; the padding is its own, so give the content +// inside it a column of its own for any other. +func SafeArea(c C) Box { + var inset gfx.Insets + if c.f.Surface != nil { + inset = c.f.Surface.SafeArea() + } + return Column(c).Fill().PadSides(inset.Top, inset.Right, inset.Bottom, inset.Left) +} + // Scroll is a scroll area whose offset is kept by the area's own name. func Scroll(c C) Box { p := c.page diff --git a/examples/touch/main.go b/examples/touch/main.go index ddf0b5b19..e3871cd59 100644 --- a/examples/touch/main.go +++ b/examples/touch/main.go @@ -21,6 +21,11 @@ type model struct { name string list ui.ListState menu string + // lifecycle is what the system last did to the application: it went to the background, came + // back, or asked for memory. + lifecycle string + // invalidator asks for a new frame after a change the page was not told of. + invalidator *app.Invalidator } func newModel() *model { @@ -30,23 +35,28 @@ func newModel() *model { } func (m *model) page(c ui.C) { - ui.Column(c).Fill().Pad(16).Gap(12).Items(ui.Stretch).Children(func() { - ui.Row(c).Gap(12).Items(ui.Center).Children(func() { - if ui.Button(c, "Tap me").Tooltip("Counts your taps").Clicked() { - m.taps++ + ui.SafeArea(c).Children(func() { + ui.Column(c).Fill().Pad(16).Gap(12).Items(ui.Stretch).Children(func() { + ui.Row(c).Gap(12).Items(ui.Center).Children(func() { + if ui.Button(c, "Tap me").Tooltip("Counts your taps").Clicked() { + m.taps++ + } + ui.Text(c, fmt.Sprintf("Tapped %d times", m.taps)) + }) + ui.Row(c).Gap(12).Items(ui.Center).Children(func() { + ui.Text(c, fmt.Sprintf("Volume %.0f", m.volume.Value)) + ui.Slider(c, &m.volume).Width(220).Step(1) + }) + ui.Switch(c, &m.notify, "Notifications") + ui.TextField(c, &m.name, "Name", "Your name").Width(320) + if m.menu != "" { + ui.Text(c, m.menu).Muted() } - ui.Text(c, fmt.Sprintf("Tapped %d times", m.taps)) - }) - ui.Row(c).Gap(12).Items(ui.Center).Children(func() { - ui.Text(c, fmt.Sprintf("Volume %.0f", m.volume.Value)) - ui.Slider(c, &m.volume).Width(220).Step(1) + if m.lifecycle != "" { + ui.Text(c, "System: "+m.lifecycle).Muted() + } + ui.List(c, &m.list, rows, m.row).Label("Rows").Grow(1) }) - ui.Switch(c, &m.notify, "Notifications") - ui.TextField(c, &m.name, "Name", "Your name").Width(320) - if m.menu != "" { - ui.Text(c, m.menu).Muted() - } - ui.List(c, &m.list, rows, m.row).Label("Rows").Grow(1) }) } @@ -69,9 +79,24 @@ func (m *model) row(r ui.ListRow) { }) } +// systemChanged notes what the system did; the next frame shows it. +func (m *model) systemChanged(event app.LifecycleEvent) { + switch event { + case app.LifecycleBackground: + m.lifecycle = "background" + case app.LifecycleForeground: + m.lifecycle = "foreground" + case app.LifecycleMemoryWarning: + m.lifecycle = "memory warning" + } + m.invalidator.Invalidate() +} + func main() { m := newModel() - if err := ui.Run(app.Config{Title: "Touch", Width: 420, Height: 760}, ui.PageConfig{View: m.page}); err != nil { + m.invalidator = new(app.Invalidator) + config := app.Config{Title: "Touch", Width: 420, Height: 760, OnLifecycle: m.systemChanged} + if err := ui.Run(config, ui.PageConfig{View: m.page, Invalidator: m.invalidator}); err != nil { log.Fatal(err) } } diff --git a/examples/touch/main_test.go b/examples/touch/main_test.go index c86592b3a..cf7fd420d 100644 --- a/examples/touch/main_test.go +++ b/examples/touch/main_test.go @@ -278,3 +278,42 @@ func TestAHeldFingerOnAControlWithAMenuShowsNoTooltip(t *testing.T) { t.Fatal("the long press did not open the row's menu") } } + +// A page keeps inside the bars a phone's system draws over its window, and the page's own +// background reaches the edges: the window being told the bars grow moves the content down. +func TestThePageKeepsInsideTheSafeArea(t *testing.T) { + m := newModel() + driver := open(t, m) + before := control(t, driver, "Tap me").Bounds + if err := driver.SetSafeArea(gfx.Insets{Top: 47, Bottom: 34, Left: 10, Right: 10}); err != nil { + t.Fatal(err) + } + after := control(t, driver, "Tap me").Bounds + if after.Y != before.Y+47 || after.X != before.X+10 { + t.Fatalf("the button moved from %v, %v to %v, %v, want 10 right and 47 down", before.X, before.Y, after.X, after.Y) + } + rows := driver.Snapshot().Hits + last := rows[len(rows)-1] + if bottom := last.Bounds.Y + last.Bounds.Height; bottom > 760-34+0.5 { + t.Fatalf("content reaches %v, into the 34 px the home indicator covers", bottom) + } +} + +// What the system does to the application shows on the page once the application says so. +func TestThePageShowsWhatTheSystemDid(t *testing.T) { + m := newModel() + m.invalidator = new(app.Invalidator) + page := ui.NewPage(ui.PageConfig{View: m.page, Invalidator: m.invalidator}) + driver, err := app.NewDriver(ui.Configure(page, app.Config{Width: 420, Height: 760, OnLifecycle: m.systemChanged}), nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(driver.Close) + driver.Lifecycle(app.LifecycleMemoryWarning) + if err := driver.Pump(); err != nil { + t.Fatal(err) + } + if !shown(driver, "System: memory warning") { + t.Fatal("the page does not show the memory warning") + } +} diff --git a/gfx/canvas.go b/gfx/canvas.go index bc03cfc3f..9e72121ef 100644 --- a/gfx/canvas.go +++ b/gfx/canvas.go @@ -765,6 +765,8 @@ type Canvas struct { onSurface bool // titlebarLeading and titlebarTrailing are the window's TitlebarInsets. titlebarLeading, titlebarTrailing float32 + // safeArea is the window's SafeArea. + safeArea Insets // prevHovered is the hit the pointer was on at the end of the previous // paint, which is what HoverCrossed compares against. prevHovered ID @@ -2094,6 +2096,15 @@ func (canvas *Canvas) TitlebarInsets() (leading, trailing float32) { return canvas.titlebarLeading, canvas.titlebarTrailing } +// SafeArea is how far the system covers the edges of the window: the status bar and the +// sensor housing, the home indicator or navigation bar, a cutout or rounded corner. A page +// keeps its content inside of on a phone, where the window runs under the bars. Zero for +// a desktop window. +func (canvas *Canvas) SafeArea() Insets { return canvas.safeArea } + +// SetSafeArea records the window's SafeArea; the runtime calls it before each paint. +func (canvas *Canvas) SetSafeArea(insets Insets) { canvas.safeArea = insets } + // SetTitlebarInsets records the window's TitlebarInsets; the runtime calls it // before each paint. func (canvas *Canvas) SetTitlebarInsets(leading, trailing float32) { diff --git a/internal/gallery/gallery.go b/internal/gallery/gallery.go index 9727058b3..39276b381 100644 --- a/internal/gallery/gallery.go +++ b/internal/gallery/gallery.go @@ -81,7 +81,9 @@ func Tree() *gfx.Tree { return tree } // the same value so their pixels and behavior originate from one implementation. type State struct { // page is 0 for the catalog and n for catalog[n-1]. - page int + page int + // safe is how far the system covers the window's edges, as of the last paint. + safe gfx.Insets lightMode bool density gfx.Density textEditing bool @@ -266,8 +268,10 @@ func (state *State) dragThumb(event gfx.PointerEvent) gfx.EventResult { // the full window width so the scrollbar sits on the window edge while the // page keeps its side insets. func (state *State) scrollArea(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) components.ScrollArea { - viewport := gfx.Rect{Y: toolbarHeight, Width: size.Width, Height: max(size.Height-toolbarHeight, 0)} - pageHeight := state.contentHeight(max(size.Width-pageInset*2, 0)) + safe := state.safe + viewport := gfx.Rect{X: safe.Left, Y: toolbarHeight + safe.Top, Width: max(size.Width-safe.Left-safe.Right, 0), + Height: max(size.Height-toolbarHeight-safe.Top-safe.Bottom, 0)} + pageHeight := state.contentHeight(max(viewport.Width-pageInset*2, 0)) return components.BeginScrollArea(canvas, theme, viewport, gfx.Size{Width: viewport.Width, Height: pageTopGap + pageHeight + pageBottomGap}). Offset(0, state.viewScroll). VerticalScrollbar(hitPageScrollbar, "Page position", "") @@ -289,6 +293,7 @@ func (state *State) contentHeight(width float32) float32 { func (state *State) Paint(canvas *gfx.Canvas, size gfx.Size) { canvas.SetTree(tree) theme := state.Theme() + state.safe = canvas.SafeArea() width, height := size.Width, size.Height canvas.Fill(gfx.Rect{Width: width, Height: height}, theme.Background) canvas.PushLayer(toolbarLayer) @@ -303,9 +308,9 @@ func (state *State) Paint(canvas *gfx.Canvas, size gfx.Size) { // Write the clamped offset back: a resize or a shorter page may have left // the stored one past the new end. state.viewScroll, state.scrollMax = geometry.OffsetY, geometry.MaxOffsetY - pageWidth := max(width-pageInset*2, 0) + pageWidth := max(width-state.safe.Left-state.safe.Right-pageInset*2, 0) content := gfx.Rect{ - X: pageInset, Y: geometry.Content.Y + pageTopGap, + X: state.safe.Left + pageInset, Y: geometry.Content.Y + pageTopGap, Width: pageWidth, Height: state.contentHeight(pageWidth), } if state.page == 0 { @@ -320,8 +325,9 @@ func (state *State) Paint(canvas *gfx.Canvas, size gfx.Size) { // open one, unless a click in this paint chose another. func (state *State) paintToolbar(canvas *gfx.Canvas, theme gfx.Theme, width float32) (page int) { page = state.page - canvas.Fill(gfx.Rect{Width: width, Height: toolbarHeight}, theme.Card) - canvas.Fill(gfx.Rect{Y: toolbarHeight - 1, Width: width, Height: 1}, theme.Border) + safe := state.safe + canvas.Fill(gfx.Rect{Width: width, Height: toolbarHeight + safe.Top}, theme.Card) + canvas.Fill(gfx.Rect{Y: toolbarHeight + safe.Top - 1, Width: width, Height: 1}, theme.Border) // Every element is centered on the bar's own centerline (the area above // its 1px border) at the active density's control height, rather than at @@ -329,23 +335,23 @@ func (state *State) paintToolbar(canvas *gfx.Canvas, theme gfx.Theme, width floa // Small size, whose height is exactly the control height; the default // button is four pixels taller and would sit below the centerline. control := theme.Metrics.ControlHeight - top := (toolbarHeight - 1 - control) / 2 + top := safe.Top + (toolbarHeight-1-control)/2 markSize := float32(20) - paintMark(canvas, theme, gfx.Rect{X: pageInset, Y: (toolbarHeight - 1 - markSize) / 2, Width: markSize, Height: markSize}) + paintMark(canvas, theme, gfx.Rect{X: safe.Left + pageInset, Y: safe.Top + (toolbarHeight-1-markSize)/2, Width: markSize, Height: markSize}) // Clicks are read where the control is painted, in the event pass of the // click (see gfx.Canvas.Clicked). - if paintIconButton(canvas, theme, hitPagePrevious, gfx.Rect{X: 72, Y: top, Width: 28, Height: control}, iconChevronLeft, "Previous page") { + if paintIconButton(canvas, theme, hitPagePrevious, gfx.Rect{X: safe.Left + 72, Y: top, Width: 28, Height: control}, iconChevronLeft, "Previous page") { page = (state.page + len(catalog)) % (len(catalog) + 1) } - if paintIconButton(canvas, theme, hitPageNext, gfx.Rect{X: 104, Y: top, Width: 28, Height: control}, iconChevronRight, "Next page") { + if paintIconButton(canvas, theme, hitPageNext, gfx.Rect{X: safe.Left + 104, Y: top, Width: 28, Height: control}, iconChevronRight, "Next page") { page = (state.page + 1) % (len(catalog) + 1) } - labelX := float32(148) + labelX := safe.Left + 148 title := "Components" // On a phone there is no room between the page arrows and the density and theme // buttons for a breadcrumb; the page's own heading already names where you are. - if titleWidth := width - labelX - 210; titleWidth >= 96 { + if titleWidth := width - safe.Right - labelX - 210; titleWidth >= 96 { if state.page != 0 { if components.BeginButton(canvas, theme, hitPageCatalog, gfx.Rect{X: labelX, Y: top, Width: 96}).Small().Ghost("Components").Clicked() { page = 0 @@ -354,11 +360,11 @@ func (state *State) paintToolbar(canvas *gfx.Canvas, theme gfx.Theme, width floa title = catalog[state.page-1].Title } canvas.Label(title, gfx.Rect{ - X: labelX, Y: top, Width: max(width-labelX-210, 0), Height: control, + X: labelX, Y: top, Width: max(width-safe.Right-labelX-210, 0), Height: control, }, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Weight: gfx.WeightMedium, Color: theme.MutedForeground}) } - densityBounds := gfx.Rect{X: width - 190, Y: top, Width: 88} + densityBounds := gfx.Rect{X: width - safe.Right - 190, Y: top, Width: 88} if components.BeginButton(canvas, theme, hitDensityCycle, densityBounds).Small().Ghost(state.densityName()).Clicked() { state.density = (state.density + 1) % 3 } @@ -367,7 +373,7 @@ func (state *State) paintToolbar(canvas *gfx.Canvas, theme gfx.Theme, width floa appearance = "Dark" } if components.BeginButton(canvas, theme, hitThemeToggle, gfx.Rect{ - X: width - 92, Y: top, Width: 76, + X: width - safe.Right - 92, Y: top, Width: 76, }).Small().Outline(appearance).Clicked() { state.lightMode = !state.lightMode } diff --git a/internal/platform/android/android.go b/internal/platform/android/android.go index d755e8c39..afb673224 100644 --- a/internal/platform/android/android.go +++ b/internal/platform/android/android.go @@ -46,6 +46,8 @@ const ( eventAppearance // the theme, the language or the animation setting may have changed eventAccessibility // a screen reader started or stopped eventAccessible // a screen reader asks something of a node + eventInsets // the system bars, the cutout or the keyboard cover other edges + eventLifecycle // the activity went to the background or came back ) // event is one thing that happened, small enough to queue by value. @@ -228,9 +230,66 @@ func (application *application) handle(ev event) { case eventAccessible: application.accessible(ev) case eventLowMemory: + application.lifecycle(platform.LifecycleMemoryWarning) + case eventLifecycle: + application.lifecycle(platform.Lifecycle(ev.action)) + case eventInsets: + application.insetsChanged(ev) } } +// lifecycle tells the application the system moved it between the foreground and the +// background, or asked for memory. +func (application *application) lifecycle(event platform.Lifecycle) { + win := application.window + if win == nil || win.closed || win.config.OnLifecycle == nil { + return + } + defer application.guard() + win.config.OnLifecycle(event) +} + +// insetsChanged follows the system covering other edges of the window: the page lays out +// again inside what is left. The host gives them in device pixels; they are kept as the +// window's own, in logical pixels, and so are known when the first frame is painted. +func (application *application) insetsChanged(ev event) { + left, top, right, bottom := ev.x, ev.y, ev.dx, ev.dy + hostInsets.Lock() + hostInsets.left, hostInsets.top, hostInsets.right, hostInsets.bottom, hostInsets.known = left, top, right, bottom, true + hostInsets.Unlock() + win := application.window + if win == nil || win.closed || win.density <= 0 { + return + } + defer application.guard() + insets := insetsIn(win.density) + if insets == win.insets { + return + } + win.insets = insets + if err := win.resized(false); err != nil { + application.fail(err) + } +} + +// hostInsets are the insets the host last gave, in device pixels. They arrive before the +// window exists and again whenever they change; the window takes them with its density. +var hostInsets struct { + sync.Mutex + left, top, right, bottom float32 + known bool +} + +// insetsIn is the host's insets in logical pixels at a density. +func insetsIn(density float32) gfx.Insets { + hostInsets.Lock() + defer hostInsets.Unlock() + if !hostInsets.known || density <= 0 { + return gfx.Insets{} + } + return gfx.Insets{Top: hostInsets.top / density, Left: hostInsets.left / density, Bottom: hostInsets.bottom / density, Right: hostInsets.right / density} +} + func (application *application) runPosts() { application.postMu.Lock() posts := application.posts @@ -273,6 +332,7 @@ type window struct { density float32 // device pixels per logical pixel renderer *vulkan.Renderer text *textInput // the application's focused text input, if it has one + insets gfx.Insets // how far the system covers each edge, in logical pixels hovering bool // a mouse is over the surface a11y bool // a screen reader reads the window treeIDs []gfx.ID // the nodes of the tree last sent to the host, by place @@ -296,7 +356,7 @@ func (win *window) Frame() (gfx.Rect, bool) { func (win *window) size() platform.Size { density := win.density - return platform.Size{Width: float32(win.width) / density, Height: float32(win.height) / density, Scale: density} + return platform.Size{Width: float32(win.width) / density, Height: float32(win.height) / density, Scale: density, SafeArea: win.insets} } // closeWindow ends the window and the loop. @@ -362,6 +422,7 @@ func (application *application) surfaceChanged(ev event) { return } density := ev.density + win.insets = insetsIn(density) switch { case win.renderer == nil: win.native, win.width, win.height, win.density = ev.surface, uint32(ev.width), uint32(ev.height), density @@ -399,6 +460,14 @@ func (application *application) surfaceChanged(ev event) { } if err := win.resized(true); err != nil { application.fail(err) + return + } + // Seen on the emulator (Android 15): the first frame presented to a surface that has + // just come back is not the one the screen shows, even though it is drawn from the + // scene that holds the application's latest frame; presenting the same scene again + // shows it. The cause below the Vulkan calls is not known (ADR 0095 keeps the note). + if err := win.renderer.Present(); err != nil { + application.fail(err) } default: // The same surface at another size (a rotation, a split screen) or density. diff --git a/internal/platform/android/exports_android.go b/internal/platform/android/exports_android.go index 192108363..5017f2132 100644 --- a/internal/platform/android/exports_android.go +++ b/internal/platform/android/exports_android.go @@ -86,11 +86,21 @@ func Java_dev_viva_host_Native_visible(env *C.JNIEnv, _ C.jclass, visible C.jboo send(event{kind: eventVisible, visible: visible != 0}) } +//export Java_dev_viva_host_Native_lifecycle +func Java_dev_viva_host_Native_lifecycle(env *C.JNIEnv, _ C.jclass, kind C.jint) { + send(event{kind: eventLifecycle, action: int32(kind)}) +} + //export Java_dev_viva_host_Native_lowMemory func Java_dev_viva_host_Native_lowMemory(env *C.JNIEnv, _ C.jclass) { send(event{kind: eventLowMemory}) } +//export Java_dev_viva_host_Native_insets +func Java_dev_viva_host_Native_insets(env *C.JNIEnv, _ C.jclass, left, top, right, bottom C.jfloat) { + send(event{kind: eventInsets, x: float32(left), y: float32(top), dx: float32(right), dy: float32(bottom)}) +} + //export Java_dev_viva_host_Native_closeRequested func Java_dev_viva_host_Native_closeRequested(env *C.JNIEnv, _ C.jclass) { send(event{kind: eventClose}) diff --git a/internal/platform/android/hostsrc/java/dev/viva/host/Native.java b/internal/platform/android/hostsrc/java/dev/viva/host/Native.java index 06196cfe8..923734d5b 100644 --- a/internal/platform/android/hostsrc/java/dev/viva/host/Native.java +++ b/internal/platform/android/hostsrc/java/dev/viva/host/Native.java @@ -32,9 +32,19 @@ private Native() {} /** The theme, the language or the animation setting may have changed. */ public static native void appearanceChanged(); + /** The activity went behind another (1) or came back (2): the program's Background and Foreground. */ + public static native void lifecycle(int kind); + /** The system is short of memory. */ public static native void lowMemory(); + /** + * How far the system covers each edge of the surface, in its pixels: the bars, the display + * cutout, and the navigation bar unless the keyboard is up. Sent before the surface is + * known and whenever it changes. + */ + public static native void insets(float left, float top, float right, float bottom); + /** The user asked to close the window (the back gesture at the root). */ public static native void closeRequested(); diff --git a/internal/platform/android/hostsrc/java/dev/viva/host/VivaActivity.java b/internal/platform/android/hostsrc/java/dev/viva/host/VivaActivity.java index 588a821ed..af582a9cf 100644 --- a/internal/platform/android/hostsrc/java/dev/viva/host/VivaActivity.java +++ b/internal/platform/android/hostsrc/java/dev/viva/host/VivaActivity.java @@ -8,6 +8,10 @@ import android.view.View; import android.view.Window; import android.view.WindowInsets; +import android.view.WindowInsetsController; +import android.view.WindowManager; +import android.graphics.Color; +import android.os.Build; import android.widget.FrameLayout; /** @@ -26,27 +30,91 @@ protected void onCreate(Bundle state) { Host.attach(this, view); view.getHolder().addCallback(this); view.setOnTouchListener(this::onTouch); - // The surface lies inside what the system covers: its bars, the display cutout - // and the keyboard. A program that wants the whole screen asks for it. + // The window runs under the system bars and the display cutout, as an Android 15 window + // must; the program is told how far they cover each edge and keeps what matters inside + // them. The keyboard still shrinks the surface from the bottom. + edgeToEdge(); FrameLayout root = new FrameLayout(this); root.addView(view, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT)); root.setOnApplyWindowInsetsListener(VivaActivity::applyInsets); setContentView(root); + barIcons(); // needs the decor view, which setContentView installs Native.start(getFilesDir().getAbsolutePath(), getCacheDir().getAbsolutePath()); } + private void edgeToEdge() { + Window window = getWindow(); + if (Build.VERSION.SDK_INT >= 30) { + window.setDecorFitsSystemWindows(false); + } else { + window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE + | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN); + } + window.setStatusBarColor(Color.TRANSPARENT); + window.setNavigationBarColor(Color.TRANSPARENT); + if (Build.VERSION.SDK_INT >= 29) { + window.setNavigationBarContrastEnforced(false); + window.setStatusBarContrastEnforced(false); + } + if (Build.VERSION.SDK_INT >= 28) { + WindowManager.LayoutParams params = window.getAttributes(); + params.layoutInDisplayCutoutMode = Build.VERSION.SDK_INT >= 30 + ? WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS + : WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES; + window.setAttributes(params); + } + } + + /** The bars' icons are dark on the light theme and light on the dark one, as the system's own are. */ + private void barIcons() { + Window window = getWindow(); + boolean night = (getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) + == Configuration.UI_MODE_NIGHT_YES; + if (Build.VERSION.SDK_INT >= 30) { + WindowInsetsController controller = window.getInsetsController(); + if (controller != null) { + int mask = WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS + | WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS; + controller.setSystemBarsAppearance(night ? 0 : mask, mask); + } + } else if (Build.VERSION.SDK_INT >= 23) { + View decor = window.getDecorView(); + int light = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR + | (Build.VERSION.SDK_INT >= 26 ? View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR : 0); + int flags = decor.getSystemUiVisibility(); + decor.setSystemUiVisibility(night ? flags & ~light : flags | light); + } + } + + private boolean stopped; + @Override protected void onStart() { super.onStart(); Native.visible(true); + if (stopped) { + Native.lifecycle(2); // Foreground: it came back, it is not the first start + } } @Override protected void onStop() { Native.visible(false); + stopped = true; + Native.lifecycle(1); // Background: the time to save what the user would miss super.onStop(); } + @Override + public void onTrimMemory(int level) { + super.onTrimMemory(level); + // From the point the system runs short (TRIM_MEMORY_RUNNING_LOW) on; the level that + // only says the user interface is hidden (TRIM_MEMORY_UI_HIDDEN) is Background's. + if (level >= TRIM_MEMORY_RUNNING_LOW && level != TRIM_MEMORY_UI_HIDDEN) { + Native.lowMemory(); + } + } + @Override public void onLowMemory() { super.onLowMemory(); @@ -56,6 +124,7 @@ public void onLowMemory() { @Override public void onConfigurationChanged(Configuration config) { super.onConfigurationChanged(config); + barIcons(); Native.appearanceChanged(); } @@ -78,15 +147,25 @@ public void surfaceDestroyed(SurfaceHolder holder) { Native.surfaceDestroyed(); } + /** + * The surface is the whole window, less the keyboard from the bottom; the program is told how + * far the bars and the cutout cover each edge (the bottom one is not covered with the + * keyboard up, which covers it instead). + */ private static WindowInsets applyInsets(View root, WindowInsets insets) { - if (android.os.Build.VERSION.SDK_INT >= 30) { + if (Build.VERSION.SDK_INT >= 30) { android.graphics.Insets bars = insets.getInsets( - WindowInsets.Type.systemBars() | WindowInsets.Type.displayCutout() | WindowInsets.Type.ime()); - root.setPadding(bars.left, bars.top, bars.right, bars.bottom); + WindowInsets.Type.systemBars() | WindowInsets.Type.displayCutout()); + boolean keyboard = insets.isVisible(WindowInsets.Type.ime()); + root.setPadding(0, 0, 0, keyboard ? insets.getInsets(WindowInsets.Type.ime()).bottom : 0); + Native.insets(bars.left, bars.top, bars.right, keyboard ? 0 : bars.bottom); return WindowInsets.CONSUMED; } - root.setPadding(insets.getSystemWindowInsetLeft(), insets.getSystemWindowInsetTop(), - insets.getSystemWindowInsetRight(), insets.getSystemWindowInsetBottom()); + int bottom = insets.getSystemWindowInsetBottom(); + boolean keyboard = bottom > insets.getStableInsetBottom(); + root.setPadding(0, 0, 0, keyboard ? bottom : 0); + Native.insets(insets.getSystemWindowInsetLeft(), insets.getSystemWindowInsetTop(), + insets.getSystemWindowInsetRight(), keyboard ? 0 : insets.getStableInsetBottom()); return insets.consumeSystemWindowInsets(); } diff --git a/internal/platform/contract.go b/internal/platform/contract.go index be9312d2a..9b569917f 100644 --- a/internal/platform/contract.go +++ b/internal/platform/contract.go @@ -83,6 +83,10 @@ type Config struct { // as far as the platform says so. An adapter that cannot tell never calls it, // and the window counts as visible. OnVisibility VisibilityHandler + // OnLifecycle, when set, runs on the window thread when the system moves the + // application between the foreground and the background, or warns it of low memory. + // Only the phone adapters call it. + OnLifecycle func(Lifecycle) // OnMaximize, when set, runs on the window thread when the window is // maximized or restored. OnMaximize MaximizeHandler @@ -502,6 +506,19 @@ type PointerEvent struct { PointerID int32 } +// Lifecycle is a change the system makes to the state of a phone application. +type Lifecycle uint8 + +const ( + // LifecycleBackground is the application going behind another: the time to save what + // the user would miss, as the system may end it from there without a word. + LifecycleBackground Lifecycle = iota + 1 + // LifecycleForeground is the application coming back to the front. + LifecycleForeground + // LifecycleMemoryWarning is the system asking applications to give memory back. + LifecycleMemoryWarning +) + // Size is a window client size in logical pixels. type Size struct { Width float32 @@ -510,6 +527,9 @@ type Size struct { // (1.25 at 125%), or zero when the platform does not say. The application paints // what must land on whole device pixels for it. Scale float32 + // SafeArea is how far the system covers each edge of the window, in logical pixels + // (status bar, sensor housing, home indicator); zero where it covers nothing. + SafeArea gfx.Insets } // KeyEvent is one normalized keyboard event. Key identities mirror diff --git a/internal/platform/darwin/callback.go b/internal/platform/darwin/callback.go index 54802a9ba..44bdcaa8d 100644 --- a/internal/platform/darwin/callback.go +++ b/internal/platform/darwin/callback.go @@ -129,7 +129,7 @@ func vivaViewResized(handle C.uintptr_t, view unsafe.Pointer, width C.double, he } }() - frame, err := state.resizeHandler(Size{Width: float32(width), Height: float32(height)}) + frame, err := state.resizeHandler(Size{Width: float32(width), Height: float32(height), SafeArea: state.safeArea}) if err == nil { // The layer presents the frame in the same Core Animation transaction as // the new bounds (see -[VivaMetalView beginLiveResizeRelaxation]), so the diff --git a/internal/platform/darwin/ios_callback.go b/internal/platform/darwin/ios_callback.go index 19c4dc726..3acf4907e 100644 --- a/internal/platform/darwin/ios_callback.go +++ b/internal/platform/darwin/ios_callback.go @@ -35,3 +35,15 @@ func vivaTouchEvent(handle C.uintptr_t, view unsafe.Pointer, kind C.int, id C.in PointerID: int32(id), }) } + +// vivaIOSSafeArea is how far the system covers each edge of the window's view, in points. +// The resize that follows carries it to the application. +// +//export vivaIOSSafeArea +func vivaIOSSafeArea(handle C.uintptr_t, view unsafe.Pointer, top, left, bottom, right C.double) { + state, ok := runStateFor(handle) + if !ok { + return + } + state.safeArea = gfx.Insets{Top: float32(top), Left: float32(left), Bottom: float32(bottom), Right: float32(right)} +} diff --git a/internal/platform/darwin/ios_host.m b/internal/platform/darwin/ios_host.m index a5358ca47..b23f6d6fc 100644 --- a/internal/platform/darwin/ios_host.m +++ b/internal/platform/darwin/ios_host.m @@ -19,7 +19,9 @@ extern void vivaTouchEvent(uintptr_t callbackHandle, void *view, int kind, int i extern int vivaIOSKeyEvent(uintptr_t callbackHandle, void *view, int usage, int modifiers, int repeat, const unsigned char *utf8, size_t utf8Length); extern void vivaIOSVisibility(uintptr_t callbackHandle, void *view, int visible); +extern void vivaIOSLifecycle(uintptr_t callbackHandle, void *view, int kind); extern void vivaIOSAppearanceChanged(void); +extern void vivaIOSSafeArea(uintptr_t callbackHandle, void *view, double top, double left, double bottom, double right); extern int vivaAccessibilityAction(uintptr_t callbackHandle, void *view, uint64_t node, int action, double number, const unsigned char *utf8, size_t utf8Length, int start, int end); extern void vivaIOSTextOp(uintptr_t callbackHandle, void *view, int operation, const unsigned char *utf8, size_t utf8Length, @@ -263,8 +265,13 @@ @interface VivaIOSView : UIView { BOOL _closed; CGSize _lastReportedSize; BOOL _reportedSize; + UIEdgeInsets _safeArea; + UIEdgeInsets _lastReportedSafeArea; } @property(nonatomic, readonly) uintptr_t callbackHandle; +/* How far the system covers each edge (status bar, sensor housing, home indicator), which + * the view controller sets; the next layout tells the application. */ +@property(nonatomic) UIEdgeInsets safeArea; @property(nonatomic, readonly) BOOL closed; @property(nonatomic, readonly) VivaIOSEditor *editor; - (instancetype)initWithFrame:(CGRect)frame @@ -294,6 +301,7 @@ @implementation VivaIOSView @synthesize callbackHandle = _callbackHandle; @synthesize closed = _closed; @synthesize editor = _editor; +@synthesize safeArea = _safeArea; + (Class)layerClass { return [CAMetalLayer class]; @@ -374,9 +382,13 @@ - (void)layoutSubviews { } [self updateDrawableSize]; CGSize size = self.bounds.size; - if (_resizeEventsEnabled && (!_reportedSize || !CGSizeEqualToSize(size, _lastReportedSize))) { + if (_resizeEventsEnabled && (!_reportedSize || !CGSizeEqualToSize(size, _lastReportedSize) || + !UIEdgeInsetsEqualToEdgeInsets(_safeArea, _lastReportedSafeArea))) { _reportedSize = YES; _lastReportedSize = size; + _lastReportedSafeArea = _safeArea; + // The insets come first: the resize that follows lays the page out inside them. + vivaIOSSafeArea(_callbackHandle, self, _safeArea.top, _safeArea.left, _safeArea.bottom, _safeArea.right); vivaViewResized(_callbackHandle, self, size.width, size.height); } } @@ -887,17 +899,25 @@ - (void)keyboardWillChange:(NSNotification *)notification { } completion:nil]; } -// viewDidLayoutSubviews puts the surface inside what the system covers: the status -// bar and the sensor housing, the home indicator, and the keyboard. A program that -// wants the whole screen asks for it (ADR 0095). +// viewDidLayoutSubviews makes the surface the whole window, as far as the keyboard +// allows, and tells it how far the system covers each edge: the status bar and the +// sensor housing, the home indicator. The application draws under them and keeps what +// matters inside them (ADR 0096). The keyboard shrinks the surface from the bottom, and +// with it up nothing covers the bottom edge but the keyboard itself. - (void)viewDidLayoutSubviews { [super viewDidLayoutSubviews]; - CGRect bounds = UIEdgeInsetsInsetRect(self.view.bounds, self.view.safeAreaInsets); + CGRect bounds = self.view.bounds; + UIEdgeInsets safe = self.view.safeAreaInsets; CGFloat keyboardTop = CGRectGetMinY(self.view.keyboardLayoutGuide.layoutFrame); - if (keyboardTop < CGRectGetMaxY(bounds)) { + // With no keyboard the guide's top is the safe area's bottom edge, the home indicator's + // line; the keyboard is up when it is higher than that. + if (keyboardTop < CGRectGetMaxY(bounds) - safe.bottom - 0.5) { bounds.size.height = MAX(keyboardTop - bounds.origin.y, 0); + safe.bottom = 0; } + _surface.safeArea = safe; _surface.frame = bounds; + [_surface setNeedsLayout]; } - (UIInterfaceOrientationMask)supportedInterfaceOrientations { @@ -915,7 +935,9 @@ - (void)traitCollectionDidChange:(UITraitCollection *)previous { @end -@interface VivaIOSAppDelegate : UIResponder +@interface VivaIOSAppDelegate : UIResponder { + BOOL _inBackground; +} @end /* The one window an iPhone application shows (see viva_application_open_window). */ @@ -929,20 +951,36 @@ - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:( return YES; } -// The application goes behind another and comes back: it is told, and on the way -// back asks for a frame, since what the layer shows may not be what it should. +// The application goes behind another and comes back: it is told. The window is drawn +// again only once the application is active, as the system gives no GPU to one that +// has only begun to return; what the layer shows may not be what it should. - (void)applicationDidEnterBackground:(UIApplication *)application { if (viva_ios_view != nil && !viva_ios_view.closed) { + _inBackground = YES; + vivaIOSLifecycle(viva_ios_view.callbackHandle, viva_ios_view, 1); // Background vivaIOSVisibility(viva_ios_view.callbackHandle, viva_ios_view, 0); } } - (void)applicationWillEnterForeground:(UIApplication *)application { if (viva_ios_view != nil && !viva_ios_view.closed) { + vivaIOSLifecycle(viva_ios_view.callbackHandle, viva_ios_view, 2); // Foreground + } +} + +- (void)applicationDidBecomeActive:(UIApplication *)application { + if (_inBackground && viva_ios_view != nil && !viva_ios_view.closed) { + _inBackground = NO; vivaIOSVisibility(viva_ios_view.callbackHandle, viva_ios_view, 1); } } +- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application { + if (viva_ios_view != nil && !viva_ios_view.closed) { + vivaIOSLifecycle(viva_ios_view.callbackHandle, viva_ios_view, 3); // MemoryWarning + } +} + @end int viva_ios_main(void) { diff --git a/internal/platform/darwin/ios_keys.go b/internal/platform/darwin/ios_keys.go index 33c13be2f..63e810b13 100644 --- a/internal/platform/darwin/ios_keys.go +++ b/internal/platform/darwin/ios_keys.go @@ -13,6 +13,7 @@ import ( "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/internal/input" + "github.com/vivaui/viva/internal/platform" ) // UIKeyModifierFlags, as UIKey reports them. @@ -128,3 +129,22 @@ func vivaIOSVisibility(handle C.uintptr_t, view unsafe.Pointer, visible C.int) { C.viva_view_close(view) } } + +// vivaIOSLifecycle is the system moving the application to the background or back, or +// warning it of low memory: the application's OnLifecycle is told, on the main thread. +// +//export vivaIOSLifecycle +func vivaIOSLifecycle(handle C.uintptr_t, view unsafe.Pointer, kind C.int) { + state, ok := runStateFor(handle) + if !ok || state.closed || state.lifecycleHandler == nil { + return + } + defer func() { + if recovered := recover(); recovered != nil { + platform.ReportFault("darwin: lifecycle handler", recovered) + state.err = fmt.Errorf("darwin: lifecycle handler panicked: %v", recovered) + C.viva_view_close(view) + } + }() + state.lifecycleHandler(platform.Lifecycle(kind)) +} diff --git a/internal/platform/darwin/platform.go b/internal/platform/darwin/platform.go index 1a1dc623b..e276e4ab9 100644 --- a/internal/platform/darwin/platform.go +++ b/internal/platform/darwin/platform.go @@ -148,6 +148,8 @@ func (window *nativeWindow) SetAlwaysOnTop(enabled bool) error { } type runState struct { + // safeArea is how far the system covers the window's edges, as the iOS host last said. + safeArea gfx.Insets application *nativeApplication callbackHandle cgo.Handle onClosed func() @@ -159,6 +161,7 @@ type runState struct { frameHandler platform.FrameChangeHandler minimizeHandler platform.MinimizeHandler visibilityHandler platform.VisibilityHandler + lifecycleHandler func(platform.Lifecycle) fullscreenHandler func(bool) onReopen func() onActivate func() @@ -365,7 +368,7 @@ func (application *nativeApplication) OpenWindow(config Config) (platform.Window } state := &runState{application: application, onClosed: config.OnClosed, waker: config.Waker, closeHandler: config.OnCloseRequest, pressAt: config.PressAt, - frameHandler: config.OnFrameChange, minimizeHandler: config.OnMinimize, visibilityHandler: config.OnVisibility, fullscreenHandler: config.OnFullscreen, onReopen: config.OnReopen, onActivate: config.OnActivate} + frameHandler: config.OnFrameChange, minimizeHandler: config.OnMinimize, visibilityHandler: config.OnVisibility, lifecycleHandler: config.OnLifecycle, fullscreenHandler: config.OnFullscreen, onReopen: config.OnReopen, onActivate: config.OnActivate} state.pointerHandler = config.OnPointer state.resizeHandler = config.OnResize state.keyHandler = config.OnKey diff --git a/ui/facade.go b/ui/facade.go index c0d5d57a6..3f4088520 100644 --- a/ui/facade.go +++ b/ui/facade.go @@ -107,6 +107,8 @@ func Column(c C) Box { return base.Column(c) } func Stack(c C) Box { return base.Stack(c) } +func SafeArea(c C) Box { return base.SafeArea(c) } + func Divider(c C) Box { return base.Divider(c) } func Spacer(c C) Box { return base.Spacer(c) } diff --git a/ui/tooltip_paint.go b/ui/tooltip_paint.go index 49e265fc5..41aea3137 100644 --- a/ui/tooltip_paint.go +++ b/ui/tooltip_paint.go @@ -17,8 +17,8 @@ func paintTooltip(f *Frame) { if event, _, ok := f.Surface.PointerPass(); ok && event.Device == gfx.PointerTouch && event.Kind == gfx.PointerDown && event.Button == gfx.PointerButtonSecondary { target = event.Target - } else if held := frameTooltipState(f).Holding(); !held.IsZero() { - target = held + } else if state, _ := f.GetTooltip().(*components.HoverTooltip); state != nil && !state.Holding().IsZero() { + target = state.Holding() } if !f.HasTooltip(target) { // The pointer is on another frame's element (a page in a pane of this one), From c6f78b4f08eab0addb133f8d93c6ed952f84e672 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Mon, 23 Nov 2026 03:15:22 +0800 Subject: [PATCH 51/64] chore(viva): regenerate the tooltip template The reference component changed with the touch tooltip. --- cmd/viva/templates/tooltip.go.txt | 49 +++++++++++++++++++++++++++++-- 1 file changed, 47 insertions(+), 2 deletions(-) diff --git a/cmd/viva/templates/tooltip.go.txt b/cmd/viva/templates/tooltip.go.txt index 5af2ab331..dd148f606 100644 --- a/cmd/viva/templates/tooltip.go.txt +++ b/cmd/viva/templates/tooltip.go.txt @@ -286,8 +286,20 @@ type HoverTooltip struct { // shown is the control whose tooltip the last Paint drew, so a press or an // explicit Dismiss can suppress that control until the pointer leaves. shown gfx.ID + // held is the control a finger held and whose tooltip the hold opened, from heldSince + // until TouchTooltipTime has passed or another finger touches. + held gfx.ID + heldSince time.Duration } +// TouchTooltipTime is how long the tooltip a held finger opened stays: a touch screen has +// no pointer to rest on a control, so a long press shows the hint, as Android's +// tooltipText and Material's long-press tooltip do, and it goes away by itself. +const TouchTooltipTime = 1500 * time.Millisecond + +// Holding returns the control whose tooltip a held finger opened and that is still open, or zero. +func (hover *HoverTooltip) Holding() gfx.ID { return hover.held } + // Showing returns the control whose tooltip the last Paint drew, or zero. func (hover *HoverTooltip) Showing() gfx.ID { return hover.shown } @@ -314,7 +326,8 @@ func (hover *HoverTooltip) ShowOnFocus() { hover.focus = true } // for hits without a Hint. func (hover *HoverTooltip) Paint(canvas *gfx.Canvas, theme gfx.Theme, viewport gfx.Rect, options TooltipOptions, delay time.Duration) bool { hovered := canvas.Hovered() - if !canvas.Pressed().IsZero() { + hover.holdByFinger(canvas) + if !canvas.Pressed().IsZero() && hover.held.IsZero() { if !hover.shown.IsZero() { hover.suppressed = hover.shown } @@ -330,7 +343,16 @@ func (hover *HoverTooltip) Paint(canvas *gfx.Canvas, theme gfx.Theme, viewport g } id := hovered immediate := false - if hover.focus { + if !hover.held.IsZero() { + id, immediate = hover.held, true + if remaining := TouchTooltipTime - (canvas.Now() - hover.heldSince); remaining > 0 { + canvas.RequestFrameIn(remaining) + } else { + hover.held = gfx.ID{} + id, immediate = hovered, false + } + } + if hover.focus && hover.held.IsZero() { if focused := canvas.FocusVisible(); !focused.IsZero() { id, immediate = focused, true } @@ -374,6 +396,29 @@ func (hover *HoverTooltip) Paint(canvas *gfx.Canvas, theme gfx.Theme, viewport g return true } +// holdByFinger opens the tooltip of a control a finger held long enough to press it as a +// right click, when nothing took that press (a control with a context menu takes it, as +// on Android a long-click listener keeps the tooltip from showing). +func (hover *HoverTooltip) holdByFinger(canvas *gfx.Canvas) { + event, consumed, ok := canvas.PointerPass() + if !ok || event.Kind != gfx.PointerDown { + return + } + if event.Button == gfx.PointerButtonPrimary { + hover.held = gfx.ID{} // another touch: what a held finger opened is closed + return + } + if consumed || event.Device != gfx.PointerTouch || event.Button != gfx.PointerButtonSecondary || event.Target.IsZero() { + return + } + for _, hit := range canvas.Hits() { + if hit.ID == event.Target && !hit.Block && hit.Hint != "" { + hover.held, hover.heldSince = event.Target, canvas.Now() + return + } + } +} + // Aliases into the style vocabulary, kept for callers of this component. type TooltipSide = style.TooltipSide From e0387534e84fde583fff4a3128a70e7eeea66e03 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Mon, 23 Nov 2026 08:07:25 +0800 Subject: [PATCH 52/64] fix(touch): ask for the pointer event pass only after a finger has touched The touch tooltip read the pointer pass on every paint, which made a mouse-only window repaint once more per pointer event. --- app/touch.go | 1 + gfx/canvas.go | 11 ++++++++++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/app/touch.go b/app/touch.go index 135b438de..6fce58577 100644 --- a/app/touch.go +++ b/app/touch.go @@ -39,6 +39,7 @@ const touchTargetSize = 44 // touchEvent reads one event of a finger. func (painter *painter) touchEvent(event platform.PointerEvent) (platform.Frame, error) { t := &painter.touch + painter.canvas.SetTouched() now := painter.canvas.Now() var step interaction.TouchStep if event.Kind == platform.PointerDown && (!t.Active() || event.PointerID == t.id) { diff --git a/gfx/canvas.go b/gfx/canvas.go index 9e72121ef..df33ee881 100644 --- a/gfx/canvas.go +++ b/gfx/canvas.go @@ -767,6 +767,8 @@ type Canvas struct { titlebarLeading, titlebarTrailing float32 // safeArea is the window's SafeArea. safeArea Insets + // touched is set once a finger has touched the window. + touched bool // prevHovered is the hit the pointer was on at the end of the previous // paint, which is what HoverCrossed compares against. prevHovered ID @@ -2364,14 +2366,21 @@ func (canvas *Canvas) Consume() { // PointerPass is the pointer event being delivered in this paint, whoever it is aimed at, and // whether a control has already consumed it; ok is false outside an event pass. A control // that comes last in the paint, as a tooltip does, reads what the others left of the event. +// +// It asks for the event pass only once a finger has touched the window (SetTouched), so a +// window used with a mouse pays nothing for a control that reads touch. func (canvas *Canvas) PointerPass() (event PointerEvent, consumed, ok bool) { - canvas.listensForPointer = true + canvas.listensForPointer = canvas.listensForPointer || canvas.touched if !canvas.hasPointer { return PointerEvent{}, false, false } return canvas.pointer, canvas.consumed, true } +// SetTouched records that a finger has touched the window. The runtime calls it on the first +// touch event. +func (canvas *Canvas) SetTouched() { canvas.touched = true } + // ListensForPointer reports whether the last paint asked PointerOn or PointerIn: // whether a pointer event needs the event pass. func (canvas *Canvas) ListensForPointer() bool { return canvas.listensForPointer } From f0874102f5fe6698f5c1129ad3a16c9f5401ee50 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Mon, 23 Nov 2026 12:49:11 +0800 Subject: [PATCH 53/64] fix(app): keep the window when the platform has no pointer to shape On a phone setCursor answers ErrUnsupported, which ended the window as soon as a control asked for a pointer shape: holding a text field closed the app. --- app/driver_test.go | 22 ++++++++++++++++++++++ app/painter.go | 4 +++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/app/driver_test.go b/app/driver_test.go index 160a0f5ce..8ae9e27d4 100644 --- a/app/driver_test.go +++ b/app/driver_test.go @@ -1196,6 +1196,28 @@ func TestDriverShowsAHitsCursorImageAndRestoresTheArrow(t *testing.T) { } } +// A target with no pointer to shape, a phone, goes on when a control asks for a pointer +// shape: holding a text field used to end the window there. +func TestAnUnsupportedCursorDoesNotEndTheWindow(t *testing.T) { + config := Config{Title: "no pointer", Width: 100, Height: 100} + config.Paint = func(canvas *gfx.Canvas, _ gfx.Size) { + canvas.HitWithOptions(gfx.Item(1), gfx.Rect{Width: 100, Height: 100}, "field", gfx.HitOptions{Cursor: gfx.PointerCursorText}) + } + driver, err := NewDriver(config, nil) + if err != nil { + t.Fatal(err) + } + defer driver.Close() + asked := 0 + driver.painter.setCursor = func(Cursor) error { asked++; return fmt.Errorf("no pointer: %w", ErrUnsupported) } + if err := driver.Move(10, 10); err != nil { + t.Fatalf("an unsupported pointer shape failed the move: %v", err) + } + if err := driver.Move(11, 10); err != nil || asked != 1 { + t.Fatalf("the shape was asked for %d times (%v), want once", asked, err) + } +} + // A target that cannot draw application pointers keeps the arrow instead of failing the pointer. func TestAnUnsupportedCursorImageFallsBackToTheArrow(t *testing.T) { image, err := gfx.NewCursorImage(1, 1, 0, 0, 1, make([]byte, 4)) diff --git a/app/painter.go b/app/painter.go index 08c48a010..4a0a710fb 100644 --- a/app/painter.go +++ b/app/painter.go @@ -1193,7 +1193,9 @@ func (painter *painter) applyCursor(next Cursor, image *gfx.CursorImage) error { } } } else if painter.setCursor != nil { - if err := painter.setCursor(next); err != nil { + // A target with no pointer to shape, a phone's, answers ErrUnsupported: there is + // nothing to show, and the window goes on. + if err := painter.setCursor(next); err != nil && !errors.Is(err, ErrUnsupported) { return err } } From 4b1c9818ec86014703d3df3f10aa2fee3dab65e4 Mon Sep 17 00:00:00 2001 From: ccq <76206374+caichangqing1120@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:01:59 +0800 Subject: [PATCH 54/64] fix(dmg): keep image builds from exposing an installable app --- cmd/viva/package_dmg_test.go | 5 ++++- tools/dmg/build.go | 17 +++++++++++++---- tools/dmg/dmg_test.go | 29 ++++++++++++++++++++++++++++- 3 files changed, 45 insertions(+), 6 deletions(-) diff --git a/cmd/viva/package_dmg_test.go b/cmd/viva/package_dmg_test.go index 1d4f5ddb4..8bb846da8 100644 --- a/cmd/viva/package_dmg_test.go +++ b/cmd/viva/package_dmg_test.go @@ -30,7 +30,10 @@ func TestPackageMakesADiskImageHoldingTheBundleAndAnApplicationsLink(t *testing. } mount := t.TempDir() - if out, err := exec.Command("hdiutil", "attach", "-nobrowse", "-readonly", "-mountpoint", mount, image).CombinedOutput(); err != nil { + // -noautoopen keeps the Finder from opening this read-only mount: -nobrowse + // hides it from the sidebar but does not stop the automatic open that offers + // to install the application. + if out, err := exec.Command("hdiutil", "attach", "-nobrowse", "-noautoopen", "-readonly", "-mountpoint", mount, image).CombinedOutput(); err != nil { t.Fatalf("hdiutil attach: %v\n%s", err, out) } t.Cleanup(func() { _ = exec.Command("hdiutil", "detach", "-force", mount).Run() }) diff --git a/tools/dmg/build.go b/tools/dmg/build.go index 239f96566..1ac30494b 100644 --- a/tools/dmg/build.go +++ b/tools/dmg/build.go @@ -17,6 +17,12 @@ import ( // keeps the Finder from showing it. const backgroundFile = ".background.png" +// stagedBundle is the bundle's name on the writable volume before the Finder +// sees it: hidden, and without an .app suffix, so the temporary volume never +// shows an installable application. settle renames it to the real name only +// after the volume is attached. +const stagedBundle = ".viva-bundle" + // Options describes one image to build. type Options struct { // Bundle is the .app directory to put in the image. @@ -45,12 +51,9 @@ func Build(options Options) error { return err } app := filepath.Base(options.Bundle) - if out, err := exec.Command("cp", "-R", options.Bundle, filepath.Join(staging, app)).CombinedOutput(); err != nil { + if out, err := exec.Command("cp", "-R", options.Bundle, filepath.Join(staging, stagedBundle)).CombinedOutput(); err != nil { return fmt.Errorf("copying the bundle: %w: %s", err, strings.TrimSpace(string(out))) } - if err := os.Symlink("/Applications", filepath.Join(staging, "Applications")); err != nil { - return err - } picture, err := options.Layout.picture() if err != nil { return err @@ -131,6 +134,12 @@ func settle(writable string, options Options, app string) (err error) { if err := os.WriteFile(filepath.Join(mount, ".DS_Store"), store, 0o644); err != nil { return err } + if err := os.Symlink("/Applications", filepath.Join(mount, "Applications")); err != nil { + return err + } + if err := os.Rename(filepath.Join(mount, stagedBundle), filepath.Join(mount, app)); err != nil { + return err + } // Mounting leaves bookkeeping behind that has no use on the next Mac. for _, name := range []string{".fseventsd", ".Trashes"} { _ = os.RemoveAll(filepath.Join(mount, name)) diff --git a/tools/dmg/dmg_test.go b/tools/dmg/dmg_test.go index 3f70e8ba5..610acb76a 100644 --- a/tools/dmg/dmg_test.go +++ b/tools/dmg/dmg_test.go @@ -10,6 +10,7 @@ import ( "os/exec" "path/filepath" "runtime" + "slices" "strings" "testing" ) @@ -125,12 +126,32 @@ func TestBuiltImageHoldsTheLayoutTheFinderReads(t *testing.T) { if err != nil { t.Fatal(err) } + run := runHdiutil + t.Cleanup(func() { runHdiutil = run }) + runHdiutil = func(arguments ...string) ([]byte, error) { + if source := slices.Index(arguments, "-srcfolder"); arguments[0] == "create" && source >= 0 { + entries, err := os.ReadDir(arguments[source+1]) + if err != nil { + t.Fatal(err) + } + for _, entry := range entries { + name := entry.Name() + if strings.EqualFold(filepath.Ext(name), ".app") || strings.EqualFold(name, "Applications") { + t.Fatalf("hdiutil create would expose %q in the root of its temporary volume", name) + } + } + } + return run(arguments...) + } image := filepath.Join(t.TempDir(), "sample.dmg") if err := Build(Options{Bundle: bundle, Volume: "Sample", Image: image, Layout: layout}); err != nil { t.Fatal(err) } mount := t.TempDir() - out, err := exec.Command("hdiutil", "attach", "-plist", "-nobrowse", "-readonly", "-mountpoint", mount, image).CombinedOutput() + // -noautoopen keeps the Finder from opening this read-only mount: -nobrowse + // hides it from the sidebar but does not stop the automatic open that offers + // to install the application. + out, err := exec.Command("hdiutil", "attach", "-plist", "-nobrowse", "-noautoopen", "-readonly", "-mountpoint", mount, image).CombinedOutput() if err != nil { t.Fatalf("attach: %v\n%s", err, out) } @@ -147,6 +168,12 @@ func TestBuiltImageHoldsTheLayoutTheFinderReads(t *testing.T) { if target, err := os.Readlink(filepath.Join(mount, "Applications")); err != nil || target != "/Applications" { t.Fatalf("Applications link = %q, %v", target, err) } + if _, err := os.Stat(filepath.Join(mount, "Sample.app", "Contents", "Info.plist")); err != nil { + t.Fatalf("the bundle is not in the image root: %v", err) + } + if _, err := os.Stat(filepath.Join(mount, stagedBundle)); !os.IsNotExist(err) { + t.Fatalf("the final image still holds the staging bundle: %v", err) + } if _, err := os.Stat(filepath.Join(mount, backgroundFile)); err != nil { t.Fatalf("the background picture is not in the image: %v", err) } From 992a27831d859345c98d49ede1012b589c0cec4b Mon Sep 17 00:00:00 2001 From: MYCF711 <1451895195@qq.com> Date: Mon, 23 Nov 2026 13:03:06 +0800 Subject: [PATCH 55/64] docs(base): explain click delivery for self-painted pages --- base/page.go | 14 ++++++++++++++ gfx/canvas.go | 9 ++++++--- 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/base/page.go b/base/page.go index 7c506b479..0c187f91d 100644 --- a/base/page.go +++ b/base/page.go @@ -753,6 +753,20 @@ func (p *Page) Paint(Surface *gfx.Canvas, Size Size) { // out at the slot's rectangle; a page given no Tree names its controls in the // canvas's. A host that draws a page this way routes its input with Key, // Pointer, Wheel and TextInput; Config does that for a whole window. +// +// Clicks are the part of that routing a host completes itself when it paints and +// presents the canvas on its own. Clicked(id) is true only in an event pass, +// which the painter opens around one paint for it (see Canvas.BeginEventPass). A +// page drawn inside another canvas's paint — Config's painter, or an embedded +// canvas such as Slot.Draw's — already runs in that pass and needs nothing more. +// A host that owns the paint loop delivers a click as the painter does: the +// target taken from Canvas.Hits when the pointer went down, reported at the +// release only while the pointer is still over it and the press was not +// consumed. Paint once between Canvas.BeginEventPass and Canvas.EndEventPass, +// call Canvas.RunAfterPaint, then ask for another paint: the event pass's own +// output is discarded, as the painter discards it, so the frame the user sees is +// the one after the change. Canvas.DeliverPointer runs that same sequence for a +// pointer pass. func (p *Page) Draw(Surface *gfx.Canvas, bounds Rect, View func(C)) { if tree := Surface.Tree(); tree != nil && tree.Len() != 0 { p.init(tree) // a page inside a window names its controls in the window's Tree diff --git a/gfx/canvas.go b/gfx/canvas.go index df33ee881..a927debbf 100644 --- a/gfx/canvas.go +++ b/gfx/canvas.go @@ -2277,8 +2277,9 @@ func (canvas *Canvas) AfterPaint(fn func()) { } // RunAfterPaint runs and clears the functions deferred by AfterPaint, and reports -// whether there were any. The runtime calls it once the event pass has ended; an -// application never does. +// whether there were any. The runtime calls it once the event pass has ended; a +// host that paints and presents its own canvas calls it too, between the event +// pass and the repaint. func (canvas *Canvas) RunAfterPaint() bool { fns := canvas.afterPaint canvas.afterPaint = nil @@ -2303,7 +2304,9 @@ type ClickInfo struct { // BeginEventPass makes the next paint the event pass of a click on id, with what // the runtime knows of it: Clicked(id) is true in the pass, and ClickInfo says how // the click came. Pair it with EndEventPass around that one paint. The runtime does -// this; an application only calls Clicked, ClickModifiers and DoubleClicked. +// this for a window; a host that paints and presents its own canvas does it too, +// and an application otherwise only calls Clicked, ClickModifiers and +// DoubleClicked. func (canvas *Canvas) BeginEventPass(id ID, info ClickInfo) { canvas.clicked, canvas.clickInfo, canvas.eventPass = id, info, true } From 936f6a62104e357312757cdb55cd2f2558fc25f3 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Mon, 23 Nov 2026 13:10:21 +0800 Subject: [PATCH 56/64] docs(readme): name Fcitx 4 in the Chinese overview a6ae841a brought the English README, the conformance table and both input guides in line with the Fcitx 4 client, but README.zh-CN.md kept saying Linux composes through IBus alone. Its overview now matches the English one: IBus, Fcitx5's IBus frontend or Fcitx 4's own protocol. Refs: t8y2/motty#1165 --- README.zh-CN.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.zh-CN.md b/README.zh-CN.md index 4bc4ee18a..0e8023e63 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -68,7 +68,7 @@ Viva 面向 macOS、Windows 和 Linux 上的原生桌面应用,同时把 WebAs - 保留式 Row/Column/Stack/Flex 布局,布局不变时 O(1) 检查。 - 按绘制顺序的指针路由、稳定的键盘焦点和 Tab 遍历。 - macOS 原生 `NSTextInputClient` 集成,支持真实的中文输入法候选组合、按字素编辑和 UTF-16 映射。 -- macOS、Windows 和 Linux 上由焦点驱动的动态原生文本编辑器,带显式的启用/替换/禁用帧更新。macOS 和 Windows 的光标定时器只在可编辑字段获得焦点时存在。Linux 通过 IBus 协议组字(IBus 以及 Fcitx5 的 IBus 前端);XIM 仍未支持。 +- macOS、Windows 和 Linux 上由焦点驱动的动态原生文本编辑器,带显式的启用/替换/禁用帧更新。macOS 和 Windows 的光标定时器只在可编辑字段获得焦点时存在。Linux 通过 IBus 协议(IBus 以及 Fcitx5 的 IBus 前端)或 Fcitx 4 自己的协议组字;XIM 仍未支持。 - 一棵独立的保留式语义无障碍树。 - 直接 CoreText 整形、系统字体回退、GPU 合成的文本纹理,以及有上限的测量缓存。 - 实验性的 Windows shell:Win32 事件、D3D11 保留式渲染、内嵌 DXBC 着色器、DirectWrite 测量,以及有上限的 GDI 标签纹理;原生构建不加载着色器编译器。 From 0f959e5c1fa1e08e3440b7ffd4941313a0fc4c7f Mon Sep 17 00:00:00 2001 From: lijhnihaoa <49388584+lijhnihaoa@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:24:10 +0800 Subject: [PATCH 57/64] windows: preserve IME composition while a menu captures keys --- .github/workflows/ci.yml | 2 +- app/app.go | 15 +- app/driver.go | 38 +++ app/painter.go | 45 ++-- app/run_canvas.go | 7 + internal/platform/contract.go | 3 + .../windows/menu_keyboard_windows_test.go | 201 ++++++++++++++++ .../platform/windows/menu_keys_windows.go | 221 ++++++++++++++++++ internal/platform/windows/shortcut_windows.go | 23 +- .../windows/system_shortcuts_windows.go | 41 ++-- .../windows/text_editing_windows_test.go | 30 +++ internal/platform/windows/window_windows.go | 10 + 12 files changed, 597 insertions(+), 39 deletions(-) create mode 100644 internal/platform/windows/menu_keyboard_windows_test.go create mode 100644 internal/platform/windows/menu_keys_windows.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4845f836e..a3d7e9f8b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -373,7 +373,7 @@ jobs: # native structure ABI tests are here for the same reason: they build only # on Windows. - name: Material contracts and controls (WARP) - run: go test ./internal/platform/windows ./ui ./components ./headless ./app -run 'Test(Backdrop|WindowBackdrop|OpeningMaximized|Notification|TaskbarCreated|CompositionClear|CompositionFallback|CompositionCreation|CustomBackdrop|AcrylicAccent|LegacyAcrylic|RoundedOutline|Translucent|MonospaceFamilies|FontWeights|(The)?MonoWeights|(The)?InterfaceWeights|EveryListedFamilyResolves|EngineReportsTheFontsUnderline|AlwaysOnTop|SaveDialogCheckbox|FileIcon|NativeStructureABI|ResizePresents|WindowSwapChain|LiveResize|FlipWindowResize|RedrawWaits|ContinuousRedraw|NoOpFrame|SameSize|ZeroSize|ResizeTimer|RedrawQueue|NativeRedrawMessage|CompositionSupersededFrame|DragPreview)' -count=1 -v + run: go test ./internal/platform/windows ./ui ./components ./headless ./app -run 'Test(Backdrop|WindowBackdrop|OpeningMaximized|Notification|TaskbarCreated|CompositionClear|CompositionFallback|CompositionCreation|CustomBackdrop|AcrylicAccent|LegacyAcrylic|RoundedOutline|Translucent|MonospaceFamilies|FontWeights|(The)?MonoWeights|(The)?InterfaceWeights|EveryListedFamilyResolves|EngineReportsTheFontsUnderline|AlwaysOnTop|SaveDialogCheckbox|FileIcon|NativeStructureABI|ResizePresents|WindowSwapChain|LiveResize|FlipWindowResize|RedrawWaits|ContinuousRedraw|NoOpFrame|SameSize|ZeroSize|ResizeTimer|RedrawQueue|NativeRedrawMessage|CompositionSupersededFrame|DragPreview|QueuedMenuKeysLeaveTerminalCompositionWithItsOwner|MenuKeysPreserveSystemChordsAndShift|TerminalMenuStopsCapturingWhenWindowLosesFocus|DisabledIMEOffersMenuShortcutDuringComposition)' -count=1 -v - name: Web view partitions run: go test ./internal/platform/windows -run '^Test(APageWithoutAPartitionAsksForNoProfileOfItsOwn|APartitionNamesTheWebView2Profile|AnEphemeralPartitionIsAnOffTheRecordProfile|EphemeralPagesWithoutAPartitionEachGetAProfileOfTheirOwn)$' -count=1 -v - name: Terminal keyboard routing diff --git a/app/app.go b/app/app.go index 1dbbd20af..848967273 100644 --- a/app/app.go +++ b/app/app.go @@ -159,9 +159,22 @@ type Config struct { // so Control+Enter still reaches the field as before. Other named keys // remain OnKey events. On Windows an ordinary (non-terminal, non-Placed) // text field that has focus takes the standard editing and clipboard chords - // first, so the application does not see them there. + // first, so the application does not see them there. While CaptureMenuKeys + // reports true, a captured key is not passed on to text or the input method + // when this callback returns unhandled, and unmodified keys are offered + // during a composition too. // This callback runs on the window thread. OnShortcut func(event gfx.KeyEvent) gfx.EventResult + // CaptureMenuKeys reports whether a transient menu owns the keyboard. + // Windows routes its keys to OnShortcut (printable) or OnKey (named) + // before IME processing, keeping the underlying text input and its + // composition installed until the menu closes. A captured key never + // reaches text or the input method: an unhandled key is dropped, a held + // key repeats with Repeat set, and a named key the runtime cannot express + // is swallowed. The callback runs on the window thread and must not change + // state. It does nothing outside Windows, and if the system refuses the + // keyboard hook the keys are delivered as usual. Also supported by Driver. + CaptureMenuKeys func() bool // OnModifierTap receives a modifier key that was pressed and released on its // own (see gfx.ModifierTapEvent), which OnKey never sees outside a terminal // that asked for the whole keyboard. It is how an application builds diff --git a/app/driver.go b/app/driver.go index 7931d39b8..841640c0e 100644 --- a/app/driver.go +++ b/app/driver.go @@ -65,6 +65,8 @@ type Driver struct { // modifierKeys is the modifier keys KeyDown holds, one bit per // gfx.KeyShiftLeft..ui.KeyMetaRight. modifierKeys uint8 + // A menu press may close the menu. Its repeats and release still belong to it. + menuKeys map[uint32]bool clipboard string notifications []Notification @@ -602,6 +604,16 @@ func driverTyped(key gfx.Key, character string, modifiers gfx.Modifiers) string return character } +func (driver *Driver) menuKey(key gfx.Key, character string, modifiers gfx.Modifiers) error { + event := platform.KeyEvent{Key: key, Modifiers: modifiers, Text: strings.ToLower(character)} + if key == gfx.KeyUnknown { + _, _, err := driver.painter.shortcut(event) + return err + } + _, err := driver.painter.key(event) + return err +} + // KeyDown presses a key and keeps it down until KeyUp, as a person holding it // would. Modifier keys (gfx.KeyShiftLeft and the like) stay held for every pointer, // scroll and key the driver delivers meanwhile, so Shift-click and Ctrl-click @@ -617,6 +629,17 @@ func (driver *Driver) KeyDown(key gfx.Key, character string) error { driver.modifierKeys |= 1 << (key - gfx.KeyShiftLeft) } modifiers := driver.heldModifiers() + code := driverKeyCode(key, character) + if driver.menuKeys[code] { + return nil + } + if driver.painter.menuCapturesKeys() && !key.IsModifier() { + if driver.menuKeys == nil { + driver.menuKeys = make(map[uint32]bool) + } + driver.menuKeys[code] = true + return driver.menuKey(key, character, modifiers) + } if !driver.HoldsKeys() { switch { case key.IsModifier(): @@ -668,6 +691,11 @@ func (driver *Driver) KeyUp(key gfx.Key, character string) error { if key.IsModifier() { driver.modifierKeys &^= 1 << (key - gfx.KeyShiftLeft) } + code := driverKeyCode(key, character) + if driver.menuKeys[code] { + delete(driver.menuKeys, code) + return nil + } if !driver.HoldsKeys() && !(key.IsModifier() && driver.painter.onModifierTap != nil) { return nil } @@ -699,6 +727,7 @@ func (driver *Driver) LoseFocus() error { return err } driver.modifierKeys = 0 + clear(driver.menuKeys) _, err := driver.painter.focusLost() return err } @@ -717,6 +746,9 @@ func (driver *Driver) Key(key gfx.Key, modifiers gfx.Modifiers) error { return err } modifiers |= driver.heldModifiers() + if driver.painter.menuCapturesKeys() { + return driver.menuKey(key, "", modifiers) + } if key == gfx.KeySpace && driver.config.OnShortcut != nil && !driver.painter.nativeText.State.Composing { _, handled, err := driver.painter.shortcut(platform.KeyEvent{Modifiers: modifiers, Text: " "}) if err != nil || handled { @@ -812,6 +844,9 @@ func (driver *Driver) Chord(modifiers gfx.Modifiers, character string) error { if err := driver.Pump(); err != nil { return err } + if driver.painter.menuCapturesKeys() { + return driver.menuKey(gfx.KeyUnknown, character, modifiers) + } if driver.config.OnShortcut != nil && !driver.painter.nativeText.State.Composing { _, handled, err := driver.painter.shortcut(platform.KeyEvent{Modifiers: modifiers, Text: strings.ToLower(character)}) if err != nil || handled { @@ -945,6 +980,9 @@ func (driver *Driver) ShortcutChord(modifiers gfx.Modifiers, character rune) (bo return false, err } shortcut := shortcutText(character) + if driver.painter.menuCapturesKeys() { + return true, driver.menuKey(gfx.KeyUnknown, shortcut, modifiers) + } if driver.editing() && !driver.terminal() { event := platform.KeyEvent{Modifiers: input.Modifiers(modifiers), Text: shortcut} if command, ok := platform.TextEditingCommand(event); ok { diff --git a/app/painter.go b/app/painter.go index 4a0a710fb..c85472b58 100644 --- a/app/painter.go +++ b/app/painter.go @@ -35,9 +35,10 @@ type painter struct { onKey func(gfx.KeyEvent) gfx.EventResult // onDeactivate is the application's, called after a window loses the // activation and the keys that were down are released. - onDeactivate func() gfx.EventResult - onShortcut func(gfx.KeyEvent) gfx.EventResult - onScroll func(gfx.ScrollEvent) gfx.EventResult + onDeactivate func() gfx.EventResult + onShortcut func(gfx.KeyEvent) gfx.EventResult + captureMenuKeys func() bool + onScroll func(gfx.ScrollEvent) gfx.EventResult // onModifierTap and tap recognize a modifier pressed and released on its own. onModifierTap func(gfx.ModifierTapEvent) gfx.EventResult tap input.ModifierTap @@ -155,20 +156,21 @@ func newPainterWithClock(canvas *gfx.Canvas, config *Config, clock func() time.D canvas.SetTree(config.Tree) } painter := &painter{ - paint: config.Paint, - onPointer: config.OnPointer, - onKey: config.OnKey, - onDeactivate: config.OnDeactivate, - onShortcut: config.OnShortcut, - onScroll: config.OnScroll, - onModifierTap: config.OnModifierTap, - onFileDrop: config.OnFileDrop, - onResize: config.OnResize, - textInput: config.TextInput, - canvas: canvas, - size: gfx.Size{Width: float32(config.Width), Height: float32(config.Height)}, - frame: framebuild.New(canvas), - accessibility: make([]platform.AccessibilityNode, 0, len(canvas.Hits())+1), + paint: config.Paint, + onPointer: config.OnPointer, + onKey: config.OnKey, + onDeactivate: config.OnDeactivate, + onShortcut: config.OnShortcut, + captureMenuKeys: config.CaptureMenuKeys, + onScroll: config.OnScroll, + onModifierTap: config.OnModifierTap, + onFileDrop: config.OnFileDrop, + onResize: config.OnResize, + textInput: config.TextInput, + canvas: canvas, + size: gfx.Size{Width: float32(config.Width), Height: float32(config.Height)}, + frame: framebuild.New(canvas), + accessibility: make([]platform.AccessibilityNode, 0, len(canvas.Hits())+1), } painter.onTextEvent = painter.applyTextEvent painter.clipboardText = func() string { @@ -1252,7 +1254,16 @@ func (painter *painter) focusedTextField() (TextInputContext, gfx.TextPlacement, return context, text.Placement, index } +func (painter *painter) menuCapturesKeys() bool { + return painter.captureMenuKeys != nil && painter.captureMenuKeys() +} + func (painter *painter) syncTextInput() platform.TextInputUpdate { + // A menu's focus trap can move UI focus to a row or to no control. + // Publishing that as a new text owner would cancel the IME composition. + if painter.menuCapturesKeys() { + return platform.TextInputUpdate{} + } if painter.textInput == nil { return painter.disableTextInput() } diff --git a/app/run_canvas.go b/app/run_canvas.go index 8d2c9fedc..b6ad48468 100644 --- a/app/run_canvas.go +++ b/app/run_canvas.go @@ -17,6 +17,9 @@ import ( // closes. When config.Paint is set the canvas is repainted on window resizes // and pointer interactions; otherwise the initial canvas stays unchanged. func RunCanvas(config Config, canvas *gfx.Canvas) error { + if runtime.GOOS != "windows" { + config.CaptureMenuKeys = nil + } attendFaults() normalized, err := config.normalize() if err != nil { @@ -196,6 +199,7 @@ func nativeWindowConfig(normalized *Config, painter *painter) (platform.Config, OnKey: keyHandler, ModifierTaps: normalized.OnModifierTap != nil, OnShortcut: painter.shortcutHandler(normalized), + CaptureMenuKeys: normalized.CaptureMenuKeys, OnAccessibility: painter.accessibilityHandler(normalized), AccessibilityTree: func() []platform.AccessibilityNode { return painter.accessibility }, OnFocusLost: painter.focusLostHandler(), @@ -227,6 +231,9 @@ func nativeWindowConfig(normalized *Config, painter *painter) (platform.Config, // The painter is what carries out an event result the window did not receive // from an event handler, such as an application menu action. func prepareNativeWindow(config Config, canvas *gfx.Canvas) (platform.Config, *painter, func(), error) { + if runtime.GOOS != "windows" { + config.CaptureMenuKeys = nil + } normalized, err := config.normalize() if err != nil { return platform.Config{}, nil, nil, err diff --git a/internal/platform/contract.go b/internal/platform/contract.go index 9b569917f..10e939ea6 100644 --- a/internal/platform/contract.go +++ b/internal/platform/contract.go @@ -105,6 +105,9 @@ type Config struct { // every other key is delivered as it was. ModifierTaps bool OnShortcut ShortcutHandler + // CaptureMenuKeys asks Windows to give a foreground menu its keys before + // text services, without ending the focused editor's composition. + CaptureMenuKeys func() bool // OnActivate, when set, runs on the window thread when the top-level // window becomes the active window. Focus moving between views inside the // window does not call it. diff --git a/internal/platform/windows/menu_keyboard_windows_test.go b/internal/platform/windows/menu_keyboard_windows_test.go new file mode 100644 index 000000000..0a6374c98 --- /dev/null +++ b/internal/platform/windows/menu_keyboard_windows_test.go @@ -0,0 +1,201 @@ +package windows + +import ( + "runtime" + "slices" + "strings" + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/input" + "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/text" +) + +// Use the Win32 queue (including TranslateMessage), not direct calls to a +// shortcut handler. Preedit updates stand in for the installed IME so this +// test also runs on a machine without a Pinyin keyboard. +func TestQueuedMenuKeysLeaveTerminalCompositionWithItsOwner(t *testing.T) { + for _, tc := range []struct { + name string + key, sent uintptr + composing bool + fromHook bool + }{ + {"C before composition", 'C', 'C', false, false}, + {"E during composition", 'E', 'E', true, false}, + {"IME-processed C", 'C', vkProcessKey, true, false}, + {"IME-processed E", 'E', vkProcessKey, true, false}, + {"keyboard hook", 'E', 'E', true, true}, + } { + t.Run(tc.name, func(t *testing.T) { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + var menuOpen bool + var shortcuts, marked, inserted []string + var raw []platform.KeyEvent + var state *windowState + var sendPress func() + var originalContext uintptr + contextOf := func() uintptr { + context, _, _ := getInputContext.Call(state.window) + if context != 0 { + releaseInputContext.Call(state.window, context) + } + return context + } + checkOwner := func(stage string) { + if context := contextOf(); context != originalContext || + state.imeDisabled || state.imeComposing != tc.composing || + state.textState.Composing != tc.composing || tc.composing && state.textState.Value != "ni" { + t.Errorf("%s: context %v (was %v), disabled=%v ime=%v state=%+v", + stage, context, originalContext, state.imeDisabled, state.imeComposing, state.textState) + } + } + field := testTextInput("", 10) + field.Terminal, field.KeyReleases = true, true + field.OnEvent = func(event platform.TextEvent) (platform.TextState, error) { + switch event.Kind { + case platform.TextSetMarked: + marked = append(marked, event.Text) + return platform.TextState{Value: event.Text, Composing: true, + Composition: text.Range{End: len([]rune(event.Text))}}, nil + case platform.TextInsert: + inserted = append(inserted, event.Text) + case platform.TextUnmark: + t.Error("the menu cancelled the pending composition") + } + return platform.TextState{}, nil + } + err := RunApplication(func(application platform.Application) error { + opened, err := application.OpenWindow(platform.Config{ + Title: "Menu input owner", Width: 180, Height: 90, + TextInput: &field, DynamicTextInput: true, + CaptureMenuKeys: func() bool { return menuOpen }, + OnPointer: func(event platform.PointerEvent) (platform.Frame, error) { + if event.Kind == platform.PointerDown && event.Button == gfx.PointerButtonSecondary { + menuOpen = true + } + if tc.fromHook && event.Kind == platform.PointerUp && event.Button == gfx.PointerButtonSecondary { + sendPress() + } + return platform.Frame{}, nil + }, + OnShortcut: func(event platform.KeyEvent) (platform.Frame, bool, error) { + shortcuts = append(shortcuts, event.Text) + if menuOpen { + checkOwner("shortcut") + menuOpen = false + return platform.Frame{}, true, nil + } + return platform.Frame{}, false, nil + }, + OnKey: func(event platform.KeyEvent) (platform.Frame, error) { + raw = append(raw, event) + return platform.Frame{}, nil + }, + }) + if err != nil { + return err + } + state = opened.(*nativeWindow).state + originalContext = contextOf() + if tc.composing { + state.applyIMEComposition(imeCompositionMessage{hasPreedit: true, preedit: "ni"}) + } + scan, _, _ := mapVirtualKey.Call(tc.key, 0) + flags := scan<<16 | 1 + postMessage.Call(state.window, wmRightDown, 2, 10<<16|10) + postMessage.Call(state.window, wmRightUp, 0, 10<<16|10) + sendPress = func() { + if tc.fromHook { + // Exercise the installed hook's key route and private message without + // sending hardware input to the user's foreground application. + if !state.shortcutsHeld || shortcutHook.handle == 0 || + !state.takePhysicalMenuKey(wmKeyDown, &kbdLLHook{VkCode: uint32(tc.sent), ScanCode: uint32(scan)}) { + t.Error("the installed hook did not consume the menu press") + } + } else { + postMessage.Call(state.window, wmKeyDown, tc.sent, flags) + } + postMessage.Call(state.window, wmKeyDown, tc.sent, flags|1<<30) + postMessage.Call(state.window, wmKeyUp, tc.sent, flags|1<<30|1<<31) + application.Post(func() { + checkOwner("after key up") + if state.shortcutsHeld || shortcutHook.handle != 0 { + t.Error("the menu kept its keyboard hook after the closing key was released") + } + if tc.composing { + state.applyIMEComposition(imeCompositionMessage{hasPreedit: true, preedit: "nihao"}) + state.applyIMEComposition(imeCompositionMessage{hasResult: true, result: "你好"}) + } + // Close posts a message behind any WM_CHAR generated above. + opened.Close() + }) + } + if !tc.fromHook { + sendPress() + } + return nil + }) + if err != nil { + t.Fatal(err) + } + if menuOpen || !slices.Equal(shortcuts, []string{strings.ToLower(string(rune(tc.key)))}) || len(raw) != 0 { + t.Fatalf("menu open=%v shortcuts=%v raw=%+v", menuOpen, shortcuts, raw) + } + if tc.composing { + if !slices.Equal(marked, []string{"ni", "nihao"}) || !slices.Equal(inserted, []string{"你好"}) { + t.Fatalf("preedit=%q inserted=%q", marked, inserted) + } + } else if len(marked) != 0 || len(inserted) != 0 { + t.Fatalf("menu key entered the text service: preedit=%q inserted=%q", marked, inserted) + } + }) + } +} + +func TestMenuKeysPreserveSystemChordsAndShift(t *testing.T) { + state := windowState{menuKeys: menuKeyboard{open: true}} + for _, key := range []struct { + vk uintptr + mods input.Modifiers + }{ + {vkTab, input.ModifierAlt}, {0x73, input.ModifierAlt}, + {vkEscape, input.ModifierControl}, {'L', input.ModifierMeta}, + } { + if state.takeMenuKey(key.vk, 1, key.mods, false) { + t.Fatalf("captured system chord: %+v", key) + } + } + var mods []input.Modifiers + state.config.OnShortcut = func(event platform.KeyEvent) (platform.Frame, bool, error) { + mods = append(mods, event.Modifiers) + return platform.Frame{}, false, nil + } + if !state.takeMenuKey(0x10, 1, 0, false) || !state.takeMenuKey('E', 1, 0, false) || + !slices.Equal(mods, []input.Modifiers{input.ModifierShift}) { + t.Errorf("Shift+E should remain modified when the menu consumes Shift, got %v", mods) + } +} + +func TestTerminalMenuStopsCapturingWhenWindowLosesFocus(t *testing.T) { + state := &windowState{ready: true, focused: true} + state.config.CaptureMenuKeys = func() bool { return true } + state.menuKeys = menuKeyboard{open: true, held: 1} + state.menuKeys.takenNoScan['E'] = true + // Invoke the native dispatcher's focus-loss path without taking keyboard + // focus away from the user during this test. + const handle = ^uintptr(0) + previous := active.Load() + windowStates.Store(handle, state) + t.Cleanup(func() { + windowStates.Delete(handle) + active.Store(previous) + }) + windowProc(handle, wmKillFocus, 0, 0) + if state.focused || state.shortcutsHeld || state.menuKeys.open || state.menuKeys.held != 0 || + state.takeMenuKey('E', 1<<31, 0, false) || state.takeMenuKey('C', 1, 0, false) { + t.Fatal("the background window still takes menu keys") + } +} diff --git a/internal/platform/windows/menu_keys_windows.go b/internal/platform/windows/menu_keys_windows.go new file mode 100644 index 000000000..c2f6de680 --- /dev/null +++ b/internal/platform/windows/menu_keys_windows.go @@ -0,0 +1,221 @@ +package windows + +import ( + "github.com/vivaui/viva/internal/input" + "github.com/vivaui/viva/internal/platform" +) + +const wmMenuKey = wmUpdateIcon + 1 + +var imeVirtualKey = imm.NewProc("ImmGetVirtualKey") + +type menuKeyboard struct { + open bool + generation uint16 // an already-posted key must not run in a later menu + // taken holds the presses the menu owns until their releases come. A key is + // identified by its scan code, the physical key, because Windows reports the + // release with the layout current at release time: a layout change while a + // key is held would otherwise strand the press and keep the global hook + // installed. A key that carries no scan code is identified by its virtual + // key in takenNoScan instead. + taken [256]bool + takenNoScan [256]bool + // shiftHeld is a Shift press the menu swallowed; a later key sees Shift in + // its modifiers even though the system never saw the press. + shiftHeld bool + shiftScan uint16 + held int +} + +func (keys *menuKeyboard) owns(scan, vk uintptr) bool { + if scan != 0 { + return keys.taken[scan] + } + return keys.takenNoScan[vk] +} + +func (keys *menuKeyboard) own(scan, vk uintptr, take bool) { + if scan != 0 { + keys.taken[scan] = take + return + } + keys.takenNoScan[vk] = take +} + +// The foreground window uses Viva's existing low-level keyboard hook before +// Windows gives the key to any input method. The focused terminal keeps its +// HIMC and edit buffer throughout the menu. +func (state *windowState) syncMenuKeyboard() { + if state.config.CaptureMenuKeys == nil { + return + } + keys := &state.menuKeys + open := state.focused && state.config.CaptureMenuKeys() + if open != keys.open { + keys.generation++ + keys.open = open + state.syncShortcutHook() + } +} + +func (state *windowState) releaseMenuKeyboard() { + gen := state.menuKeys.generation + state.menuKeys = menuKeyboard{generation: gen} +} + +func (state *windowState) takePhysicalMenuKey(kind uintptr, event *kbdLLHook) bool { + vk := uintptr(event.VkCode) + if vk >= 256 { + return false + } + scan := uintptr(event.ScanCode & 0xff) + down := kind == wmKeyDown || kind == wmSysKeyDown + alt := event.Flags&llkhfAltDown != 0 + flags := shortcutKeyLParam(event, down, alt, state.menuKeys.owns(scan, vk)) + // This callback runs before the asynchronous key state reflects *this* + // transition. Other modifiers already held are visible; a Shift press + // eaten by the menu is tracked in taken and added in takeMenuKey below. + var mods input.Modifiers + if asyncKeyDown(0x10) { + mods |= input.ModifierShift + } + if asyncKeyDown(0x11) { + mods |= input.ModifierControl + } + if asyncKeyDown(vkLeftWin) || asyncKeyDown(vkRightWin) { + mods |= input.ModifierMeta + } + if alt { + mods |= input.ModifierAlt + } + if down && !state.menuKeys.owns(scan, vk) && asyncKeyDown(vk) { + flags |= 1 << 30 // was already down when the menu opened + } + return state.takeMenuKey(vk, flags, mods, true) +} + +// takeMenuKey owns a press through its release, even if the first press +// closes the menu. A release from before the menu still belongs to the +// original key owner. The hook only posts a private message; application +// callbacks and repaint run in the ordinary dispatcher. +func (state *windowState) takeMenuKey(vk, flags uintptr, mods input.Modifiers, fromHook bool) bool { + keys := &state.menuKeys + if !keys.open && keys.held == 0 || vk >= 256 { + return false + } + scan := (flags >> 16) & 0xff + if vk == vkProcessKey && !fromHook { + // Some input methods expose VK_PROCESSKEY rather than the letter. + // The scan code still names the original key on this thread's layout. + if scan != 0 { + if original, _, _ := mapVirtualKey.Call(scan, 1 /* MAPVK_VSC_TO_VK */); original > 0 && original < 256 { + vk = original + } + } + if vk == vkProcessKey { + // A virtual-key-only injection can have no scan code. Ask IMM + // before TranslateMessage, while it still knows the original VK. + if original, _, _ := imeVirtualKey.Call(state.window); original > 0 && original < 256 { + vk = original + } + } + } + if flags&(1<<31) != 0 { + if !keys.owns(scan, vk) { + return false + } + keys.own(scan, vk, false) + if keys.shiftHeld && (scan != 0 && keys.shiftScan == uint16(scan) || scan == 0 && isShiftKey(vk)) { + keys.shiftHeld, keys.shiftScan = false, 0 + } + keys.held-- + if keys.held == 0 && !keys.open { + // Unhooking a low-level hook from inside its own callback is not + // safe; let the dispatcher re-sync once this hook returns. + if fromHook { + postMessage.Call(state.window, wmCaptureShortcuts, 0, 0) + } else { + state.syncShortcutHook() + } + } + return true + } + repeat := flags&(1<<30) != 0 + if keys.owns(scan, vk) { + // A later press of a key the menu already owns is its auto-repeat. + // Deliver it with Repeat set so a menu can move like a native one. + if repeat { + state.sendMenuKey(vk, flags, mods, fromHook) + } + return true + } + if !keys.open { + return false + } + if repeat { + // A repeat of a key that was down before the menu opened: its press + // never reached the menu, so there is nothing to repeat. + return true + } + // Leave system chords such as Alt+Tab and Win+L with Windows. Swallow a + // plain Shift press: some input methods use it to toggle language, which + // could end the composition while the menu is up. + mod := modifierKey(vk, flags) + systemChord := mods&input.ModifierMeta != 0 || mods&input.ModifierControl != 0 && vk == vkEscape || + mods&input.ModifierAlt != 0 && (vk == vkTab || vk == vkEscape || vk == 0x73 /* F4 */ || vk == 0x20) + if systemChord || mod != input.KeyUnknown && mod.Modifier() != input.ModifierShift { + return false + } + // AltGr types a character of the layout; it is not a menu chord. Leave the + // key to text and the input method, as offerShortcut does. + if altGrHeld() { + return false + } + if keys.shiftHeld { + mods |= input.ModifierShift + } + keys.own(scan, vk, true) + keys.held++ + if mod != input.KeyUnknown { + if mod.Modifier() == input.ModifierShift { + keys.shiftHeld, keys.shiftScan = true, uint16(scan) + } + return true + } + state.sendMenuKey(vk, flags, mods, fromHook) + return true +} + +// sendMenuKey hands an owned press to the dispatcher. The hook posts it; a key +// message already on the dispatcher's thread delivers it in place. +func (state *windowState) sendMenuKey(vk, flags uintptr, mods input.Modifiers, fromHook bool) { + first := vk | uintptr(mods)<<8 | uintptr(state.menuKeys.generation)<<16 + if fromHook { + postMessage.Call(state.window, wmMenuKey, first, flags) + return + } + state.deliverMenuMessage(first, flags) +} + +func isShiftKey(vk uintptr) bool { + return vk == 0x10 || vk == 0xa0 || vk == 0xa1 +} + +func (state *windowState) deliverMenuMessage(first, flags uintptr) { + if !state.menuKeys.open || uint16(first>>16) != state.menuKeys.generation { + return + } + vk, mods := first&0xff, input.Modifiers((first>>8)&0xff) + event := platform.KeyEvent{Key: normalizedKey(vk), Modifiers: mods, Repeat: flags&(1<<30) != 0} + if event.Key != input.KeyUnknown { + if state.config.OnKey != nil { + state.sendKey(event) + } + } else if state.config.OnShortcut != nil { + event.Text = chordKeyText(vk, flags, mods&input.ModifierShift != 0) + if event.Text != "" { + frame, _, err := state.config.OnShortcut(event) + state.frame(frame, err) + } + } +} diff --git a/internal/platform/windows/shortcut_windows.go b/internal/platform/windows/shortcut_windows.go index 76cf552c8..70b2b507e 100644 --- a/internal/platform/windows/shortcut_windows.go +++ b/internal/platform/windows/shortcut_windows.go @@ -56,7 +56,11 @@ func chordKeyText(first, second uintptr, shift bool) string { // took it (or failed doing it), which ends the message. AltGr is no chord: it // types a character of the layout. func (state *windowState) offerShortcut(first, second uintptr, mods input.Modifiers) bool { - if state.config.OnShortcut == nil || state.imeComposing || altGrHeld() || + // A terminal that disabled the input method takes its keys on the remote + // side; a composition flag left over from the suppressed text input must + // not block its shortcuts. + imeBlocksShortcut := state.imeComposing && !(state.textInput.Terminal && state.textInput.DisableIME) + if state.config.OnShortcut == nil || imeBlocksShortcut || altGrHeld() || (normalizedKey(first) != input.KeyUnknown && normalizedKey(first) != input.KeySpace && normalizedKey(first) != input.KeyEnter) { return false } @@ -89,7 +93,9 @@ func (state *windowState) offerShortcut(first, second uintptr, mods input.Modifi // thread and with the same fault handling as windowProc. Unhandled messages // continue through TranslateMessage and the normal native editor/IME path. func offerQueuedShortcut(event *message) (handled bool) { - if event.Kind != wmKeyDown && event.Kind != wmSysKeyDown { + switch event.Kind { + case wmKeyDown, wmSysKeyDown, wmKeyUp, wmSysKeyUp: + default: return false } value, ok := windowStates.Load(event.Window) @@ -105,5 +111,18 @@ func offerQueuedShortcut(event *message) (handled bool) { } }() active.Store(state) + // Posted keys bypass low-level keyboard hooks. Offer those keys at the same + // boundary, before TranslateMessage can enqueue a character. + flags := event.Second + release := event.Kind == wmKeyUp || event.Kind == wmSysKeyUp + if release { + flags |= 1 << 31 + } + if (state.menuKeys.open || state.menuKeys.held > 0) && state.takeMenuKey(event.First, flags, modifiers(), false) { + return true + } + if release { + return false + } return state.offerShortcut(event.First, event.Second, modifiers()) } diff --git a/internal/platform/windows/system_shortcuts_windows.go b/internal/platform/windows/system_shortcuts_windows.go index 6b318c0d2..f6b597d32 100644 --- a/internal/platform/windows/system_shortcuts_windows.go +++ b/internal/platform/windows/system_shortcuts_windows.go @@ -37,6 +37,11 @@ const ( vkRightWin = 0x5c ) +func asyncKeyDown(vk uintptr) bool { + state, _, _ := getAsyncKeyState.Call(vk) + return state&0x8000 != 0 +} + // kbdLLHook is the KBDLLHOOKSTRUCT a low-level keyboard hook receives. type kbdLLHook struct { VkCode uint32 @@ -74,7 +79,7 @@ func (window *nativeWindow) CaptureSystemShortcuts(capture bool) error { // syncShortcutHook installs the hook while this window wants the shortcuts and has the focus, and // removes it when no window does. It runs on the windows' thread. func (state *windowState) syncShortcutHook() { - want := state.shortcuts.Load() && state.focused && state.window != 0 + want := (state.shortcuts.Load() || state.menuKeys.open || state.menuKeys.held != 0) && state.focused && state.window != 0 if want == state.shortcutsHeld { return } @@ -108,31 +113,31 @@ func shortcutHookProc(code, kind, data uintptr) (result uintptr) { result = 0 } }() - if int32(code) >= 0 { - event := (*kbdLLHook)(pointer(data)) - if shortcutTaken(kind, event) { - return 1 + if code == 0 { + // This hook runs for the desktop. Look at the payload only for + // an opted-in, focused Viva window that is actually foreground. + foreground, _, _ := getForegroundWindow.Call() + if value, found := windowStates.Load(foreground); found { + state := value.(*windowState) + if state.focused && state.shortcutsHeld { + event := (*kbdLLHook)(pointer(data)) + if (state.menuKeys.open || state.menuKeys.held != 0) && state.takePhysicalMenuKey(kind, event) || + state.shortcuts.Load() && state.takeSystemShortcut(kind, event) { + return 1 + } + } } } result, _, _ = callNextHookEx.Call(shortcutHook.handle, code, kind, data) return result } -// shortcutTaken decides whether this key belongs to the system's shortcuts and, if so, hands it +// takeSystemShortcut decides whether this key belongs to the system's shortcuts and, if so, hands it // to the foreground window as an ordinary key message. -func shortcutTaken(kind uintptr, event *kbdLLHook) bool { +func (state *windowState) takeSystemShortcut(kind uintptr, event *kbdLLHook) bool { if event.VkCode > 0xff { return false } - foreground, _, _ := getForegroundWindow.Call() - value, found := windowStates.Load(foreground) - if !found { - return false - } - state := value.(*windowState) - if !state.shortcuts.Load() || !state.focused { - return false - } down := kind == wmKeyDown || kind == wmSysKeyDown vk := event.VkCode if !shortcutKeyBelongsToSystem(vk, down, shortcutHook.taken[vk]) { @@ -150,7 +155,7 @@ func shortcutTaken(kind uintptr, event *kbdLLHook) bool { case !down: message = wmKeyUp } - postMessage.Call(foreground, message, uintptr(vk), shortcutKeyLParam(event, down, altDown, wasTaken)) + postMessage.Call(state.window, message, uintptr(vk), shortcutKeyLParam(event, down, altDown, wasTaken)) return true } @@ -169,7 +174,7 @@ func shortcutKeyBelongsToSystem(vk uint32, down, tookPress bool) bool { } held := func(keys ...uintptr) bool { for _, key := range keys { - if state, _, _ := getAsyncKeyState.Call(key); state&0x8000 != 0 { + if asyncKeyDown(key) { return true } } diff --git a/internal/platform/windows/text_editing_windows_test.go b/internal/platform/windows/text_editing_windows_test.go index b19b43e8f..c39012266 100644 --- a/internal/platform/windows/text_editing_windows_test.go +++ b/internal/platform/windows/text_editing_windows_test.go @@ -78,6 +78,36 @@ func TestNativeEditorOwnsClipboardAndEditingShortcuts(t *testing.T) { } } +func TestDisabledIMEOffersMenuShortcutDuringComposition(t *testing.T) { + state := windowState{ + textEnabled: true, + imeComposing: true, + textInput: platform.TextInput{Terminal: true, DisableIME: true}, + } + calls := 0 + state.config.OnShortcut = func(event platform.KeyEvent) (platform.Frame, bool, error) { + calls++ + if event.Text != "e" { + t.Fatalf("shortcut text = %q, want e", event.Text) + } + return platform.Frame{}, true, nil + } + if !state.offerShortcut('E', 0, 0) { + t.Fatal("disabled IME did not offer the printable key to OnShortcut") + } + if calls != 1 { + t.Fatalf("OnShortcut calls = %d, want 1", calls) + } + + state.textInput.Terminal = false + if state.offerShortcut('E', 0, 0) { + t.Fatal("a non-terminal disabled-IME field bypassed its active composition") + } + if calls != 1 { + t.Fatalf("OnShortcut calls after non-terminal field = %d, want 1", calls) + } +} + func TestNativeEditingKeysUseTheMessageModifiers(t *testing.T) { if value, _, ready := decodeUTF16Character(0, 0x7f); ready || value != "" { t.Fatal("Ctrl+Backspace's DEL character must not be inserted after deleting a word") diff --git a/internal/platform/windows/window_windows.go b/internal/platform/windows/window_windows.go index 4388833c8..dba732464 100644 --- a/internal/platform/windows/window_windows.go +++ b/internal/platform/windows/window_windows.go @@ -121,6 +121,7 @@ type windowState struct { // (any goroutine sets it); shortcutsHeld says this window's share of the hook is installed. shortcuts atomic.Bool shortcutsHeld bool + menuKeys menuKeyboard caretTimer uintptr baseRectangleCount, baseTextLabelCount int textLabels []platform.TextLabel @@ -547,6 +548,7 @@ func windowProc(window, kind, first, second uintptr) (result uintptr) { state.constrainTracking((*minMaxInfo)(pointer(second))) return 0 case wmDestroy: + state.releaseMenuKeyboard() state.shortcuts.Store(false) state.syncShortcutHook() state.destroyed(window) @@ -671,6 +673,7 @@ func windowProc(window, kind, first, second uintptr) (result uintptr) { } case wmSetFocus: state.focused = true + state.syncMenuKeyboard() state.syncShortcutHook() state.setCaretVisible(true) if err := state.restartCaretTimer(); err != nil { @@ -981,6 +984,7 @@ func windowProc(window, kind, first, second uintptr) (result uintptr) { state.endIMEComposition() } state.focused = false + state.releaseMenuKeyboard() state.syncShortcutHook() state.textDragging = false state.stopCaretTimer() @@ -996,6 +1000,9 @@ func windowProc(window, kind, first, second uintptr) (result uintptr) { return 0 } state.modifierTap(first, second, true, modifiers()) + case wmMenuKey: + state.deliverMenuMessage(first, second) + return 0 case wmKeyDown, wmSysKeyDown: if state.textEnabled && state.imeComposing { break // IME candidate keys must not submit or dismiss the surrounding form. @@ -1287,6 +1294,9 @@ func (state *windowState) frameWithTextAndCancel(frame platform.Frame, err error if err == nil && state.window == 0 { return nil } + if err == nil { + state.syncMenuKeyboard() + } views := frame.NativeViews if err == nil { state.applyBackdrop() From 37fd9d704eb05365c0f21588f6bc4e4145845787 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Mon, 23 Nov 2026 13:25:04 +0800 Subject: [PATCH 58/64] fix(android): draw a new surface before it is shown and drop the splash at once The host now implements SurfaceHolder.Callback2.surfaceRedrawNeeded, so the system shows a new surface only after the window is presented on it; this replaces the second present after returning to the app. It also removes the splash screen itself, whose reveal stopped part way over the surface and left the window faded after a fresh install. --- internal/platform/android/android.go | 45 +++++++++++++++---- internal/platform/android/exports_android.go | 8 ++++ .../hostsrc/java/dev/viva/host/Native.java | 6 +++ .../java/dev/viva/host/VivaActivity.java | 14 +++++- 4 files changed, 64 insertions(+), 9 deletions(-) diff --git a/internal/platform/android/android.go b/internal/platform/android/android.go index afb673224..50b718a07 100644 --- a/internal/platform/android/android.go +++ b/internal/platform/android/android.go @@ -48,6 +48,7 @@ const ( eventAccessible // a screen reader asks something of a node eventInsets // the system bars, the cutout or the keyboard cover other edges eventLifecycle // the activity went to the background or came back + eventRedrawNeeded // the system shows the surface once a frame is on it: draw one, then answer ) // event is one thing that happened, small enough to queue by value. @@ -231,6 +232,8 @@ func (application *application) handle(ev event) { application.accessible(ev) case eventLowMemory: application.lifecycle(platform.LifecycleMemoryWarning) + case eventRedrawNeeded: + application.redrawNeeded(ev) case eventLifecycle: application.lifecycle(platform.Lifecycle(ev.action)) case eventInsets: @@ -460,14 +463,6 @@ func (application *application) surfaceChanged(ev event) { } if err := win.resized(true); err != nil { application.fail(err) - return - } - // Seen on the emulator (Android 15): the first frame presented to a surface that has - // just come back is not the one the screen shows, even though it is drawn from the - // scene that holds the application's latest frame; presenting the same scene again - // shows it. The cause below the Vulkan calls is not known (ADR 0095 keeps the note). - if err := win.renderer.Present(); err != nil { - application.fail(err) } default: // The same surface at another size (a rotation, a split screen) or density. @@ -542,6 +537,40 @@ func (application *application) surfaceLost(ev event) { } } +// redrawNeeded draws the window on the surface the system is about to show, and answers +// once the frame is presented (SurfaceHolder.Callback2.surfaceRedrawNeeded): the system +// shows a new surface only after it, so the user never sees one without the window on it. +// The frame is presented even when nothing in it changed, as the surface may hold none. +func (application *application) redrawNeeded(ev event) { + defer close(ev.ack) + win := application.window + if win == nil || win.closed || win.renderer == nil || win.native == nil { + return + } + defer application.guard() + if win.config.OnRedraw != nil { + frame, err := win.config.OnRedraw() + if err == nil { + _, err = win.renderer.Apply(frame) + } + if err == nil { + win.setTextInput(frame.TextInput) + win.syncTree(frame) + } + if err != nil { + application.fail(err) + return + } + } + if err := win.renderer.Present(); err != nil { + application.fail(err) + return + } + if win.config.FramePresented != nil { + win.config.FramePresented() + } +} + // present draws a frame the application answered with. func (win *window) present(frame platform.Frame) error { if win.renderer == nil || win.native == nil || !win.visible { diff --git a/internal/platform/android/exports_android.go b/internal/platform/android/exports_android.go index 5017f2132..016da06d1 100644 --- a/internal/platform/android/exports_android.go +++ b/internal/platform/android/exports_android.go @@ -70,6 +70,14 @@ func Java_dev_viva_host_Native_surfaceDestroyed(env *C.JNIEnv, _ C.jclass) { <-ack } +//export Java_dev_viva_host_Native_redrawNeeded +func Java_dev_viva_host_Native_redrawNeeded(env *C.JNIEnv, _ C.jclass) { + // The system shows the surface when this returns, so the window must be on it by then. + ack := make(chan struct{}) + send(event{kind: eventRedrawNeeded, ack: ack}) + <-ack +} + //export Java_dev_viva_host_Native_touch func Java_dev_viva_host_Native_touch(env *C.JNIEnv, _ C.jclass, action, pointer C.jint, x, y C.jfloat, tool, buttons, modifiers C.jint, uptime C.jlong) { ev := event{kind: eventTouch, action: int32(action), pointer: int32(pointer), x: float32(x), y: float32(y), diff --git a/internal/platform/android/hostsrc/java/dev/viva/host/Native.java b/internal/platform/android/hostsrc/java/dev/viva/host/Native.java index 923734d5b..3f040cb82 100644 --- a/internal/platform/android/hostsrc/java/dev/viva/host/Native.java +++ b/internal/platform/android/hostsrc/java/dev/viva/host/Native.java @@ -20,6 +20,12 @@ private Native() {} /** The surface of the window has a size (and the display a density), or a new one. */ public static native void surfaceChanged(Surface surface, int width, int height, float density); + /** + * The system shows the surface once it has a frame: the program draws the window on it + * and this returns when the frame is presented. + */ + public static native void redrawNeeded(); + /** The surface is going away; the program must stop drawing to it before this returns. */ public static native void surfaceDestroyed(); diff --git a/internal/platform/android/hostsrc/java/dev/viva/host/VivaActivity.java b/internal/platform/android/hostsrc/java/dev/viva/host/VivaActivity.java index af582a9cf..2cb32eaa0 100644 --- a/internal/platform/android/hostsrc/java/dev/viva/host/VivaActivity.java +++ b/internal/platform/android/hostsrc/java/dev/viva/host/VivaActivity.java @@ -19,7 +19,7 @@ * program draws on with Vulkan. Everything the user does reaches the program as * what happened; nothing here lays anything out. */ -public class VivaActivity extends Activity implements SurfaceHolder.Callback { +public class VivaActivity extends Activity implements SurfaceHolder.Callback2 { private VivaView view; @Override @@ -39,6 +39,12 @@ protected void onCreate(Bundle state) { root.setOnApplyWindowInsetsListener(VivaActivity::applyInsets); setContentView(root); barIcons(); // needs the decor view, which setContentView installs + if (Build.VERSION.SDK_INT >= 31) { + // The window is drawn on the surface, which the system's reveal of the splash screen + // does not follow: left to it, the reveal stops part way and leaves the window faded + // until the next layout. The splash screen goes as soon as the window is drawn. + getSplashScreen().setOnExitAnimationListener(splash -> splash.remove()); + } Native.start(getFilesDir().getAbsolutePath(), getCacheDir().getAbsolutePath()); } @@ -142,6 +148,12 @@ public void surfaceChanged(SurfaceHolder holder, int format, int width, int heig Native.surfaceChanged(holder.getSurface(), width, height, getResources().getDisplayMetrics().density); } + /** The system waits for this before it shows the surface, so the program draws on it first. */ + @Override + public void surfaceRedrawNeeded(SurfaceHolder holder) { + Native.redrawNeeded(); + } + @Override public void surfaceDestroyed(SurfaceHolder holder) { Native.surfaceDestroyed(); From 1f0bf0208d1f07a41040f81100a5f5fe8b44f4d3 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Mon, 23 Nov 2026 13:25:04 +0800 Subject: [PATCH 59/64] feat(touch): place the caret with a tap and select a word with a held finger Text fields answer where their text is (index at a point, caret, range rectangles), so a finger places the caret in any field and a long press selects the word under it. Fields take the long press over a tooltip. --- app/painter.go | 56 ++++++++++++-- app/text_geometry.go | 117 ++++++++++++++++++++++++++++++ cmd/viva/templates/tooltip.go.txt | 3 + components/tooltip.go | 3 + examples/touch/main_test.go | 81 +++++++++++++++++++++ 5 files changed, 253 insertions(+), 7 deletions(-) create mode 100644 app/text_geometry.go diff --git a/app/painter.go b/app/painter.go index c85472b58..fd53ee49a 100644 --- a/app/painter.go +++ b/app/painter.go @@ -7,7 +7,6 @@ import ( "slices" "time" "unicode" - "unicode/utf8" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/internal/framebuild" @@ -387,14 +386,23 @@ func (painter *painter) pointerStep(event platform.PointerEvent) (result gfx.Eve // placeCaret puts the caret of the focused text field where a press, or the drag // of one, lands, when the field lays its rows out itself (gfx.TextPlacement): the // platform editor knows one line only and leaves such a field to this. A press -// puts the caret there and a drag extends the selection from it. It reports -// whether the selection changed. +// puts the caret there and a drag extends the selection from it. A finger's press +// places it in any field: the platform editor reads the mouse only, and a phone +// has none. A finger held on a field selects the word under it, as a phone's text +// field does. It reports whether the selection changed. func (painter *painter) placeCaret(event platform.PointerEvent) bool { + touch := event.Device == gfx.PointerTouch switch event.Kind { case platform.PointerDown: painter.placing = false + if painter.focus.Focused().IsZero() || painter.pointer.Hovered() != painter.focus.Focused() { + return false + } + if touch && event.Button == gfx.PointerButtonSecondary { + return painter.selectWordAt(event.X, event.Y) + } primary := event.Button == gfx.PointerButtonPrimary || event.Button == gfx.PointerButtonNone - if !primary || painter.focus.Focused().IsZero() || painter.pointer.Hovered() != painter.focus.Focused() { + if !primary { return false } case platform.PointerMove: @@ -411,11 +419,15 @@ func (painter *painter) placeCaret(event platform.PointerEvent) bool { return false } context, placement, _ := painter.focusedTextField() - if placement == nil || context.ReadOnly || painter.textInput == nil { + if placement == nil && !touch || context.ReadOnly || painter.textInput == nil { painter.placing = false return false } - offset, ok := placement.OffsetAt(gfx.Point{X: event.X, Y: event.Y}) + geometry, ok := painter.focusedTextGeometry() + if !ok { + return false + } + index, ok := geometry.IndexAt(event.X, event.Y) input := painter.textInput(context) if !ok || input == nil { return false @@ -424,7 +436,6 @@ func (painter *painter) placeCaret(event platform.PointerEvent) bool { input.State = TextStateOf(input.Editor) } value := input.State.Value - index := utf8.RuneCountInString(value[:max(0, min(offset, len(value)))]) selection := TextEvent{Kind: TextSetSelection, Selection: TextRange{Start: painter.placeAnchor, End: index}} switch event.Kind { case platform.PointerDown: @@ -455,6 +466,37 @@ func (painter *painter) placeCaret(event platform.PointerEvent) bool { painter.placeUnit, painter.placeUnitRange = 0, text.Range{} } } + return applySelection(input, selection) +} + +// selectWordAt selects the word of the focused field under a window point, or puts the +// caret there when the point is on no word (between words, past the end). +func (painter *painter) selectWordAt(x, y float32) bool { + context, _, _ := painter.focusedTextField() + if context.ReadOnly || painter.textInput == nil { + return false + } + geometry, ok := painter.focusedTextGeometry() + if !ok { + return false + } + index, ok := geometry.IndexAt(x, y) + input := painter.textInput(context) + if !ok || input == nil { + return false + } + if input.Editor != nil { + input.State = TextStateOf(input.Editor) + } + word := text.WordRange(input.State.Value, index) + if context.Secure || rangeIsSpace(input.State.Value, word) { + word = text.Range{Start: index, End: index} + } + return applySelection(input, TextEvent{Kind: TextSetSelection, Selection: TextRange{Start: word.Start, End: word.End}}) +} + +// applySelection gives a selection to the field's editor, or to its handler. +func applySelection(input *TextInput, selection TextEvent) bool { if input.Editor != nil { selection.Apply(input.Editor) input.State = TextStateOf(input.Editor) diff --git a/app/text_geometry.go b/app/text_geometry.go new file mode 100644 index 000000000..763bb16fd --- /dev/null +++ b/app/text_geometry.go @@ -0,0 +1,117 @@ +package app + +import ( + "strings" + "unicode/utf8" + + "github.com/vivaui/viva/gfx" +) + +// textGeometry is where the text of the focused field is on the window: the character +// boundary nearest a point, the caret at a boundary and the rectangles a range covers. The +// framework draws the text, so it is the one that can say; a phone's text interaction (the +// caret a tap places, the word a long press selects, the handles and the magnifier) is +// built on it. Indexes are runes of the field's value, as in TextState. +// +// A field that lays its rows out itself answers through its gfx.TextPlacement. Any other +// is one line, measured the way the components paint it: from the line's origin in the +// declared text bounds, with the canvas's text engine and the field's size, weight and +// alignment. A password field is measured on the bullets it shows, one per rune. +type textGeometry struct { + canvas *gfx.Canvas + placement gfx.TextPlacement + bounds gfx.Rect + style gfx.TextStyle + alignment gfx.Alignment + value string // the field's value + shown string // what is drawn: the value, or one bullet per rune +} + +// focusedTextGeometry is the geometry of the focused field, false when no field with text +// bounds has the focus. +func (painter *painter) focusedTextGeometry() (textGeometry, bool) { + context, placement, _ := painter.focusedTextField() + if context.ID.IsZero() || painter.textInput == nil { + return textGeometry{}, false + } + input := painter.textInput(context) + if input == nil { + return textGeometry{}, false + } + value := input.State.Value + if input.Editor != nil { + value = input.Editor.String() + } + geometry := textGeometry{ + canvas: painter.canvas, placement: placement, bounds: context.TextBounds, + style: gfx.TextStyle{Size: context.FontSize, Weight: context.FontWeight}, + alignment: context.Alignment, value: value, shown: value, + } + if placement == nil && (context.TextBounds.Width <= 0 || context.TextBounds.Height <= 0 || context.FontSize <= 0) { + return textGeometry{}, false + } + if context.Secure { + geometry.shown = strings.Repeat("•", utf8.RuneCountInString(value)) + } + return geometry, true +} + +// IndexAt is the character boundary nearest a window point. +func (geometry textGeometry) IndexAt(x, y float32) (int, bool) { + if geometry.placement != nil { + offset, ok := geometry.placement.OffsetAt(gfx.Point{X: x, Y: y}) + if !ok { + return 0, false + } + return utf8.RuneCountInString(geometry.value[:max(0, min(offset, len(geometry.value)))]), true + } + origin := geometry.origin() + offset := geometry.canvas.TextOffsetAtStyle(geometry.shown, geometry.style, x-origin) + return utf8.RuneCountInString(geometry.shown[:max(0, min(offset, len(geometry.shown)))]), true +} + +// CaretRect is the caret at a boundary, as tall as the line. +func (geometry textGeometry) CaretRect(index int) (gfx.Rect, bool) { + if geometry.placement != nil { + return geometry.placement.CaretBounds() + } + offset := byteOffsetOfRune(geometry.shown, index) + x := geometry.origin() + geometry.canvas.TextCaretStyle(geometry.shown, geometry.style, offset) + return gfx.Rect{X: x, Y: geometry.bounds.Y, Width: 1, Height: geometry.bounds.Height}, true +} + +// RangeRects appends the rectangles the runes [start, end) cover, inside the field. +func (geometry textGeometry) RangeRects(dst []gfx.Rect, start, end int) []gfx.Rect { + if geometry.placement != nil || end <= start { + return dst + } + from, to := byteOffsetOfRune(geometry.shown, start), byteOffsetOfRune(geometry.shown, end) + origin, bounds := geometry.origin(), geometry.bounds + var spans [4]gfx.TextSpan + for _, span := range geometry.canvas.TextSelectionStyle(spans[:0], geometry.shown, geometry.style, from, to) { + left := max(origin+span.X, bounds.X) + right := min(origin+span.X+span.Width, bounds.X+bounds.Width) + if right > left { + dst = append(dst, gfx.Rect{X: left, Y: bounds.Y, Width: right - left, Height: bounds.Height}) + } + } + return dst +} + +func (geometry textGeometry) origin() float32 { + return geometry.canvas.LabelOrigin(geometry.shown, geometry.bounds, geometry.style, geometry.alignment) +} + +// byteOffsetOfRune is the byte offset of rune index in value, clamped to its ends. +func byteOffsetOfRune(value string, index int) int { + if index <= 0 { + return 0 + } + for offset := range value { + if index == 0 { + return offset + } + index-- + } + return len(value) +} diff --git a/cmd/viva/templates/tooltip.go.txt b/cmd/viva/templates/tooltip.go.txt index dd148f606..125bb2926 100644 --- a/cmd/viva/templates/tooltip.go.txt +++ b/cmd/viva/templates/tooltip.go.txt @@ -412,6 +412,9 @@ func (hover *HoverTooltip) holdByFinger(canvas *gfx.Canvas) { return } for _, hit := range canvas.Hits() { + if hit.ID == event.Target && (hit.Role == gfx.RoleTextField || hit.Role == gfx.RoleTerminal) { + return // a held finger selects the text of a field + } if hit.ID == event.Target && !hit.Block && hit.Hint != "" { hover.held, hover.heldSince = event.Target, canvas.Now() return diff --git a/components/tooltip.go b/components/tooltip.go index e4d4cbff7..7d9d52b14 100644 --- a/components/tooltip.go +++ b/components/tooltip.go @@ -412,6 +412,9 @@ func (hover *HoverTooltip) holdByFinger(canvas *gfx.Canvas) { return } for _, hit := range canvas.Hits() { + if hit.ID == event.Target && (hit.Role == gfx.RoleTextField || hit.Role == gfx.RoleTerminal) { + return // a held finger selects the text of a field + } if hit.ID == event.Target && !hit.Block && hit.Hint != "" { hover.held, hover.heldSince = event.Target, canvas.Now() return diff --git a/examples/touch/main_test.go b/examples/touch/main_test.go index cf7fd420d..b68e57b5f 100644 --- a/examples/touch/main_test.go +++ b/examples/touch/main_test.go @@ -2,6 +2,7 @@ package main import ( "runtime" + "strings" "testing" "time" @@ -317,3 +318,83 @@ func TestThePageShowsWhatTheSystemDid(t *testing.T) { t.Fatal("the page does not show the memory warning") } } + +// typeInName focuses the name field with a tap and types value into it. +func typeInName(t *testing.T, driver *app.Driver, value string) gfx.Rect { + t.Helper() + field := control(t, driver, "Name").Bounds + x, y := field.X+field.Width/2, field.Y+field.Height/2 + if err := driver.TouchDown(1, x, y); err != nil { + t.Fatal(err) + } + if err := driver.TouchUp(1, x, y); err != nil { + t.Fatal(err) + } + if err := driver.Type(value); err != nil { + t.Fatal(err) + } + return field +} + +// wordX is the x of the middle of a word of the name field, from where the +// field paints it. +func wordX(t *testing.T, driver *app.Driver, word string) float32 { + t.Helper() + for _, label := range driver.Snapshot().Labels { + if strings.Contains(label.Value, word) { + at := strings.Index(label.Value, word) + share := (float32(at) + float32(len(word))/2) / float32(len(label.Value)) + return label.Bounds.X + label.Bounds.Width*share + } + } + t.Fatalf("no label shows %q", word) + return 0 +} + +// A finger lifted inside the text puts the caret there, as on a phone; typing goes in +// at that point, not at the end. +func TestATapPutsTheCaretWhereTheFingerLifts(t *testing.T) { + skipWithoutTouchRuntime(t) + m := newModel() + driver := open(t, m) + field := typeInName(t, driver, "hello world") + y := field.Y + field.Height/2 + // Between "hello" and " world": where the space starts. + x := wordX(t, driver, "hello") + (wordX(t, driver, "world")-wordX(t, driver, "hello"))/2 - 4 + if err := driver.TouchDown(1, x, y); err != nil { + t.Fatal(err) + } + if err := driver.TouchUp(1, x, y); err != nil { + t.Fatal(err) + } + if err := driver.Type("X"); err != nil { + t.Fatal(err) + } + if got := m.name; got == "hello worldX" || !strings.Contains(got, "X") { + t.Fatalf("typed after a tap mid-text: %q, want the X inside the text", got) + } +} + +// A finger held on a word selects it; typing replaces it. +func TestAHeldFingerSelectsTheWord(t *testing.T) { + skipWithoutTouchRuntime(t) + m := newModel() + driver := open(t, m) + field := typeInName(t, driver, "hello world") + x, y := wordX(t, driver, "world"), field.Y+field.Height/2 + if err := driver.TouchDown(1, x, y); err != nil { + t.Fatal(err) + } + if err := driver.Advance(700 * time.Millisecond); err != nil { + t.Fatal(err) + } + if err := driver.TouchUp(1, x, y); err != nil { + t.Fatal(err) + } + if err := driver.Type("there"); err != nil { + t.Fatal(err) + } + if m.name != "hello there" { + t.Fatalf("name = %q after holding on \"world\" and typing, want %q", m.name, "hello there") + } +} From 302faef44d3fac2d969d8db6a40b819ef4b698d3 Mon Sep 17 00:00:00 2001 From: ccq <76206374+caichangqing1120@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:30:11 +0800 Subject: [PATCH 60/64] fix(components): keep graphemes whole in CodeEditor placement --- cmd/viva/templates/code_editor.go.txt | 4 +- cmd/viva/templates/code_editor_layout.go.txt | 68 ++++++++++++++++---- components/code_editor.go | 4 +- components/code_editor_grapheme_test.go | 63 ++++++++++++++++++ components/code_editor_layout.go | 68 ++++++++++++++++---- 5 files changed, 177 insertions(+), 30 deletions(-) create mode 100644 components/code_editor_grapheme_test.go diff --git a/cmd/viva/templates/code_editor.go.txt b/cmd/viva/templates/code_editor.go.txt index 9db91b741..68da4ce36 100644 --- a/cmd/viva/templates/code_editor.go.txt +++ b/cmd/viva/templates/code_editor.go.txt @@ -430,7 +430,7 @@ func (editor *CodeEditor) Paint(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx. editor.content, editor.cellWidth, editor.lineHeight = content, cellWidth, lineHeight placeholder := value == "" - caret := textareaBoundary(value, snapshot.Caret) + caret := gridCaretStart(value, snapshot.Caret) selectionStart, selectionEnd := textareaRange(value, snapshot.SelectionStart, snapshot.SelectionEnd) selectionRanges := normalizedSpans(editor.spans, value, snapshot.SelectionRanges) editor.spans = selectionRanges @@ -439,7 +439,7 @@ func (editor *CodeEditor) Paint(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx. caretColumn := editor.columnOf(editor.rows[caretRow], caret) editor.extraCarets = editor.extraCarets[:0] for _, extra := range snapshot.ExtraCarets { - offset := textareaBoundary(value, extra.Offset) + offset := gridCaretStart(value, extra.Offset) row := editor.rowOf(offset) editor.extraCarets = append(editor.extraCarets, codeExtraCaret{ row: row, column: editor.columnOf(editor.rows[row], offset) + max(0, extra.VirtualCells), diff --git a/cmd/viva/templates/code_editor_layout.go.txt b/cmd/viva/templates/code_editor_layout.go.txt index e6791b1fc..9b1c6d621 100644 --- a/cmd/viva/templates/code_editor_layout.go.txt +++ b/cmd/viva/templates/code_editor_layout.go.txt @@ -14,9 +14,8 @@ import ( // A CodeEditor lays its text out on a grid of character cells, as a terminal // does: every character is one cell wide, a wide one (CJK, emoji) two, a -// combining mark none, and a tab runs to the next tab stop. Columns, caret -// movement, selections and indentation all become cell arithmetic, which needs no -// text measurement and so costs the same however long the text is. +// combining mark none, and a tab runs to the next tab stop. Row breaks and +// caret hits keep grapheme clusters together within that grid. // codeRow is one row of the grid: the bytes value[start:end] of one logical // line, which a soft wrap splits into several rows. @@ -130,6 +129,35 @@ func decodeAt(value string, at int) (rune, int) { return utf8.DecodeRuneInString(value[at:]) } +// gridCluster returns the byte end and cell width of the grapheme at a +// boundary. The cells still use the same widths as the drawing runs. +func (editor *CodeEditor) gridCluster(value string, at, column int) (end, cells int) { + r, size := decodeAt(value, at) + end = at + size + cells = displayCells(r, column, editor.tabWidth, editor.reps) + if end == len(value) || r < utf8.RuneSelf && value[end] < utf8.RuneSelf { + return end, cells + } + boundary := text.NextGraphemeBoundary(value, at) + for end < boundary { + r, size = decodeAt(value, end) + cells += displayCells(r, column+cells, editor.tabWidth, editor.reps) + end += size + } + return end, cells +} + +func gridCaretStart(value string, offset int) int { + offset = min(max(offset, 0), len(value)) + if offset == 0 || offset == len(value) { + return offset + } + if before, after := value[offset-1], value[offset]; before|after < utf8.RuneSelf && (before != '\r' || after != '\n') { + return offset + } + return gfx.GraphemeStart(value, offset) +} + // fit lays value out in rows of cols cells unless it already is. func (editor *CodeEditor) fit(value string, cols int, wrap bool, tabWidth int) { editor.fitWithFolds(value, cols, wrap, tabWidth, nil) @@ -346,17 +374,20 @@ func (editor *CodeEditor) SoftWrapOffsets(dst []int) []int { // before the word that does not fit, or inside it when it is longer than a row; // the spaces that end a row hang past its right edge instead of wrapping. func (editor *CodeEditor) appendLine(value string, start, end, line int) { + if !editor.wrap { + editor.addRow(value, start, end, start, line, editor.columnBetween(value, start, end)) + return + } rowStart, column := start, 0 wordStart, wordColumn := -1, 0 previousSpace := false for at := start; at < end; { - r, size := decodeAt(value, at) - width := displayCells(r, column, editor.tabWidth, editor.reps) - space := r == ' ' || r == '\t' + next, width := editor.gridCluster(value[:end], at, column) + space := value[at] == ' ' || value[at] == '\t' if !space && previousSpace { wordStart, wordColumn = at, column } - if editor.wrap && !space && column+width > editor.cols && column > 0 { + if !space && column+width > editor.cols && column > 0 { cut, cutColumn := at, column if wordStart > rowStart { cut, cutColumn = wordStart, wordColumn @@ -364,11 +395,16 @@ func (editor *CodeEditor) appendLine(value string, start, end, line int) { editor.addRow(value, rowStart, cut, start, line, cutColumn) rowStart, wordStart = cut, -1 column = editor.columnBetween(value, cut, at) - width = displayCells(r, column, editor.tabWidth, editor.reps) + // Only a tab's width depends on column. Tabs are separate clusters + // and do not wrap here. A wide cluster can still overflow the moved word. + if column > 0 && column+width > editor.cols { + editor.addRow(value, rowStart, at, start, line, column) + rowStart, column = at, 0 + } } previousSpace = space column += width - at += size + at = next } editor.addRow(value, rowStart, end, start, line, column) } @@ -487,14 +523,19 @@ func (walker *columnWalker) column(offset int) int { // distance in cells from the start of the row. func (editor *CodeEditor) offsetAtColumn(row codeRow, x float32) int { column := 0 - for at := int(row.start); at < int(row.end); { - r, size := decodeAt(editor.text, at) - width := displayCells(r, column, editor.tabWidth, editor.reps) + value := editor.text[:row.end] + for at := int(row.start); at < len(value); { + next, width := at+1, 0 + if r := value[at]; r < utf8.RuneSelf && (next == len(value) || value[next] < utf8.RuneSelf) { + width = displayCells(rune(r), column, editor.tabWidth, editor.reps) + } else { + next, width = editor.gridCluster(value, at, column) + } if x < float32(column)+float32(width)/2 { return at } column += width - at += size + at = next } return int(row.end) } @@ -564,6 +605,7 @@ func (editor *CodeEditor) Move(text string, caret int, movement TextareaMovement if !editor.painted || len(editor.rows) == 0 || editor.text != text { return caret } + caret = gridCaretStart(text, caret) index := editor.rowOf(caret) row := editor.rows[index] switch movement { diff --git a/components/code_editor.go b/components/code_editor.go index 1fef7b271..4406fde2e 100644 --- a/components/code_editor.go +++ b/components/code_editor.go @@ -430,7 +430,7 @@ func (editor *CodeEditor) Paint(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx. editor.content, editor.cellWidth, editor.lineHeight = content, cellWidth, lineHeight placeholder := value == "" - caret := textareaBoundary(value, snapshot.Caret) + caret := gridCaretStart(value, snapshot.Caret) selectionStart, selectionEnd := textareaRange(value, snapshot.SelectionStart, snapshot.SelectionEnd) selectionRanges := normalizedSpans(editor.spans, value, snapshot.SelectionRanges) editor.spans = selectionRanges @@ -439,7 +439,7 @@ func (editor *CodeEditor) Paint(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx. caretColumn := editor.columnOf(editor.rows[caretRow], caret) editor.extraCarets = editor.extraCarets[:0] for _, extra := range snapshot.ExtraCarets { - offset := textareaBoundary(value, extra.Offset) + offset := gridCaretStart(value, extra.Offset) row := editor.rowOf(offset) editor.extraCarets = append(editor.extraCarets, codeExtraCaret{ row: row, column: editor.columnOf(editor.rows[row], offset) + max(0, extra.VirtualCells), diff --git a/components/code_editor_grapheme_test.go b/components/code_editor_grapheme_test.go new file mode 100644 index 000000000..8198df1e6 --- /dev/null +++ b/components/code_editor_grapheme_test.go @@ -0,0 +1,63 @@ +package components + +import ( + "slices" + "testing" + + "github.com/vivaui/viva/gfx" +) + +func TestCodeEditorClickAndMoveKeepGraphemesWhole(t *testing.T) { + const joined = "\U0001f469\u200d\U0001f4bb" + const value = "abc\n" + joined + "x" + f := newCodeFixture(value) + f.paint() + cell, _, line := f.cell() + const start, end = len("abc\n"), len("abc\n" + joined) + for _, check := range []struct { + column float32 + offset int + }{{1.75, start}, {3.25, end}} { + point := gfx.Point{X: f.editor.content.X + check.column*cell, Y: f.editor.content.Y + 1.5*line} + if got, ok := f.editor.OffsetAt(point); !ok || got != check.offset { + t.Errorf("click at column %.2f returned %d, %t; want offset %d", check.column, got, ok, check.offset) + } + } + if got := f.editor.Move(value, 2, TextareaMoveDown); got != start { + t.Errorf("Down from column 2 landed at %d; want offset %d", got, start) + } + f.snapshot.Caret = start + len("\U0001f469") + f.paint() + if caret, ok := f.editor.CaretBounds(); !ok || !near(caret.X, f.editor.content.X) { + t.Errorf("a caret inside the sequence was painted at %+v, %t; want the start of the cluster", caret, ok) + } +} + +func TestCodeEditorSoftWrapKeepsGraphemesWhole(t *testing.T) { + const joined = "\U0001f469\u200d\U0001f4bb" + t.Run("after a wrapped word", func(t *testing.T) { + value := "x ab" + joined + "c" + f := newCodeFixture(value) + f.editor.fit(value, 4, true, 4) + if got, want := f.rowTexts(), []string{"x ", "ab", joined, "c"}; !slices.Equal(got, want) { + t.Errorf("rows %q; want %q", got, want) + } + }) + const value = "a" + joined + "b" + f := newCodeFixture(value) + f.snapshot.Wrap = true + f.bounds.Width = f.widthFor(3) + f.paint() + if got, want := f.rowTexts(), []string{"a", joined, "b"}; !slices.Equal(got, want) { + t.Errorf("painted rows %q; want %q", got, want) + } + want := []int{1, 1 + len(joined)} + if got := f.editor.SoftWrapOffsets(nil); !slices.Equal(got, want) { + t.Errorf("live wrap offsets %v; want %v", got, want) + } + f.snapshot.Wrap = false + f.paint() + if got := f.editor.SoftWrapOffsets(nil); !slices.Equal(got, want) { + t.Errorf("preview wrap offsets %v; want %v", got, want) + } +} diff --git a/components/code_editor_layout.go b/components/code_editor_layout.go index a0b9de986..ec1658250 100644 --- a/components/code_editor_layout.go +++ b/components/code_editor_layout.go @@ -14,9 +14,8 @@ import ( // A CodeEditor lays its text out on a grid of character cells, as a terminal // does: every character is one cell wide, a wide one (CJK, emoji) two, a -// combining mark none, and a tab runs to the next tab stop. Columns, caret -// movement, selections and indentation all become cell arithmetic, which needs no -// text measurement and so costs the same however long the text is. +// combining mark none, and a tab runs to the next tab stop. Row breaks and +// caret hits keep grapheme clusters together within that grid. // codeRow is one row of the grid: the bytes value[start:end] of one logical // line, which a soft wrap splits into several rows. @@ -130,6 +129,35 @@ func decodeAt(value string, at int) (rune, int) { return utf8.DecodeRuneInString(value[at:]) } +// gridCluster returns the byte end and cell width of the grapheme at a +// boundary. The cells still use the same widths as the drawing runs. +func (editor *CodeEditor) gridCluster(value string, at, column int) (end, cells int) { + r, size := decodeAt(value, at) + end = at + size + cells = displayCells(r, column, editor.tabWidth, editor.reps) + if end == len(value) || r < utf8.RuneSelf && value[end] < utf8.RuneSelf { + return end, cells + } + boundary := text.NextGraphemeBoundary(value, at) + for end < boundary { + r, size = decodeAt(value, end) + cells += displayCells(r, column+cells, editor.tabWidth, editor.reps) + end += size + } + return end, cells +} + +func gridCaretStart(value string, offset int) int { + offset = min(max(offset, 0), len(value)) + if offset == 0 || offset == len(value) { + return offset + } + if before, after := value[offset-1], value[offset]; before|after < utf8.RuneSelf && (before != '\r' || after != '\n') { + return offset + } + return gfx.GraphemeStart(value, offset) +} + // fit lays value out in rows of cols cells unless it already is. func (editor *CodeEditor) fit(value string, cols int, wrap bool, tabWidth int) { editor.fitWithFolds(value, cols, wrap, tabWidth, nil) @@ -346,17 +374,20 @@ func (editor *CodeEditor) SoftWrapOffsets(dst []int) []int { // before the word that does not fit, or inside it when it is longer than a row; // the spaces that end a row hang past its right edge instead of wrapping. func (editor *CodeEditor) appendLine(value string, start, end, line int) { + if !editor.wrap { + editor.addRow(value, start, end, start, line, editor.columnBetween(value, start, end)) + return + } rowStart, column := start, 0 wordStart, wordColumn := -1, 0 previousSpace := false for at := start; at < end; { - r, size := decodeAt(value, at) - width := displayCells(r, column, editor.tabWidth, editor.reps) - space := r == ' ' || r == '\t' + next, width := editor.gridCluster(value[:end], at, column) + space := value[at] == ' ' || value[at] == '\t' if !space && previousSpace { wordStart, wordColumn = at, column } - if editor.wrap && !space && column+width > editor.cols && column > 0 { + if !space && column+width > editor.cols && column > 0 { cut, cutColumn := at, column if wordStart > rowStart { cut, cutColumn = wordStart, wordColumn @@ -364,11 +395,16 @@ func (editor *CodeEditor) appendLine(value string, start, end, line int) { editor.addRow(value, rowStart, cut, start, line, cutColumn) rowStart, wordStart = cut, -1 column = editor.columnBetween(value, cut, at) - width = displayCells(r, column, editor.tabWidth, editor.reps) + // Only a tab's width depends on column. Tabs are separate clusters + // and do not wrap here. A wide cluster can still overflow the moved word. + if column > 0 && column+width > editor.cols { + editor.addRow(value, rowStart, at, start, line, column) + rowStart, column = at, 0 + } } previousSpace = space column += width - at += size + at = next } editor.addRow(value, rowStart, end, start, line, column) } @@ -487,14 +523,19 @@ func (walker *columnWalker) column(offset int) int { // distance in cells from the start of the row. func (editor *CodeEditor) offsetAtColumn(row codeRow, x float32) int { column := 0 - for at := int(row.start); at < int(row.end); { - r, size := decodeAt(editor.text, at) - width := displayCells(r, column, editor.tabWidth, editor.reps) + value := editor.text[:row.end] + for at := int(row.start); at < len(value); { + next, width := at+1, 0 + if r := value[at]; r < utf8.RuneSelf && (next == len(value) || value[next] < utf8.RuneSelf) { + width = displayCells(rune(r), column, editor.tabWidth, editor.reps) + } else { + next, width = editor.gridCluster(value, at, column) + } if x < float32(column)+float32(width)/2 { return at } column += width - at += size + at = next } return int(row.end) } @@ -564,6 +605,7 @@ func (editor *CodeEditor) Move(text string, caret int, movement TextareaMovement if !editor.painted || len(editor.rows) == 0 || editor.text != text { return caret } + caret = gridCaretStart(text, caret) index := editor.rowOf(caret) row := editor.rows[index] switch movement { From eccbe2e99df309e852c5909a4247ee74329cc655 Mon Sep 17 00:00:00 2001 From: ccq <76206374+caichangqing1120@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:30:52 +0800 Subject: [PATCH 61/64] feat(gfx): keep the visual caret edge of a text hit --- gfx/canvas.go | 17 ++++ gfx/text_engine.go | 19 +++++ gfx/text_hit_test.go | 29 +++++++ internal/platform/darwin/core_text.m | 7 ++ internal/platform/darwin/native.h | 5 ++ internal/platform/darwin/text_engine.go | 15 ++++ internal/platform/darwin/text_engine_test.go | 28 +++++++ internal/textmetrics/bidi.go | 87 +++++++++++++++++--- internal/textmetrics/bidi_test.go | 45 ++++++++++ 9 files changed, 242 insertions(+), 10 deletions(-) create mode 100644 gfx/text_hit_test.go diff --git a/gfx/canvas.go b/gfx/canvas.go index a927debbf..5322050bb 100644 --- a/gfx/canvas.go +++ b/gfx/canvas.go @@ -1548,6 +1548,23 @@ func (canvas *Canvas) TextOffsetAt(value string, size, weight, x float32) int { return textmetrics.OffsetAt(value, size, weight, x) } +// TextHitAt reports a byte boundary together with the caret position picked by +// a click. Keep X as well as Offset when a mixed-direction line can draw the +// same boundary at either end of a run. A custom measurer or engine without +// TextHitEngine supplies its ordinary caret position. +func (canvas *Canvas) TextHitAt(value string, size, weight, x float32) TextHit { + if canvas.measurer == nil { + if engine, ok := canvas.engine.(TextHitEngine); ok { + return engine.HitAt(value, size, weight, x) + } + if canvas.engine == nil { + return referenceEngine{}.HitAt(value, size, weight, x) + } + } + offset := canvas.TextOffsetAt(value, size, weight, x) + return TextHit{Offset: offset, X: canvas.TextCaret(value, size, weight, offset)} +} + // TextOffsetAtStyle is TextOffsetAt for a style that may be italic or fixed-pitch (see // TextWidthStyle). func (canvas *Canvas) TextOffsetAtStyle(value string, style TextStyle, x float32) int { diff --git a/gfx/text_engine.go b/gfx/text_engine.go index e6ab4f953..c748acee3 100644 --- a/gfx/text_engine.go +++ b/gfx/text_engine.go @@ -32,6 +32,21 @@ type TextEngine interface { OffsetAt(value string, size, weight, x float32) int } +// TextHit identifies a byte boundary and its visual position in logical pixels +// from the left of the line. A mixed-direction boundary can have two positions. +type TextHit struct { + Offset int + X float32 +} + +// TextHitEngine is an optional capability for engines that can report which +// visual position of a boundary was hit. Offset follows the TextEngine byte +// offset contract. X is the caret position nearest the click on the side hit. +type TextHitEngine interface { + TextEngine + HitAt(value string, size, weight, x float32) TextHit +} + // TextRasterizer is an optional TextEngine capability that draws one shaped // proportional line into a transparent premultiplied BGRA bitmap at scale. // Width and height are bitmap pixels. The same platform font, fallback and @@ -249,6 +264,10 @@ func (referenceEngine) OffsetAt(value string, size, weight, x float32) int { return textmetrics.OffsetAt(value, size, weight, x) } +func (referenceEngine) HitAt(value string, size, weight, x float32) TextHit { + return TextHit(textmetrics.HitAt(value, size, weight, x)) +} + // offsetAtByPrefix is the character boundary of value whose prefix width is nearest to // x: OffsetAt for a measurer that only knows widths. Boundaries are those of grapheme // clusters, so a click never lands between a letter and its marks. diff --git a/gfx/text_hit_test.go b/gfx/text_hit_test.go new file mode 100644 index 000000000..39595a99f --- /dev/null +++ b/gfx/text_hit_test.go @@ -0,0 +1,29 @@ +package gfx + +import ( + "math" + "testing" +) + +func TestTextHitAtKeepsTwoPositionsForOneOffset(t *testing.T) { + const prefix, rtl, suffix = "ab ", "\u05d0\u05b7\u05d1", " cd" + const value = prefix + rtl + suffix + const size = 20 + for _, engine := range []TextEngine{nil, ReferenceTextEngine()} { + var canvas Canvas + canvas.SetTextEngine(engine) + left := canvas.TextWidth(prefix, size) + right := canvas.TextWidth(prefix+rtl, size) + first := canvas.TextHitAt(value, size, 0, left-0.5) + second := canvas.TextHitAt(value, size, 0, right-0.5) + if first.Offset != len(prefix) || second.Offset != first.Offset { + t.Fatalf("engine %T: mixed hits %+v and %+v; both should name byte %d", engine, first, second, len(prefix)) + } + if math.Abs(float64(first.X-left)) > 0.01 || math.Abs(float64(second.X-right)) > 0.01 { + t.Errorf("engine %T: mixed hits %+v and %+v; want positions %g and %g", engine, first, second, left, right) + } + if got := canvas.TextOffsetAt(value, size, 0, right-0.5); got == second.Offset { + t.Errorf("engine %T: primary-only offset unexpectedly picked the alternate edge", engine) + } + } +} diff --git a/internal/platform/darwin/core_text.m b/internal/platform/darwin/core_text.m index 01c1aa3e7..d3bf22a9f 100644 --- a/internal/platform/darwin/core_text.m +++ b/internal/platform/darwin/core_text.m @@ -243,6 +243,13 @@ size_t viva_text_line_index_at(const viva_text_line *line, double x) { return (size_t)index; } +viva_text_hit viva_text_line_hit_at(const viva_text_line *line, double x) { + size_t index = viva_text_line_index_at(line, x); + CGFloat alternate = 0; + CGFloat primary = CTLineGetOffsetForStringIndex((CTLineRef)line->line, (CFIndex)index, &alternate); + return (viva_text_hit){index, fabs(x - alternate) < fabs(x - primary) ? alternate : primary}; +} + // The most extents viva_text_line_selection tells apart before it folds the rest into the // last: a selection crossing a change of direction more often than this is not text. #define VIVA_SELECTION_PIECES 32 diff --git a/internal/platform/darwin/native.h b/internal/platform/darwin/native.h index 0c8d258d3..25cfd55cc 100644 --- a/internal/platform/darwin/native.h +++ b/internal/platform/darwin/native.h @@ -550,6 +550,11 @@ void viva_text_line_release(viva_text_line *line); // caret there, and viva_text_line_index_at the cluster boundary nearest x. double viva_text_line_caret(const viva_text_line *line, size_t offset); size_t viva_text_line_index_at(const viva_text_line *line, double x); +typedef struct { + size_t index; + double x; +} viva_text_hit; +viva_text_hit viva_text_line_hit_at(const viva_text_line *line, double x); // viva_text_line_selection writes the extents of [start, end) as (x, width) pairs, left // to right, and returns how many it wrote (at most capacity): one, or several where the // selection crosses a change of direction. diff --git a/internal/platform/darwin/text_engine.go b/internal/platform/darwin/text_engine.go index c18a7294a..5341211ed 100644 --- a/internal/platform/darwin/text_engine.go +++ b/internal/platform/darwin/text_engine.go @@ -326,6 +326,21 @@ func (engine *TextEngine) OffsetAt(value string, size, weight, x float32) int { return engine.OffsetAtStyle(value, size, weight, false, x) } +// HitAt reports the selected CoreText boundary and the caret edge nearest x. +func (engine *TextEngine) HitAt(value string, size, weight, x float32) gfx.TextHit { + if value == "" || size <= 0 { + return gfx.TextHit{} + } + engine.mutex.Lock() + defer engine.mutex.Unlock() + line := engine.line(value, size, weight) + if line == nil { + return gfx.TextHit{} + } + hit := C.viva_text_line_hit_at(line, C.double(x)) + return gfx.TextHit{Offset: byteOffset(value, int(hit.index)), X: float32(hit.x)} +} + func (engine *TextEngine) OffsetAtStyle(value string, size, weight float32, italic bool, x float32) int { if value == "" || size <= 0 { return 0 diff --git a/internal/platform/darwin/text_engine_test.go b/internal/platform/darwin/text_engine_test.go index 248c95a67..8054316b9 100644 --- a/internal/platform/darwin/text_engine_test.go +++ b/internal/platform/darwin/text_engine_test.go @@ -13,6 +13,34 @@ func TestTextEnginePassesTheContract(t *testing.T) { textenginetest.Run(t, SharedTextEngine()) } +func TestCoreTextHitRetainsTheMixedDirectionEdge(t *testing.T) { + const prefix, first, second, suffix = "a\U00010437 ", "\u05d0\u05b7", "\u05d1", " cd" + const value, size = prefix + first + second + suffix, 20 + engine := SharedTextEngine() + var canvas gfx.Canvas + canvas.SetTextEngine(engine) + span := func(from, to int) gfx.TextSpan { + t.Helper() + spans := engine.Selection(nil, value, size, 0, from, to) + if len(spans) != 1 || spans[0].Width <= 0 { + t.Fatalf("range [%d,%d) spans %v", from, to, spans) + } + return spans[0] + } + start, middle, end := len(prefix), len(prefix+first), len(prefix+first+second) + left := span(start-1, start) + right := span(start, middle) + for _, check := range []struct{ x, edge float32 }{ + {left.X + left.Width*0.9, left.X + left.Width}, + {right.X + right.Width*0.9, right.X + right.Width}, + } { + hit := canvas.TextHitAt(value, size, 0, check.x) + if hit.Offset != start || hit.X-check.edge > 0.02 || check.edge-hit.X > 0.02 { + t.Errorf("clicked %g: hit %+v; want byte %d at %g (RTL ends at byte %d)", check.x, hit, start, check.edge, end) + } + } +} + func TestTextEngineRasterizesProportionalText(t *testing.T) { engine := SharedTextEngine() textenginetest.TransparentColorGlyphs(t, engine) diff --git a/internal/textmetrics/bidi.go b/internal/textmetrics/bidi.go index 0a52920a4..f4031f98d 100644 --- a/internal/textmetrics/bidi.go +++ b/internal/textmetrics/bidi.go @@ -237,16 +237,20 @@ func (b *bidiLine) edge(value string, offset int) int { x := 0 for _, run := range b.runs { if run.Start == use.Start && run.End == use.End { - if run.Level&1 != 0 { - return x + units(value[offset:run.End], b.weight) - } - return x + units(value[run.Start:offset], b.weight) + return x + b.runEdge(value, run, offset) } x += units(value[run.Start:run.End], b.weight) } return x } +func (b *bidiLine) runEdge(value string, run bidi.Run, offset int) int { + if run.Level&1 != 0 { + return units(value[offset:run.End], b.weight) + } + return units(value[run.Start:offset], b.weight) +} + // runAt is the run that holds the character at byte offset (the runs are in visual order); // offsets before the line belong to its first run in logical order, offsets after it to its // last. @@ -327,23 +331,86 @@ func OffsetAt(value string, size, weight float32, x float32) int { if !bidi.NeedsBidi(value) { return NearestBoundary(value, x, func(offset int) float32 { return Width(value[:offset], size, weight) }) } - // A line read in more than one direction has carets that do not grow with the - // offset: every boundary is measured, against one resolution of the line. + b := bidiPool.Get().(*bidiLine) + b.resolve(value, weightIndex(weight)) + hit := b.nearestPrimary(value, size, x) + b.release() + return hit.Offset +} + +// CaretHit is both the source offset and the visual position of a text hit. +// At a direction change there may be two positions for the same byte offset. +type CaretHit struct { + Offset int + X float32 +} + +// HitAt places the caret within the directional run under x. This keeps the +// two sides of a direction change distinct even when they share a visual edge. +func HitAt(value string, size, weight float32, x float32) CaretHit { + if !bidi.NeedsBidi(value) { + caret := func(offset int) float32 { return Width(value[:offset], size, weight) } + offset := NearestBoundary(value, x, caret) + return CaretHit{Offset: offset, X: caret(offset)} + } + return hitBidi(value, size, weight, x) +} + +func hitBidi(value string, size, weight float32, x float32) CaretHit { table := weightIndex(weight) b := bidiPool.Get().(*bidiLine) b.resolve(value, table) - best, bestDistance := 0, float32(-1) + px := func(at int) float32 { return float32(at) * size / unitsPerEm } + left := 0 + for _, run := range b.runs { + width := units(value[run.Start:run.End], table) + // A click exactly on a run's edge belongs to the run whose right edge + // it is, and the first and last runs keep the line's own ends: without + // that a click on the leftmost or rightmost pixel falls through to the + // inner caret of the nearest run. + if x >= px(left) && x <= px(left+width) { + best, distance := CaretHit{}, float32(-1) + at := snap(value, run.Start) + if at < run.Start { + at = grapheme.Next(value, at) + } + for ; at <= run.End; at = grapheme.Next(value, at) { + pos := px(left + b.runEdge(value, run, at)) + if gap := absf(pos - x); distance < 0 || gap < distance { + best, distance = CaretHit{Offset: at, X: pos}, gap + } + if at == run.End { + break + } + } + if distance >= 0 { + b.release() + return best + } + break + } + left += width + } + hit := b.nearestPrimary(value, size, x) + b.release() + return hit +} + +// At the exact meeting point of two runs, use the paragraph's usual caret +// affinity. This also handles clicks outside the visible advances. +func (b *bidiLine) nearestPrimary(value string, size, x float32) CaretHit { + best, bestDistance := CaretHit{}, float32(-1) for offset := 0; ; { - d := absf(float32(b.edge(value, offset))*size/unitsPerEm - x) + pos := float32(b.edge(value, offset)) * size / unitsPerEm + d := absf(pos - x) if bestDistance < 0 || d < bestDistance { - best, bestDistance = offset, d + best, bestDistance = CaretHit{Offset: offset, X: pos}, d } if offset >= len(value) { break } offset = grapheme.Next(value, offset) } - b.release() return best } diff --git a/internal/textmetrics/bidi_test.go b/internal/textmetrics/bidi_test.go index 639f1b9d1..575ac9952 100644 --- a/internal/textmetrics/bidi_test.go +++ b/internal/textmetrics/bidi_test.go @@ -179,6 +179,51 @@ func TestOffsetAtInvertsCaret(t *testing.T) { } } +func TestHitAtUsesTheSideOfADirectionBoundary(t *testing.T) { + const left, first, second, right = "ab ", "\u05d0\u05b7", "\u05d1", " cd" + const value = left + first + second + right + const size = 20 + lo, hi := len(left), len(left+first+second) + xLeft := Width(left, size, 0) + xRight := Width(left+first+second, size, 0) + for _, check := range []struct { + name string + x float32 + want int + edge float32 + }{ + {"Latin at the left edge", xLeft - 0.5, lo, xLeft}, + {"Hebrew at the left edge", xLeft + 0.5, hi, xLeft}, + {"Hebrew at the right edge", xRight - 0.5, lo, xRight}, + {"Latin at the right edge", xRight + 0.5, hi, xRight}, + } { + t.Run(check.name, func(t *testing.T) { + if got := HitAt(value, size, 0, check.x); got.Offset != check.want || abs(got.X-check.edge) > 0.01 { + t.Errorf("at x=%g: hit %+v, want byte %d at %g", check.x, got, check.want, check.edge) + } + }) + } +} + +func TestHitAtKeepsTheLineEdges(t *testing.T) { + const value = "ab אַב cd" + const size = 20 + width := Width(value, size, 0) + for _, check := range []struct { + name string + edge, inside float32 + }{ + {"left", 0, 0.0001}, + {"right", width, width - 0.0001}, + } { + t.Run(check.name, func(t *testing.T) { + if got, want := HitAt(value, size, 0, check.edge), HitAt(value, size, 0, check.inside); got != want { + t.Fatalf("click on the %s edge at %g gave %+v, just inside gave %+v", check.name, check.edge, got, want) + } + }) + } +} + func nextRuneOffset(value string, offset int) int { if offset >= len(value) { return offset + 1 From e320ba5d5d8169db1636f449f2138bd23ad14dc8 Mon Sep 17 00:00:00 2001 From: ccq <76206374+caichangqing1120@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:32:09 +0800 Subject: [PATCH 62/64] feat(components): keep fitted bidi caret placement in CodeEditor --- cmd/viva/components_gen.go | 4 +- cmd/viva/templates/code_editor.go.txt | 62 ++++- cmd/viva/templates/code_editor_layout.go.txt | 35 ++- cmd/viva/templates/code_editor_shaped.go.txt | 252 ++++++++++++++++++ components/code_editor.go | 64 ++++- components/code_editor_layout.go | 35 ++- components/code_editor_shaped.go | 262 +++++++++++++++++++ components/code_editor_shaped_darwin_test.go | 49 ++++ components/code_editor_shaped_test.go | 111 ++++++++ components/doc_test.go | 1 + gfx/text_engine.go | 27 ++ internal/platform/darwin/core_text.m | 27 ++ internal/platform/darwin/native.h | 6 + internal/platform/darwin/text_engine.go | 33 +++ tools/docs/catalog.go | 2 +- 15 files changed, 938 insertions(+), 32 deletions(-) create mode 100644 cmd/viva/templates/code_editor_shaped.go.txt create mode 100644 components/code_editor_shaped.go create mode 100644 components/code_editor_shaped_darwin_test.go create mode 100644 components/code_editor_shaped_test.go diff --git a/cmd/viva/components_gen.go b/cmd/viva/components_gen.go index 3da3a6345..ec28798b8 100644 --- a/cmd/viva/components_gen.go +++ b/cmd/viva/components_gen.go @@ -31,6 +31,7 @@ var componentFiles = map[string]string{ "code-editor": "code_editor.go.txt", "code-editor-decorations": "code_editor_decorations.go.txt", "code-editor-layout": "code_editor_layout.go.txt", + "code-editor-shaped": "code_editor_shaped.go.txt", "code-merge": "code_merge.go.txt", "collapsible": "collapsible.go.txt", "color-picker": "color_picker.go.txt", @@ -123,9 +124,10 @@ var componentRequires = map[string][]string{ "checkbox": {"button"}, "code-diff": {"code-diff-model", "code-editor", "code-editor-layout", "scroll-area", "textarea"}, "code-diff-model": {"code-diff-inline"}, - "code-editor": {"caret-blink", "code-editor-decorations", "code-editor-layout", "input", "scroll-area", "textarea", "tree"}, + "code-editor": {"caret-blink", "code-editor-decorations", "code-editor-layout", "code-editor-shaped", "input", "scroll-area", "textarea", "tree"}, "code-editor-decorations": {"code-editor", "code-editor-layout"}, "code-editor-layout": {"code-editor", "textarea"}, + "code-editor-shaped": {"code-editor", "code-editor-layout"}, "code-merge": {"code-diff", "code-diff-model", "code-editor", "code-editor-layout", "scroll-area"}, "color-picker": {"button", "input", "popover"}, "column-resize": {"button"}, diff --git a/cmd/viva/templates/code_editor.go.txt b/cmd/viva/templates/code_editor.go.txt index 68da4ce36..60ac391c7 100644 --- a/cmd/viva/templates/code_editor.go.txt +++ b/cmd/viva/templates/code_editor.go.txt @@ -34,6 +34,8 @@ type CodeEditorCaret struct { type codeExtraCaret struct { row, column int + x float32 + shaped bool } // CodeEditorGutterMarker decorates one zero-based logical line with a dot in the @@ -137,6 +139,11 @@ type CodeEditorSnapshot struct { FontSize float32 // MonoFace is the fixed-pitch font the code is set in. MonoFace gfx.MonoFace + // ShapedBidi opts unwrapped plain grid rows into native bidi shaping where + // available. Tabs, representations and visual whitespace/indent markers + // still use the logical grid, as do editors with highlighting or decorations. + // Horizontal movement remains caller-owned. + ShapedBidi bool // TabWidth is the width of a tab stop in cells; zero is four. TabWidth int // Wrap folds a line longer than the box onto several rows. Without it each @@ -262,6 +269,7 @@ type CodeEditor struct { // there, and otherwise at the start of the next. upstream bool upstreamCaret int + shaping *codeShaping // Scratch kept between paints. runs []gfx.TextRun @@ -428,6 +436,7 @@ func (editor *CodeEditor) Paint(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx. editor.measureIndents() } editor.content, editor.cellWidth, editor.lineHeight = content, cellWidth, lineHeight + editor.configureShaping(canvas, snapshot, size, cellWidth) placeholder := value == "" caret := gridCaretStart(value, snapshot.Caret) @@ -437,13 +446,20 @@ func (editor *CodeEditor) Paint(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx. compositionStart, compositionEnd := textareaRange(value, snapshot.CompositionStart, snapshot.CompositionEnd) caretRow := editor.rowOf(caret) caretColumn := editor.columnOf(editor.rows[caretRow], caret) + caretX, shapedCaret := editor.shapedCaretX(editor.rows[caretRow], caret) editor.extraCarets = editor.extraCarets[:0] for _, extra := range snapshot.ExtraCarets { offset := gridCaretStart(value, extra.Offset) row := editor.rowOf(offset) - editor.extraCarets = append(editor.extraCarets, codeExtraCaret{ - row: row, column: editor.columnOf(editor.rows[row], offset) + max(0, extra.VirtualCells), - }) + virtual := max(0, extra.VirtualCells) + x, shaped := editor.shapedCaretX(editor.rows[row], offset) + column := editor.columnOf(editor.rows[row], offset) + virtual + if shaped { + x += float32(virtual) * cellWidth + } else { + x = float32(column) * cellWidth + } + editor.extraCarets = append(editor.extraCarets, codeExtraCaret{row: row, column: column, x: x, shaped: shaped}) } // ExtraCarets is documented as sorted, but the paint walks them with one // cursor that only moves forward: an out-of-order caller would silently paint @@ -453,7 +469,7 @@ func (editor *CodeEditor) Paint(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx. for i := 1; i < len(editor.extraCarets); i++ { for j := i; j > 0; j-- { left, right := editor.extraCarets[j-1], editor.extraCarets[j] - if left.row < right.row || left.row == right.row && left.column <= right.column { + if left.row < right.row || left.row == right.row && left.x <= right.x { break } editor.extraCarets[j-1], editor.extraCarets[j] = right, left @@ -462,7 +478,7 @@ func (editor *CodeEditor) Paint(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx. if placeholder { editor.scrollX, editor.scrollY, editor.followedValid = 0, 0, false } else { - editor.follow(caret, caretRow, caretColumn) + editor.follow(caret, caretRow, caretColumn, caretX, shapedCaret) } editor.painted = true @@ -483,7 +499,7 @@ func (editor *CodeEditor) Paint(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx. selectionStart: selectionStart, selectionEnd: selectionEnd, selectionRanges: selectionRanges, compositionStart: compositionStart, compositionEnd: compositionEnd, - caretRow: caretRow, caretColumn: caretColumn, + caretRow: caretRow, caretColumn: caretColumn, caretX: caretX, shapedCaret: shapedCaret, showCaret: showCaret, caretWidth: editorCaretWidth(snapshot.CaretWidth), caretColor: caretColor(snapshot.CaretColor, foreground), lineNumberPadding: lineNumberPadding, @@ -775,6 +791,9 @@ type codePaint struct { selectionRanges []text.Span compositionStart, compositionEnd int caretRow, caretColumn int + caretX float32 + shapedCaret bool + shapedSpans []gfx.TextSpan caretCursor int showCaret bool caretWidth float32 @@ -909,6 +928,12 @@ func caretColor(requested, text gfx.Color) gfx.Color { func (paint *codePaint) row(index int, y float32) { editor, canvas := paint.editor, paint.canvas row := editor.rows[index] + if editor.shaping != nil { + if carets := editor.shapedRow(row); len(carets) != 0 { + paint.shapedRow(index, row, y, carets) + return + } + } left := editor.content.X - editor.scrollX rowStart, rowEnd := int(row.start), int(row.end) if paint.showIndentGuides && editor.firstOfLine(index) { @@ -1041,15 +1066,25 @@ func (paint *codePaint) overlays(index int, y float32) { rowStart, rowEnd := int(row.start), int(row.end) left := editor.content.X - editor.scrollX if paint.compositionEnd > paint.compositionStart && paint.compositionStart <= rowEnd && paint.compositionEnd >= rowStart { - walker := columnWalker{editor: editor, row: row, at: rowStart} - first, last := walker.column(max(paint.compositionStart, rowStart)), walker.column(min(paint.compositionEnd, rowEnd)) - if last > first { - canvas.Fill(gfx.Rect{X: left + float32(first)*paint.cellWidth, Y: y + paint.lineHeight - 3, Width: float32(last-first) * paint.cellWidth, Height: 1}, paint.foreground) + if carets := editor.shapedRow(row); len(carets) != 0 { + paint.shapedSpans = codeShapedSpans(paint.shapedSpans, carets, paint.compositionStart-rowStart, paint.compositionEnd-rowStart) + for _, span := range paint.shapedSpans { + canvas.Fill(gfx.Rect{X: left + span.X, Y: y + paint.lineHeight - 3, Width: span.Width, Height: 1}, paint.foreground) + } + } else { + walker := columnWalker{editor: editor, row: row, at: rowStart} + first, last := walker.column(max(paint.compositionStart, rowStart)), walker.column(min(paint.compositionEnd, rowEnd)) + if last > first { + canvas.Fill(gfx.Rect{X: left + float32(first)*paint.cellWidth, Y: y + paint.lineHeight - 3, Width: float32(last-first) * paint.cellWidth, Height: 1}, paint.foreground) + } } } if index == paint.caretRow && editor.content.Width > 0 { x := left + float32(paint.caretColumn)*paint.cellWidth + if paint.shapedCaret { + x = left + paint.caretX + } if x >= editor.content.X-1 && x <= editor.content.X+editor.content.Width { editor.caretRect, editor.caretShown = gfx.Rect{X: x, Y: y, Width: paint.caretWidth, Height: paint.lineHeight}, true if paint.showCaret { @@ -1061,8 +1096,11 @@ func (paint *codePaint) overlays(index int, y float32) { paint.caretCursor++ } for paint.caretCursor < len(editor.extraCarets) && editor.extraCarets[paint.caretCursor].row == index { - column := editor.extraCarets[paint.caretCursor].column - x := left + float32(column)*paint.cellWidth + extra := editor.extraCarets[paint.caretCursor] + x := left + float32(extra.column)*paint.cellWidth + if extra.shaped { + x = left + extra.x + } if paint.showCaret && editor.content.Width > 0 && x >= editor.content.X-1 && x <= editor.content.X+editor.content.Width { canvas.Fill(gfx.Rect{X: x, Y: y + (paint.lineHeight-paint.cellHeight)/2, Width: paint.caretWidth, Height: paint.cellHeight}, paint.caretColor) } diff --git a/cmd/viva/templates/code_editor_layout.go.txt b/cmd/viva/templates/code_editor_layout.go.txt index 9b1c6d621..ab58dc6f9 100644 --- a/cmd/viva/templates/code_editor_layout.go.txt +++ b/cmd/viva/templates/code_editor_layout.go.txt @@ -560,7 +560,17 @@ func (editor *CodeEditor) OffsetWithVirtualAt(point gfx.Point) (offset, virtualC } index = max(0, min(index, len(editor.rows)-1)) row := editor.rows[index] - column := (point.X - editor.content.X + editor.scrollX) / editor.cellWidth + x := point.X - editor.content.X + editor.scrollX + if hit, shaped := editor.shapedHit(row, x); shaped { + editor.rememberShapedHit(row, hit) + editor.goalActive = false + editor.setUpstream(hit.Offset, false) + return hit.Offset, 0, true + } + if editor.shaping != nil { + editor.shaping.hitValid = false + } + column := x / editor.cellWidth offset = editor.offsetAtColumn(row, column) editor.setUpstream(offset, offset == int(row.end) && editor.softWrapped(index)) if offset == int(row.end) && !editor.softWrapped(index) { @@ -582,6 +592,9 @@ func (editor *CodeEditor) setUpstream(offset int, upstream bool) { // arrive notes where a movement ended and returns it. func (editor *CodeEditor) arrive(offset int, upstream bool) int { + if editor.shaping != nil { + editor.shaping.hitValid = false + } editor.setUpstream(offset, upstream) editor.goalActive = false return offset @@ -637,21 +650,34 @@ func (editor *CodeEditor) Move(text string, caret int, movement TextareaMovement } if !editor.goalActive || editor.goalCaret != caret { editor.goal = float32(editor.columnOf(row, caret)) + if x, shaped := editor.shapedCaretX(row, caret); shaped && editor.cellWidth > 0 { + editor.goal = x / editor.cellWidth + } } target := index + step var offset int var upstream bool + var hit gfx.TextHit + var shaped bool switch { case target < 0: offset = 0 case target >= len(editor.rows): offset = len(text) default: - offset = editor.offsetAtColumn(editor.rows[target], editor.goal) + hit, shaped = editor.shapedHit(editor.rows[target], editor.goal*editor.cellWidth) + if shaped { + offset = hit.Offset + } else { + offset = editor.offsetAtColumn(editor.rows[target], editor.goal) + } upstream = offset == int(editor.rows[target].end) && editor.softWrapped(target) } goal := editor.goal offset = editor.arrive(offset, upstream) + if shaped { + editor.rememberShapedHit(editor.rows[target], hit) + } editor.goal, editor.goalCaret, editor.goalActive = goal, offset, true return offset } @@ -724,7 +750,7 @@ func clampScroll(scroll, most float32) float32 { // follow scrolls to keep the caret in view when the caret, or the row it is on, // is not where the last paint left it. A wheel or a drag of a scrollbar moves the // view and the next paint leaves it there until the caret moves. -func (editor *CodeEditor) follow(caret, row, column int) { +func (editor *CodeEditor) follow(caret, row, column int, x float32, shaped bool) { if !editor.followedValid || editor.followed != caret || editor.followedRow != row { top := float32(row) * editor.lineHeight if top < editor.scrollY { @@ -734,6 +760,9 @@ func (editor *CodeEditor) follow(caret, row, column int) { } if !editor.wrap { left, right := float32(column)*editor.cellWidth, float32(column+1)*editor.cellWidth + if shaped { + left, right = x, x+editor.cellWidth + } if left < editor.scrollX { editor.scrollX = max(0, left-editor.cellWidth*2) } else if right > editor.scrollX+editor.content.Width { diff --git a/cmd/viva/templates/code_editor_shaped.go.txt b/cmd/viva/templates/code_editor_shaped.go.txt new file mode 100644 index 000000000..b68a42ba8 --- /dev/null +++ b/cmd/viva/templates/code_editor_shaped.go.txt @@ -0,0 +1,252 @@ +package {{PACKAGE}} + +import ( + "cmp" + "slices" + "sort" + "strings" + + "github.com/vivaui/viva/gfx" +) + +type codeShaping struct { + canvas *gfx.Canvas + value string + style gfx.TextStyle + cell float32 + generation uint32 + rows map[int32][]gfx.FittedMonoCaret + hit gfx.TextHit + hitRow int32 + hitValid bool +} + +func (editor *CodeEditor) configureShaping(canvas *gfx.Canvas, snapshot CodeEditorSnapshot, size, cell float32) { + if !snapshot.ShapedBidi || snapshot.Wrap || len(snapshot.Representations) != 0 || snapshot.ShowWhitespace || + snapshot.ShowIndentGuides || snapshot.ShowEOL || snapshot.Decorations != nil || snapshot.Highlight != nil || snapshot.HighlightLine != nil { + editor.shaping = nil + return + } + style := gfx.TextStyle{Size: size, Mono: true, MonoFace: snapshot.MonoFace} + generation := canvas.FontGeneration() + s := editor.shaping + if s == nil || s.canvas != canvas || s.value != editor.text || s.style != style || s.cell != cell || s.generation != generation { + s = &codeShaping{canvas: canvas, value: editor.text, style: style, cell: cell, generation: generation, rows: make(map[int32][]gfx.FittedMonoCaret)} + editor.shaping = s + } + if s.hitValid && s.hit.Offset != snapshot.Caret { + s.hitValid = false + } +} + +func (editor *CodeEditor) shapedRow(row codeRow) []gfx.FittedMonoCaret { + s := editor.shaping + // Bound both the cost of shaping a single line and the number of cached rows. + if s == nil || row.shown >= 0 || row.end <= row.start || row.end-row.start > 4096 { + return nil + } + if carets, ok := s.rows[row.start]; ok { + return carets + } + value := s.value[row.start:row.end] + if strings.IndexByte(value, '\t') >= 0 { + return nil + } + carets, ok := s.canvas.FittedBidiMonoCarets(nil, value, s.style, float32(row.cells)*s.cell) + if !ok || len(carets) < 2 || carets[0].Offset != 0 || carets[len(carets)-1].Offset != len(value) { + carets = nil + } + if len(s.rows) >= 64 { + clear(s.rows) + } + s.rows[row.start] = carets + return carets +} + +func (editor *CodeEditor) shapedCaretX(row codeRow, offset int) (float32, bool) { + if carets := editor.shapedRow(row); len(carets) != 0 { + s := editor.shaping + if s.hitValid && s.hitRow == row.start && s.hit.Offset == offset { + return s.hit.X, true + } + local := max(0, min(offset-int(row.start), int(row.end-row.start))) + at, exact := slices.BinarySearchFunc(carets, local, func(caret gfx.FittedMonoCaret, local int) int { + return cmp.Compare(caret.Offset, local) + }) + if !exact { + at = max(0, at-1) + } + if at == 0 { + return carets[0].Leading, true + } + return carets[at].Trailing, true + } + return 0, false +} + +func (editor *CodeEditor) shapedHit(row codeRow, x float32) (gfx.TextHit, bool) { + carets := editor.shapedRow(row) + if len(carets) == 0 { + return gfx.TextHit{}, false + } + best := gfx.TextHit{Offset: int(row.start), X: carets[0].Leading} + gap := float32(-1) + for i := 0; i+1 < len(carets); i++ { + leading, trailing := carets[i].Leading, carets[i+1].Trailing + left, right := min(leading, trailing), max(leading, trailing) + if left == right { + continue + } + distance := max(left-x, x-right, 0) + if gap >= 0 && distance >= gap { + continue + } + position, boundary := leading, i + if max(x-trailing, trailing-x) < max(x-leading, leading-x) { + position, boundary = trailing, i+1 + } + best = gfx.TextHit{Offset: int(row.start) + carets[boundary].Offset, X: position} + gap = distance + if gap == 0 { + break + } + } + return best, true +} + +func (editor *CodeEditor) rememberShapedHit(row codeRow, hit gfx.TextHit) { + if s := editor.shaping; s != nil { + s.hit, s.hitRow, s.hitValid = hit, row.start, true + } +} + +func codeShapedSpans(dst []gfx.TextSpan, carets []gfx.FittedMonoCaret, start, end int) []gfx.TextSpan { + dst = dst[:0] + if start >= end { + return dst + } + for i := 0; i+1 < len(carets); i++ { + if carets[i].Offset >= end { + break + } + if carets[i+1].Offset <= start { + continue + } + a, b := carets[i].Leading, carets[i+1].Trailing + if a != b { + dst = append(dst, gfx.TextSpan{X: min(a, b), Width: max(a, b) - min(a, b)}) + } + } + slices.SortFunc(dst, func(a, b gfx.TextSpan) int { return cmp.Compare(a.X, b.X) }) + kept := dst[:0] + for _, span := range dst { + if n := len(kept); n != 0 && span.X <= kept[n-1].X+kept[n-1].Width+0.001 { + last := &kept[n-1] + last.Width = max(last.X+last.Width, span.X+span.Width) - last.X + } else { + kept = append(kept, span) + } + } + return kept +} + +func (paint *codePaint) shapedRow(index int, row codeRow, y float32, carets []gfx.FittedMonoCaret) { + start, end := int(row.start), int(row.end) + left := paint.editor.content.X - paint.editor.scrollX + fill := func(from, to int, color gfx.Color) { + paint.shapedSpans = codeShapedSpans(paint.shapedSpans, carets, from-start, to-start) + for _, span := range paint.shapedSpans { + paint.canvas.Fill(gfx.Rect{X: left + span.X, Y: y, Width: span.Width, Height: paint.lineHeight}, color) + } + } + for _, layer := range paint.markLayers { + if layer.Color.Alpha <= 0 { + continue + } + first := sort.Search(len(layer.Spans), func(i int) bool { return layer.Spans[i].End > start }) + for _, mark := range layer.Spans[first:] { + if mark.Start >= end { + break + } + fill(mark.Start, mark.End, layer.Color) + } + } + for paint.markCursor < len(paint.marks) && paint.marks[paint.markCursor].End <= start { + paint.markCursor++ + } + for i := paint.markCursor; i < len(paint.marks) && paint.marks[i].Start < end; i++ { + mark := paint.marks[i] + color := codeMatchColor + if mark == paint.current { + color = codeCurrentColor + } + fill(mark.Start, mark.End, color) + } + if paint.bracketsOK { + color := paint.emphasis + color.Alpha *= 0.22 + for _, at := range paint.brackets { + if at >= start && at < end { + fill(at, at+1, color) + } + } + } + selection := func(from, to int) { + if from >= to || from > end || to <= start { + return + } + fill(from, to, paint.selectionBackground) + if to > end && end < len(paint.value) { + extra := paint.cellWidth / 2 + x := left + carets[len(carets)-1].Trailing + if carets[0].Leading > carets[len(carets)-1].Trailing { + x -= extra + } + paint.canvas.Fill(gfx.Rect{X: x, Y: y, Width: extra, Height: paint.lineHeight}, paint.selectionBackground) + } + } + if len(paint.selectionRanges) == 0 { + selection(paint.selectionStart, paint.selectionEnd) + } else { + first := sort.Search(len(paint.selectionRanges), func(i int) bool { return paint.selectionRanges[i].End > start }) + for _, span := range paint.selectionRanges[first:] { + if span.Start > end { + break + } + selection(span.Start, span.End) + } + } + value := paint.value[start:end] + bounds := gfx.Rect{X: left, Y: y + (paint.lineHeight-paint.cellHeight)/2, Width: float32(row.cells) * paint.cellWidth, Height: paint.cellHeight} + run := gfx.TextRun{Bytes: int32(len(value)), Cells: row.cells, Ligatures: true, Color: paint.foreground} + style := gfx.TextStyle{Size: paint.size, Color: paint.foreground, Mono: true, MonoFace: paint.face} + paint.canvas.LabelRuns(value, bounds, style, paint.cellWidth, []gfx.TextRun{run}) + run.Color = paint.selectionForeground + paint.shapedSelectionText(carets, start, value, bounds, run) + paint.overlays(index, y) +} + +func (paint *codePaint) shapedSelectionText(carets []gfx.FittedMonoCaret, start int, value string, bounds gfx.Rect, run gfx.TextRun) { + style := gfx.TextStyle{Size: paint.size, Mono: true, MonoFace: paint.face, Color: run.Color} + paintSelection := func(from, to int) { + paint.shapedSpans = codeShapedSpans(paint.shapedSpans, carets, from-start, to-start) + for _, span := range paint.shapedSpans { + paint.canvas.Clip(gfx.Rect{X: bounds.X + span.X, Y: bounds.Y, Width: span.Width, Height: bounds.Height}) + // Clipping a duplicate of the complete run preserves its joins. + paint.canvas.LabelRuns(value, bounds, style, paint.cellWidth, []gfx.TextRun{run}) + paint.canvas.Unclip() + } + } + if len(paint.selectionRanges) != 0 { + for _, selection := range paint.selectionRanges { + if selection.Start >= start+len(value) { + break + } + if selection.End > start { + paintSelection(selection.Start, selection.End) + } + } + } else if paint.selectionEnd > start && paint.selectionStart < start+len(value) { + paintSelection(paint.selectionStart, paint.selectionEnd) + } +} diff --git a/components/code_editor.go b/components/code_editor.go index 4406fde2e..afa54bcfc 100644 --- a/components/code_editor.go +++ b/components/code_editor.go @@ -34,6 +34,8 @@ type CodeEditorCaret struct { type codeExtraCaret struct { row, column int + x float32 + shaped bool } // CodeEditorGutterMarker decorates one zero-based logical line with a dot in the @@ -137,6 +139,13 @@ type CodeEditorSnapshot struct { FontSize float32 // MonoFace is the fixed-pitch font the code is set in. MonoFace gfx.MonoFace + // ShapedBidi opts unwrapped plain grid rows into native bidi shaping where + // available. Tabs, representations and visual whitespace/indent markers + // still use the logical grid, as do editors with highlighting or decorations. + // A row over 4096 bytes keeps the grid, and a platform whose text engine + // cannot shape a fitted monospaced run draws the grid unchanged. + // Horizontal movement remains caller-owned. + ShapedBidi bool // TabWidth is the width of a tab stop in cells; zero is four. TabWidth int // Wrap folds a line longer than the box onto several rows. Without it each @@ -262,6 +271,7 @@ type CodeEditor struct { // there, and otherwise at the start of the next. upstream bool upstreamCaret int + shaping *codeShaping // Scratch kept between paints. runs []gfx.TextRun @@ -428,6 +438,7 @@ func (editor *CodeEditor) Paint(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx. editor.measureIndents() } editor.content, editor.cellWidth, editor.lineHeight = content, cellWidth, lineHeight + editor.configureShaping(canvas, snapshot, size, cellWidth) placeholder := value == "" caret := gridCaretStart(value, snapshot.Caret) @@ -437,13 +448,20 @@ func (editor *CodeEditor) Paint(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx. compositionStart, compositionEnd := textareaRange(value, snapshot.CompositionStart, snapshot.CompositionEnd) caretRow := editor.rowOf(caret) caretColumn := editor.columnOf(editor.rows[caretRow], caret) + caretX, shapedCaret := editor.shapedCaretX(editor.rows[caretRow], caret) editor.extraCarets = editor.extraCarets[:0] for _, extra := range snapshot.ExtraCarets { offset := gridCaretStart(value, extra.Offset) row := editor.rowOf(offset) - editor.extraCarets = append(editor.extraCarets, codeExtraCaret{ - row: row, column: editor.columnOf(editor.rows[row], offset) + max(0, extra.VirtualCells), - }) + virtual := max(0, extra.VirtualCells) + x, shaped := editor.shapedCaretX(editor.rows[row], offset) + column := editor.columnOf(editor.rows[row], offset) + virtual + if shaped { + x += float32(virtual) * cellWidth + } else { + x = float32(column) * cellWidth + } + editor.extraCarets = append(editor.extraCarets, codeExtraCaret{row: row, column: column, x: x, shaped: shaped}) } // ExtraCarets is documented as sorted, but the paint walks them with one // cursor that only moves forward: an out-of-order caller would silently paint @@ -453,7 +471,7 @@ func (editor *CodeEditor) Paint(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx. for i := 1; i < len(editor.extraCarets); i++ { for j := i; j > 0; j-- { left, right := editor.extraCarets[j-1], editor.extraCarets[j] - if left.row < right.row || left.row == right.row && left.column <= right.column { + if left.row < right.row || left.row == right.row && left.x <= right.x { break } editor.extraCarets[j-1], editor.extraCarets[j] = right, left @@ -462,7 +480,7 @@ func (editor *CodeEditor) Paint(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx. if placeholder { editor.scrollX, editor.scrollY, editor.followedValid = 0, 0, false } else { - editor.follow(caret, caretRow, caretColumn) + editor.follow(caret, caretRow, caretColumn, caretX, shapedCaret) } editor.painted = true @@ -483,7 +501,7 @@ func (editor *CodeEditor) Paint(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx. selectionStart: selectionStart, selectionEnd: selectionEnd, selectionRanges: selectionRanges, compositionStart: compositionStart, compositionEnd: compositionEnd, - caretRow: caretRow, caretColumn: caretColumn, + caretRow: caretRow, caretColumn: caretColumn, caretX: caretX, shapedCaret: shapedCaret, showCaret: showCaret, caretWidth: editorCaretWidth(snapshot.CaretWidth), caretColor: caretColor(snapshot.CaretColor, foreground), lineNumberPadding: lineNumberPadding, @@ -775,6 +793,9 @@ type codePaint struct { selectionRanges []text.Span compositionStart, compositionEnd int caretRow, caretColumn int + caretX float32 + shapedCaret bool + shapedSpans []gfx.TextSpan caretCursor int showCaret bool caretWidth float32 @@ -909,6 +930,12 @@ func caretColor(requested, text gfx.Color) gfx.Color { func (paint *codePaint) row(index int, y float32) { editor, canvas := paint.editor, paint.canvas row := editor.rows[index] + if editor.shaping != nil { + if carets := editor.shapedRow(row); len(carets) != 0 { + paint.shapedRow(index, row, y, carets) + return + } + } left := editor.content.X - editor.scrollX rowStart, rowEnd := int(row.start), int(row.end) if paint.showIndentGuides && editor.firstOfLine(index) { @@ -1041,15 +1068,25 @@ func (paint *codePaint) overlays(index int, y float32) { rowStart, rowEnd := int(row.start), int(row.end) left := editor.content.X - editor.scrollX if paint.compositionEnd > paint.compositionStart && paint.compositionStart <= rowEnd && paint.compositionEnd >= rowStart { - walker := columnWalker{editor: editor, row: row, at: rowStart} - first, last := walker.column(max(paint.compositionStart, rowStart)), walker.column(min(paint.compositionEnd, rowEnd)) - if last > first { - canvas.Fill(gfx.Rect{X: left + float32(first)*paint.cellWidth, Y: y + paint.lineHeight - 3, Width: float32(last-first) * paint.cellWidth, Height: 1}, paint.foreground) + if carets := editor.shapedRow(row); len(carets) != 0 { + paint.shapedSpans = codeShapedSpans(paint.shapedSpans, carets, paint.compositionStart-rowStart, paint.compositionEnd-rowStart) + for _, span := range paint.shapedSpans { + canvas.Fill(gfx.Rect{X: left + span.X, Y: y + paint.lineHeight - 3, Width: span.Width, Height: 1}, paint.foreground) + } + } else { + walker := columnWalker{editor: editor, row: row, at: rowStart} + first, last := walker.column(max(paint.compositionStart, rowStart)), walker.column(min(paint.compositionEnd, rowEnd)) + if last > first { + canvas.Fill(gfx.Rect{X: left + float32(first)*paint.cellWidth, Y: y + paint.lineHeight - 3, Width: float32(last-first) * paint.cellWidth, Height: 1}, paint.foreground) + } } } if index == paint.caretRow && editor.content.Width > 0 { x := left + float32(paint.caretColumn)*paint.cellWidth + if paint.shapedCaret { + x = left + paint.caretX + } if x >= editor.content.X-1 && x <= editor.content.X+editor.content.Width { editor.caretRect, editor.caretShown = gfx.Rect{X: x, Y: y, Width: paint.caretWidth, Height: paint.lineHeight}, true if paint.showCaret { @@ -1061,8 +1098,11 @@ func (paint *codePaint) overlays(index int, y float32) { paint.caretCursor++ } for paint.caretCursor < len(editor.extraCarets) && editor.extraCarets[paint.caretCursor].row == index { - column := editor.extraCarets[paint.caretCursor].column - x := left + float32(column)*paint.cellWidth + extra := editor.extraCarets[paint.caretCursor] + x := left + float32(extra.column)*paint.cellWidth + if extra.shaped { + x = left + extra.x + } if paint.showCaret && editor.content.Width > 0 && x >= editor.content.X-1 && x <= editor.content.X+editor.content.Width { canvas.Fill(gfx.Rect{X: x, Y: y + (paint.lineHeight-paint.cellHeight)/2, Width: paint.caretWidth, Height: paint.cellHeight}, paint.caretColor) } diff --git a/components/code_editor_layout.go b/components/code_editor_layout.go index ec1658250..b4866f95e 100644 --- a/components/code_editor_layout.go +++ b/components/code_editor_layout.go @@ -560,7 +560,17 @@ func (editor *CodeEditor) OffsetWithVirtualAt(point gfx.Point) (offset, virtualC } index = max(0, min(index, len(editor.rows)-1)) row := editor.rows[index] - column := (point.X - editor.content.X + editor.scrollX) / editor.cellWidth + x := point.X - editor.content.X + editor.scrollX + if hit, shaped := editor.shapedHit(row, x); shaped { + editor.rememberShapedHit(row, hit) + editor.goalActive = false + editor.setUpstream(hit.Offset, false) + return hit.Offset, 0, true + } + if editor.shaping != nil { + editor.shaping.hitValid = false + } + column := x / editor.cellWidth offset = editor.offsetAtColumn(row, column) editor.setUpstream(offset, offset == int(row.end) && editor.softWrapped(index)) if offset == int(row.end) && !editor.softWrapped(index) { @@ -582,6 +592,9 @@ func (editor *CodeEditor) setUpstream(offset int, upstream bool) { // arrive notes where a movement ended and returns it. func (editor *CodeEditor) arrive(offset int, upstream bool) int { + if editor.shaping != nil { + editor.shaping.hitValid = false + } editor.setUpstream(offset, upstream) editor.goalActive = false return offset @@ -637,21 +650,34 @@ func (editor *CodeEditor) Move(text string, caret int, movement TextareaMovement } if !editor.goalActive || editor.goalCaret != caret { editor.goal = float32(editor.columnOf(row, caret)) + if x, shaped := editor.shapedCaretX(row, caret); shaped && editor.cellWidth > 0 { + editor.goal = x / editor.cellWidth + } } target := index + step var offset int var upstream bool + var hit gfx.TextHit + var shaped bool switch { case target < 0: offset = 0 case target >= len(editor.rows): offset = len(text) default: - offset = editor.offsetAtColumn(editor.rows[target], editor.goal) + hit, shaped = editor.shapedHit(editor.rows[target], editor.goal*editor.cellWidth) + if shaped { + offset = hit.Offset + } else { + offset = editor.offsetAtColumn(editor.rows[target], editor.goal) + } upstream = offset == int(editor.rows[target].end) && editor.softWrapped(target) } goal := editor.goal offset = editor.arrive(offset, upstream) + if shaped { + editor.rememberShapedHit(editor.rows[target], hit) + } editor.goal, editor.goalCaret, editor.goalActive = goal, offset, true return offset } @@ -724,7 +750,7 @@ func clampScroll(scroll, most float32) float32 { // follow scrolls to keep the caret in view when the caret, or the row it is on, // is not where the last paint left it. A wheel or a drag of a scrollbar moves the // view and the next paint leaves it there until the caret moves. -func (editor *CodeEditor) follow(caret, row, column int) { +func (editor *CodeEditor) follow(caret, row, column int, x float32, shaped bool) { if !editor.followedValid || editor.followed != caret || editor.followedRow != row { top := float32(row) * editor.lineHeight if top < editor.scrollY { @@ -734,6 +760,9 @@ func (editor *CodeEditor) follow(caret, row, column int) { } if !editor.wrap { left, right := float32(column)*editor.cellWidth, float32(column+1)*editor.cellWidth + if shaped { + left, right = x, x+editor.cellWidth + } if left < editor.scrollX { editor.scrollX = max(0, left-editor.cellWidth*2) } else if right > editor.scrollX+editor.content.Width { diff --git a/components/code_editor_shaped.go b/components/code_editor_shaped.go new file mode 100644 index 000000000..cebaf7c3f --- /dev/null +++ b/components/code_editor_shaped.go @@ -0,0 +1,262 @@ +package components + +import ( + "cmp" + "slices" + "sort" + "strings" + + "github.com/vivaui/viva/gfx" +) + +type codeShaping struct { + canvas *gfx.Canvas + value string + style gfx.TextStyle + cell float32 + generation uint32 + rows map[int32][]gfx.FittedMonoCaret + // limit is the most rows the cache keeps: the visible rows of the last + // paint, and never fewer than the old fixed bound. A viewport taller than + // that bound used to clear the cache in the middle of the paint, so every + // row missed again on the next frame. + limit int + hit gfx.TextHit + hitRow int32 + hitValid bool +} + +func (editor *CodeEditor) configureShaping(canvas *gfx.Canvas, snapshot CodeEditorSnapshot, size, cell float32) { + if !snapshot.ShapedBidi || snapshot.Wrap || len(snapshot.Representations) != 0 || snapshot.ShowWhitespace || + snapshot.ShowIndentGuides || snapshot.ShowEOL || snapshot.Decorations != nil || snapshot.Highlight != nil || snapshot.HighlightLine != nil { + editor.shaping = nil + return + } + style := gfx.TextStyle{Size: size, Mono: true, MonoFace: snapshot.MonoFace} + generation := canvas.FontGeneration() + s := editor.shaping + if s == nil || s.canvas != canvas || s.value != editor.text || s.style != style || s.cell != cell || s.generation != generation { + s = &codeShaping{canvas: canvas, value: editor.text, style: style, cell: cell, generation: generation, rows: make(map[int32][]gfx.FittedMonoCaret)} + editor.shaping = s + } + limit := 64 + if visible := int(editor.content.Height/editor.lineHeight) + 2; visible > limit { + limit = visible + } + s.limit = limit + if len(s.rows) > limit { + clear(s.rows) + } + if s.hitValid && s.hit.Offset != snapshot.Caret { + s.hitValid = false + } +} + +func (editor *CodeEditor) shapedRow(row codeRow) []gfx.FittedMonoCaret { + s := editor.shaping + // Bound both the cost of shaping a single line and the number of cached rows. + if s == nil || row.shown >= 0 || row.end <= row.start || row.end-row.start > 4096 { + return nil + } + if carets, ok := s.rows[row.start]; ok { + return carets + } + value := s.value[row.start:row.end] + if strings.IndexByte(value, '\t') >= 0 { + return nil + } + carets, ok := s.canvas.FittedBidiMonoCarets(nil, value, s.style, float32(row.cells)*s.cell) + if !ok || len(carets) < 2 || carets[0].Offset != 0 || carets[len(carets)-1].Offset != len(value) { + carets = nil + } + s.rows[row.start] = carets + return carets +} + +func (editor *CodeEditor) shapedCaretX(row codeRow, offset int) (float32, bool) { + if carets := editor.shapedRow(row); len(carets) != 0 { + s := editor.shaping + if s.hitValid && s.hitRow == row.start && s.hit.Offset == offset { + return s.hit.X, true + } + local := max(0, min(offset-int(row.start), int(row.end-row.start))) + at, exact := slices.BinarySearchFunc(carets, local, func(caret gfx.FittedMonoCaret, local int) int { + return cmp.Compare(caret.Offset, local) + }) + if !exact { + at = max(0, at-1) + } + if at == 0 { + return carets[0].Leading, true + } + return carets[at].Trailing, true + } + return 0, false +} + +func (editor *CodeEditor) shapedHit(row codeRow, x float32) (gfx.TextHit, bool) { + carets := editor.shapedRow(row) + if len(carets) == 0 { + return gfx.TextHit{}, false + } + best := gfx.TextHit{Offset: int(row.start), X: carets[0].Leading} + gap := float32(-1) + for i := 0; i+1 < len(carets); i++ { + leading, trailing := carets[i].Leading, carets[i+1].Trailing + left, right := min(leading, trailing), max(leading, trailing) + if left == right { + continue + } + distance := max(left-x, x-right, 0) + if gap >= 0 && distance >= gap { + continue + } + position, boundary := leading, i + if max(x-trailing, trailing-x) < max(x-leading, leading-x) { + position, boundary = trailing, i+1 + } + best = gfx.TextHit{Offset: int(row.start) + carets[boundary].Offset, X: position} + gap = distance + if gap == 0 { + break + } + } + return best, true +} + +func (editor *CodeEditor) rememberShapedHit(row codeRow, hit gfx.TextHit) { + if s := editor.shaping; s != nil { + s.hit, s.hitRow, s.hitValid = hit, row.start, true + } +} + +func codeShapedSpans(dst []gfx.TextSpan, carets []gfx.FittedMonoCaret, start, end int) []gfx.TextSpan { + dst = dst[:0] + if start >= end { + return dst + } + for i := 0; i+1 < len(carets); i++ { + if carets[i].Offset >= end { + break + } + if carets[i+1].Offset <= start { + continue + } + a, b := carets[i].Leading, carets[i+1].Trailing + if a != b { + dst = append(dst, gfx.TextSpan{X: min(a, b), Width: max(a, b) - min(a, b)}) + } + } + slices.SortFunc(dst, func(a, b gfx.TextSpan) int { return cmp.Compare(a.X, b.X) }) + kept := dst[:0] + for _, span := range dst { + if n := len(kept); n != 0 && span.X <= kept[n-1].X+kept[n-1].Width+0.001 { + last := &kept[n-1] + last.Width = max(last.X+last.Width, span.X+span.Width) - last.X + } else { + kept = append(kept, span) + } + } + return kept +} + +func (paint *codePaint) shapedRow(index int, row codeRow, y float32, carets []gfx.FittedMonoCaret) { + start, end := int(row.start), int(row.end) + left := paint.editor.content.X - paint.editor.scrollX + fill := func(from, to int, color gfx.Color) { + paint.shapedSpans = codeShapedSpans(paint.shapedSpans, carets, from-start, to-start) + for _, span := range paint.shapedSpans { + paint.canvas.Fill(gfx.Rect{X: left + span.X, Y: y, Width: span.Width, Height: paint.lineHeight}, color) + } + } + for _, layer := range paint.markLayers { + if layer.Color.Alpha <= 0 { + continue + } + first := sort.Search(len(layer.Spans), func(i int) bool { return layer.Spans[i].End > start }) + for _, mark := range layer.Spans[first:] { + if mark.Start >= end { + break + } + fill(mark.Start, mark.End, layer.Color) + } + } + for paint.markCursor < len(paint.marks) && paint.marks[paint.markCursor].End <= start { + paint.markCursor++ + } + for i := paint.markCursor; i < len(paint.marks) && paint.marks[i].Start < end; i++ { + mark := paint.marks[i] + color := codeMatchColor + if mark == paint.current { + color = codeCurrentColor + } + fill(mark.Start, mark.End, color) + } + if paint.bracketsOK { + color := paint.emphasis + color.Alpha *= 0.22 + for _, at := range paint.brackets { + if at >= start && at < end { + fill(at, at+1, color) + } + } + } + selection := func(from, to int) { + if from >= to || from > end || to <= start { + return + } + fill(from, to, paint.selectionBackground) + if to > end && end < len(paint.value) { + extra := paint.cellWidth / 2 + x := left + carets[len(carets)-1].Trailing + if carets[0].Leading > carets[len(carets)-1].Trailing { + x -= extra + } + paint.canvas.Fill(gfx.Rect{X: x, Y: y, Width: extra, Height: paint.lineHeight}, paint.selectionBackground) + } + } + if len(paint.selectionRanges) == 0 { + selection(paint.selectionStart, paint.selectionEnd) + } else { + first := sort.Search(len(paint.selectionRanges), func(i int) bool { return paint.selectionRanges[i].End > start }) + for _, span := range paint.selectionRanges[first:] { + if span.Start > end { + break + } + selection(span.Start, span.End) + } + } + value := paint.value[start:end] + bounds := gfx.Rect{X: left, Y: y + (paint.lineHeight-paint.cellHeight)/2, Width: float32(row.cells) * paint.cellWidth, Height: paint.cellHeight} + run := gfx.TextRun{Bytes: int32(len(value)), Cells: row.cells, Ligatures: true, Color: paint.foreground} + style := gfx.TextStyle{Size: paint.size, Color: paint.foreground, Mono: true, MonoFace: paint.face} + paint.canvas.LabelRuns(value, bounds, style, paint.cellWidth, []gfx.TextRun{run}) + run.Color = paint.selectionForeground + paint.shapedSelectionText(carets, start, value, bounds, run) + paint.overlays(index, y) +} + +func (paint *codePaint) shapedSelectionText(carets []gfx.FittedMonoCaret, start int, value string, bounds gfx.Rect, run gfx.TextRun) { + style := gfx.TextStyle{Size: paint.size, Mono: true, MonoFace: paint.face, Color: run.Color} + paintSelection := func(from, to int) { + paint.shapedSpans = codeShapedSpans(paint.shapedSpans, carets, from-start, to-start) + for _, span := range paint.shapedSpans { + paint.canvas.Clip(gfx.Rect{X: bounds.X + span.X, Y: bounds.Y, Width: span.Width, Height: bounds.Height}) + // Clipping a duplicate of the complete run preserves its joins. + paint.canvas.LabelRuns(value, bounds, style, paint.cellWidth, []gfx.TextRun{run}) + paint.canvas.Unclip() + } + } + if len(paint.selectionRanges) != 0 { + for _, selection := range paint.selectionRanges { + if selection.Start >= start+len(value) { + break + } + if selection.End > start { + paintSelection(selection.Start, selection.End) + } + } + } else if paint.selectionEnd > start && paint.selectionStart < start+len(value) { + paintSelection(paint.selectionStart, paint.selectionEnd) + } +} diff --git a/components/code_editor_shaped_darwin_test.go b/components/code_editor_shaped_darwin_test.go new file mode 100644 index 000000000..e93021fec --- /dev/null +++ b/components/code_editor_shaped_darwin_test.go @@ -0,0 +1,49 @@ +//go:build darwin && !ios + +package components + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/platform/darwin" +) + +func TestCodeEditorCoreTextKeepsFittedArabicCaretEdges(t *testing.T) { + const prefix = "a\u0301\U00010437 " + const value = prefix + "\u0633\u0644\u0627\u0645 z" + f := newCodeFixture(value) + f.canvas.SetTextEngine(darwin.SharedTextEngine()) + f.snapshot.ShapedBidi = true + f.paint() + row := f.editor.rows[0] + carets := f.editor.shapedRow(row) + if len(carets) != 10 { + t.Fatalf("fitted carets did not preserve the ten grapheme boundaries: %+v", carets) + } + edge := carets[3] + if edge.Offset != len(prefix) || edge.Leading-edge.Trailing < f.editor.cellWidth { + t.Fatalf("expected separate leading and trailing positions for byte %d: %+v", len(prefix), edge) + } + labels := f.canvas.Texts() + if len(labels) != 1 || labels[0].Value != value { + t.Fatalf("expected one intact shaped label: %+v", labels) + } + runs := f.canvas.TextRuns(labels[0]) + if len(runs) != 1 || !runs[0].Ligatures || int(runs[0].Bytes) != len(value) || runs[0].Cells != row.cells { + t.Fatalf("expected the measured run to be fitted without subruns: %+v", runs) + } + for _, x := range []float32{edge.Trailing, edge.Leading} { + want := f.editor.content.X + x + y := f.editor.content.Y + f.editor.lineHeight/2 + at, ok := f.editor.OffsetAt(gfx.Point{X: want - 0.25, Y: y}) + if !ok || at != len(prefix) { + t.Fatalf("click at %g: byte %d, %v; want %d", want-0.25, at, ok, len(prefix)) + } + f.snapshot.Caret = at + f.paint() + if got, ok := f.editor.CaretBounds(); !ok || !near(got.X, want) { + t.Errorf("IME placement at byte %d: %+v, %v; want X=%g", at, got, ok, want) + } + } +} diff --git a/components/code_editor_shaped_test.go b/components/code_editor_shaped_test.go new file mode 100644 index 000000000..f7c7a5af6 --- /dev/null +++ b/components/code_editor_shaped_test.go @@ -0,0 +1,111 @@ +package components + +import ( + "strings" + "testing" + + "github.com/vivaui/viva/gfx" +) + +type shapedCodeTestEngine struct{ gfx.TextEngine } + +func (shapedCodeTestEngine) FittedMonoCarets(dst []gfx.FittedMonoCaret, value string, style gfx.TextStyle, span float32) ([]gfx.FittedMonoCaret, bool) { + if value != "a\u05d0\u05d1z" { + return dst, false + } + // Visual order is a bet alef z. The boundary before alef is at 1/4 + // after the Latin letter and at 3/4 before the RTL letter. + return append(dst, + gfx.FittedMonoCaret{Offset: 0, Leading: 0, Trailing: 0}, + gfx.FittedMonoCaret{Offset: 1, Leading: span * 0.75, Trailing: span * 0.25}, + gfx.FittedMonoCaret{Offset: 3, Leading: span * 0.5, Trailing: span * 0.5}, + gfx.FittedMonoCaret{Offset: 5, Leading: span * 0.75, Trailing: span * 0.25}, + gfx.FittedMonoCaret{Offset: 6, Leading: span, Trailing: span}, + ), true +} + +type countingShapedEngine struct { + gfx.TextEngine + calls int +} + +func (engine *countingShapedEngine) FittedMonoCarets(dst []gfx.FittedMonoCaret, value string, style gfx.TextStyle, span float32) ([]gfx.FittedMonoCaret, bool) { + engine.calls++ + return append(dst, + gfx.FittedMonoCaret{Offset: 0, Leading: 0, Trailing: 0}, + gfx.FittedMonoCaret{Offset: len(value), Leading: span, Trailing: span}, + ), true +} + +// A viewport taller than the fixed 64-row cache bound keeps its rows: the cache +// used to clear in the middle of a paint, so every row missed again every frame. +func TestCodeEditorShapedCacheHoldsATallViewport(t *testing.T) { + const lines = 70 + const row = "aא" + value := strings.Repeat(row+"\n", lines-1) + row + f := newCodeFixture(value) + engine := &countingShapedEngine{TextEngine: gfx.ReferenceTextEngine()} + f.canvas.SetTextEngine(engine) + f.snapshot.ShapedBidi = true + f.bounds.Height = 2000 + f.paint() + if engine.calls < lines { + t.Fatalf("first paint shaped %d rows, want at least %d", engine.calls, lines) + } + engine.calls = 0 + f.paint() + if engine.calls != 0 { + t.Fatalf("repainting an unchanged viewport shaped %d rows again, want 0", engine.calls) + } +} + +func TestCodeEditorRetainsTheClickedShapedCaretEdge(t *testing.T) { + f := newCodeFixture("a\u05d0\u05d1z") + f.canvas.SetTextEngine(shapedCodeTestEngine{gfx.ReferenceTextEngine()}) + f.snapshot.ShapedBidi = true + f.paint() + cell, _, line := f.cell() + left := f.editor.content.X + y := f.editor.content.Y + line/2 + for _, column := range []float32{1, 3} { + at, ok := f.editor.OffsetAt(gfx.Point{X: left + (column-0.1)*cell, Y: y}) + if !ok || at != 1 { + t.Fatalf("hit near column %g = %d, %v; want byte 1", column, at, ok) + } + f.snapshot.Caret = at + f.paint() + if caret, ok := f.editor.CaretBounds(); !ok || !near(caret.X, left+column*cell) { + t.Errorf("click near %g: IME caret %+v, %v; want X=%g", column, caret, ok, left+column*cell) + } + } + f.snapshot.ShapedBidi = false + f.paint() + if caret, ok := f.editor.CaretBounds(); !ok || !near(caret.X, left+cell) { + t.Errorf("turning off shape kept an alternate edge: %+v, %v", caret, ok) + } +} + +func TestCodeEditorShapedSelectionAndCompositionUseVisualSpans(t *testing.T) { + f := newCodeFixture("a\u05d0\u05d1z") + f.canvas.SetTextEngine(shapedCodeTestEngine{gfx.ReferenceTextEngine()}) + f.snapshot.ShapedBidi = true + f.snapshot.SelectionEnd = 3 + f.snapshot.CompositionStart, f.snapshot.CompositionEnd = 3, 5 + f.paint() + cell, _, _ := f.cell() + left := f.editor.content.X + spans := f.fills(f.theme.Selection) + if len(spans) != 2 || !near(spans[0].X, left) || !near(spans[0].Width, cell) || + !near(spans[1].X, left+2*cell) || !near(spans[1].Width, cell) { + t.Fatalf("selection spanned the wrong visual cells: %+v", spans) + } + found := false + for _, fill := range f.fills(f.theme.Foreground) { + if fill.Height == 1 && near(fill.X, left+cell) && near(fill.Width, cell) { + found = true + } + } + if !found { + t.Fatal("composition did not underline the middle visual cell") + } +} diff --git a/components/doc_test.go b/components/doc_test.go index 7d329427f..c16552bc9 100644 --- a/components/doc_test.go +++ b/components/doc_test.go @@ -24,6 +24,7 @@ var docPrimaryEntries = map[string][]string{ "chart_downsample.go": {"ChartDownsample"}, "code_editor.go": {"CodeEditor"}, "code_editor_layout.go": {"CodeEditor"}, + "code_editor_shaped.go": {"CodeEditor"}, "code_diff.go": {"CodeDiff"}, "code_diff_inline.go": {"CodeDiffInline"}, "code_diff_model.go": {"DiffCodeLines"}, diff --git a/gfx/text_engine.go b/gfx/text_engine.go index c748acee3..36213d32c 100644 --- a/gfx/text_engine.go +++ b/gfx/text_engine.go @@ -47,6 +47,33 @@ type TextHitEngine interface { HitAt(value string, size, weight, x float32) TextHit } +// FittedMonoCaret gives the two edges at one grapheme boundary of a shaped +// monospace run. Leading belongs to the following grapheme; Trailing to the +// preceding one. Positions are logical pixels from the left edge of the run. +type FittedMonoCaret struct { + Offset int + Leading, Trailing float32 +} + +// FittedMonoCaretEngine measures the same shaping and horizontal fit used to +// draw one complete LabelRuns run with Ligatures set. Carets are appended in +// increasing UTF-8 byte order, starting at zero and ending at len(value). +// A false result leaves dst unchanged. +type FittedMonoCaretEngine interface { + TextEngine + FittedMonoCarets(dst []FittedMonoCaret, value string, style TextStyle, span float32) ([]FittedMonoCaret, bool) +} + +// FittedBidiMonoCarets measures a mixed or right-to-left monospace label. It +// returns false when the canvas cannot measure its fitted native shape. +func (canvas *Canvas) FittedBidiMonoCarets(dst []FittedMonoCaret, value string, style TextStyle, span float32) ([]FittedMonoCaret, bool) { + engine, ok := canvas.engine.(FittedMonoCaretEngine) + if !ok || canvas.measurer != nil || span <= 0 || !textmetrics.Bidirectional(value) { + return dst, false + } + return engine.FittedMonoCarets(dst, value, style, span) +} + // TextRasterizer is an optional TextEngine capability that draws one shaped // proportional line into a transparent premultiplied BGRA bitmap at scale. // Width and height are bitmap pixels. The same platform font, fallback and diff --git a/internal/platform/darwin/core_text.m b/internal/platform/darwin/core_text.m index d3bf22a9f..6fd331850 100644 --- a/internal/platform/darwin/core_text.m +++ b/internal/platform/darwin/core_text.m @@ -250,6 +250,33 @@ viva_text_hit viva_text_line_hit_at(const viva_text_line *line, double x) { return (viva_text_hit){index, fabs(x - alternate) < fabs(x - primary) ? alternate : primary}; } +int viva_fitted_mono_carets(const unsigned char *bytes, size_t length, double size, double weight, + int face, double span, viva_fitted_mono_caret *carets, size_t count) { + @autoreleasepool { + NSString *shown = [[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding]; + if (shown == nil) { + return 0; + } + CTLineRef line = viva_mono_fallback_line(shown, viva_mono_font(size, weight, face), face, NULL); + [shown release]; + if (line == NULL) { + return 0; + } + CGFloat width = CTLineGetTypographicBounds(line, NULL, NULL, NULL); + if (width > 0 && span > 0) { + CGFloat scale = span / width; + for (size_t i = 0; i < count; ++i) { + CGFloat leading = 0; + CGFloat trailing = CTLineGetOffsetForStringIndex(line, (CFIndex)carets[i].index, &leading); + carets[i].leading = leading * scale; + carets[i].trailing = trailing * scale; + } + } + CFRelease(line); + return width > 0 && span > 0; + } +} + // The most extents viva_text_line_selection tells apart before it folds the rest into the // last: a selection crossing a change of direction more often than this is not text. #define VIVA_SELECTION_PIECES 32 diff --git a/internal/platform/darwin/native.h b/internal/platform/darwin/native.h index 25cfd55cc..76e40f09e 100644 --- a/internal/platform/darwin/native.h +++ b/internal/platform/darwin/native.h @@ -555,6 +555,12 @@ typedef struct { double x; } viva_text_hit; viva_text_hit viva_text_line_hit_at(const viva_text_line *line, double x); +typedef struct { + size_t index; + double leading, trailing; +} viva_fitted_mono_caret; +int viva_fitted_mono_carets(const unsigned char *bytes, size_t length, double size, double weight, + int face, double span, viva_fitted_mono_caret *carets, size_t count); // viva_text_line_selection writes the extents of [start, end) as (x, width) pairs, left // to right, and returns how many it wrote (at most capacity): one, or several where the // selection crosses a change of direction. diff --git a/internal/platform/darwin/text_engine.go b/internal/platform/darwin/text_engine.go index 5341211ed..b8b1cdcb6 100644 --- a/internal/platform/darwin/text_engine.go +++ b/internal/platform/darwin/text_engine.go @@ -18,6 +18,7 @@ import ( "unsafe" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/grapheme" "github.com/vivaui/viva/internal/textcache" ) @@ -341,6 +342,38 @@ func (engine *TextEngine) HitAt(value string, size, weight, x float32) gfx.TextH return gfx.TextHit{Offset: byteOffset(value, int(hit.index)), X: float32(hit.x)} } +// FittedMonoCarets measures boundaries in the same fitted font used by a +// shaped grid label. The cache for proportional text is not used for this. +func (engine *TextEngine) FittedMonoCarets(dst []gfx.FittedMonoCaret, value string, style gfx.TextStyle, span float32) ([]gfx.FittedMonoCaret, bool) { + if value == "" || !validTextSize(style.Size) || style.Italic || !validTextSize(span) { + return dst, false + } + var scratch [64]C.viva_fitted_mono_caret + native := scratch[:0] + units := 0 + start := len(dst) + for at := 0; ; { + dst = append(dst, gfx.FittedMonoCaret{Offset: at}) + native = append(native, C.viva_fitted_mono_caret{index: C.size_t(units)}) + if at == len(value) { + break + } + next := grapheme.Next(value, at) + for _, r := range value[at:next] { + units += utf16Units(r) + } + at = next + } + bytes := (*C.uchar)(unsafe.Pointer(unsafe.StringData(value))) + if C.viva_fitted_mono_carets(bytes, C.size_t(len(value)), C.double(style.Size), C.double(style.Weight), C.int(style.MonoFace), C.double(span), &native[0], C.size_t(len(native))) == 0 { + return dst[:start], false + } + for i, caret := range native { + dst[start+i].Leading, dst[start+i].Trailing = float32(caret.leading), float32(caret.trailing) + } + return dst, true +} + func (engine *TextEngine) OffsetAtStyle(value string, size, weight float32, italic bool, x float32) int { if value == "" || size <= 0 { return 0 diff --git a/tools/docs/catalog.go b/tools/docs/catalog.go index 39d258c17..c03575843 100644 --- a/tools/docs/catalog.go +++ b/tools/docs/catalog.go @@ -127,7 +127,7 @@ func loadPages(root string) ([]Page, Manifest, error) { // bars its examples show. if file.Name() == "doc.go" || file.Name() == "direction.go" || file.Name() == "menu_typeahead.go" || file.Name() == "code_diff_model.go" || file.Name() == "code_diff_inline.go" || - file.Name() == "code_editor_layout.go" || file.Name() == "code_editor_decorations.go" || file.Name() == "caret_blink.go" || file.Name() == "find_bar.go" || file.Name() == "go_to_line.go" || file.Name() == "hierarchy_menu.go" || + file.Name() == "code_editor_layout.go" || file.Name() == "code_editor_decorations.go" || file.Name() == "code_editor_shaped.go" || file.Name() == "caret_blink.go" || file.Name() == "find_bar.go" || file.Name() == "go_to_line.go" || file.Name() == "hierarchy_menu.go" || file.Name() == "graph_sim.go" || file.Name() == "markdown_anchor.go" || file.Name() == "text_selection.go" { continue } From ee7ba1300f84a9a773f20a7fc1e1d9d9bcd962fb Mon Sep 17 00:00:00 2001 From: ccq <76206374+caichangqing1120@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:46:29 +0800 Subject: [PATCH 63/64] feat(components): keep shaped bidi placement across wraps and tabs --- cmd/viva/templates/code_editor.go.txt | 26 ++-- cmd/viva/templates/code_editor_layout.go.txt | 2 +- cmd/viva/templates/code_editor_shaped.go.txt | 131 +++++++++++++++---- components/code_editor.go | 28 ++-- components/code_editor_layout.go | 2 +- components/code_editor_shaped.go | 111 +++++++++++++--- components/code_editor_shaped_darwin_test.go | 102 +++++++++++++++ gfx/canvas.go | 4 +- internal/platform/darwin/core.h | 1 + internal/platform/darwin/core_render.m | 3 +- internal/platform/darwin/core_text.m | 14 +- 11 files changed, 353 insertions(+), 71 deletions(-) diff --git a/cmd/viva/templates/code_editor.go.txt b/cmd/viva/templates/code_editor.go.txt index 60ac391c7..ee9dcd661 100644 --- a/cmd/viva/templates/code_editor.go.txt +++ b/cmd/viva/templates/code_editor.go.txt @@ -139,9 +139,14 @@ type CodeEditorSnapshot struct { FontSize float32 // MonoFace is the fixed-pitch font the code is set in. MonoFace gfx.MonoFace - // ShapedBidi opts unwrapped plain grid rows into native bidi shaping where - // available. Tabs, representations and visual whitespace/indent markers - // still use the logical grid, as do editors with highlighting or decorations. + // ShapedBidi opts plain grid rows into native bidi shaping where available. + // Representations and visual whitespace/indent markers still use the logical + // grid, as do editors with highlighting or decorations. A row over 4096 + // bytes keeps the grid, and a platform whose text engine cannot shape a + // fitted monospaced run draws the grid unchanged. A wrapped continuation + // takes its paragraph's base direction, not the full bidi levels a strong + // context before the break could give it; an explicit embedding or isolate + // keeps the grid. // Horizontal movement remains caller-owned. ShapedBidi bool // TabWidth is the width of a tab stop in cells; zero is four. @@ -1048,11 +1053,7 @@ func (paint *codePaint) row(index int, y float32) { paint.lineEnding(row, y, left) } if paint.showWrapSymbol && editor.softWrapped(index) { - canvas.Label("↪", gfx.Rect{ - X: editor.content.X + editor.content.Width - paint.cellWidth, - Y: y + (paint.lineHeight-paint.cellHeight)/2, - Width: paint.cellWidth, Height: paint.cellHeight, - }, gfx.TextStyle{Size: paint.size * 0.75, Color: paint.invisibleColor, Mono: true, MonoFace: paint.face}) + paint.wrapSymbol(y) } if !paint.deferOverlays { @@ -1060,6 +1061,15 @@ func (paint *codePaint) row(index int, y float32) { } } +func (paint *codePaint) wrapSymbol(y float32) { + content := paint.editor.content + paint.canvas.Label("↪", gfx.Rect{ + X: content.X + content.Width - paint.cellWidth, + Y: y + (paint.lineHeight-paint.cellHeight)/2, + Width: paint.cellWidth, Height: paint.cellHeight, + }, gfx.TextStyle{Size: paint.size * 0.75, Color: paint.invisibleColor, Mono: true, MonoFace: paint.face}) +} + func (paint *codePaint) overlays(index int, y float32) { editor, canvas := paint.editor, paint.canvas row := editor.rows[index] diff --git a/cmd/viva/templates/code_editor_layout.go.txt b/cmd/viva/templates/code_editor_layout.go.txt index ab58dc6f9..7f7ab7342 100644 --- a/cmd/viva/templates/code_editor_layout.go.txt +++ b/cmd/viva/templates/code_editor_layout.go.txt @@ -564,7 +564,7 @@ func (editor *CodeEditor) OffsetWithVirtualAt(point gfx.Point) (offset, virtualC if hit, shaped := editor.shapedHit(row, x); shaped { editor.rememberShapedHit(row, hit) editor.goalActive = false - editor.setUpstream(hit.Offset, false) + editor.setUpstream(hit.Offset, hit.Offset == int(row.end) && editor.softWrapped(index)) return hit.Offset, 0, true } if editor.shaping != nil { diff --git a/cmd/viva/templates/code_editor_shaped.go.txt b/cmd/viva/templates/code_editor_shaped.go.txt index b68a42ba8..eab2e2a8b 100644 --- a/cmd/viva/templates/code_editor_shaped.go.txt +++ b/cmd/viva/templates/code_editor_shaped.go.txt @@ -15,14 +15,27 @@ type codeShaping struct { style gfx.TextStyle cell float32 generation uint32 - rows map[int32][]gfx.FittedMonoCaret - hit gfx.TextHit - hitRow int32 - hitValid bool + cols int + tabWidth int + wrap bool + rows map[int32]codeShapedRow + // limit is the most rows the cache keeps: the visible rows of the last + // paint, and never fewer than the old fixed bound. A viewport taller than + // that bound used to clear the cache in the middle of the paint, so every + // row missed again on the next frame. + limit int + hit gfx.TextHit + hitRow int32 + hitValid bool +} + +type codeShapedRow struct { + value string + carets []gfx.FittedMonoCaret } func (editor *CodeEditor) configureShaping(canvas *gfx.Canvas, snapshot CodeEditorSnapshot, size, cell float32) { - if !snapshot.ShapedBidi || snapshot.Wrap || len(snapshot.Representations) != 0 || snapshot.ShowWhitespace || + if !snapshot.ShapedBidi || len(snapshot.Representations) != 0 || snapshot.ShowWhitespace || snapshot.ShowIndentGuides || snapshot.ShowEOL || snapshot.Decorations != nil || snapshot.Highlight != nil || snapshot.HighlightLine != nil { editor.shaping = nil return @@ -30,10 +43,20 @@ func (editor *CodeEditor) configureShaping(canvas *gfx.Canvas, snapshot CodeEdit style := gfx.TextStyle{Size: size, Mono: true, MonoFace: snapshot.MonoFace} generation := canvas.FontGeneration() s := editor.shaping - if s == nil || s.canvas != canvas || s.value != editor.text || s.style != style || s.cell != cell || s.generation != generation { - s = &codeShaping{canvas: canvas, value: editor.text, style: style, cell: cell, generation: generation, rows: make(map[int32][]gfx.FittedMonoCaret)} + if s == nil || s.canvas != canvas || s.value != editor.text || s.style != style || s.cell != cell || s.generation != generation || + s.cols != editor.cols || s.tabWidth != editor.tabWidth || s.wrap != editor.wrap { + s = &codeShaping{canvas: canvas, value: editor.text, style: style, cell: cell, generation: generation, + cols: editor.cols, tabWidth: editor.tabWidth, wrap: editor.wrap, rows: make(map[int32]codeShapedRow)} editor.shaping = s } + limit := 64 + if visible := int(editor.content.Height/editor.lineHeight) + 2; visible > limit { + limit = visible + } + s.limit = limit + if len(s.rows) > limit { + clear(s.rows) + } if s.hitValid && s.hit.Offset != snapshot.Caret { s.hitValid = false } @@ -42,25 +65,78 @@ func (editor *CodeEditor) configureShaping(canvas *gfx.Canvas, snapshot CodeEdit func (editor *CodeEditor) shapedRow(row codeRow) []gfx.FittedMonoCaret { s := editor.shaping // Bound both the cost of shaping a single line and the number of cached rows. - if s == nil || row.shown >= 0 || row.end <= row.start || row.end-row.start > 4096 { + if s == nil || row.end <= row.start || row.end-row.start > 4096 { return nil } - if carets, ok := s.rows[row.start]; ok { - return carets + if shaped, ok := s.rows[row.start]; ok { + return shaped.carets } - value := s.value[row.start:row.end] - if strings.IndexByte(value, '\t') >= 0 { - return nil + shaped := editor.measureShapedRow(row) + s.rows[row.start] = shaped + return shaped.carets +} + +func (editor *CodeEditor) measureShapedRow(row codeRow) codeShapedRow { + s := editor.shaping + value := editor.rowText(row) + var prefix string + if editor.wrap { + // Give each plain continuation the base direction of its logical line. + // Explicit embedding and isolate state cannot be reconstructed by a mark. + line := editor.text[row.lineStart:] + if len(line) > 4097 { + line = line[:4097] + } + if end := strings.IndexByte(line, '\n'); end >= 0 { + line = line[:end] + } + if len(line) > 4096 || strings.ContainsAny(line, "\u202a\u202b\u202c\u202d\u202e\u2066\u2067\u2068\u2069") { + return codeShapedRow{} + } + dir := gfx.TextDirectionOf(line) + if dir != gfx.TextDirectionOf(value) { + prefix = "\u200e" + if dir == gfx.DirectionRTL { + prefix = "\u200f" + } + } } - carets, ok := s.canvas.FittedBidiMonoCarets(nil, value, s.style, float32(row.cells)*s.cell) - if !ok || len(carets) < 2 || carets[0].Offset != 0 || carets[len(carets)-1].Offset != len(value) { - carets = nil + label := prefix + value + carets, ok := s.canvas.FittedBidiMonoCarets(nil, label, s.style, float32(row.cells)*s.cell) + if !ok || len(carets) < 2 || carets[0].Offset != 0 || carets[len(carets)-1].Offset != len(label) { + return codeShapedRow{} } - if len(s.rows) >= 64 { - clear(s.rows) + if row.shown >= 0 || prefix != "" { + // Retain only source grapheme boundaries. Every byte of an expanded tab + // lies between the same two source offsets; the direction mark has none. + source := editor.text[row.start:row.end] + mapped := carets[:0] + column, rendered, at := 0, len(prefix), 0 + for offset := 0; ; { + for at < len(carets) && carets[at].Offset < rendered { + at++ + } + if at == len(carets) || carets[at].Offset != rendered { + return codeShapedRow{} + } + caret := carets[at] + caret.Offset = offset + mapped = append(mapped, caret) + if offset == len(source) { + break + } + next, cells := editor.gridCluster(source, offset, column) + if source[offset] == '\t' { + rendered += cells + } else { + rendered += next - offset + } + column += cells + offset = next + } + carets = mapped } - s.rows[row.start] = carets - return carets + return codeShapedRow{value: label, carets: carets} } func (editor *CodeEditor) shapedCaretX(row codeRow, offset int) (float32, bool) { @@ -196,7 +272,7 @@ func (paint *codePaint) shapedRow(index int, row codeRow, y float32, carets []gf return } fill(from, to, paint.selectionBackground) - if to > end && end < len(paint.value) { + if to > end && end < len(paint.value) && !paint.editor.softWrapped(index) { extra := paint.cellWidth / 2 x := left + carets[len(carets)-1].Trailing if carets[0].Leading > carets[len(carets)-1].Trailing { @@ -216,17 +292,20 @@ func (paint *codePaint) shapedRow(index int, row codeRow, y float32, carets []gf selection(span.Start, span.End) } } - value := paint.value[start:end] + value := paint.editor.shaping.rows[row.start].value bounds := gfx.Rect{X: left, Y: y + (paint.lineHeight-paint.cellHeight)/2, Width: float32(row.cells) * paint.cellWidth, Height: paint.cellHeight} run := gfx.TextRun{Bytes: int32(len(value)), Cells: row.cells, Ligatures: true, Color: paint.foreground} style := gfx.TextStyle{Size: paint.size, Color: paint.foreground, Mono: true, MonoFace: paint.face} paint.canvas.LabelRuns(value, bounds, style, paint.cellWidth, []gfx.TextRun{run}) run.Color = paint.selectionForeground - paint.shapedSelectionText(carets, start, value, bounds, run) + paint.shapedSelectionText(carets, start, end, value, bounds, run) + if paint.showWrapSymbol && paint.editor.softWrapped(index) { + paint.wrapSymbol(y) + } paint.overlays(index, y) } -func (paint *codePaint) shapedSelectionText(carets []gfx.FittedMonoCaret, start int, value string, bounds gfx.Rect, run gfx.TextRun) { +func (paint *codePaint) shapedSelectionText(carets []gfx.FittedMonoCaret, start, end int, value string, bounds gfx.Rect, run gfx.TextRun) { style := gfx.TextStyle{Size: paint.size, Mono: true, MonoFace: paint.face, Color: run.Color} paintSelection := func(from, to int) { paint.shapedSpans = codeShapedSpans(paint.shapedSpans, carets, from-start, to-start) @@ -239,14 +318,14 @@ func (paint *codePaint) shapedSelectionText(carets []gfx.FittedMonoCaret, start } if len(paint.selectionRanges) != 0 { for _, selection := range paint.selectionRanges { - if selection.Start >= start+len(value) { + if selection.Start >= end { break } if selection.End > start { paintSelection(selection.Start, selection.End) } } - } else if paint.selectionEnd > start && paint.selectionStart < start+len(value) { + } else if paint.selectionEnd > start && paint.selectionStart < end { paintSelection(paint.selectionStart, paint.selectionEnd) } } diff --git a/components/code_editor.go b/components/code_editor.go index afa54bcfc..eccd3c3e1 100644 --- a/components/code_editor.go +++ b/components/code_editor.go @@ -139,11 +139,14 @@ type CodeEditorSnapshot struct { FontSize float32 // MonoFace is the fixed-pitch font the code is set in. MonoFace gfx.MonoFace - // ShapedBidi opts unwrapped plain grid rows into native bidi shaping where - // available. Tabs, representations and visual whitespace/indent markers - // still use the logical grid, as do editors with highlighting or decorations. - // A row over 4096 bytes keeps the grid, and a platform whose text engine - // cannot shape a fitted monospaced run draws the grid unchanged. + // ShapedBidi opts plain grid rows into native bidi shaping where available. + // Representations and visual whitespace/indent markers still use the logical + // grid, as do editors with highlighting or decorations. A row over 4096 + // bytes keeps the grid, and a platform whose text engine cannot shape a + // fitted monospaced run draws the grid unchanged. A wrapped continuation + // takes its paragraph's base direction, not the full bidi levels a strong + // context before the break could give it; an explicit embedding or isolate + // keeps the grid. // Horizontal movement remains caller-owned. ShapedBidi bool // TabWidth is the width of a tab stop in cells; zero is four. @@ -1050,11 +1053,7 @@ func (paint *codePaint) row(index int, y float32) { paint.lineEnding(row, y, left) } if paint.showWrapSymbol && editor.softWrapped(index) { - canvas.Label("↪", gfx.Rect{ - X: editor.content.X + editor.content.Width - paint.cellWidth, - Y: y + (paint.lineHeight-paint.cellHeight)/2, - Width: paint.cellWidth, Height: paint.cellHeight, - }, gfx.TextStyle{Size: paint.size * 0.75, Color: paint.invisibleColor, Mono: true, MonoFace: paint.face}) + paint.wrapSymbol(y) } if !paint.deferOverlays { @@ -1062,6 +1061,15 @@ func (paint *codePaint) row(index int, y float32) { } } +func (paint *codePaint) wrapSymbol(y float32) { + content := paint.editor.content + paint.canvas.Label("↪", gfx.Rect{ + X: content.X + content.Width - paint.cellWidth, + Y: y + (paint.lineHeight-paint.cellHeight)/2, + Width: paint.cellWidth, Height: paint.cellHeight, + }, gfx.TextStyle{Size: paint.size * 0.75, Color: paint.invisibleColor, Mono: true, MonoFace: paint.face}) +} + func (paint *codePaint) overlays(index int, y float32) { editor, canvas := paint.editor, paint.canvas row := editor.rows[index] diff --git a/components/code_editor_layout.go b/components/code_editor_layout.go index b4866f95e..ea9a9696c 100644 --- a/components/code_editor_layout.go +++ b/components/code_editor_layout.go @@ -564,7 +564,7 @@ func (editor *CodeEditor) OffsetWithVirtualAt(point gfx.Point) (offset, virtualC if hit, shaped := editor.shapedHit(row, x); shaped { editor.rememberShapedHit(row, hit) editor.goalActive = false - editor.setUpstream(hit.Offset, false) + editor.setUpstream(hit.Offset, hit.Offset == int(row.end) && editor.softWrapped(index)) return hit.Offset, 0, true } if editor.shaping != nil { diff --git a/components/code_editor_shaped.go b/components/code_editor_shaped.go index cebaf7c3f..ef7025b0a 100644 --- a/components/code_editor_shaped.go +++ b/components/code_editor_shaped.go @@ -15,7 +15,10 @@ type codeShaping struct { style gfx.TextStyle cell float32 generation uint32 - rows map[int32][]gfx.FittedMonoCaret + cols int + tabWidth int + wrap bool + rows map[int32]codeShapedRow // limit is the most rows the cache keeps: the visible rows of the last // paint, and never fewer than the old fixed bound. A viewport taller than // that bound used to clear the cache in the middle of the paint, so every @@ -26,8 +29,13 @@ type codeShaping struct { hitValid bool } +type codeShapedRow struct { + value string + carets []gfx.FittedMonoCaret +} + func (editor *CodeEditor) configureShaping(canvas *gfx.Canvas, snapshot CodeEditorSnapshot, size, cell float32) { - if !snapshot.ShapedBidi || snapshot.Wrap || len(snapshot.Representations) != 0 || snapshot.ShowWhitespace || + if !snapshot.ShapedBidi || len(snapshot.Representations) != 0 || snapshot.ShowWhitespace || snapshot.ShowIndentGuides || snapshot.ShowEOL || snapshot.Decorations != nil || snapshot.Highlight != nil || snapshot.HighlightLine != nil { editor.shaping = nil return @@ -35,8 +43,10 @@ func (editor *CodeEditor) configureShaping(canvas *gfx.Canvas, snapshot CodeEdit style := gfx.TextStyle{Size: size, Mono: true, MonoFace: snapshot.MonoFace} generation := canvas.FontGeneration() s := editor.shaping - if s == nil || s.canvas != canvas || s.value != editor.text || s.style != style || s.cell != cell || s.generation != generation { - s = &codeShaping{canvas: canvas, value: editor.text, style: style, cell: cell, generation: generation, rows: make(map[int32][]gfx.FittedMonoCaret)} + if s == nil || s.canvas != canvas || s.value != editor.text || s.style != style || s.cell != cell || s.generation != generation || + s.cols != editor.cols || s.tabWidth != editor.tabWidth || s.wrap != editor.wrap { + s = &codeShaping{canvas: canvas, value: editor.text, style: style, cell: cell, generation: generation, + cols: editor.cols, tabWidth: editor.tabWidth, wrap: editor.wrap, rows: make(map[int32]codeShapedRow)} editor.shaping = s } limit := 64 @@ -55,22 +65,78 @@ func (editor *CodeEditor) configureShaping(canvas *gfx.Canvas, snapshot CodeEdit func (editor *CodeEditor) shapedRow(row codeRow) []gfx.FittedMonoCaret { s := editor.shaping // Bound both the cost of shaping a single line and the number of cached rows. - if s == nil || row.shown >= 0 || row.end <= row.start || row.end-row.start > 4096 { + if s == nil || row.end <= row.start || row.end-row.start > 4096 { return nil } - if carets, ok := s.rows[row.start]; ok { - return carets + if shaped, ok := s.rows[row.start]; ok { + return shaped.carets } - value := s.value[row.start:row.end] - if strings.IndexByte(value, '\t') >= 0 { - return nil + shaped := editor.measureShapedRow(row) + s.rows[row.start] = shaped + return shaped.carets +} + +func (editor *CodeEditor) measureShapedRow(row codeRow) codeShapedRow { + s := editor.shaping + value := editor.rowText(row) + var prefix string + if editor.wrap { + // Give each plain continuation the base direction of its logical line. + // Explicit embedding and isolate state cannot be reconstructed by a mark. + line := editor.text[row.lineStart:] + if len(line) > 4097 { + line = line[:4097] + } + if end := strings.IndexByte(line, '\n'); end >= 0 { + line = line[:end] + } + if len(line) > 4096 || strings.ContainsAny(line, "\u202a\u202b\u202c\u202d\u202e\u2066\u2067\u2068\u2069") { + return codeShapedRow{} + } + dir := gfx.TextDirectionOf(line) + if dir != gfx.TextDirectionOf(value) { + prefix = "\u200e" + if dir == gfx.DirectionRTL { + prefix = "\u200f" + } + } } - carets, ok := s.canvas.FittedBidiMonoCarets(nil, value, s.style, float32(row.cells)*s.cell) - if !ok || len(carets) < 2 || carets[0].Offset != 0 || carets[len(carets)-1].Offset != len(value) { - carets = nil + label := prefix + value + carets, ok := s.canvas.FittedBidiMonoCarets(nil, label, s.style, float32(row.cells)*s.cell) + if !ok || len(carets) < 2 || carets[0].Offset != 0 || carets[len(carets)-1].Offset != len(label) { + return codeShapedRow{} } - s.rows[row.start] = carets - return carets + if row.shown >= 0 || prefix != "" { + // Retain only source grapheme boundaries. Every byte of an expanded tab + // lies between the same two source offsets; the direction mark has none. + source := editor.text[row.start:row.end] + mapped := carets[:0] + column, rendered, at := 0, len(prefix), 0 + for offset := 0; ; { + for at < len(carets) && carets[at].Offset < rendered { + at++ + } + if at == len(carets) || carets[at].Offset != rendered { + return codeShapedRow{} + } + caret := carets[at] + caret.Offset = offset + mapped = append(mapped, caret) + if offset == len(source) { + break + } + next, cells := editor.gridCluster(source, offset, column) + if source[offset] == '\t' { + rendered += cells + } else { + rendered += next - offset + } + column += cells + offset = next + } + carets = mapped + } + return codeShapedRow{value: label, carets: carets} } func (editor *CodeEditor) shapedCaretX(row codeRow, offset int) (float32, bool) { @@ -206,7 +272,7 @@ func (paint *codePaint) shapedRow(index int, row codeRow, y float32, carets []gf return } fill(from, to, paint.selectionBackground) - if to > end && end < len(paint.value) { + if to > end && end < len(paint.value) && !paint.editor.softWrapped(index) { extra := paint.cellWidth / 2 x := left + carets[len(carets)-1].Trailing if carets[0].Leading > carets[len(carets)-1].Trailing { @@ -226,17 +292,20 @@ func (paint *codePaint) shapedRow(index int, row codeRow, y float32, carets []gf selection(span.Start, span.End) } } - value := paint.value[start:end] + value := paint.editor.shaping.rows[row.start].value bounds := gfx.Rect{X: left, Y: y + (paint.lineHeight-paint.cellHeight)/2, Width: float32(row.cells) * paint.cellWidth, Height: paint.cellHeight} run := gfx.TextRun{Bytes: int32(len(value)), Cells: row.cells, Ligatures: true, Color: paint.foreground} style := gfx.TextStyle{Size: paint.size, Color: paint.foreground, Mono: true, MonoFace: paint.face} paint.canvas.LabelRuns(value, bounds, style, paint.cellWidth, []gfx.TextRun{run}) run.Color = paint.selectionForeground - paint.shapedSelectionText(carets, start, value, bounds, run) + paint.shapedSelectionText(carets, start, end, value, bounds, run) + if paint.showWrapSymbol && paint.editor.softWrapped(index) { + paint.wrapSymbol(y) + } paint.overlays(index, y) } -func (paint *codePaint) shapedSelectionText(carets []gfx.FittedMonoCaret, start int, value string, bounds gfx.Rect, run gfx.TextRun) { +func (paint *codePaint) shapedSelectionText(carets []gfx.FittedMonoCaret, start, end int, value string, bounds gfx.Rect, run gfx.TextRun) { style := gfx.TextStyle{Size: paint.size, Mono: true, MonoFace: paint.face, Color: run.Color} paintSelection := func(from, to int) { paint.shapedSpans = codeShapedSpans(paint.shapedSpans, carets, from-start, to-start) @@ -249,14 +318,14 @@ func (paint *codePaint) shapedSelectionText(carets []gfx.FittedMonoCaret, start } if len(paint.selectionRanges) != 0 { for _, selection := range paint.selectionRanges { - if selection.Start >= start+len(value) { + if selection.Start >= end { break } if selection.End > start { paintSelection(selection.Start, selection.End) } } - } else if paint.selectionEnd > start && paint.selectionStart < start+len(value) { + } else if paint.selectionEnd > start && paint.selectionStart < end { paintSelection(paint.selectionStart, paint.selectionEnd) } } diff --git a/components/code_editor_shaped_darwin_test.go b/components/code_editor_shaped_darwin_test.go index e93021fec..b686aef92 100644 --- a/components/code_editor_shaped_darwin_test.go +++ b/components/code_editor_shaped_darwin_test.go @@ -47,3 +47,105 @@ func TestCodeEditorCoreTextKeepsFittedArabicCaretEdges(t *testing.T) { } } } + +func TestCodeEditorCoreTextWrapKeepsBothRowsOfTheBoundary(t *testing.T) { + const first = "\u05d0\u05d1 " + const value = first + "cd" + f := newCodeFixture(value) + f.canvas.SetTextEngine(darwin.SharedTextEngine()) + f.snapshot.ShapedBidi = true + f.snapshot.Wrap = true + f.bounds.Width = f.widthFor(3) + f.paint() + rows := f.editor.rows + if len(rows) != 2 || int(rows[0].end) != len(first) { + t.Fatalf("expected a soft wrap after %q: %+v", first, rows) + } + labels := f.canvas.Texts() + if len(labels) != 2 || labels[0].Value != first || labels[1].Value != "\u200fcd" { + t.Fatalf("the continuation should inherit the RTL paragraph direction: %+v", labels) + } + for index, row := range rows { + carets := f.editor.shapedRow(row) + if len(carets) == 0 { + t.Fatalf("row %d did not retain shaped geometry", index) + } + x := carets[0].Leading + inside := carets[1].Trailing + if index == 0 { + x = carets[len(carets)-1].Trailing + inside = carets[len(carets)-2].Leading + } + left, top := f.editor.content.X, f.editor.content.Y + line := f.editor.lineHeight + point := gfx.Point{X: left + x + 0.1*(inside-x), Y: top + (float32(index)+0.5)*line} + at, ok := f.editor.OffsetAt(point) + if !ok || at != len(first) { + t.Fatalf("hit row %d: byte %d, %v; want %d", index, at, ok, len(first)) + } + f.snapshot.Caret = at + f.paint() + caret, ok := f.editor.CaretBounds() + if !ok || !near(caret.Y, top+float32(index)*line) || !near(caret.X, left+x) { + t.Errorf("hit row %d painted caret %+v, %v; want (%g,%g)", index, caret, ok, left+x, top+float32(index)*line) + } + } + f.snapshot.Wrap = false + f.bounds.Width = f.widthFor(12) + f.paint() + if labels := f.canvas.Texts(); len(labels) != 1 || labels[0].Value != value { + t.Errorf("switching wrap off retained a cached continuation: %+v", labels) + } +} + +func TestCodeEditorCoreTextTabUsesOnlySourceOffsets(t *testing.T) { + const value = "\u05d0\u05d1\tx" + const before, after = len("\u05d0\u05d1"), len("\u05d0\u05d1\t") + f := newCodeFixture(value) + f.canvas.SetTextEngine(darwin.SharedTextEngine()) + f.snapshot.ShapedBidi = true + f.snapshot.TabWidth = 8 + f.paint() + row := f.editor.rows[0] + carets := f.editor.shapedRow(row) + if len(carets) != 5 || carets[2].Offset != before || carets[3].Offset != after || carets[4].Offset != len(value) { + t.Fatalf("expanded tab must not be hit as multiple source bytes: %+v", carets) + } + labels := f.canvas.Texts() + if len(labels) != 1 || labels[0].Value != "\u05d0\u05d1 x" { + t.Fatalf("expected the expanded text as one shaped label: %+v", labels) + } + lead, trail := carets[2].Leading, carets[3].Trailing + for _, check := range []struct { + fraction float32 + want int + }{{0.2, before}, {0.8, after}} { + left, top := f.editor.content.X, f.editor.content.Y + point := gfx.Point{X: left + lead + (trail-lead)*check.fraction, Y: top + 0.5*f.editor.lineHeight} + if at, ok := f.editor.OffsetAt(point); !ok || at != check.want { + t.Errorf("hit at %.2f of tab = %d, %v; want %d", check.fraction, at, ok, check.want) + } + } + f.snapshot.TabWidth = 4 + f.paint() + if labels := f.canvas.Texts(); len(labels) != 1 || labels[0].Value != "\u05d0\u05d1 x" { + t.Errorf("changing the tab width retained the old shaped label: %+v", labels) + } +} + +func TestCodeEditorCoreTextWrapInheritsLTRBeforeHebrew(t *testing.T) { + const value = "ab \u05d0\u05d1" + f := newCodeFixture(value) + f.canvas.SetTextEngine(darwin.SharedTextEngine()) + f.snapshot.ShapedBidi, f.snapshot.Wrap, f.snapshot.ShowWrapSymbol = true, true, true + f.bounds.Width = f.widthFor(4) + f.paint() + var label, marker bool + for _, text := range f.canvas.Texts() { + label = label || text.Value == "\u200e\u05d0\u05d1" + marker = marker || text.Value == "\u21aa" + } + if !label || !marker { + t.Errorf("inherited LTR label=%t, wrap marker=%t; both should paint", label, marker) + } +} diff --git a/gfx/canvas.go b/gfx/canvas.go index 5322050bb..b13d945e1 100644 --- a/gfx/canvas.go +++ b/gfx/canvas.go @@ -222,7 +222,9 @@ const ( // Ligatures asks the fixed-pitch renderer to shape the run as one line instead // of placing one glyph per cell, so a font's programming ligatures appear. The // shaped run is fitted to the run's full cell span; it therefore needs ASCII -// text and at least two cells. Other runs keep the one-glyph-per-cell rule. +// text and at least two cells. A run that Canvas.FittedBidiMonoCarets measured +// is the exception: its mixed-direction label is shaped whole so its joins and +// caret positions survive. Other runs keep the one-glyph-per-cell rule. type TextRun struct { Column int32 Bytes int32 diff --git a/internal/platform/darwin/core.h b/internal/platform/darwin/core.h index 9b0f4b3d2..8210b010a 100644 --- a/internal/platform/darwin/core.h +++ b/internal/platform/darwin/core.h @@ -268,6 +268,7 @@ NSString *viva_mono_fallback_family(NSString *cluster); BOOL viva_mono_is_last_resort_name(CFStringRef name); BOOL viva_mono_font_is_last_resort(CTFontRef font); CTLineRef viva_mono_fallback_line(NSString *value, VivaFont *base, int face, CGColorRef color); +CGFloat viva_fitted_mono_origin(CTLineRef line, CFIndex length); void viva_prepare_text_context(CGContextRef context, CGFloat scale); void viva_draw_terminal_preedit( CGContextRef context, NSString *shown, CGFloat fontSize, int monoFace, diff --git a/internal/platform/darwin/core_render.m b/internal/platform/darwin/core_render.m index 026224d05..1753f832c 100644 --- a/internal/platform/darwin/core_render.m +++ b/internal/platform/darwin/core_render.m @@ -1002,7 +1002,8 @@ - (void)drawRunsInContext:(CGContextRef)context pixelScale:(CGFloat)pixelScale { CGContextSaveGState(context); CGContextTranslateCTM(context, cellLeft, baseline); CGContextScaleCTM(context, span / width, 1); - CGContextSetTextPosition(context, 0, 0); + CGFloat origin = ascii ? 0 : viva_fitted_mono_origin(line, (CFIndex)shown.length); + CGContextSetTextPosition(context, -origin, 0); CTLineDraw(line, context); CGContextRestoreGState(context); } diff --git a/internal/platform/darwin/core_text.m b/internal/platform/darwin/core_text.m index 6fd331850..ca59194e1 100644 --- a/internal/platform/darwin/core_text.m +++ b/internal/platform/darwin/core_text.m @@ -250,6 +250,14 @@ viva_text_hit viva_text_line_hit_at(const viva_text_line *line, double x) { return (viva_text_hit){index, fabs(x - alternate) < fabs(x - primary) ? alternate : primary}; } +CGFloat viva_fitted_mono_origin(CTLineRef line, CFIndex length) { + // CoreText puts trailing RTL whitespace before the line's origin, but + // includes its advance in typographic width. Fit both into the grid span. + CGFloat alternate = 0; + CGFloat end = CTLineGetOffsetForStringIndex(line, length, &alternate); + return MIN(0, MIN(end, alternate)); +} + int viva_fitted_mono_carets(const unsigned char *bytes, size_t length, double size, double weight, int face, double span, viva_fitted_mono_caret *carets, size_t count) { @autoreleasepool { @@ -257,6 +265,7 @@ int viva_fitted_mono_carets(const unsigned char *bytes, size_t length, double si if (shown == nil) { return 0; } + CFIndex units = (CFIndex)shown.length; CTLineRef line = viva_mono_fallback_line(shown, viva_mono_font(size, weight, face), face, NULL); [shown release]; if (line == NULL) { @@ -265,11 +274,12 @@ int viva_fitted_mono_carets(const unsigned char *bytes, size_t length, double si CGFloat width = CTLineGetTypographicBounds(line, NULL, NULL, NULL); if (width > 0 && span > 0) { CGFloat scale = span / width; + CGFloat origin = viva_fitted_mono_origin(line, units); for (size_t i = 0; i < count; ++i) { CGFloat leading = 0; CGFloat trailing = CTLineGetOffsetForStringIndex(line, (CFIndex)carets[i].index, &leading); - carets[i].leading = leading * scale; - carets[i].trailing = trailing * scale; + carets[i].leading = (leading - origin) * scale; + carets[i].trailing = (trailing - origin) * scale; } } CFRelease(line); From 68be843c3195255764aab556ec3a2c2cde8089cb Mon Sep 17 00:00:00 2001 From: ccq <76206374+caichangqing1120@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:49:53 +0800 Subject: [PATCH 64/64] feat(components): preserve shaped bidi geometry under syntax styles --- cmd/viva/templates/code_editor.go.txt | 14 +-- cmd/viva/templates/code_editor_shaped.go.txt | 108 ++++++++++++++---- components/code_editor.go | 14 +-- components/code_editor_shaped.go | 108 ++++++++++++++---- components/code_editor_shaped_darwin_test.go | 56 +++++++++ components/code_editor_shaped_test.go | 36 ++++++ internal/platform/darwin/core_render.m | 21 +++- .../darwin/text_italic_regression_test.go | 50 ++++++++ 8 files changed, 339 insertions(+), 68 deletions(-) diff --git a/cmd/viva/templates/code_editor.go.txt b/cmd/viva/templates/code_editor.go.txt index ee9dcd661..984d1dd80 100644 --- a/cmd/viva/templates/code_editor.go.txt +++ b/cmd/viva/templates/code_editor.go.txt @@ -139,14 +139,14 @@ type CodeEditorSnapshot struct { FontSize float32 // MonoFace is the fixed-pitch font the code is set in. MonoFace gfx.MonoFace - // ShapedBidi opts plain grid rows into native bidi shaping where available. + // ShapedBidi opts grid rows into native bidi shaping where available. // Representations and visual whitespace/indent markers still use the logical - // grid, as do editors with highlighting or decorations. A row over 4096 - // bytes keeps the grid, and a platform whose text engine cannot shape a - // fitted monospaced run draws the grid unchanged. A wrapped continuation - // takes its paragraph's base direction, not the full bidi levels a strong - // context before the break could give it; an explicit embedding or isolate - // keeps the grid. + // grid, as do editors with custom decorations. A row over 4096 bytes keeps + // the grid, and a platform whose text engine cannot shape a fitted + // monospaced run draws the grid unchanged. A wrapped continuation takes its + // paragraph's base direction, not the full bidi levels a strong context + // before the break could give it; an explicit embedding or isolate keeps the + // grid. // Horizontal movement remains caller-owned. ShapedBidi bool // TabWidth is the width of a tab stop in cells; zero is four. diff --git a/cmd/viva/templates/code_editor_shaped.go.txt b/cmd/viva/templates/code_editor_shaped.go.txt index eab2e2a8b..e40816df3 100644 --- a/cmd/viva/templates/code_editor_shaped.go.txt +++ b/cmd/viva/templates/code_editor_shaped.go.txt @@ -27,6 +27,7 @@ type codeShaping struct { hit gfx.TextHit hitRow int32 hitValid bool + styles []codeShapedStyle } type codeShapedRow struct { @@ -36,7 +37,7 @@ type codeShapedRow struct { func (editor *CodeEditor) configureShaping(canvas *gfx.Canvas, snapshot CodeEditorSnapshot, size, cell float32) { if !snapshot.ShapedBidi || len(snapshot.Representations) != 0 || snapshot.ShowWhitespace || - snapshot.ShowIndentGuides || snapshot.ShowEOL || snapshot.Decorations != nil || snapshot.Highlight != nil || snapshot.HighlightLine != nil { + snapshot.ShowIndentGuides || snapshot.ShowEOL || snapshot.Decorations != nil { editor.shaping = nil return } @@ -294,38 +295,97 @@ func (paint *codePaint) shapedRow(index int, row codeRow, y float32, carets []gf } value := paint.editor.shaping.rows[row.start].value bounds := gfx.Rect{X: left, Y: y + (paint.lineHeight-paint.cellHeight)/2, Width: float32(row.cells) * paint.cellWidth, Height: paint.cellHeight} - run := gfx.TextRun{Bytes: int32(len(value)), Cells: row.cells, Ligatures: true, Color: paint.foreground} - style := gfx.TextStyle{Size: paint.size, Color: paint.foreground, Mono: true, MonoFace: paint.face} - paint.canvas.LabelRuns(value, bounds, style, paint.cellWidth, []gfx.TextRun{run}) - run.Color = paint.selectionForeground - paint.shapedSelectionText(carets, start, end, value, bounds, run) + paint.shapedText(row, value, bounds, carets) if paint.showWrapSymbol && paint.editor.softWrapped(index) { paint.wrapSymbol(y) } paint.overlays(index, y) } -func (paint *codePaint) shapedSelectionText(carets []gfx.FittedMonoCaret, start, end int, value string, bounds gfx.Rect, run gfx.TextRun) { - style := gfx.TextStyle{Size: paint.size, Mono: true, MonoFace: paint.face, Color: run.Color} - paintSelection := func(from, to int) { - paint.shapedSpans = codeShapedSpans(paint.shapedSpans, carets, from-start, to-start) - for _, span := range paint.shapedSpans { - paint.canvas.Clip(gfx.Rect{X: bounds.X + span.X, Y: bounds.Y, Width: span.Width, Height: bounds.Height}) - // Clipping a duplicate of the complete run preserves its joins. - paint.canvas.LabelRuns(value, bounds, style, paint.cellWidth, []gfx.TextRun{run}) - paint.canvas.Unclip() - } +type codeShapedStyle struct { + left, right float32 + color gfx.Color + italic bool +} + +func (paint *codePaint) shapedText(row codeRow, value string, bounds gfx.Rect, carets []gfx.FittedMonoCaret) { + style := gfx.TextStyle{Size: paint.size, Mono: true, MonoFace: paint.face, Color: paint.foreground} + run := gfx.TextRun{Bytes: int32(len(value)), Cells: row.cells, Ligatures: true, Color: paint.foreground} + start, end := int(row.start), int(row.end) + highlight := paint.lineRuns(row) + selection := sort.Search(len(paint.selectionRanges), func(i int) bool { return paint.selectionRanges[i].End > start }) + selected := paint.selectionStart < paint.selectionEnd && paint.selectionStart < end && paint.selectionEnd > start + if len(paint.selectionRanges) > 0 { + selected = selection < len(paint.selectionRanges) && paint.selectionRanges[selection].Start < end } - if len(paint.selectionRanges) != 0 { - for _, selection := range paint.selectionRanges { - if selection.Start >= end { - break + if !selected && len(highlight) == 0 { + paint.canvas.LabelRuns(value, bounds, style, paint.cellWidth, []gfx.TextRun{run}) + return + } + + // Assign styles in source order, then paint disjoint visual intervals. + // Each interval draws the complete fitted label, preserving shaping and joins. + s := paint.editor.shaping + intervals := s.styles[:0] + for i := 0; i+1 < len(carets); i++ { + from, to := start+carets[i].Offset, start+carets[i+1].Offset + local := from - int(row.lineStart) + for len(highlight) > 0 && highlight[0].End <= local { + highlight = highlight[1:] + } + color, italic := paint.foreground, false + if len(highlight) > 0 && highlight[0].Start <= local { + color, italic = highlight[0].Color, highlight[0].Italic + if paint.editor.disabled { + color.Alpha *= 0.5 + } + } + if selected { + inSelection := paint.selectionStart < to && paint.selectionEnd > from + if len(paint.selectionRanges) > 0 { + for selection < len(paint.selectionRanges) && paint.selectionRanges[selection].End <= from { + selection++ + } + inSelection = selection < len(paint.selectionRanges) && paint.selectionRanges[selection].Start < to } - if selection.End > start { - paintSelection(selection.Start, selection.End) + if inSelection { + color = paint.selectionForeground } } - } else if paint.selectionEnd > start && paint.selectionStart < end { - paintSelection(paint.selectionStart, paint.selectionEnd) + a, b := carets[i].Leading, carets[i+1].Trailing + left, right := max(0, min(a, b)), min(bounds.Width, max(a, b)) + if right > left { + intervals = append(intervals, codeShapedStyle{left, right, color, italic}) + } + } + s.styles = intervals + slices.SortFunc(intervals, func(a, b codeShapedStyle) int { return cmp.Compare(a.left, b.left) }) + pos := float32(0) + visibleLeft := paint.editor.content.X - bounds.X + visibleRight := visibleLeft + paint.editor.content.Width + draw := func(left, right float32, color gfx.Color, italic bool) { + if right <= left || right <= visibleLeft || left >= visibleRight { + return + } + run.Color, run.Italic, style.Color = color, italic, color + if left == 0 && right == bounds.Width { + paint.canvas.LabelRuns(value, bounds, style, paint.cellWidth, []gfx.TextRun{run}) + return + } + paint.canvas.Clip(gfx.Rect{X: bounds.X + left, Y: bounds.Y, Width: right - left, Height: bounds.Height}) + paint.canvas.LabelRuns(value, bounds, style, paint.cellWidth, []gfx.TextRun{run}) + paint.canvas.Unclip() + } + for i := 0; i < len(intervals); { + span := intervals[i] + i++ + for i < len(intervals) && intervals[i].left <= span.right && intervals[i].color == span.color && intervals[i].italic == span.italic { + span.right = max(span.right, intervals[i].right) + i++ + } + draw(pos, span.left, paint.foreground, false) + draw(max(pos, span.left), span.right, span.color, span.italic) + pos = max(pos, span.right) } + draw(pos, bounds.Width, paint.foreground, false) } diff --git a/components/code_editor.go b/components/code_editor.go index eccd3c3e1..aff34054e 100644 --- a/components/code_editor.go +++ b/components/code_editor.go @@ -139,14 +139,14 @@ type CodeEditorSnapshot struct { FontSize float32 // MonoFace is the fixed-pitch font the code is set in. MonoFace gfx.MonoFace - // ShapedBidi opts plain grid rows into native bidi shaping where available. + // ShapedBidi opts grid rows into native bidi shaping where available. // Representations and visual whitespace/indent markers still use the logical - // grid, as do editors with highlighting or decorations. A row over 4096 - // bytes keeps the grid, and a platform whose text engine cannot shape a - // fitted monospaced run draws the grid unchanged. A wrapped continuation - // takes its paragraph's base direction, not the full bidi levels a strong - // context before the break could give it; an explicit embedding or isolate - // keeps the grid. + // grid, as do editors with custom decorations. A row over 4096 bytes keeps + // the grid, and a platform whose text engine cannot shape a fitted + // monospaced run draws the grid unchanged. A wrapped continuation takes its + // paragraph's base direction, not the full bidi levels a strong context + // before the break could give it; an explicit embedding or isolate keeps the + // grid. // Horizontal movement remains caller-owned. ShapedBidi bool // TabWidth is the width of a tab stop in cells; zero is four. diff --git a/components/code_editor_shaped.go b/components/code_editor_shaped.go index ef7025b0a..8dc5aa399 100644 --- a/components/code_editor_shaped.go +++ b/components/code_editor_shaped.go @@ -27,6 +27,7 @@ type codeShaping struct { hit gfx.TextHit hitRow int32 hitValid bool + styles []codeShapedStyle } type codeShapedRow struct { @@ -36,7 +37,7 @@ type codeShapedRow struct { func (editor *CodeEditor) configureShaping(canvas *gfx.Canvas, snapshot CodeEditorSnapshot, size, cell float32) { if !snapshot.ShapedBidi || len(snapshot.Representations) != 0 || snapshot.ShowWhitespace || - snapshot.ShowIndentGuides || snapshot.ShowEOL || snapshot.Decorations != nil || snapshot.Highlight != nil || snapshot.HighlightLine != nil { + snapshot.ShowIndentGuides || snapshot.ShowEOL || snapshot.Decorations != nil { editor.shaping = nil return } @@ -294,38 +295,97 @@ func (paint *codePaint) shapedRow(index int, row codeRow, y float32, carets []gf } value := paint.editor.shaping.rows[row.start].value bounds := gfx.Rect{X: left, Y: y + (paint.lineHeight-paint.cellHeight)/2, Width: float32(row.cells) * paint.cellWidth, Height: paint.cellHeight} - run := gfx.TextRun{Bytes: int32(len(value)), Cells: row.cells, Ligatures: true, Color: paint.foreground} - style := gfx.TextStyle{Size: paint.size, Color: paint.foreground, Mono: true, MonoFace: paint.face} - paint.canvas.LabelRuns(value, bounds, style, paint.cellWidth, []gfx.TextRun{run}) - run.Color = paint.selectionForeground - paint.shapedSelectionText(carets, start, end, value, bounds, run) + paint.shapedText(row, value, bounds, carets) if paint.showWrapSymbol && paint.editor.softWrapped(index) { paint.wrapSymbol(y) } paint.overlays(index, y) } -func (paint *codePaint) shapedSelectionText(carets []gfx.FittedMonoCaret, start, end int, value string, bounds gfx.Rect, run gfx.TextRun) { - style := gfx.TextStyle{Size: paint.size, Mono: true, MonoFace: paint.face, Color: run.Color} - paintSelection := func(from, to int) { - paint.shapedSpans = codeShapedSpans(paint.shapedSpans, carets, from-start, to-start) - for _, span := range paint.shapedSpans { - paint.canvas.Clip(gfx.Rect{X: bounds.X + span.X, Y: bounds.Y, Width: span.Width, Height: bounds.Height}) - // Clipping a duplicate of the complete run preserves its joins. - paint.canvas.LabelRuns(value, bounds, style, paint.cellWidth, []gfx.TextRun{run}) - paint.canvas.Unclip() - } +type codeShapedStyle struct { + left, right float32 + color gfx.Color + italic bool +} + +func (paint *codePaint) shapedText(row codeRow, value string, bounds gfx.Rect, carets []gfx.FittedMonoCaret) { + style := gfx.TextStyle{Size: paint.size, Mono: true, MonoFace: paint.face, Color: paint.foreground} + run := gfx.TextRun{Bytes: int32(len(value)), Cells: row.cells, Ligatures: true, Color: paint.foreground} + start, end := int(row.start), int(row.end) + highlight := paint.lineRuns(row) + selection := sort.Search(len(paint.selectionRanges), func(i int) bool { return paint.selectionRanges[i].End > start }) + selected := paint.selectionStart < paint.selectionEnd && paint.selectionStart < end && paint.selectionEnd > start + if len(paint.selectionRanges) > 0 { + selected = selection < len(paint.selectionRanges) && paint.selectionRanges[selection].Start < end } - if len(paint.selectionRanges) != 0 { - for _, selection := range paint.selectionRanges { - if selection.Start >= end { - break + if !selected && len(highlight) == 0 { + paint.canvas.LabelRuns(value, bounds, style, paint.cellWidth, []gfx.TextRun{run}) + return + } + + // Assign styles in source order, then paint disjoint visual intervals. + // Each interval draws the complete fitted label, preserving shaping and joins. + s := paint.editor.shaping + intervals := s.styles[:0] + for i := 0; i+1 < len(carets); i++ { + from, to := start+carets[i].Offset, start+carets[i+1].Offset + local := from - int(row.lineStart) + for len(highlight) > 0 && highlight[0].End <= local { + highlight = highlight[1:] + } + color, italic := paint.foreground, false + if len(highlight) > 0 && highlight[0].Start <= local { + color, italic = highlight[0].Color, highlight[0].Italic + if paint.editor.disabled { + color.Alpha *= 0.5 + } + } + if selected { + inSelection := paint.selectionStart < to && paint.selectionEnd > from + if len(paint.selectionRanges) > 0 { + for selection < len(paint.selectionRanges) && paint.selectionRanges[selection].End <= from { + selection++ + } + inSelection = selection < len(paint.selectionRanges) && paint.selectionRanges[selection].Start < to } - if selection.End > start { - paintSelection(selection.Start, selection.End) + if inSelection { + color = paint.selectionForeground } } - } else if paint.selectionEnd > start && paint.selectionStart < end { - paintSelection(paint.selectionStart, paint.selectionEnd) + a, b := carets[i].Leading, carets[i+1].Trailing + left, right := max(0, min(a, b)), min(bounds.Width, max(a, b)) + if right > left { + intervals = append(intervals, codeShapedStyle{left, right, color, italic}) + } + } + s.styles = intervals + slices.SortFunc(intervals, func(a, b codeShapedStyle) int { return cmp.Compare(a.left, b.left) }) + pos := float32(0) + visibleLeft := paint.editor.content.X - bounds.X + visibleRight := visibleLeft + paint.editor.content.Width + draw := func(left, right float32, color gfx.Color, italic bool) { + if right <= left || right <= visibleLeft || left >= visibleRight { + return + } + run.Color, run.Italic, style.Color = color, italic, color + if left == 0 && right == bounds.Width { + paint.canvas.LabelRuns(value, bounds, style, paint.cellWidth, []gfx.TextRun{run}) + return + } + paint.canvas.Clip(gfx.Rect{X: bounds.X + left, Y: bounds.Y, Width: right - left, Height: bounds.Height}) + paint.canvas.LabelRuns(value, bounds, style, paint.cellWidth, []gfx.TextRun{run}) + paint.canvas.Unclip() + } + for i := 0; i < len(intervals); { + span := intervals[i] + i++ + for i < len(intervals) && intervals[i].left <= span.right && intervals[i].color == span.color && intervals[i].italic == span.italic { + span.right = max(span.right, intervals[i].right) + i++ + } + draw(pos, span.left, paint.foreground, false) + draw(max(pos, span.left), span.right, span.color, span.italic) + pos = max(pos, span.right) } + draw(pos, bounds.Width, paint.foreground, false) } diff --git a/components/code_editor_shaped_darwin_test.go b/components/code_editor_shaped_darwin_test.go index b686aef92..f92d8abd9 100644 --- a/components/code_editor_shaped_darwin_test.go +++ b/components/code_editor_shaped_darwin_test.go @@ -3,12 +3,42 @@ package components import ( + "strings" "testing" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/internal/platform/darwin" ) +func TestCodeEditorShapedHighlightSkipsClipsOutsideTheViewport(t *testing.T) { + const count = 120 + const letter = "\u05d0" + f := newCodeFixture(strings.Repeat(letter, count)) + f.canvas.SetTextEngine(darwin.SharedTextEngine()) + f.snapshot.ShapedBidi = true + f.bounds.Width = f.widthFor(8) + f.snapshot.Highlight = func(_, source string, dst []CodeEditorRun) []CodeEditorRun { + for i := 0; i < len(source); i += len(letter) { + color := gfx.RGB(220, 40, 40) + if i/len(letter)%2 == 1 { + color = gfx.RGB(40, 40, 220) + } + dst = append(dst, CodeEditorRun{Start: i, End: i + len(letter), Color: color}) + } + return dst + } + f.paint() + labels := f.canvas.Texts() + if len(labels) < 3 || len(labels) > 10 { + t.Fatalf("painted %d labels for an eight-cell viewport", len(labels)) + } + for _, label := range labels { + if label.Value != f.snapshot.Value || !label.HasClip || label.ClipOf.Width <= 0 { + t.Errorf("nonvisible or split shaped label: clip=%+v, bytes=%d", label.ClipOf, len(label.Value)) + } + } +} + func TestCodeEditorCoreTextKeepsFittedArabicCaretEdges(t *testing.T) { const prefix = "a\u0301\U00010437 " const value = prefix + "\u0633\u0644\u0627\u0645 z" @@ -46,6 +76,32 @@ func TestCodeEditorCoreTextKeepsFittedArabicCaretEdges(t *testing.T) { t.Errorf("IME placement at byte %d: %+v, %v; want X=%g", at, got, ok, want) } } + before, ok := f.editor.CaretBounds() + if !ok { + t.Fatal("shaped caret missing before applying styles") + } + comment := gfx.RGB(30, 110, 65) + f.snapshot.HighlightLine = func(_ string, index int, source string, dst []CodeEditorRun) []CodeEditorRun { + if index != 0 || source != value { + t.Fatalf("highlight got line %d %q; want the logical source", index, source) + } + return append(dst, CodeEditorRun{Start: len(prefix), End: len(value) - 2, Color: comment, Italic: true}) + } + f.paint() + if after, ok := f.editor.CaretBounds(); !ok || after != before { + t.Fatalf("applying an italic style moved the remembered caret: before %+v, after %+v, %v", before, after, ok) + } + styled := false + for _, label := range f.canvas.Texts() { + runs := f.canvas.TextRuns(label) + if len(runs) != 1 || !runs[0].Ligatures || label.Value != value { + t.Fatalf("highlight split the fitted run: label=%q runs=%+v", label.Value, runs) + } + styled = styled || (label.HasClip && runs[0].Color == comment && runs[0].Italic) + } + if !styled { + t.Fatal("the fitted Arabic range was not drawn in the requested style") + } } func TestCodeEditorCoreTextWrapKeepsBothRowsOfTheBoundary(t *testing.T) { diff --git a/components/code_editor_shaped_test.go b/components/code_editor_shaped_test.go index f7c7a5af6..3b6bf7c13 100644 --- a/components/code_editor_shaped_test.go +++ b/components/code_editor_shaped_test.go @@ -109,3 +109,39 @@ func TestCodeEditorShapedSelectionAndCompositionUseVisualSpans(t *testing.T) { t.Fatal("composition did not underline the middle visual cell") } } + +func TestCodeEditorShapedHighlightKeepsTheFullRunAndSelectionStyle(t *testing.T) { + const value = "a\u05d0\u05d1z" + f := newCodeFixture(value) + f.canvas.SetTextEngine(shapedCodeTestEngine{gfx.ReferenceTextEngine()}) + f.snapshot.ShapedBidi = true + keyword := gfx.RGB(230, 60, 40) + f.snapshot.Highlight = func(_, line string, dst []CodeEditorRun) []CodeEditorRun { + if line != value { + t.Errorf("highlighter got %q; want logical source %q", line, value) + } + return append(dst, CodeEditorRun{Start: 0, End: 3, Color: keyword, Italic: true}) + } + f.snapshot.SelectionStart, f.snapshot.SelectionEnd = 1, 3 + f.paint() + labels := f.canvas.Texts() + cell, _, _ := f.cell() + left := f.editor.content.X + if len(labels) != 4 { + t.Fatalf("painted %d labels; want four disjoint visual styles", len(labels)) + } + for i, want := range []struct { + color gfx.Color + italic bool + }{{keyword, true}, {f.theme.Foreground, false}, {f.theme.SelectionForeground, true}, {f.theme.Foreground, false}} { + label := labels[i] + runs := f.canvas.TextRuns(label) + if label.Value != value || len(runs) != 1 || !runs[0].Ligatures || runs[0].Bytes != int32(len(value)) { + t.Fatalf("clip %d changed the shaped source: label=%q runs=%+v", i, label.Value, runs) + } + if !label.HasClip || !near(label.ClipOf.X, left+float32(i)*cell) || !near(label.ClipOf.Width, cell) || + runs[0].Color != want.color || runs[0].Italic != want.italic { + t.Errorf("clip %d: bounds=%+v run=%+v; want column %d with %+v", i, label.ClipOf, runs[0], i, want) + } + } +} diff --git a/internal/platform/darwin/core_render.m b/internal/platform/darwin/core_render.m index 1753f832c..9729adda8 100644 --- a/internal/platform/darwin/core_render.m +++ b/internal/platform/darwin/core_render.m @@ -954,7 +954,9 @@ - (void)drawRunsInContext:(CGContextRef)context pixelScale:(CGFloat)pixelScale { const unsigned char *start = bytes + offset; size_t count = run->bytes; offset += count; - BOOL italic = (run->flags & VIVA_RUN_ITALIC) != 0; + BOOL fitted = (run->flags & VIVA_RUN_LIGATURES) != 0; + BOOL slant = (run->flags & VIVA_RUN_ITALIC) != 0; + BOOL italic = slant && !fitted; CTFontRef font = NULL; for (int slot = 0; slot < cacheCount; slot++) { if (cachedWeight[slot] == run->weight && cachedItalic[slot] == italic) { @@ -987,7 +989,7 @@ - (void)drawRunsInContext:(CGContextRef)context pixelScale:(CGFloat)pixelScale { for (size_t at = 0; ascii && at < count; at++) { ascii = start[at] >= 0x20 && start[at] < 0x7F; } - if ((run->flags & VIVA_RUN_LIGATURES) != 0 && count > 0) { + if (fitted && count > 0) { // A ligature run is shaped as one line and scaled to its cells, so // the font's substitutions survive and the run still ends where // the grid says it does. @@ -1002,6 +1004,10 @@ - (void)drawRunsInContext:(CGContextRef)context pixelScale:(CGFloat)pixelScale { CGContextSaveGState(context); CGContextTranslateCTM(context, cellLeft, baseline); CGContextScaleCTM(context, span / width, 1); + // Oblique fitted text keeps the unmodified font's shaping and caret advances. + if (slant) { + CGContextConcatCTM(context, CGAffineTransformMake(1, 0, 0.2126, 1, 0, 0)); + } CGFloat origin = ascii ? 0 : viva_fitted_mono_origin(line, (CFIndex)shown.length); CGContextSetTextPosition(context, -origin, 0); CTLineDraw(line, context); @@ -1355,10 +1361,13 @@ void viva_encode_scene( BOOL scissored = NO; if ([layer clipped]) { CGRect clip = [layer clip]; - NSInteger left = MAX((NSInteger)floor(clip.origin.x * targetScale), 0); - NSInteger top = MAX((NSInteger)floor(clip.origin.y * targetScale), 0); - NSInteger right = MIN((NSInteger)ceil((clip.origin.x + clip.size.width) * targetScale), (NSInteger)targetWidth); - NSInteger bottom = MIN((NSInteger)ceil((clip.origin.y + clip.size.height) * targetScale), (NSInteger)targetHeight); + // Round both edges to the nearest device pixel, as the rectangle + // path does: two abutting text clips must share one edge, or both + // include the boundary column and composite the run twice. + NSInteger left = MIN(MAX((NSInteger)floor(clip.origin.x * targetScale + 0.5), 0), (NSInteger)targetWidth); + NSInteger top = MIN(MAX((NSInteger)floor(clip.origin.y * targetScale + 0.5), 0), (NSInteger)targetHeight); + NSInteger right = MIN(MAX((NSInteger)floor((clip.origin.x + clip.size.width) * targetScale + 0.5), 0), (NSInteger)targetWidth); + NSInteger bottom = MIN(MAX((NSInteger)floor((clip.origin.y + clip.size.height) * targetScale + 0.5), 0), (NSInteger)targetHeight); if (right <= left || bottom <= top) { continue; } diff --git a/internal/platform/darwin/text_italic_regression_test.go b/internal/platform/darwin/text_italic_regression_test.go index 79666a086..7efd9dc92 100644 --- a/internal/platform/darwin/text_italic_regression_test.go +++ b/internal/platform/darwin/text_italic_regression_test.go @@ -151,3 +151,53 @@ func TestItalicGridRunSlantsItsCells(t *testing.T) { t.Errorf("italic grid run leans %.2f px, upright %.2f; want the italic to lean right", slant, up) } } + +func TestFittedArabicRunRemainsWholeWhenClipped(t *testing.T) { + const text = "ab \u0633\u0644\u0627\u0645 cd" + const x, y, width, height = 10, 3, 120, 32 + offscreen, err := NewOffscreen(140, 40, 2, Color{Alpha: 1}) + if err != nil { + t.Skipf("no Metal device: %v", err) + } + defer offscreen.Close() + white := gfx.RGB(255, 255, 255) + render := func(italic, split bool, at float32) []byte { + t.Helper() + label := TextLabel{ + Value: text, X: x, Y: y, Width: width, Height: height, FontSize: 24, Mono: true, CellWidth: 12, + Color: platform.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1}, + Runs: []gfx.TextRun{{Bytes: int32(len(text)), Cells: 10, Color: white, Italic: italic, Ligatures: true}}, + } + labels := []TextLabel{label} + if split { + label.Clipped = true + label.Clip = gfx.Rect{X: x, Y: y, Width: at, Height: height} + right := label + right.Clip.X += at + labels = []TextLabel{label, right} + } + if err := offscreen.Set(nil, labels, nil); err != nil { + t.Fatal(err) + } + pixels, _, _, err := offscreen.Render() + if err != nil { + t.Fatal(err) + } + return pixels + } + upright := render(false, false, 0) + slanted := render(true, false, 0) + if bytes.Equal(upright, slanted) { + t.Fatal("fitted italic text was painted upright") + } + for _, style := range []struct { + italic bool + whole []byte + }{{false, upright}, {true, slanted}} { + for _, at := range []float32{width / 2, width/2 + 0.25} { + if !bytes.Equal(style.whole, render(style.italic, true, at)) { + t.Errorf("clipping at %.2f changed the pixels of the full Arabic line (italic=%v)", at, style.italic) + } + } + } +}