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", "ab", "א", "ا", "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