diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9c876250..926747fc 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -169,6 +169,12 @@ jobs: GOOS=js GOARCH=wasm go build \ ./cmd/component-preview ./cmd/gallery-web \ ./examples/guides/hello ./examples/guides/webview + # The docs previews and the gallery build through the same public command + # an application uses, so a break in the deployment path fails here. + - name: build the public web entry points + run: | + go run ./cmd/viva build --target web ./cmd/component-preview -o build/component-preview-web + go run ./cmd/viva build --target web ./cmd/gallery-web -o build/gallery-web # The real browser gate. It builds the fixture and drives it through the # three engines in parallel with the wasm tests above; most of its elapsed @@ -197,12 +203,14 @@ jobs: tools/webcheck/node_modules/.bin/playwright install --with-deps chromium firefox webkit # Each engine gets its own step so a failure names the engine that broke # and the others still report their own result. - - name: drive the browser verification page (chromium) - run: node tools/webcheck/check.mjs --dir build/webcheck --browser chromium + - name: drive the browser verification page (chromium, WebGL2) + run: node tools/webcheck/check.mjs --dir build/webcheck --browser chromium --renderer webgl2 + - name: drive the browser verification page (chromium, Canvas2D fallback) + run: node tools/webcheck/check.mjs --dir build/webcheck --browser chromium --renderer canvas2d - name: drive the browser verification page (firefox) - run: node tools/webcheck/check.mjs --dir build/webcheck --browser firefox + run: node tools/webcheck/check.mjs --dir build/webcheck --browser firefox --renderer auto - name: drive the browser verification page (webkit) - run: node tools/webcheck/check.mjs --dir build/webcheck --browser webkit + run: node tools/webcheck/check.mjs --dir build/webcheck --browser webkit --renderer auto # The whole test suite except the packages that carry darwin-only files, split # over several runners. .github/scripts/test-packages.sh decides what this @@ -293,7 +301,7 @@ jobs: # native structure ABI tests are here for the same reason: they build only # on Windows. - name: Material contracts and controls (WARP) - run: go test ./internal/platform/windows ./ui ./components ./headless ./app -run 'Test(Backdrop|WindowBackdrop|Notification|TaskbarCreated|CompositionClear|CompositionFallback|CompositionCreation|CustomBackdrop|AcrylicAccent|LegacyAcrylic|RoundedOutline|Translucent|MonospaceFamilies|FontWeights|(The)?MonoWeights|(The)?InterfaceWeights|EveryListedFamilyResolves|EngineReportsTheFontsUnderline|AlwaysOnTop|SaveDialogCheckbox|FileIcon|NativeStructureABI|ResizePresents|WindowSwapChain|LiveResize|FlipWindowResize|RedrawWaits|ContinuousRedraw|NoOpFrame|SameSize|ZeroSize|ResizeTimer|RedrawQueue|NativeRedrawMessage|CompositionSupersededFrame)' -count=1 -v + run: go test ./internal/platform/windows ./ui ./components ./headless ./app -run 'Test(Backdrop|WindowBackdrop|Notification|TaskbarCreated|CompositionClear|CompositionFallback|CompositionCreation|CustomBackdrop|AcrylicAccent|LegacyAcrylic|RoundedOutline|Translucent|MonospaceFamilies|FontWeights|(The)?MonoWeights|(The)?InterfaceWeights|EveryListedFamilyResolves|EngineReportsTheFontsUnderline|AlwaysOnTop|SaveDialogCheckbox|FileIcon|NativeStructureABI|ResizePresents|WindowSwapChain|LiveResize|FlipWindowResize|RedrawWaits|ContinuousRedraw|NoOpFrame|SameSize|ZeroSize|ResizeTimer|RedrawQueue|NativeRedrawMessage|CompositionSupersededFrame|DragPreview)' -count=1 -v - name: Terminal keyboard routing run: go test ./internal/platform/windows -run '^TestATerminalGetsEditingKeysAndChordsAsRawKeys$' -count=1 -v - name: Native Windows global shortcut diff --git a/.github/workflows/website.yml b/.github/workflows/website.yml index 9536c3a5..327f730a 100644 --- a/.github/workflows/website.yml +++ b/.github/workflows/website.yml @@ -11,8 +11,15 @@ on: - "website/**" - "components/**" - "internal/componentdemo/**" + - "internal/framebuild/**" + - "internal/platform/web/**" + - "internal/previewmeasure/**" + - "internal/render/**" + - "internal/scene/**" + - "internal/webbuild/**" - "tools/docs/**" - "cmd/component-preview/**" + - "cmd/viva/**" - "ui/**" - "app/**" - "text/**" diff --git a/README.md b/README.md index a9c615ff..3ba06b78 100644 --- a/README.md +++ b/README.md @@ -50,9 +50,11 @@ opening one, `viva.toml`, and an `AGENTS.md` describing the programming model. platform's own bundle. Requirements: Go 1.26 or newer (viva fetches it when missing). On macOS the Xcode command-line tools, because -Viva reaches Cocoa and Metal through cgo; on Linux, X11 with the system XCB and -Vulkan loaders; on Windows, Win32 with Direct3D 11 and DirectWrite. Viva loads -the system libraries at runtime and bundles none of them. +Viva reaches Cocoa and Metal through cgo; on Linux, X11 with the system XCB, +Pango and Cairo libraries, and a Vulkan loader and driver for GPU acceleration +(a machine without them draws on the CPU); on Windows, Win32 with Direct3D 11 +and DirectWrite. Viva loads the system libraries at runtime and bundles none of +them. The current release is `v0.6.5`; name it explicitly (`@v0.6.5`) to pin it. Guides, the API reference, and a component catalog with live previews live in @@ -66,7 +68,8 @@ and how to work on the framework rather than with it. ## Scope Viva targets native desktop applications on macOS, Windows, and Linux, and -treats WebAssembly/Canvas2D as a supported web deployment target. Both targets +treats WebAssembly as a supported web deployment target, rendered with WebGL2 +and falling back to Canvas2D when WebGL2 is unavailable. Both targets share components, input, text, focus and accessibility semantics; capabilities the browser does not have are reported through explicit asynchronous APIs and `Capability`, never faked. The web target must not add cost to native builds. @@ -210,8 +213,9 @@ without changing build commands. Unconfigured windows keep the ordinary renderer limits, fallback behavior and the platforms actually verified. Native label renderers draw single-line labels. The browser target runs the same -components on the Canvas2D backend; see [Web deployment](docs/web-deployment.md) -for its capability matrix and hosting requirements. +components on the WebGL2 backend, with Canvas2D as its fallback; see +[Web deployment](docs/web-deployment.md) for its capability matrix and hosting +requirements. ## Run the repository @@ -224,8 +228,9 @@ tools/build_web.sh # viva build --target web, then serves http://127.0 go run ./tools/docs -check # the API and component data the website generates from ``` -The browser build paints the same Go components through the Canvas2D -WebAssembly backend. It is a deployment target, not only a gallery: file +The browser build paints the same Go components through WebGL2, falling back to +the Canvas2D WebAssembly backend when WebGL2 is unavailable or a context is +lost. It is a deployment target, not only a gallery: file pickers, drops, clipboard, notifications, encrypted secret storage and embedded fonts have typed asynchronous APIs. Its visual direction and measured costs are recorded in `docs/benchmarks/m3-gallery-style-darwin-arm64.md`. diff --git a/README.zh-CN.md b/README.zh-CN.md index 33bf0a24..be713423 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -32,7 +32,7 @@ viva dev . # hot reload: save a file, the window updates and keeps its st `viva init` 会写一个可直接运行的项目:一个窗口、一个不用打开窗口就能驱动它的测试、`viva.toml`,以及一份描述编程模型的 `AGENTS.md`。`viva build` 把发布程序写到 `build/`,`viva package` 写出平台自己的包。 -环境要求:Go 1.26 或更新版本(缺失时 viva 会自己下载)。macOS 上需要 Xcode 命令行工具,因为 Viva 通过 cgo 访问 Cocoa 和 Metal;Linux 上需要带系统 XCB 和 Vulkan 加载库的 X11;Windows 上需要 Win32、Direct3D 11 和 DirectWrite。Viva 在运行时加载系统库,自身不捆绑任何一个。 +环境要求:Go 1.26 或更新版本(缺失时 viva 会自己下载)。macOS 上需要 Xcode 命令行工具,因为 Viva 通过 cgo 访问 Cocoa 和 Metal;Linux 上需要带系统 XCB、Pango 和 Cairo 库的 X11,Vulkan 加载库和驱动用于 GPU 加速,缺失时窗口用 CPU 渲染;Windows 上需要 Win32、Direct3D 11 和 DirectWrite。Viva 在运行时加载系统库,自身不捆绑任何一个。 当前版本是 `v0.6.5`;要固定版本就写明(`@v0.6.5`)。指南、API 参考和带实时预览的组件目录在 [`website/`](website/) 里,本地用 `npm run dev` 运行;也已经发布在 [vivaui.dev](https://vivaui.dev/zh/)。 @@ -40,7 +40,7 @@ viva dev . # hot reload: save a file, the window updates and keeps its st ## 范围 -Viva 面向 macOS、Windows 和 Linux 上的原生桌面应用,同时把 WebAssembly/Canvas2D 作为正式的 Web 发布目标:两个目标共享组件、输入、文本、焦点和无障碍语义,浏览器缺失的能力通过显式异步 API 和 `Capability` 报告,而不是伪造原生行为。Web 目标不得给原生构建增加成本。iOS、iPadOS、Android、移动端打包,以及以触摸为主的移动运行时,明确不在范围内。不会为了保留假设中的未来移动兼容性而削弱桌面性能与原生集成。 +Viva 面向 macOS、Windows 和 Linux 上的原生桌面应用,同时把 WebAssembly 作为正式的 Web 发布目标:浏览器构建优先使用 WebGL2,WebGL2 不可用时回退 Canvas2D。两个目标共享组件、输入、文本、焦点和无障碍语义,浏览器缺失的能力通过显式异步 API 和 `Capability` 报告,而不是伪造原生行为。Web 目标不得给原生构建增加成本。iOS、iPadOS、Android、移动端打包,以及以触摸为主的移动运行时,明确不在范围内。不会为了保留假设中的未来移动兼容性而削弱桌面性能与原生集成。 三个后端都直接使用操作系统自己的窗口和 GPU API,没有 WebView,也不捆绑渲染运行时。 @@ -83,7 +83,7 @@ Viva 面向 macOS、Windows 和 Linux 上的原生桌面应用,同时把 WebAs Windows 后端支持 amd64 和 arm64 交叉构建,并在 Wine/DXVK 下通过平台测试以及 Gallery 的启动、指针和键盘冒烟测试。平台测试、conformance 场景,以及输入、拖放和设备丢失路径,在一台 Windows 11 虚拟机(WARP)和一台 Debian KDE/X11 机器(lavapipe)上运行;`docs/conformance.md` 记录了需要真实硬件的场景。UI Automation 在一台真实的 Windows 11 机器上由外部客户端检查(见 docs/accessibility.md),AT-SPI 在 KDE/X11 机器上针对 libatspi 检查。Linux 后端通过 Ubuntu arm64 Xvfb/llvmpipe 的 M0 和 Debian amd64 X11/Lavapipe 的保留式场景冒烟测试,包括中英混排文本和局部场景更新。macOS 运行时测试和基准在 arm64 上运行。 -原生标签渲染器绘制单行标签。浏览器目标运行在 Canvas2D 后端;能力矩阵、生命周期与静态托管要求见 [Web 部署](docs/web-deployment.md)。 +原生标签渲染器绘制单行标签。浏览器目标运行在 WebGL2 后端,WebGL2 不可用时回退 Canvas2D;能力矩阵、生命周期与静态托管要求见 [Web 部署](docs/web-deployment.md)。 ## 运行这个仓库 @@ -96,7 +96,7 @@ tools/build_web.sh # viva build --target web,然后服务 http://127 go run ./tools/docs -check # 网站生成的 API 与组件数据 ``` -浏览器构建通过 Canvas2D WebAssembly 后端绘制相同的 Go 组件,并且是正式发布目标:文件选择、拖放、剪贴板、通知、加密密钥存储和内置字体都有类型化的异步 API。视觉方向与测量成本记录在 `docs/benchmarks/m3-gallery-style-darwin-arm64.md`。 +浏览器构建通过 WebGL2(不可用时回退 Canvas2D)WebAssembly 后端绘制相同的 Go 组件,并且是正式发布目标:文件选择、拖放、剪贴板、通知、加密密钥存储和内置字体都有类型化的异步 API。视觉方向与测量成本记录在 `docs/benchmarks/m3-gallery-style-darwin-arm64.md`。 ## 文档网站 diff --git a/app/accessibility_test.go b/app/accessibility_test.go index 65944341..530b8edb 100644 --- a/app/accessibility_test.go +++ b/app/accessibility_test.go @@ -45,6 +45,24 @@ func TestAccessibilityNodesCarryWhatAssistiveTechnologyNeeds(t *testing.T) { } } +func TestAccessibilityNodesCarryInvalid(t *testing.T) { + var canvas gfx.Canvas + config := Config{Title: "invalid", Width: 200, Height: 120} + config.Paint = func(canvas *gfx.Canvas, size gfx.Size) { + canvas.HitWithOptions(gfx.Item(1), gfx.Rect{Width: 100, Height: 24}, "Email", gfx.HitOptions{ + Role: gfx.RoleTextField, Invalid: true, + }) + } + painter := newTestPainter(t, &canvas, config) + if len(painter.accessibility) != 1 || !painter.accessibility[0].Invalid { + t.Fatalf("accessibility = %+v", painter.accessibility) + } + node, ok := painter.semantics.Get(painter.semanticIDs[0]) + if !ok || !node.Invalid { + t.Fatalf("semantic node = %+v", node) + } +} + func TestAccessibilityPressClicksOnceAndIgnoresDisabledControls(t *testing.T) { var canvas gfx.Canvas var clicks []gfx.ID diff --git a/app/accessnodes.go b/app/accessnodes.go index 87093ee5..00d8f37f 100644 --- a/app/accessnodes.go +++ b/app/accessnodes.go @@ -32,6 +32,8 @@ type AccessNode struct { Expanded bool Multiline bool ReadOnly bool + // Invalid marks a control whose value failed validation. + Invalid bool Secure bool Focusable bool // Expandable marks a control that opens and closes something, whatever its @@ -77,7 +79,7 @@ func (driver *Driver) Accessibility() []AccessNode { Label: node.Label, Value: node.Value, Hint: node.Hint, Description: node.Description, Focused: node.Focused, Disabled: node.Disabled, Checked: node.Checked, Mixed: node.Mixed, Selected: node.Selected, Expanded: node.Expanded, Multiline: node.Multiline, - ReadOnly: node.ReadOnly, Secure: node.Secure, Focusable: node.Focusable, + ReadOnly: node.ReadOnly, Invalid: node.Invalid, Secure: node.Secure, Focusable: node.Focusable, Expandable: node.Expandable, Level: node.Level, PosInSet: node.PosInSet, SetSize: node.SetSize, Live: node.Live, Range: node.Range, Selection: AccessSelection{Start: node.Selection.Start, End: node.Selection.End, Valid: node.Selection.Valid}, diff --git a/app/app.go b/app/app.go index f1a9fbea..1030e8c9 100644 --- a/app/app.go +++ b/app/app.go @@ -166,6 +166,12 @@ type Config struct { // OnScroll receives normalized pixel deltas and the hovered hit target. // Handled suppresses the window's default canvas scroll offset. OnScroll func(event gfx.ScrollEvent) gfx.EventResult + // ForwardWheel, when set, receives a wheel gesture the application did not + // use, so an embedding page can scroll instead. Setting it makes the page + // own the default scroll: only a gesture the application handled scrolls + // the canvas. It is a browser deployment option and is ignored on native + // platforms. + ForwardWheel func(deltaX, deltaY float32) // OnFileDrop receives files dragged from the system over this window: the // pointer entering and moving with them (FileDropOver), leaving // (FileDropLeave), and the drop. Each event carries the hit under the point; diff --git a/app/application_native.go b/app/application_native.go index 92d5fd25..b6836e62 100644 --- a/app/application_native.go +++ b/app/application_native.go @@ -78,6 +78,17 @@ type resultWindow struct { waker *platform.Waker } +// The embedded WindowControl intentionally exposes only the methods every +// native window has. Forward optional capabilities explicitly so wrapping a +// window for event-result handling does not hide resize, fullscreen, +// always-on-top, or shortcut capture support. +var _ platform.WindowSizer = resultWindow{} +var _ fullscreenControl = resultWindow{} +var _ alwaysOnTopControl = resultWindow{} +var _ shortcutCapturer = resultWindow{} +var _ titleControl = resultWindow{} +var _ platform.WindowMover = resultWindow{} + // What OpenWindow looks for in a host's window control. var _ interface { applyResult(gfx.EventResult) bool @@ -85,6 +96,61 @@ var _ interface { runShortcut(keymap.Chord) (gfx.EventResult, bool) } = resultWindow{} +func (window resultWindow) SetSize(width, height int) error { + sizer, ok := window.WindowControl.(platform.WindowSizer) + if !ok { + return platform.ErrWindowSizeUnsupported + } + return sizer.SetSize(width, height) +} + +func (window resultWindow) SetFullscreen(fullscreen bool) error { + control, ok := window.WindowControl.(fullscreenControl) + if !ok { + return platform.ErrFullscreenUnsupported + } + return control.SetFullscreen(fullscreen) +} + +func (window resultWindow) Fullscreen() bool { + control, ok := window.WindowControl.(fullscreenControl) + return ok && control.Fullscreen() +} + +func (window resultWindow) SetTitle(title string) error { + control, ok := window.WindowControl.(titleControl) + if !ok { + return fmt.Errorf("%w: window titles", ErrUnsupported) + } + return control.SetTitle(title) +} + +func (window resultWindow) SetAlwaysOnTop(enabled bool) error { + control, ok := window.WindowControl.(alwaysOnTopControl) + if !ok { + return platform.ErrAlwaysOnTopUnsupported + } + return control.SetAlwaysOnTop(enabled) +} + +func (window resultWindow) MoveTo(origin gfx.Point) { + if control, ok := window.WindowControl.(platform.WindowMover); ok { + control.MoveTo(origin) + } +} + +func (window resultWindow) unwrapWindowControl() WindowControl { + return window.WindowControl +} + +func (window resultWindow) CaptureSystemShortcuts(capture bool) error { + control, ok := window.WindowControl.(shortcutCapturer) + if !ok { + return fmt.Errorf("%w: this platform keeps the system's shortcuts", ErrUnsupported) + } + return control.CaptureSystemShortcuts(capture) +} + func (window resultWindow) applyResult(result gfx.EventResult) bool { return window.painter.applyEventResult(result) } diff --git a/app/application_native_test.go b/app/application_native_test.go new file mode 100644 index 00000000..b0295f91 --- /dev/null +++ b/app/application_native_test.go @@ -0,0 +1,56 @@ +//go:build darwin || windows || linux + +package app + +import ( + "errors" + "testing" +) + +func TestResultWindowForwardsSetSize(t *testing.T) { + native := &sizingWindow{} + window := &Window{control: resultWindow{WindowControl: native}} + if err := window.SetSize(1280, 720); err != nil { + t.Fatal(err) + } + if native.width != 1280 || native.height != 720 { + t.Fatalf("SetSize = %dx%d", native.width, native.height) + } + + unsupported := &Window{control: resultWindow{WindowControl: struct{ WindowControl }{}}} + if err := unsupported.SetSize(800, 600); !errors.Is(err, ErrUnsupported) { + t.Fatalf("wrapped unsupported window error = %v", err) + } +} + +func TestResultWindowForwardsAlwaysOnTop(t *testing.T) { + native := &topmostTestControl{} + window := &Window{control: resultWindow{WindowControl: native}} + if err := window.SetAlwaysOnTop(true); err != nil { + t.Fatal(err) + } + if !window.AlwaysOnTop() || len(native.requests) != 1 || !native.requests[0] { + t.Fatalf("always-on-top request did not reach the native window: requests=%v", native.requests) + } + + unsupported := &Window{control: resultWindow{WindowControl: &fakeWindow{}}} + if err := unsupported.SetAlwaysOnTop(true); !errors.Is(err, ErrUnsupported) { + t.Fatalf("wrapped unsupported window error = %v", err) + } +} + +func TestResultWindowForwardsSetTitle(t *testing.T) { + native := &titleTestControl{} + window := &Window{control: resultWindow{WindowControl: native}} + if err := window.SetTitle("project – main.go"); err != nil { + t.Fatal(err) + } + if len(native.titles) != 1 || native.titles[0] != "project – main.go" { + t.Fatalf("titles = %q", native.titles) + } + + unsupported := &Window{control: resultWindow{WindowControl: &fakeWindow{}}} + if err := unsupported.SetTitle("x"); !errors.Is(err, ErrUnsupported) { + t.Fatalf("wrapped unsupported window error = %v", err) + } +} diff --git a/app/drag_preview.go b/app/drag_preview.go index 2eb09ed8..b3bd4ca3 100644 --- a/app/drag_preview.go +++ b/app/drag_preview.go @@ -60,22 +60,42 @@ func (application *Application) OpenDragPreview(config DragPreviewConfig) (*Drag Paint: config.Paint, }, nil) if err != nil { + // A host that cannot show the preview at all keeps the drag going + // without it, as the API promises. + if errors.Is(err, platform.ErrDragPreviewUnsupported) { + return nil, ErrNoDragPreview + } return nil, err } - if _, ok := window.control.(platform.WindowMover); !ok { + if _, ok := previewMover(window.control); !ok { window.Close() return nil, ErrNoDragPreview } return &DragPreview{window: window}, nil } +type windowControlUnwrapper interface { + unwrapWindowControl() WindowControl +} + +// previewMover unwraps a host wrapper before checking the adapter's capability. +// A wrapper can forward MoveTo, but it must not make a native window that +// cannot move look movable. +func previewMover(control WindowControl) (platform.WindowMover, bool) { + if wrapped, ok := control.(windowControlUnwrapper); ok { + control = wrapped.unwrapWindowControl() + } + mover, ok := control.(platform.WindowMover) + return mover, ok +} + // MoveTo puts the picture's top-left at origin, in screen coordinates. Call it // on the application thread, as from a pointer callback. func (preview *DragPreview) MoveTo(origin gfx.Point) { if preview == nil || preview.window == nil || preview.window.closed.Load() { return } - if mover, ok := preview.window.control.(platform.WindowMover); ok { + if mover, ok := previewMover(preview.window.control); ok { mover.MoveTo(origin) } } diff --git a/app/drag_preview_test.go b/app/drag_preview_test.go index 55f62bc7..7a899897 100644 --- a/app/drag_preview_test.go +++ b/app/drag_preview_test.go @@ -4,9 +4,11 @@ package app import ( "errors" + "fmt" "testing" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/platform" ) // movableWindow is a fake window that can be moved, as a preview's is. @@ -35,6 +37,22 @@ func (host *previewingHost) OpenWindow(config Config, canvas *gfx.Canvas, closed return window, nil } +// resultPreviewingHost mimics the native host that wraps an adapter window in +// resultWindow before handing it to an application. +type resultPreviewingHost struct { + *fakeHost +} + +func (host *resultPreviewingHost) CanPreview() bool { return true } + +func (host *resultPreviewingHost) OpenWindow(config Config, canvas *gfx.Canvas, closed func()) (WindowControl, error) { + control, err := host.fakeHost.OpenWindow(config, canvas, closed) + if err != nil { + return nil, err + } + return resultWindow{WindowControl: control}, nil +} + func usePreviewHost(t *testing.T, host *previewingHost) { t.Helper() previous := applicationRunner @@ -81,6 +99,34 @@ func TestADragPreviewFollowsMovesAndGoesWhenClosed(t *testing.T) { } } +func TestADragPreviewRejectsANativeWindowThatCannotMove(t *testing.T) { + host := &resultPreviewingHost{fakeHost: &fakeHost{}} + previous := applicationRunner + t.Cleanup(func() { + applicationRunner = previous + for _, window := range host.windows { + window.Close() + } + }) + applicationRunner = func(start func(Host) error) error { return start(host) } + + err := RunApplication(func(application *Application) error { + if _, err := application.OpenWindow(Config{Title: "main"}, nil); err != nil { + return err + } + if _, err := application.OpenDragPreview(DragPreviewConfig{Width: 10, Height: 10}); !errors.Is(err, ErrUnsupported) { + t.Fatalf("OpenDragPreview error = %v, want ErrUnsupported", err) + } + return nil + }) + if err != nil { + t.Fatal(err) + } + if len(host.windows) != 2 || !host.windows[1].done { + t.Fatalf("unmovable preview was not closed: windows=%d done=%v", len(host.windows), len(host.windows) > 1 && host.windows[1].done) + } +} + func TestADragPreviewIsRefusedWhereTheHostCannotShowOne(t *testing.T) { host := &fakeHost{} useHost(t, host) @@ -102,6 +148,19 @@ func TestADragPreviewIsRefusedWhereTheHostCannotShowOne(t *testing.T) { } } +func TestANativeWindowResultStillMovesAPreview(t *testing.T) { + moving := &movableWindow{fakeWindow: &fakeWindow{}} + control := resultWindow{WindowControl: moving} + mover, ok := any(control).(platform.WindowMover) + if !ok { + t.Fatal("a native window result hid the platform's MoveTo") + } + mover.MoveTo(gfx.Point{X: 30, Y: 40}) + if len(moving.moves) != 1 || moving.moves[0] != (gfx.Point{X: 30, Y: 40}) { + t.Fatalf("moves = %v", moving.moves) + } +} + func BenchmarkDragPreviewMoveTo(b *testing.B) { host := &previewingHost{fakeHost: &fakeHost{}} var preview *DragPreview @@ -120,3 +179,41 @@ func BenchmarkDragPreviewMoveTo(b *testing.B) { preview.MoveTo(gfx.Point{X: float32(i), Y: 1}) } } + +// unavailablePreviewHost is a host that advertises previews but cannot create +// one: the compositor is missing. +type unavailablePreviewHost struct{ *fakeHost } + +func (host *unavailablePreviewHost) CanPreview() bool { return true } + +func (host *unavailablePreviewHost) OpenWindow(config Config, canvas *gfx.Canvas, closed func()) (WindowControl, error) { + if config.WindowMode == windowPreview { + return nil, fmt.Errorf("%w: no compositor", platform.ErrDragPreviewUnsupported) + } + return host.fakeHost.OpenWindow(config, canvas, closed) +} + +func TestADragPreviewTheHostCannotShowKeepsTheDrag(t *testing.T) { + host := &unavailablePreviewHost{fakeHost: &fakeHost{}} + previous := applicationRunner + t.Cleanup(func() { + applicationRunner = previous + for _, window := range host.windows { + window.Close() + } + }) + applicationRunner = func(start func(Host) error) error { return start(host) } + err := RunApplication(func(application *Application) error { + if _, err := application.OpenWindow(Config{Title: "main"}, nil); err != nil { + return err + } + _, err := application.OpenDragPreview(DragPreviewConfig{Width: 120, Height: 28}) + if !errors.Is(err, ErrNoDragPreview) || !errors.Is(err, ErrUnsupported) { + t.Fatalf("open error = %v, want ErrNoDragPreview", err) + } + return nil + }) + if err != nil { + t.Fatal(err) + } +} diff --git a/app/driver.go b/app/driver.go index 8e243db9..c2581960 100644 --- a/app/driver.go +++ b/app/driver.go @@ -1195,7 +1195,7 @@ func (driver *Driver) Snapshot() Snapshot { } snapshot.TextWidths[index] = painter.canvas.TextWidthStyle(text.Value, text.Style) } - for _, rectangle := range painter.renderer.Rectangles() { + for _, rectangle := range painter.frame.Rectangles() { primitive := Primitive{ Bounds: gfx.Rect{X: rectangle.Bounds.X, Y: rectangle.Bounds.Y, Width: rectangle.Bounds.Width, Height: rectangle.Bounds.Height}, Color: gfx.Color{Red: rectangle.Color.Red, Green: rectangle.Color.Green, Blue: rectangle.Color.Blue, Alpha: rectangle.Color.Alpha}, @@ -1224,7 +1224,7 @@ func (driver *Driver) Snapshot() Snapshot { } snapshot.Primitives = append(snapshot.Primitives, primitive) } - for _, label := range painter.labels { + for _, label := range painter.frame.Labels() { captured := Label{ Value: label.Value, Bounds: gfx.Rect{X: label.X, Y: label.Y, Width: label.Width, Height: label.Height}, diff --git a/app/driver_test.go b/app/driver_test.go index 109d68ac..160a0f5c 100644 --- a/app/driver_test.go +++ b/app/driver_test.go @@ -11,6 +11,7 @@ import ( "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/framebuild" "github.com/vivaui/viva/text" ) @@ -200,7 +201,7 @@ func TestDriverEditsAFocusedTextFieldThroughTheTextSystem(t *testing.T) { break } } - if fieldText.Bounds == (gfx.Rect{}) || !containsRect(field.Bounds, fieldText.Bounds) { + if fieldText.Bounds == (gfx.Rect{}) || !framebuild.ContainsRect(field.Bounds, fieldText.Bounds) { t.Fatalf("field declared no text line inside its control: %+v", field) } if snapshot.Editor.Bounds != fieldText.Bounds { diff --git a/app/first_frame_bench_test.go b/app/first_frame_bench_test.go index d46a003a..ad4ce706 100644 --- a/app/first_frame_bench_test.go +++ b/app/first_frame_bench_test.go @@ -28,3 +28,16 @@ func BenchmarkPainterFirstFrame(b *testing.B) { } } } + +// An empty window is the floor an application pays before its own paint: +// constructor, first frame, scene and renderer setup. +func BenchmarkPainterEmptyWindow(b *testing.B) { + config := Config{Title: "empty", Width: 480, Height: 240} + b.ReportAllocs() + for b.Loop() { + var canvas gfx.Canvas + if painter := newTestPainter(b, &canvas, config); painter == nil { + b.Fatal("no painter") + } + } +} diff --git a/app/fullscreen_test.go b/app/fullscreen_test.go index 72ba330c..618bde29 100644 --- a/app/fullscreen_test.go +++ b/app/fullscreen_test.go @@ -55,6 +55,24 @@ func TestFullscreenRequestsAndObservedStateAreDistinct(t *testing.T) { } } +func TestNativeResultWindowForwardsFullscreenRequests(t *testing.T) { + control := &fullscreenTestControl{} + window := &Window{control: resultWindow{WindowControl: control}} + for _, fullscreen := range []bool{true, false} { + if err := window.SetFullscreen(fullscreen); err != nil { + t.Fatal(err) + } + } + if len(control.requests) != 2 || !control.requests[0] || control.requests[1] { + t.Fatalf("native fullscreen requests = %v, want [true false]", control.requests) + } + + unsupported := &Window{control: resultWindow{WindowControl: &fakeWindow{}}} + if err := unsupported.SetFullscreen(true); !errors.Is(err, ErrUnsupported) { + t.Fatalf("unsupported native window: %v", err) + } +} + func TestFullscreenHostCallbackPublishesBeforeApplicationCallback(t *testing.T) { host := &fakeHost{} application := &Application{host: host} diff --git a/app/interface_font_test.go b/app/interface_font_test.go index 2e3be3e3..3d75e8bf 100644 --- a/app/interface_font_test.go +++ b/app/interface_font_test.go @@ -143,10 +143,10 @@ func TestAFamilyChangeSendsTheSameTextToTheRendererAgain(t *testing.T) { t.Fatal(err) } generation := func() (interfaceText, fixedPitch uint32) { - if len(painter.labels) != 2 { - t.Fatalf("labels = %+v", painter.labels) + if len(painter.frame.Labels()) != 2 { + t.Fatalf("labels = %+v", painter.frame.Labels()) } - return painter.labels[0].FontGeneration, painter.labels[1].FontGeneration + return painter.frame.Labels()[0].FontGeneration, painter.frame.Labels()[1].FontGeneration } before, _ := generation() frame, err := painter.repaint() diff --git a/app/key_traversal_frame_test.go b/app/key_traversal_frame_test.go index 89b9233f..b0d7f49d 100644 --- a/app/key_traversal_frame_test.go +++ b/app/key_traversal_frame_test.go @@ -47,12 +47,12 @@ func TestContinueTraversalKeyPublishesOneConsistentFrame(t *testing.T) { } painter := newTestPainter(t, &canvas, config) - base := len(painter.renderer.Rectangles()) + base := len(painter.frame.Rectangles()) frame, err := painter.key(platform.KeyEvent{Key: input.KeyTab}) if err != nil { t.Fatal(err) } - count := len(painter.renderer.Rectangles()) + count := len(painter.frame.Rectangles()) if count >= base { t.Fatalf("the popup did not close: %d -> %d", base, count) } @@ -115,12 +115,12 @@ func TestContinueTraversalKeyPublishesOneFrameWhenThePageGrows(t *testing.T) { } painter := newTestPainter(t, &canvas, config) - base := len(painter.renderer.Rectangles()) + base := len(painter.frame.Rectangles()) frame, err := painter.key(platform.KeyEvent{Key: input.KeyTab}) if err != nil { t.Fatal(err) } - count := len(painter.renderer.Rectangles()) + count := len(painter.frame.Rectangles()) if count <= base { t.Fatalf("the page did not grow: %d -> %d", base, count) } diff --git a/app/label_replace_test.go b/app/label_replace_test.go index 6151c1eb..fe64ee72 100644 --- a/app/label_replace_test.go +++ b/app/label_replace_test.go @@ -6,39 +6,6 @@ import ( "github.com/vivaui/viva/gfx" ) -// The memo hands a line that arrives unchanged back as it replaced it, and a -// line whose runs changed — a recolour keeps the value — gets a replacement -// built for the new runs, not the remembered one. -func TestReplaceCellGlyphsMemoFollowsItsInput(t *testing.T) { - painter := &painter{} - value := "┌──┐ ok" - runs := []gfx.TextRun{{Bytes: int32(len(value)), Cells: 6, Color: gfx.Color{Alpha: 1}}} - firstValue, firstRuns := painter.replaceCellGlyphs(value, runs) - if firstValue == value { - t.Fatalf("a line with cell glyphs came back unchanged: %q", firstValue) - } - againValue, againRuns := painter.replaceCellGlyphs(value, runs) - if againValue != firstValue || &againRuns[0] != &firstRuns[0] { - t.Fatal("the same line was replaced again instead of remembered") - } - - recolored := []gfx.TextRun{{Bytes: int32(len(value)), Cells: 6, Color: gfx.Color{Red: 1, Alpha: 1}}} - recValue, recRuns := painter.replaceCellGlyphs(value, recolored) - if recRuns[0].Color != recolored[0].Color { - t.Fatalf("a recoloured line got the remembered colour %+v", recRuns[0].Color) - } - if recValue != firstValue { - t.Fatalf("the replacement text changed with the colour: %q and %q", recValue, firstValue) - } - - plain := "plain line" - plainRuns := []gfx.TextRun{{Bytes: int32(len(plain)), Cells: 10, Color: gfx.Color{Alpha: 1}}} - outValue, outRuns := painter.replaceCellGlyphs(plain, plainRuns) - if outValue != plain || &outRuns[0] != &plainRuns[0] { - t.Fatal("a line without cell glyphs was copied or remembered") - } -} - // A keystroke in a grid-shaped page re-sends every row's label; the rows that // did not change reach the label sync with the same value and runs, and their // cell glyph replacement is remembered rather than rebuilt. diff --git a/app/labels_test.go b/app/labels_test.go index b0d41ac2..292011ec 100644 --- a/app/labels_test.go +++ b/app/labels_test.go @@ -89,3 +89,105 @@ func TestALabelWithoutWordsLeavesTheControlsOwnName(t *testing.T) { t.Fatalf("label = %q, want the control's own", got) } } + +// A large page with one changed label keeps every other accessible name and +// updates the one that changed. This is the incremental-mirror path: the hit +// list keeps its count, ids and label/control order. +func TestOneChangedLabelOnALargePageUpdatesOnlyItsControl(t *testing.T) { + const controls = 128 + changed := "first" + paint := func(canvas *gfx.Canvas) { + for index := 0; index < controls; index++ { + id := gfx.Item(index + 1) + at := gfx.Rect{X: float32(index%16) * 10, Y: float32(index/16) * 10, Width: 8, Height: 8} + canvas.HitWithLabel(id, at, "control") + words := "label" + if index == 3 { + words = changed + } + canvas.HitLabel(id, gfx.Rect{X: at.X, Y: at.Y + 2, Width: 4, Height: 4}, words, false) + } + } + painter := labelledPainter(t, paint) + if got := accessibilityLabel(t, painter, gfx.Item(4)); got != "first" { + t.Fatalf("initial label = %q", got) + } + changed = "second" + if _, err := painter.repaint(); err != nil { + t.Fatal(err) + } + if got := accessibilityLabel(t, painter, gfx.Item(4)); got != "second" { + t.Fatalf("changed label = %q", got) + } + if got := accessibilityLabel(t, painter, gfx.Item(5)); got != "label" { + t.Fatalf("untouched label = %q", got) + } +} + +// A large page with one changed value updates that control's accessible value +// without touching the other controls. +func TestOneChangedValueOnALargePageUpdatesOnlyItsControl(t *testing.T) { + const controls = 128 + changed := "before" + paint := func(canvas *gfx.Canvas) { + for index := 0; index < controls; index++ { + id := gfx.Item(index + 1) + at := gfx.Rect{X: float32(index%16) * 10, Y: float32(index/16) * 10, Width: 8, Height: 8} + value := "same" + if index == 7 { + value = changed + } + canvas.HitWithOptions(id, at, "field", gfx.HitOptions{Role: gfx.RoleTextField, Value: value}) + } + } + painter := labelledPainter(t, paint) + if got := accessibilityValue(t, painter, gfx.Item(8)); got != "before" { + t.Fatalf("initial value = %q", got) + } + changed = "after" + if _, err := painter.repaint(); err != nil { + t.Fatal(err) + } + if got := accessibilityValue(t, painter, gfx.Item(8)); got != "after" { + t.Fatalf("changed value = %q", got) + } + if got := accessibilityValue(t, painter, gfx.Item(9)); got != "same" { + t.Fatalf("untouched value = %q", got) + } +} + +func accessibilityValue(t *testing.T, painter *painter, id gfx.ID) string { + t.Helper() + for _, node := range painter.accessibility { + if node.ID == id { + return node.Value + } + } + t.Fatalf("no accessibility node for %v", id) + return "" +} + +// Changing every label on a large page falls back to the full mirror and still +// updates every control; the incremental path is bounded, not lossy. +func TestAllLabelsChangedOnALargePageUpdatesEveryControl(t *testing.T) { + const controls = 128 + words := "first" + paint := func(canvas *gfx.Canvas) { + for index := 0; index < controls; index++ { + id := gfx.Item(index + 1) + at := gfx.Rect{X: float32(index%16) * 10, Y: float32(index/16) * 10, Width: 8, Height: 8} + canvas.HitWithLabel(id, at, "control") + canvas.HitLabel(id, gfx.Rect{X: at.X, Y: at.Y + 2, Width: 4, Height: 4}, words, false) + } + } + painter := labelledPainter(t, paint) + words = "second" + if _, err := painter.repaint(); err != nil { + t.Fatal(err) + } + for _, id := range []gfx.ID{gfx.Item(1), gfx.Item(64), gfx.Item(controls)} { + if got := accessibilityLabel(t, painter, id); got != "second" { + t.Fatalf("control %v label = %q", id, got) + } + } +} diff --git a/app/painter.go b/app/painter.go index 3ef2afe2..8912aeab 100644 --- a/app/painter.go +++ b/app/painter.go @@ -12,11 +12,10 @@ import ( "unsafe" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/framebuild" "github.com/vivaui/viva/internal/input" "github.com/vivaui/viva/internal/interaction" "github.com/vivaui/viva/internal/platform" - "github.com/vivaui/viva/internal/render" - "github.com/vivaui/viva/internal/scene" "github.com/vivaui/viva/internal/semantic" "github.com/vivaui/viva/keymap" "github.com/vivaui/viva/text" @@ -65,52 +64,23 @@ type painter struct { size gfx.Size focus interaction.Focus pointer interaction.Pointer - graph *scene.Scene - renderer render.Store + frame *framebuild.Builder semantics *semantic.Tree semanticIDs []semantic.ID accessibility []platform.AccessibilityNode lastAccess []platform.AccessibilityNode - changes []scene.Change semanticChanges []semantic.Change - resyncs int // times the renderer had to be rebuilt after a failed batch - reusedHits int // publishes that kept the previous regions and semantics - shapeIDs []scene.ID // one scene node per entry of order, in paint order - labels []platform.TextLabel - lastTexts []gfx.Text - lastRuns []gfx.TextRun // the runs lastTexts refer to, copied out of the application's memory - // lastFontGeneration is the canvas's font generation at the labels last sent: text - // that has not changed still needs sending when the fonts have, so the renderer - // draws it again. - lastFontGeneration uint32 - lastImages []gfx.Image - // labelImage names, for each label of this frame, the image it was drawn - // from (an index into clippedImages, -1 for a text label); lastLabelImage is - // the same for the labels last sent. A bitmap needs its pixels again unless - // the label in its place showed the same picture: the platform hands a - // label its predecessor's texture when both are at the same index and carry - // the same content. - labelImage []int32 - lastLabelImage []int32 - lastTextBefores []uint32 // clippedTextBefores last sent - lastImageBefores []uint32 // clippedImageBefores last sent - views []platform.NativeView // the native views of this publish - lastViews []platform.NativeView // the ones last sent - covers []gfx.Rect // backing of the views' Covers - stateBySlot []instanceState - // layerShift is 1 while the frame has a backdrop, which takes platform layer - // zero; every canvas layer then travels one higher. It is 0 otherwise. - layerShift uint16 - hitScratch []gfx.Hit + reusedHits int // publishes that kept the previous regions and semantics + views []platform.NativeView // the native views of this publish + lastViews []platform.NativeView // the ones last sent + covers []gfx.Rect // backing of the views' Covers + hitScratch []gfx.Hit // publishedHits is the hit list the regions and the semantic tree were last // built from. Comparing it byte for byte (the strings keep the previous // allocations alive, so equal pointers mean equal bytes) lets a repaint that // declared the same hits reuse both instead of mirroring the list again. - publishedHits []gfx.Hit - // cellReplace remembers the font-ready form of lines that hold cell glyphs; - // a frame that changed one row of a grid-shaped page sends every row again, - // and the rows that did not change rebuild no string and runs. - cellReplace []cellReplaceMemo + publishedHits []gfx.Hit + semanticDirty []gfx.ID publishedFocus gfx.ID publishedTrap gfx.ID publishedInitial gfx.ID @@ -126,20 +96,6 @@ type painter struct { semanticsDirty bool labelNames map[gfx.ID]string labelNamePeak int - clipRects [4]gfx.Rect - clipped []gfx.Rectangle - clippedPaths []gfx.Triangle - clippedSoft []gfx.Shadow - order []shapeRef // clipped, clippedPaths and clippedSoft interleaved in paint order - blocks []gfx.Rectangle // scratch for appendCellGlyphs - strokes []gfx.Triangle // scratch for appendCellGlyphs - clippedTexts []gfx.Text - clippedImages []gfx.Image - // clippedTextBefores and clippedImageBefores are how many shapes the frame - // paints before each of those labels: the place a renderer puts the label - // back among the shapes. - clippedTextBefores []uint32 - clippedImageBefores []uint32 // controls draws the window buttons of a custom titlebar, on platforms where // Viva does; it is nil otherwise. controls *windowControls @@ -199,13 +155,11 @@ func newPainterWithClock(canvas *gfx.Canvas, config *Config, clock func() time.D textInput: config.TextInput, canvas: canvas, size: gfx.Size{Width: float32(config.Width), Height: float32(config.Height)}, - graph: scene.NewWithCapacity(len(canvas.Rectangles()) + len(canvas.Triangles()) + len(canvas.Shadows()) + 1), + frame: framebuild.New(canvas), semantics: semantic.NewWithCapacity("Viva", len(canvas.Hits())+1), semanticIDs: make([]semantic.ID, 0, len(canvas.Hits())+1), accessibility: make([]platform.AccessibilityNode, 0, len(canvas.Hits())+1), lastAccess: make([]platform.AccessibilityNode, 0, len(canvas.Hits())+1), - shapeIDs: make([]scene.ID, 0, len(canvas.Rectangles())+len(canvas.Triangles())+len(canvas.Shadows())), - labels: make([]platform.TextLabel, 0, len(canvas.Texts())+len(canvas.Images())+1), } painter.onTextEvent = painter.applyTextEvent painter.clipboardText = func() string { @@ -237,10 +191,7 @@ func newPainterWithClock(canvas *gfx.Canvas, config *Config, clock func() time.D return nil, err } } - for index := range painter.labels { - painter.labels[index].BitmapUpload = len(painter.labels[index].Bitmap) > 0 - } - painter.saveContent() + painter.frame.MarkInitialBitmapUploads() painter.lastAccess = append(painter.lastAccess[:0], painter.accessibility...) return painter, nil } @@ -994,28 +945,9 @@ func (painter *painter) scheduleIfAnimating() { // publish reconciles the canvas with the scene, router, and label list and // returns the resulting renderer frame. func (painter *painter) publish() (platform.Frame, error) { - painter.applyClipping() - painter.syncShapes() - painter.changes = painter.graph.DrainChanges(painter.changes[:0]) - update, err := painter.renderer.Apply(painter.changes) + frame, err := painter.frame.Build() if err != nil { - // The scene has already absorbed this frame, so the failed batch will - // never be sent again: leaving the store as it is would freeze every - // node it skipped at its old value for good. Rebuild both from the - // canvas instead. - if update, err = painter.resyncRenderer(); err != nil { - return platform.Frame{}, fmt.Errorf("app: render state is inconsistent: %w", err) - } - } - if painter.stampState() && !update.Rebuild { - update = render.Update{Count: len(painter.renderer.Rectangles()), Rebuild: true} - } - - frame := platform.Frame{Update: update, Rectangles: painter.renderer.Rectangles()} - if !painter.sameAsLastContent() { - painter.syncLabels() - painter.saveContent() - frame.TextLabels = painter.labels + return platform.Frame{}, fmt.Errorf("app: render state is inconsistent: %w", err) } if views, changed := painter.syncNativeViews(); changed { @@ -1044,8 +976,9 @@ func (painter *painter) publish() (platform.Frame, error) { // field reports to assistive technology is the one the editor holds now. // A repaint that changed neither the hits, the focus, nor the text state // keeps the payload from the previous publish. - if !hitStructuresUnchanged || !painter.structuresUnchanged() { - painter.syncSemantics() + structuresUnchanged := painter.structuresUnchanged() + if !hitStructuresUnchanged || !structuresUnchanged { + painter.syncSemantics(!hitStructuresUnchanged && structuresUnchanged) painter.recordHitStructures() if !sameAccessibility(painter.accessibility, painter.lastAccess) { painter.lastAccess = append(painter.lastAccess[:0], painter.accessibility...) @@ -1076,7 +1009,7 @@ func (painter *painter) syncNativeViews() ([]platform.NativeView, bool) { } bounds = gfx.Rect{X: left, Y: top, Width: right - left, Height: bottom - top} } - native := platform.NativeView{ID: uint32(view.ID), Bounds: bounds, Layer: painter.platformLayer(view.Layer)} + native := platform.NativeView{ID: uint32(view.ID), Bounds: bounds, Layer: painter.frame.PlatformLayer(view.Layer)} start := len(painter.covers) painter.covers = painter.coversOf(view.Layer, bounds, painter.covers) native.Covers = painter.covers[start:len(painter.covers):len(painter.covers)] @@ -1126,15 +1059,8 @@ func (painter *painter) trim() { // for a page that stays large, but after a large page is replaced by a // small one the slots are pure retention. Rebuild both from the small // frame instead of carrying the peak for the rest of the session. + painter.frame.Trim() const trimAt, trimRatio = 4096, 4 - if slots := painter.graph.Slots(); slots > trimAt && painter.graph.Len()*trimRatio < slots { - if _, err := painter.resyncRenderer(); err == nil { - painter.stateBySlot = nil - } - // A page the scene rebuilt wholesale shows other lines; its memoized - // replacements are stale retention. - painter.cellReplace = painter.cellReplace[:0] - } if slots := painter.semantics.Slots(); slots > trimAt && painter.semantics.Len()*trimRatio < slots { painter.semantics = semantic.NewWithCapacity("Viva", len(painter.hitScratch)+1) painter.semanticIDs = painter.semanticIDs[:0] @@ -1143,52 +1069,20 @@ func (painter *painter) trim() { } painter.canvas.Trim() painter.focus.Trim() - painter.shapeIDs = trimPainterCapacity(painter.shapeIDs) - painter.labels = trimPainterCapacity(painter.labels) - painter.lastTexts = trimPainterCapacity(painter.lastTexts) - painter.lastRuns = trimPainterCapacity(painter.lastRuns) - painter.lastImages = trimPainterCapacity(painter.lastImages) - painter.labelImage = trimPainterCapacity(painter.labelImage) - painter.lastLabelImage = trimPainterCapacity(painter.lastLabelImage) - painter.hitScratch = trimPainterCapacity(painter.hitScratch) - painter.publishedHits = trimPainterCapacity(painter.publishedHits) - painter.publishedReturns = trimPainterCapacity(painter.publishedReturns) - painter.clipped = trimPainterCapacity(painter.clipped) - painter.clippedPaths = trimPainterCapacity(painter.clippedPaths) - painter.clippedSoft = trimPainterCapacity(painter.clippedSoft) - painter.order = trimPainterCapacity(painter.order) - painter.blocks = trimPainterCapacity(painter.blocks) - painter.strokes = trimPainterCapacity(painter.strokes) - painter.clippedTexts = trimPainterCapacity(painter.clippedTexts) - painter.clippedImages = trimPainterCapacity(painter.clippedImages) - painter.clippedTextBefores = trimPainterCapacity(painter.clippedTextBefores) - painter.clippedImageBefores = trimPainterCapacity(painter.clippedImageBefores) - painter.lastTextBefores = trimPainterCapacity(painter.lastTextBefores) - painter.lastImageBefores = trimPainterCapacity(painter.lastImageBefores) - painter.accessibility = trimPainterCapacity(painter.accessibility) - painter.lastAccess = trimPainterCapacity(painter.lastAccess) - painter.changes = trimPainterCapacity(painter.changes) - painter.semanticChanges = trimPainterCapacity(painter.semanticChanges) - painter.semanticIDs = trimPainterCapacity(painter.semanticIDs) + painter.hitScratch = framebuild.TrimCapacity(painter.hitScratch) + painter.publishedHits = framebuild.TrimCapacity(painter.publishedHits) + painter.semanticDirty = framebuild.TrimCapacity(painter.semanticDirty) + painter.publishedReturns = framebuild.TrimCapacity(painter.publishedReturns) + painter.accessibility = framebuild.TrimCapacity(painter.accessibility) + painter.lastAccess = framebuild.TrimCapacity(painter.lastAccess) + painter.semanticChanges = framebuild.TrimCapacity(painter.semanticChanges) + painter.semanticIDs = framebuild.TrimCapacity(painter.semanticIDs) if painter.labelNamePeak > 4096 && len(painter.labelNames)*4 < painter.labelNamePeak { painter.labelNames = nil painter.labelNamePeak = 0 } } -// trimPainterCapacity is trimCapacity for the painter's buffers. The same -// threshold is used so a page that stays near its capacity never reallocates. -func trimPainterCapacity[T any](items []T) []T { - const minCapacity = 4096 - const ratio = 4 - if cap(items) <= minCapacity || len(items)*ratio >= cap(items) { - return items - } - next := make([]T, len(items), max(len(items)*2, minCapacity/64)) - copy(next, items) - return next -} - func (painter *painter) syncCursor() error { next := CursorArrow var image *gfx.CursorImage @@ -1262,18 +1156,6 @@ func cursorFromHit(cursor gfx.PointerCursor) Cursor { } } -// resyncRenderer discards the retained scene and render store and rebuilds -// both from the current canvas, returning the full-rebuild update. -func (painter *painter) resyncRenderer() (render.Update, error) { - painter.resyncs++ - painter.graph = scene.NewWithCapacity(len(painter.clipped) + len(painter.clippedPaths) + len(painter.clippedSoft) + 1) - painter.renderer = render.Store{} - painter.shapeIDs = painter.shapeIDs[:0] - painter.syncShapes() - painter.changes = painter.graph.DrainChanges(painter.changes[:0]) - return painter.renderer.Apply(painter.changes) -} - // focusedTextField describes the focused text field of the last paint, and how // it places its caret when it lays its rows out itself. func (painter *painter) focusedTextField() (TextInputContext, gfx.TextPlacement, int) { @@ -1326,12 +1208,12 @@ func (painter *painter) syncTextInput() platform.TextInputUpdate { alignment := input.Alignment if bounds == (gfx.Rect{}) { bounds = context.TextBounds - if bounds == (gfx.Rect{}) { + if bounds.Width <= 0 || bounds.Height <= 0 { bounds = context.Bounds } } if transformed, moving := painter.canvas.HitPresenceRect(hitIndex, bounds); moving { - bounds = roundPresenceRect(transformed) + bounds = framebuild.RoundPresenceRect(transformed) } if fontSize == 0 { fontSize = context.FontSize @@ -1351,7 +1233,7 @@ func (painter *painter) syncTextInput() platform.TextInputUpdate { fontSize = gfx.DefaultMetrics().FontSizeM } if bounds.Width <= 0 || bounds.Height <= 0 || - roundPixel(bounds.Width) <= 0 || roundPixel(bounds.Height) <= 0 { + framebuild.RoundPixel(bounds.Width) <= 0 || framebuild.RoundPixel(bounds.Height) <= 0 { return painter.disableTextInput() } var cellWidth, baseline float32 @@ -1371,7 +1253,7 @@ func (painter *painter) syncTextInput() platform.TextInputUpdate { X: bounds.X, Y: bounds.Y, Width: bounds.Width, Height: bounds.Height, FontSize: fontSize, Weight: weight, FontGeneration: painter.canvas.FontGeneration(), - Alignment: alignment, Layer: painter.platformLayer(context.Layer), Multiline: context.Multiline, Secure: context.Secure, Terminal: context.Terminal || context.TypeAhead, + Alignment: alignment, Layer: painter.frame.PlatformLayer(context.Layer), Multiline: context.Multiline, Secure: context.Secure, Terminal: context.Terminal || context.TypeAhead, AltSendsEscape: input.AltSendsEscape, KeyReleases: context.Terminal && input.KeyReleases, DisableIME: input.DisableIME, MonoFace: input.MonoFace, CellWidth: cellWidth, Baseline: baseline, NavigationKeys: input.NavigationKeys || context.NavigationKeys, CopyOverride: input.CopyOverride, @@ -1389,7 +1271,7 @@ func (painter *painter) syncTextInput() platform.TextInputUpdate { native.Placed = true if caret, ok := placement.CaretBounds(); ok { if transformed, moving := painter.canvas.HitPresenceRect(hitIndex, caret); moving { - caret = roundPresenceRect(transformed) + caret = framebuild.RoundPresenceRect(transformed) } native.CaretX, native.CaretY, native.CaretWidth, native.CaretHeight = caret.X, caret.Y, caret.Width, caret.Height } @@ -1532,410 +1414,6 @@ func samePlatformTextInput(left, right platform.TextInput) bool { left.Color == right.Color && left.State == right.State } -// shapeRef names one clipped shape: an entry of painter.clippedPaths when -// triangle is set, of painter.clippedSoft when shadow is set, of painter.clipped -// otherwise. -type shapeRef struct { - index int32 - triangle bool - shadow bool -} - -// applyClipping drops every shape, image and text its canvas clip hides and -// notes, on the others, whether the clip cuts them: a shape left with HasClip -// set is drawn through a scissor rectangle by the renderer, which is how a -// partial shape is cut, so no geometry is cut here. It also merges rectangles, -// triangles, shadows, texts and images back into the order they were painted -// in: each primitive carries the paint order the canvas gave it. -func (painter *painter) applyClipping() { - painter.clipped = painter.clipped[:0] - painter.clippedPaths = painter.clippedPaths[:0] - painter.clippedSoft = painter.clippedSoft[:0] - painter.clippedTexts = painter.clippedTexts[:0] - painter.clippedImages = painter.clippedImages[:0] - painter.clippedTextBefores = painter.clippedTextBefores[:0] - painter.clippedImageBefores = painter.clippedImageBefores[:0] - painter.order = painter.order[:0] - painter.layerShift = 0 - rectangles := painter.canvas.Rectangles() - triangles := painter.canvas.Triangles() - shadows := painter.canvas.Shadows() - texts := painter.canvas.Texts() - images := painter.canvas.Images() - // Walk the five lists as one paint order. A primitive with a smaller Order - // is painted first; on a tie (a border ring shares its backing rectangle's - // order, cell glyphs share their line's) shapes come before images and - // images before text. - ri, ti, si, xi, ii := 0, 0, 0, 0, 0 - for ri < len(rectangles) || ti < len(triangles) || si < len(shadows) || xi < len(texts) || ii < len(images) { - kind, best := 0, ^uint32(0) - if ri < len(rectangles) && rectangles[ri].Order < best { - kind, best = 1, rectangles[ri].Order - } - if ti < len(triangles) && triangles[ti].Order < best { - kind, best = 2, triangles[ti].Order - } - if si < len(shadows) && shadows[si].Order < best { - kind, best = 3, shadows[si].Order - } - if ii < len(images) && images[ii].Order < best { - kind, best = 4, images[ii].Order - } - if xi < len(texts) && texts[xi].Order < best { - kind = 5 - } - switch kind { - case 1: - painter.appendRectangle(rectangles[ri]) - ri++ - case 2: - painter.appendTriangle(triangles[ti]) - ti++ - case 3: - painter.appendShadow(shadows[si]) - si++ - case 4: - painter.appendImage(images[ii]) - ii++ - case 5: - painter.appendText(texts[xi]) - xi++ - } - } -} - -// appendImage adds image to the frame's label list unless its clip hides it or -// it has no area, cutting its source to the visible part. A backdrop is kept -// apart: its layer moves the rest of the frame above it. -func (painter *painter) appendImage(image gfx.Image) { - if roundPixel(image.Bounds.Width) <= 0 || roundPixel(image.Bounds.Height) <= 0 { - return - } - if image.Backdrop { - // A backdrop is beneath every layer, before any shape: it carries no - // place among them. - painter.layerShift = 1 - painter.clippedImages = append(painter.clippedImages, image) - painter.clippedImageBefores = append(painter.clippedImageBefores, 0) - return - } - if !image.HasClip { - painter.clippedImages = append(painter.clippedImages, image) - painter.clippedImageBefores = append(painter.clippedImageBefores, uint32(len(painter.order))) - return - } - visible, ok := intersectVisible(image.Bounds, image.ClipOf) - if !ok { - return - } - if image.DevicePixels { - // The clip may end between device pixels; the picture is cut at one. - scale := painter.canvas.PixelScale() - if visible = deviceBounds(visible, scale); visible.Width <= 0 || visible.Height <= 0 { - return - } - } - if visible != image.Bounds { - sx := image.Source.Width / image.Bounds.Width - sy := image.Source.Height / image.Bounds.Height - image.Source.X += (visible.X - image.Bounds.X) * sx - image.Source.Y += (visible.Y - image.Bounds.Y) * sy - image.Source.Width = visible.Width * sx - image.Source.Height = visible.Height * sy - image.Bounds = visible - if image.DevicePixels { - image.Source = wholePixels(image.Source) - } - } - painter.clippedImages = append(painter.clippedImages, image) - painter.clippedImageBefores = append(painter.clippedImageBefores, uint32(len(painter.order))) -} - -// appendText adds text to the frame's label list and paints the cell glyph -// geometry that belongs to it, unless the text paints nothing. -func (painter *painter) appendText(text gfx.Text) { - // A label with no area or no font size paints nothing, and the native label - // backends require positive values. Transient layouts (a closing drawer, a - // pane squeezed to nothing) can produce one; drop it here rather than failing - // the whole frame. - if roundPixel(text.Bounds.Width) <= 0 || roundPixel(text.Bounds.Height) <= 0 || text.Style.Size <= 0 { - return - } - if text.HasClip && !textClipVisible(text) { - return - } - painter.clippedTexts = append(painter.clippedTexts, text) - if text.RunCount > 0 { - painter.appendCellGlyphs(text) - } - // The cell glyph geometry is part of the line: it is painted before the - // glyphs, so the label comes after the shapes just appended. - painter.clippedTextBefores = append(painter.clippedTextBefores, uint32(len(painter.order))) -} - -// appendShadow puts shadow in the frame's order after cutting it to its clip, -// and drops it when nothing of it is inside. -func (painter *painter) appendShadow(shadow gfx.Shadow) { - if shadow.HasClip { - visible, cut := clipVisibility(shadowBounds(shadow), shadow.ClipOf) - if !visible { - return - } - shadow.HasClip = cut - } - painter.order = append(painter.order, shapeRef{index: int32(len(painter.clippedSoft)), shadow: true}) - painter.clippedSoft = append(painter.clippedSoft, shadow) -} - -// appendCellGlyphs paints the geometry of a fixed-pitch line's cell glyphs — the Block Elements, -// Box Drawing, Braille, the corner shapes of Geometric Shapes, the Powerline separators and the -// Symbols for Legacy Computing — after the canvas's own, as the line's text is drawn after them -// (see gfx.Canvas.CellGlyphGeometry). -func (painter *painter) appendCellGlyphs(text gfx.Text) { - shapes := painter.canvas.CellGlyphGeometry(gfx.CellGlyphShapes{ - Rectangles: painter.blocks[:0], - Triangles: painter.strokes[:0], - }, text) - painter.blocks, painter.strokes = shapes.Rectangles, shapes.Triangles - for _, rectangle := range painter.blocks { - painter.appendRectangle(rectangle) - } - for _, triangle := range painter.strokes { - painter.appendTriangle(triangle) - } -} - -// appendRectangle puts rectangle in the frame's order after cutting it to its clip, and drops it -// when nothing of it is inside. -func (painter *painter) appendRectangle(rectangle gfx.Rectangle) { - if rectangle.HasClip { - visible, cut := clipVisibility(rectangle.Bounds, rectangle.ClipOf) - if !visible { - return - } - rectangle.HasClip = cut - } - painter.order = append(painter.order, shapeRef{index: int32(len(painter.clipped))}) - painter.clipped = append(painter.clipped, rectangle) -} - -// appendTriangle is appendRectangle for the triangles a renderer feathers: their scissor keeps the -// half device pixel the edge reaches past the silhouette. -func (painter *painter) appendTriangle(triangle gfx.Triangle) { - if triangle.HasClip { - bounds := triangleBounds(triangle.Points) - if triangle.EdgeMask != 0 { - half := 0.5 / painter.canvas.PixelScale() - bounds.X -= half - bounds.Y -= half - bounds.Width += 2 * half - bounds.Height += 2 * half - } - visible, cut := clipVisibility(bounds, triangle.ClipOf) - if !visible { - return - } - triangle.HasClip = cut - } - painter.order = append(painter.order, shapeRef{index: int32(len(painter.clippedPaths)), triangle: true}) - painter.clippedPaths = append(painter.clippedPaths, triangle) -} - -// clipVisibility reports whether any of bounds lies inside clip and whether the -// clip cuts it, that is, whether part of bounds lies outside. -func clipVisibility(bounds, clip gfx.Rect) (visible, cut bool) { - if bounds.X+bounds.Width <= clip.X || bounds.Y+bounds.Height <= clip.Y || - bounds.X >= clip.X+clip.Width || bounds.Y >= clip.Y+clip.Height { - return false, false - } - return true, !containsRect(clip, bounds) -} - -// shadowBounds is the region a shadow paints in: the rectangle that casts it -// grown by how far its blur, spread and offset reach. -func shadowBounds(shadow gfx.Shadow) gfx.Rect { - extent := shadow.Style.Extent() - return gfx.Rect{ - X: shadow.Bounds.X - extent, Y: shadow.Bounds.Y - extent, - Width: shadow.Bounds.Width + 2*extent, Height: shadow.Bounds.Height + 2*extent, - } -} - -func triangleBounds(points [3]gfx.Point) gfx.Rect { - left := min32(points[0].X, min32(points[1].X, points[2].X)) - top := min32(points[0].Y, min32(points[1].Y, points[2].Y)) - right := max32(points[0].X, max32(points[1].X, points[2].X)) - bottom := max32(points[0].Y, max32(points[1].Y, points[2].Y)) - return gfx.Rect{X: left, Y: top, Width: right - left, Height: bottom - top} -} - -func quadBounds(points [4]gfx.Point) gfx.Rect { - left := min32(min32(points[0].X, points[1].X), min32(points[2].X, points[3].X)) - top := min32(min32(points[0].Y, points[1].Y), min32(points[2].Y, points[3].Y)) - right := max32(max32(points[0].X, points[1].X), max32(points[2].X, points[3].X)) - bottom := max32(max32(points[0].Y, points[1].Y), max32(points[2].Y, points[3].Y)) - return gfx.Rect{X: left, Y: top, Width: right - left, Height: bottom - top} -} - -func textClipVisible(text gfx.Text) bool { - _, visible := intersectVisible(text.Bounds, text.ClipOf) - if text.HasQuad { - _, warped := intersectVisible(quadBounds(text.Quad), text.ClipOf) - visible = visible || warped - } - return visible -} - -func textClipCuts(text gfx.Text) bool { - return !containsRect(text.ClipOf, text.Bounds) || - text.HasQuad && !containsRect(text.ClipOf, quadBounds(text.Quad)) -} - -func intersectVisible(bounds, clip gfx.Rect) (gfx.Rect, bool) { - left := max32(bounds.X, clip.X) - top := max32(bounds.Y, clip.Y) - right := min32(bounds.X+bounds.Width, clip.X+clip.Width) - bottom := min32(bounds.Y+bounds.Height, clip.Y+clip.Height) - if right <= left || bottom <= top { - return gfx.Rect{}, false - } - return gfx.Rect{X: left, Y: top, Width: right - left, Height: bottom - top}, true -} - -func max32(a, b float32) float32 { - if a > b { - return a - } - return b -} - -func min32(a, b float32) float32 { - if a < b { - return a - } - return b -} - -// drawnBy reports whether a stored instance already draws a clipped shape. -// Both sides are compared field by field, as the scene stores them. -func (painter *painter) drawnBy(stored *render.Rectangle, ref shapeRef) bool { - if ref.triangle { - triangle := &painter.clippedPaths[ref.index] - return stored.Kind == scene.KindTriangle && stored.Color == scene.Color(triangle.Color) && - stored.EdgeMask == triangle.EdgeMask && stored.Shade == sceneShade(*triangle) && - stored.Points[0] == scene.Point(triangle.Points[0]) && - stored.Points[1] == scene.Point(triangle.Points[1]) && - stored.Points[2] == scene.Point(triangle.Points[2]) - } - if ref.shadow { - shadow := &painter.clippedSoft[ref.index] - return stored.Kind == scene.KindShadow && stored.Radius == shadow.Radius && - stored.Color == scene.Color(shadow.Color) && stored.Bounds == scene.Rect(shadow.Bounds) && - stored.Shadow == scene.Shadow(shadow.Style) - } - rectangle := &painter.clipped[ref.index] - return stored.Kind == scene.KindRectangle && stored.Radius == rectangle.Radius && - stored.Color == scene.Color(rectangle.Color) && stored.Bounds == scene.Rect(rectangle.Bounds) -} - -// syncShapes aligns the scene's nodes with the clipped shapes, rectangles and -// triangles together in paint order, so the render store, which paints in node -// order, always equals the canvas. -// -// A repaint usually changes one stretch of the shapes: a highlight appears, a -// tab closes, a page swaps. The shapes before and after that stretch are left -// alone; inside it the nodes are rewritten in place (a node that held a -// rectangle may become a triangle and keeps its place), and the difference in -// length is inserted or removed at the end of the stretch. Cost follows the -// size of the change, not of the page, and no node is ever painted out of -// order. -func (painter *painter) syncShapes() { - root := painter.graph.Root() - stored := painter.renderer.Rectangles() // what the previous frame painted - oldCount, newCount := len(painter.shapeIDs), len(painter.order) - if len(stored) != oldCount { - // Not reachable while the store follows the scene; if it ever does not, - // rewrite every node rather than trust the comparison below. - stored = nil - } - - prefix := 0 - for prefix < min(len(stored), newCount) && painter.drawnBy(&stored[prefix], painter.order[prefix]) { - prefix++ - } - suffix := 0 - for suffix < min(oldCount, newCount)-prefix && len(stored) == oldCount && - painter.drawnBy(&stored[oldCount-1-suffix], painter.order[newCount-1-suffix]) { - suffix++ - } - oldMiddle, newMiddle := oldCount-prefix-suffix, newCount-prefix-suffix - - for index := prefix; index < prefix+min(oldMiddle, newMiddle); index++ { - painter.setShape(painter.shapeIDs[index], painter.order[index]) - } - switch { - case newMiddle > oldMiddle: - at := prefix + oldMiddle - add := newMiddle - oldMiddle - var previous scene.ID - if at > 0 { - previous = painter.shapeIDs[at-1] - } - for range add { - painter.shapeIDs = append(painter.shapeIDs, 0) - } - copy(painter.shapeIDs[at+add:], painter.shapeIDs[at:oldCount]) - for index := at; index < at+add; index++ { - previous = painter.insertShape(root, previous, painter.order[index]) - painter.shapeIDs[index] = previous - } - case oldMiddle > newMiddle: - from := prefix + newMiddle - for _, id := range painter.shapeIDs[from : prefix+oldMiddle] { - painter.graph.Remove(id) - } - painter.shapeIDs = slices.Delete(painter.shapeIDs, from, prefix+oldMiddle) - } -} - -// setShape makes an existing node draw a shape, whatever it drew before. -func (painter *painter) setShape(id scene.ID, ref shapeRef) { - if ref.triangle { - value := sceneTriangle(painter.clippedPaths[ref.index]) - painter.graph.SetTriangle(id, value.Points, value.Color, value.EdgeMask, value.Shade) - return - } - if ref.shadow { - shadow := &painter.clippedSoft[ref.index] - painter.graph.SetShadow(id, scene.Rect(shadow.Bounds), scene.Color(shadow.Color), shadow.Radius, scene.Shadow(shadow.Style)) - return - } - painter.setRectangle(id, painter.clipped[ref.index]) -} - -// insertShape adds a node drawing a shape right after previous. -func (painter *painter) insertShape(root, previous scene.ID, ref shapeRef) scene.ID { - if ref.triangle { - value := sceneTriangle(painter.clippedPaths[ref.index]) - id, _ := painter.graph.InsertTriangle(root, previous, value.Points, value.Color, value.EdgeMask, value.Shade) - return id - } - if ref.shadow { - shadow := &painter.clippedSoft[ref.index] - id, _ := painter.graph.InsertShadow(root, previous, scene.Rect(shadow.Bounds), scene.Color(shadow.Color), shadow.Radius, scene.Shadow(shadow.Style)) - return id - } - rectangle := painter.clipped[ref.index] - value := sceneRectangle(rectangle) - id, _ := painter.graph.InsertRoundedRectangle(root, previous, value.Bounds, value.Color, rectangle.Radius) - return id -} - -func (painter *painter) setRectangle(id scene.ID, rectangle gfx.Rectangle) { - value := sceneRectangle(rectangle) - painter.graph.SetRoundedRectangle(id, value.Bounds, value.Color, rectangle.Radius) -} - // hitStructuresUnchanged reports whether the paint produced exactly the input // the semantic tree and the accessibility payload were last built from, so both // can be kept. It compares every field those structures read, plus the focus, @@ -2082,7 +1560,7 @@ func (painter *painter) recordHitStructures() { // syncSemantics mirrors the canvas hit list into the retained semantic tree // and the flattened accessibility payload. -func (painter *painter) syncSemantics() { +func (painter *painter) syncSemantics(incremental bool) { root := painter.semantics.Root() // Blocks are occluders, not targets: they have no accessible meaning. Labels // are no nodes either; their words name the control they label. @@ -2099,6 +1577,41 @@ func (painter *painter) syncSemantics() { pendingCount := 0 trap := painter.canvas.TrappedFocusScope() canvasHits := painter.canvas.Hits() + // incremental is set when only the hit list changed: the focus, text state + // and view are the same, so a control whose hit and label are unchanged + // keeps its accessibility node. Compare the raw hits first and remember the + // few ids whose entry may have moved; a structural change, a label-map + // fallback or too many dirty ids falls back to the full mirror below. + fast := incremental && len(canvasHits) == len(painter.publishedHits) + dirty := painter.semanticDirty[:0] + if fast { + for index := range canvasHits { + current, previous := &canvasHits[index], &painter.publishedHits[index] + if current.ID != previous.ID || current.IsLabel != previous.IsLabel || + current.Block != previous.Block || current.MovesWindow != previous.MovesWindow || + current.Backdrop != previous.Backdrop { + fast = false + break + } + if *current != *previous && !current.ID.IsZero() { + known := false + for _, id := range dirty { + if id == current.ID { + known = true + break + } + } + if !known { + dirty = append(dirty, current.ID) + if len(dirty) > 64 { + fast = false + break + } + } + } + } + } + painter.semanticDirty = dirty for index := range canvasHits { hit := &canvasHits[index] switch { @@ -2157,6 +1670,36 @@ func (painter *painter) syncSemantics() { } painter.hitScratch = hits + if fast && labelled && (needsLabelMap || pendingCount > 0) { + fast = false + } + if fast && len(hits) != len(painter.semanticIDs) { + fast = false + } + if fast { + focused := painter.focus.Focused() + previous := painter.accessibility + for index := range hits { + dirtyHit := false + for _, id := range dirty { + if id == hits[index].ID { + dirtyHit = true + break + } + } + if !dirtyHit { + continue + } + node := painter.accessibilityNode(&hits[index], focused) + if index < len(previous) && previous[index] == node { + continue + } + painter.accessibility[index] = node + painter.semantics.Set(painter.semanticIDs[index], semanticNode(hits[index], focused)) + } + painter.semanticChanges = painter.semantics.DrainChanges(painter.semanticChanges[:0]) + return + } common := len(painter.semanticIDs) if len(hits) < common { common = len(hits) @@ -2221,6 +1764,7 @@ func (painter *painter) accessibilityNode(hit *gfx.Hit, focused gfx.ID) platform Expanded: hit.Expanded, Multiline: hit.Multiline, ReadOnly: hit.ReadOnly, + Invalid: hit.Invalid, Secure: hit.Secure, Focusable: hit.Focusable, Expandable: hit.Expandable, @@ -2293,6 +1837,7 @@ func semanticNode(hit gfx.Hit, focused gfx.ID) semantic.Node { Expanded: hit.Expanded, Multiline: hit.Multiline, ReadOnly: hit.ReadOnly, + Invalid: hit.Invalid, Secure: hit.Secure, } } @@ -2344,463 +1889,6 @@ func semanticRole(role gfx.Role) semantic.Role { } } -// syncLabels rebuilds the label list. A bitmap label carries its pixels across -// the native boundary only when that bitmap is not exactly what the same place -// in the previous frame showed, so a picture made of many bitmaps (see -// gfx.Surface) stages just the ones that changed. -func (painter *painter) syncLabels() { - painter.labels = painter.labels[:0] - painter.labelImage = painter.labelImage[:0] - images := painter.clippedImages - texts := painter.clippedTexts - fontGeneration := painter.canvas.FontGeneration() - // Images and texts are each in paint order; merge them back into one order, - // because a label and a bitmap are both platform text labels. A backdrop is - // beneath everything whatever its own paint order, so it goes first. Each - // label carries how many shapes the frame painted before it, which is where - // the renderers put it back among them. - for ii := range images { - if images[ii].Backdrop { - painter.appendImageLabel(ii, painter.clippedImageBefores[ii]) - } - } - for ii, ti := 0, 0; ii < len(images) || ti < len(texts); { - for ii < len(images) && images[ii].Backdrop { - ii++ - } - if ti >= len(texts) || (ii < len(images) && images[ii].Order <= texts[ti].Order) { - painter.appendImageLabel(ii, painter.clippedImageBefores[ii]) - ii++ - continue - } - painter.appendTextLabel(texts[ti], fontGeneration, painter.clippedTextBefores[ti]) - ti++ - } -} - -// appendImageLabel adds image number index of painter.clippedImages to the -// frame's labels, after shapesBefore shapes. -func (painter *painter) appendImageLabel(index int, shapesBefore uint32) { - image := painter.clippedImages[index] - bitmap := image.Bitmap - left := max(int(image.Source.X), 0) - top := max(int(image.Source.Y), 0) - right := min(int(math.Ceil(float64(image.Source.X+image.Source.Width))), bitmap.Width) - bottom := min(int(math.Ceil(float64(image.Source.Y+image.Source.Height))), bitmap.Height) - if left >= right || top >= bottom { - return - } - offset := top*bitmap.Stride + left*4 - length := (bottom-top-1)*bitmap.Stride + (right-left)*4 - if offset < 0 || length <= 0 || offset > len(bitmap.Pix) || length > len(bitmap.Pix)-offset { - return - } - width := roundPixel(image.Bounds.Width) - height := roundPixel(image.Bounds.Height) - if width <= 0 || height <= 0 { - return - } - layer := painter.platformLayer(image.Layer) - if image.Backdrop { - layer = 0 - } - // Rounded to logical pixels, unless the image is laid out in device pixels. - x, y, w, h := float32(roundPosition(image.Bounds.X)), float32(roundPosition(image.Bounds.Y)), float32(width), float32(height) - if image.DevicePixels { - x, y, w, h = image.Bounds.X, image.Bounds.Y, image.Bounds.Width, image.Bounds.Height - } - painter.labels = append(painter.labels, platform.TextLabel{ - X: x, Y: y, - Width: w, Height: h, - Layer: layer, - ShapesBefore: shapesBefore, - Bitmap: bitmap.Pix[offset : offset+length], BitmapWidth: right - left, BitmapHeight: bottom - top, - BitmapStride: bitmap.Stride, BitmapID: bitmap.ID, BitmapVersion: bitmap.Version, - BitmapUpload: painter.bitmapUpload(image, index), - }) - painter.labelImage = append(painter.labelImage, int32(index)) -} - -// bitmapUpload reports whether image number index must carry its pixels to the -// platform. It may omit them only when the label it is about to become showed -// the same picture in the frame last sent: the platform then reuses that -// label's texture. Another draw of the same bitmap elsewhere is no substitute, -// because the platform decides which label takes which old texture by position -// first. -func (painter *painter) bitmapUpload(image gfx.Image, index int) bool { - label := len(painter.labels) - if image.Bitmap.ID == 0 || label >= len(painter.lastLabelImage) { - return true - } - previous := int(painter.lastLabelImage[label]) - if previous < 0 || previous >= len(painter.lastImages) { - return true - } - return !sameImageBitmap(image, painter.lastImages[previous]) -} - -// appendTextLabel adds one canvas text to the frame's labels. -func (painter *painter) appendTextLabel(label gfx.Text, fontGeneration uint32, shapesBefore uint32) { - width := roundPixel(label.Bounds.Width) - height := roundPixel(label.Bounds.Height) - if width <= 0 || height <= 0 { - return - } - // Integer logical-pixel bounds keep the texture exactly one texel per - // physical pixel so linear sampling stays crisp on scaled displays. - entry := platform.TextLabel{ - Value: label.Value, - Identity: label.Identity, - X: float32(roundPosition(label.Bounds.X)), Y: float32(roundPosition(label.Bounds.Y)), - Width: float32(width), Height: float32(height), - OriginX: roundingRemainder(label.Bounds.X), OriginY: roundingRemainder(label.Bounds.Y), - FontSize: label.Style.Size, Weight: label.Style.Weight, Italic: label.Style.Italic, - Color: platform.Color{ - Red: float64(label.Style.Color.Red), Green: float64(label.Style.Color.Green), - Blue: float64(label.Style.Color.Blue), Alpha: float64(label.Style.Color.Alpha), - }, - Layer: painter.platformLayer(label.Layer), - ShapesBefore: shapesBefore, - Mono: label.Style.Mono, MonoFace: label.Style.MonoFace, CellWidth: label.CellWidth, Baseline: label.Baseline, Runs: painter.canvas.TextRuns(label), - } - if !label.Style.Mono && label.RunCount == 0 { - // Only text in the interface font follows its generation. - entry.FontGeneration = fontGeneration - } - if label.RunCount > 0 { - // The font does not draw the cell glyphs; appendCellGlyphs did. - entry.Value, entry.Runs = painter.replaceCellGlyphs(entry.Value, entry.Runs) - } - if label.HasClip { - if textClipCuts(label) { - // The clip cuts the label partway: the renderers scissor to it. - entry.Clip, entry.Clipped = label.ClipOf, true - } - } - if label.HasQuad { - // A warped line keeps its rasterisation box and moves only where the - // picture lands, so the platform draws the same texture as a quad. - entry.Quad, entry.HasQuad = label.Quad, true - for corner, tint := range label.Tint { - entry.Tint[corner] = platform.Color{ - Red: float64(tint.Red), Green: float64(tint.Green), - Blue: float64(tint.Blue), Alpha: float64(tint.Alpha), - } - } - } - painter.labels = append(painter.labels, entry) - painter.labelImage = append(painter.labelImage, -1) -} - -// cellReplaceLimit bounds the memoized cell glyph replacements: a screen holds -// its grid's rows and a little slack, and past the limit the memo starts over -// rather than keeping every line a session ever showed. -const cellReplaceLimit = 256 - -// cellReplaceMemo is one line's font-ready form: out is what ReplaceCellGlyphs -// built for in, kept while the same value and runs keep arriving. -type cellReplaceMemo struct { - inValue, outValue string - inRuns, outRuns []gfx.TextRun -} - -// replaceCellGlyphs is gfx.ReplaceCellGlyphs with a memory. A label sync that -// one changed row opened sends every row again; the rows that kept their value -// and runs get the replacement they already have instead of a fresh copy of the -// line and its runs, which is most of the garbage a keystroke in a bordered -// grid page otherwise makes. -func (painter *painter) replaceCellGlyphs(value string, runs []gfx.TextRun) (string, []gfx.TextRun) { - for i := range painter.cellReplace { - if memo := &painter.cellReplace[i]; memo.inValue == value && slices.Equal(memo.inRuns, runs) { - return memo.outValue, memo.outRuns - } - } - outValue, outRuns := gfx.ReplaceCellGlyphs(value, runs) - // A line without cell glyphs comes back as it went in; it has nothing to - // remember, and its runs are the caller's own slice. - if len(outRuns) == 0 || len(runs) == 0 || &outRuns[0] == &runs[0] { - return outValue, outRuns - } - if len(painter.cellReplace) >= cellReplaceLimit { - painter.cellReplace = painter.cellReplace[:0] - } - painter.cellReplace = append(painter.cellReplace, cellReplaceMemo{ - inValue: value, inRuns: append([]gfx.TextRun(nil), runs...), - outValue: outValue, outRuns: outRuns, - }) - return outValue, outRuns -} - -// deviceBounds rounds the edges of bounds to whole device pixels of scale. -func deviceBounds(bounds gfx.Rect, scale float32) gfx.Rect { - edge := func(value float32) float32 { return float32(math.Floor(float64(value)*float64(scale) + 0.5)) } - left, top := edge(bounds.X), edge(bounds.Y) - right, bottom := edge(bounds.X+bounds.Width), edge(bounds.Y+bounds.Height) - return gfx.Rect{X: left / scale, Y: top / scale, Width: (right - left) / scale, Height: (bottom - top) / scale} -} - -// wholePixels rounds the edges of a bitmap region to whole bitmap pixels. -func wholePixels(region gfx.Rect) gfx.Rect { - left, top := math.Floor(float64(region.X)+0.5), math.Floor(float64(region.Y)+0.5) - right, bottom := math.Floor(float64(region.X+region.Width)+0.5), math.Floor(float64(region.Y+region.Height)+0.5) - return gfx.Rect{X: float32(left), Y: float32(top), Width: float32(right - left), Height: float32(bottom - top)} -} - -// containsRect reports whether inner lies wholly inside outer. -func containsRect(outer, inner gfx.Rect) bool { - return inner.X >= outer.X && inner.Y >= outer.Y && - inner.X+inner.Width <= outer.X+outer.Width && inner.Y+inner.Height <= outer.Y+outer.Height -} - -// roundingRemainder is what roundPosition took off value: the sub-pixel position -// backends that place text at device pixels draw it at (platform.TextLabel.OriginX). -func roundingRemainder(value float32) float32 { - return value - float32(roundPosition(value)) -} - -func roundPixel(value float32) int32 { - if value < 0 { - return 0 - } - return int32(value + 0.5) -} - -// roundPosition rounds a coordinate to the nearest logical pixel. Unlike a -// size, a position may be negative: a leaving drawer and its text move past the -// window edge together, and clamping either to zero would stop it at the edge. -func roundPosition(value float32) int32 { - return int32(math.Floor(float64(value) + 0.5)) -} - -// roundPresenceRect puts a native overlay on the same whole logical pixels as -// the moving label it covers. Presence rounds a text label's origin so its -// texture is not rebuilt every frame; the platform editor next to it has to -// land on the same pixel. -func roundPresenceRect(rect gfx.Rect) gfx.Rect { - return gfx.Rect{ - X: float32(roundPosition(rect.X)), Y: float32(roundPosition(rect.Y)), - Width: float32(roundPixel(rect.Width)), Height: float32(roundPixel(rect.Height)), - } -} - -func sceneRectangle(rectangle gfx.Rectangle) render.Rectangle { - return render.Rectangle{ - Kind: scene.KindRectangle, - Bounds: scene.Rect{ - X: rectangle.Bounds.X, Y: rectangle.Bounds.Y, - Width: rectangle.Bounds.Width, Height: rectangle.Bounds.Height, - }, - Color: scene.Color{ - Red: rectangle.Color.Red, Green: rectangle.Color.Green, - Blue: rectangle.Color.Blue, Alpha: rectangle.Color.Alpha, - }, - Radius: rectangle.Radius, - Layer: rectangle.Layer, - } -} - -func sceneTriangle(triangle gfx.Triangle) render.Rectangle { - return render.Rectangle{ - Kind: scene.KindTriangle, - Points: [3]scene.Point{ - {X: triangle.Points[0].X, Y: triangle.Points[0].Y}, - {X: triangle.Points[1].X, Y: triangle.Points[1].Y}, - {X: triangle.Points[2].X, Y: triangle.Points[2].Y}, - }, - EdgeMask: triangle.EdgeMask, - Color: scene.Color{ - Red: triangle.Color.Red, Green: triangle.Color.Green, - Blue: triangle.Color.Blue, Alpha: triangle.Color.Alpha, - }, - Shade: sceneShade(triangle), - Layer: triangle.Layer, - } -} - -// sceneShade is the vertex colors of a shaded triangle, and the zero Shade for a -// flat one, whatever stale colors its Shade array holds. -func sceneShade(triangle gfx.Triangle) scene.Shade { - if !triangle.Shaded { - return scene.Shade{} - } - return scene.Shade{On: true, Colors: [2]scene.Color{scene.Color(triangle.Shade[0]), scene.Color(triangle.Shade[1])}} -} - -// instanceState is what a render instance knows about its place on screen that -// the scene does not carry: the layer it composes in and the clip that cuts it. -type instanceState struct { - layer uint16 - clipped bool - clip scene.Rect -} - -// stampState copies each primitive's canvas layer and clip onto its render -// instance and reports whether either changed anywhere, which a partial update -// would not carry to the GPU. Instances are listed by the scene's tree order, -// which syncShapes keeps equal to paint order, so the shape at index i is the -// instance at index i; should the store ever disagree, the state travels with -// the node's storage slot instead. -func (painter *painter) stampState() (changed bool) { - instances := painter.renderer.Rectangles() - if len(instances) != len(painter.shapeIDs) { - return painter.stampBySlot() - } - for index, id := range painter.shapeIDs { - instance := &instances[index] - if instance.ID != id { - return painter.stampBySlot() - } - state := painter.shapeState(painter.order[index]) - if instance.Layer != state.layer || instance.Clipped != state.clipped || instance.Clip != state.clip { - instance.Layer, instance.Clipped, instance.Clip = state.layer, state.clipped, state.clip - changed = true - } - } - return changed -} - -// stampBySlot is stampState for a store whose order is not the paint order. -func (painter *painter) stampBySlot() (changed bool) { - for index, id := range painter.shapeIDs { - slot, ok := id.Slot() - if !ok { - continue - } - for int(slot) >= len(painter.stateBySlot) { - painter.stateBySlot = append(painter.stateBySlot, instanceState{}) - } - painter.stateBySlot[slot] = painter.shapeState(painter.order[index]) - } - instances := painter.renderer.Rectangles() - for index := range instances { - slot, _ := instances[index].ID.Slot() - state := painter.stateBySlot[slot] - if instances[index].Layer != state.layer || instances[index].Clipped != state.clipped || instances[index].Clip != state.clip { - instances[index].Layer, instances[index].Clipped, instances[index].Clip = state.layer, state.clipped, state.clip - changed = true - } - } - return changed -} - -// shapeState is the layer and clip the platform draws a shape with. -func (painter *painter) shapeState(ref shapeRef) instanceState { - var state instanceState - if ref.shadow { - shadow := &painter.clippedSoft[ref.index] - state = instanceState{layer: shadow.Layer, clipped: shadow.HasClip} - if shadow.HasClip { - state.clip = scene.Rect(shadow.ClipOf) - } - } else if ref.triangle { - triangle := &painter.clippedPaths[ref.index] - state = instanceState{layer: triangle.Layer, clipped: triangle.HasClip} - if triangle.HasClip { - state.clip = scene.Rect(triangle.ClipOf) - } - } else { - rectangle := &painter.clipped[ref.index] - state = instanceState{layer: rectangle.Layer, clipped: rectangle.HasClip} - if rectangle.HasClip { - state.clip = scene.Rect(rectangle.ClipOf) - } - } - state.layer = painter.platformLayer(state.layer) - return state -} - -// platformLayer is the layer a canvas layer takes on the platform. The topmost -// layer stays topmost. -func (painter *painter) platformLayer(layer uint16) uint16 { - if painter.layerShift == 0 || layer == math.MaxUint16 { - return layer - } - return layer + painter.layerShift -} - -// sameAsLastTexts reports whether the texts to draw are exactly those last -// sent to the platform. -func (painter *painter) sameAsLastContent() bool { - if painter.canvas.FontGeneration() != painter.lastFontGeneration || !sameImages(painter.clippedImages, painter.lastImages) { - return false - } - // A label's place among the shapes can move while the label itself does - // not: a shape before it can drop out of the clip, or paint nothing, and - // then the renderers must be told where the label goes. - if !slices.Equal(painter.clippedTextBefores, painter.lastTextBefores) || - !slices.Equal(painter.clippedImageBefores, painter.lastImageBefores) { - return false - } - left, right := painter.clippedTexts, painter.lastTexts - if len(left) != len(right) { - return false - } - for index := range left { - a, b := left[index], right[index] - if a.Value != b.Value || a.Style != b.Style || a.Identity != b.Identity || a.Layer != b.Layer || a.Order != b.Order { - return false - } - if a.Bounds != b.Bounds || a.CellWidth != b.CellWidth || a.Baseline != b.Baseline || a.RunCount != b.RunCount { - return false - } - if a.HasClip != b.HasClip || a.HasClip && a.ClipOf != b.ClipOf { - return false - } - // Where a warped line lands changes every frame of an animation while - // its picture stays the same: the platform must still see the new quad. - if a.HasQuad != b.HasQuad { - return false - } - if a.HasQuad && (a.Quad != b.Quad || a.Tint != b.Tint) { - return false - } - if a.RunCount == 0 { - continue - } - current := painter.canvas.TextRuns(a) - if len(current) != int(a.RunCount) || b.RunFirst < 0 || b.RunCount < 0 || int(b.RunFirst+b.RunCount) > len(painter.lastRuns) { - return false - } - saved := painter.lastRuns[b.RunFirst : b.RunFirst+b.RunCount] - for run := range current { - if current[run] != saved[run] { - return false - } - } - } - return true -} - -func sameImages(left, right []gfx.Image) bool { - if len(left) != len(right) { - return false - } - for index := range left { - a, b := left[index], right[index] - if a.Bounds != b.Bounds || a.Source != b.Source || a.Layer != b.Layer || a.Order != b.Order || a.Backdrop != b.Backdrop || a.Bitmap.Width != b.Bitmap.Width || - a.Bitmap.Height != b.Bitmap.Height || a.Bitmap.Stride != b.Bitmap.Stride || a.Bitmap.ID != b.Bitmap.ID || - a.Bitmap.Version != b.Bitmap.Version || len(a.Bitmap.Pix) != len(b.Bitmap.Pix) { - return false - } - if len(a.Bitmap.Pix) > 0 && &a.Bitmap.Pix[0] != &b.Bitmap.Pix[0] { - return false - } - } - return true -} - -// sameImageBitmap reports whether two draws show the very same pixels: the same -// identity and version, source region and storage. A bitmap with no identity -// (ID 0) is never the same: nothing says its pixels did not change. -func sameImageBitmap(a, b gfx.Image) bool { - if a.Source != b.Source || a.Bitmap.Width != b.Bitmap.Width || a.Bitmap.Height != b.Bitmap.Height || - a.Bitmap.Stride != b.Bitmap.Stride || a.Bitmap.ID != b.Bitmap.ID || a.Bitmap.Version != b.Bitmap.Version || - len(a.Bitmap.Pix) != len(b.Bitmap.Pix) || a.Bitmap.ID == 0 { - return false - } - return len(a.Bitmap.Pix) == 0 || &a.Bitmap.Pix[0] == &b.Bitmap.Pix[0] -} - func sameAccessibility(left, right []platform.AccessibilityNode) bool { if len(left) != len(right) { return false @@ -2813,24 +1901,6 @@ func sameAccessibility(left, right []platform.AccessibilityNode) bool { return true } -// saveTexts remembers this frame's texts for the next comparison. Their runs -// live in the canvas, which is rewritten by the next paint, so they are copied. -func (painter *painter) saveContent() { - painter.lastFontGeneration = painter.canvas.FontGeneration() - painter.lastImages = append(painter.lastImages[:0], painter.clippedImages...) - painter.lastLabelImage = append(painter.lastLabelImage[:0], painter.labelImage...) - painter.lastTexts = append(painter.lastTexts[:0], painter.clippedTexts...) - painter.lastTextBefores = append(painter.lastTextBefores[:0], painter.clippedTextBefores...) - painter.lastImageBefores = append(painter.lastImageBefores[:0], painter.clippedImageBefores...) - painter.lastRuns = painter.lastRuns[:0] - for index := range painter.lastTexts { - text := &painter.lastTexts[index] - runs := painter.canvas.TextRuns(*text) - text.RunFirst = int32(len(painter.lastRuns)) - painter.lastRuns = append(painter.lastRuns, runs...) - } -} - // windowActions makes the set of operations the window buttons need, for the // platform adapter to fill, or nil when the system draws the buttons. func (painter *painter) windowActions() *platform.WindowActions { diff --git a/app/painter_bitmap_test.go b/app/painter_bitmap_test.go index 376c6124..407ccd40 100644 --- a/app/painter_bitmap_test.go +++ b/app/painter_bitmap_test.go @@ -6,6 +6,7 @@ import ( "testing" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/framebuild" "github.com/vivaui/viva/internal/platform" ) @@ -25,10 +26,10 @@ func TestBitmapPaintIsRetainedAndClippedWithoutPixelCopies(t *testing.T) { if err != nil { t.Fatal(err) } - if len(painter.labels) != 2 || !painter.labels[0].BitmapUpload { - t.Fatalf("labels = %+v", painter.labels) + if len(painter.frame.Labels()) != 2 || !painter.frame.Labels()[0].BitmapUpload { + t.Fatalf("labels = %+v", painter.frame.Labels()) } - label := painter.labels[0] + label := painter.frame.Labels()[0] if label.X != 10 || label.Y != 10 || label.Width != 20 || label.Height != 20 || label.BitmapWidth != 2 || label.BitmapHeight != 2 { t.Fatalf("clipped bitmap label = %+v", label) } @@ -89,8 +90,8 @@ func TestBitmapPixelsFollowTheLabelAndNotThePictureOrder(t *testing.T) { if _, err := painter.repaint(); err != nil { t.Fatal(err) } - previous := append([]int32(nil), painter.lastLabelImage...) - previousImages := append([]gfx.Image(nil), painter.lastImages...) + previous := append([]int32(nil), painter.frame.LastLabelImages()...) + previousImages := append([]gfx.Image(nil), painter.frame.LastImages()...) // The icon is gone and the page's copy is whole again: both pictures move up // one image place, while the labels keep the places the text gives them. showIcon = false @@ -102,14 +103,14 @@ func TestBitmapPixelsFollowTheLabelAndNotThePictureOrder(t *testing.T) { if frame.TextLabels == nil { t.Fatal("the clipped picture changed but no labels were sent") } - current := append([]int32(nil), painter.labelImage...) - currentImages := append([]gfx.Image(nil), painter.clippedImages...) + current := append([]int32(nil), painter.frame.LabelImages()...) + currentImages := append([]gfx.Image(nil), painter.frame.ClippedImages()...) for index, label := range frame.TextLabels { if len(label.Bitmap) == 0 || label.BitmapUpload { continue } if index >= len(previous) || previous[index] < 0 || int(previous[index]) >= len(previousImages) || - !sameImageBitmap(currentImages[current[index]], previousImages[previous[index]]) { + !framebuild.SameImageBitmap(currentImages[current[index]], previousImages[previous[index]]) { t.Fatalf("label %d at %v,%v omits its pixels though the label in its place showed no such picture", index, label.X, label.Y) } @@ -155,7 +156,7 @@ func TestInitialBitmapUploadAfterPreparationPaint(test *testing.T) { test.Fatal(err) } found := false - for _, label := range painter.labels { + for _, label := range painter.frame.Labels() { if label.BitmapID == bitmap.ID { found = true if !label.BitmapUpload { @@ -242,10 +243,10 @@ func TestBackdropIsBeneathEveryLayerAndShiftsThemOnlyWhilePresent(t *testing.T) t.Fatal(err) } layers := func() (rectangles, labels []uint16) { - for _, rectangle := range painter.renderer.Rectangles() { + for _, rectangle := range painter.frame.Rectangles() { rectangles = append(rectangles, rectangle.Layer) } - for _, label := range painter.labels { + for _, label := range painter.frame.Labels() { labels = append(labels, label.Layer) } return @@ -254,8 +255,8 @@ func TestBackdropIsBeneathEveryLayerAndShiftsThemOnlyWhilePresent(t *testing.T) if !slices.Equal(rectangles, []uint16{1, 601, math.MaxUint16}) || !slices.Equal(labels, []uint16{0, 1}) { t.Fatalf("with a backdrop: rectangles %v, labels %v", rectangles, labels) } - if painter.labels[0].BitmapID != 7 || painter.labels[0].BitmapWidth != 4 { - t.Fatalf("backdrop label = %+v", painter.labels[0]) + if painter.frame.Labels()[0].BitmapID != 7 || painter.frame.Labels()[0].BitmapWidth != 4 { + t.Fatalf("backdrop label = %+v", painter.frame.Labels()[0]) } backdrop = false @@ -324,7 +325,7 @@ func TestOnlyChangedBitmapsCrossTheNativeBoundary(t *testing.T) { } return count } - if got := uploads(painter.labels); got != 6 { + if got := uploads(painter.frame.Labels()); got != 6 { t.Fatalf("first frame uploads %d bitmaps, want all 6", got) } // A patch inside the first tile: one upload, the other five stay on the GPU. @@ -373,7 +374,7 @@ func TestDevicePixelBitmapsKeepTheirDevicePixelsAtFractionalScales(t *testing.T) t.Fatal(err) } covered := 0 - for _, label := range painter.labels { + for _, label := range painter.frame.Labels() { if len(label.Bitmap) == 0 { continue } diff --git a/app/painter_leak_test.go b/app/painter_leak_test.go index caf5898a..dfd64cb6 100644 --- a/app/painter_leak_test.go +++ b/app/painter_leak_test.go @@ -34,20 +34,20 @@ func TestAPageThatIsRemovedLeavesNothingRetained(t *testing.T) { } settle(0) - scenes, semantics, rectangles := painter.graph.Len(), painter.semantics.Len(), len(painter.renderer.Rectangles()) + scenes, semantics, rectangles := painter.frame.Graph().Len(), painter.semantics.Len(), len(painter.frame.Rectangles()) for round := 0; round < 5; round++ { settle(12) - if painter.graph.Len() <= scenes || painter.semantics.Len() <= semantics { + if painter.frame.Graph().Len() <= scenes || painter.semantics.Len() <= semantics { t.Fatal("the busy page retained nothing; the test is not exercising what it claims") } settle(0) - if got := painter.graph.Len(); got != scenes { + if got := painter.frame.Graph().Len(); got != scenes { t.Fatalf("round %d: the scene holds %d nodes after the page was removed, %d before it was shown", round, got, scenes) } if got := painter.semantics.Len(); got != semantics { t.Fatalf("round %d: the semantic tree holds %d nodes after the page was removed, %d before", round, got, semantics) } - if got := len(painter.renderer.Rectangles()); got != rectangles { + if got := len(painter.frame.Rectangles()); got != rectangles { t.Fatalf("round %d: the renderer holds %d rectangles after the page was removed, %d before", round, got, rectangles) } } @@ -72,11 +72,11 @@ func TestALargePageThenASmallOneReleasesSlots(t *testing.T) { } } settle(5000) - if painter.graph.Slots() < 5000 || painter.semantics.Slots() < 5000 { - t.Fatalf("the large page did not allocate its slots: graph=%d semantics=%d", painter.graph.Slots(), painter.semantics.Slots()) + if painter.frame.Graph().Slots() < 5000 || painter.semantics.Slots() < 5000 { + t.Fatalf("the large page did not allocate its slots: graph=%d semantics=%d", painter.frame.Graph().Slots(), painter.semantics.Slots()) } settle(1) - if painter.graph.Slots() > 64 || painter.semantics.Slots() > 64 { - t.Fatalf("the small page kept the large page's slots: graph=%d semantics=%d", painter.graph.Slots(), painter.semantics.Slots()) + if painter.frame.Graph().Slots() > 64 || painter.semantics.Slots() > 64 { + t.Fatalf("the small page kept the large page's slots: graph=%d semantics=%d", painter.frame.Graph().Slots(), painter.semantics.Slots()) } } diff --git a/app/painter_origin_test.go b/app/painter_origin_test.go index 5b10c864..c503534e 100644 --- a/app/painter_origin_test.go +++ b/app/painter_origin_test.go @@ -1,17 +1,21 @@ package app -import "testing" +import ( + "testing" + + "github.com/vivaui/viva/internal/framebuild" +) // A label's frame is on whole logical pixels, and the text keeps the rest of its position: // the two add up to where layout put it, so a backend that places glyphs at device pixels // loses nothing to the rounding. func TestLabelOriginIsWhatRoundingTookOff(t *testing.T) { for _, value := range []float32{-99.9, -20.75, -10.3, -3.49, -0.5, -0.25, 0, 0.25, 0.5, 3.49, 10.3, 20.75, 99.9} { - got := float32(roundPosition(value)) + roundingRemainder(value) + got := float32(framebuild.RoundPosition(value)) + framebuild.RoundingRemainder(value) if diff := got - value; diff > 1e-4 || diff < -1e-4 { - t.Errorf("%v: frame %d + origin %v = %v", value, roundPosition(value), roundingRemainder(value), got) + t.Errorf("%v: frame %d + origin %v = %v", value, framebuild.RoundPosition(value), framebuild.RoundingRemainder(value), got) } - if r := roundingRemainder(value); r < -0.5 || r > 0.5 { + if r := framebuild.RoundingRemainder(value); r < -0.5 || r > 0.5 { t.Errorf("%v: origin %v is further than half a pixel from the frame", value, r) } } diff --git a/app/painter_presence_test.go b/app/painter_presence_test.go index 1a39b583..9d4e0d38 100644 --- a/app/painter_presence_test.go +++ b/app/painter_presence_test.go @@ -44,8 +44,8 @@ func TestPresenceExitPublishesLabelsPastTheWindowEdge(t *testing.T) { if _, err := painter.repaint(); err != nil { t.Fatal(err) } - startPanelX := painter.clipped[0].Bounds.X - startLabelX := painter.labels[0].X + startPanelX := painter.frame.ClippedRectangles()[0].Bounds.X + startLabelX := painter.frame.Labels()[0].X show = false now += 16 * time.Millisecond if _, err := painter.repaint(); err != nil { @@ -62,7 +62,7 @@ func TestPresenceExitPublishesLabelsPastTheWindowEdge(t *testing.T) { if frame.TextLabels[0].OriginX != 0 || frame.TextLabels[0].OriginY != 0 { t.Fatalf("moving label kept sub-pixel origin %v,%v", frame.TextLabels[0].OriginX, frame.TextLabels[0].OriginY) } - movedPanelX, movedLabelX := painter.clipped[0].Bounds.X, frame.TextLabels[0].X + movedPanelX, movedLabelX := painter.frame.ClippedRectangles()[0].Bounds.X, frame.TextLabels[0].X if movedPanelX >= startPanelX || movedLabelX >= startLabelX { t.Fatalf("leaving panel %v->%v and label %v->%v did not move left", startPanelX, movedPanelX, startLabelX, movedLabelX) } diff --git a/app/painter_test.go b/app/painter_test.go index 33e2a186..ab71a5e0 100644 --- a/app/painter_test.go +++ b/app/painter_test.go @@ -410,11 +410,11 @@ func TestPainterInitialSyncPublishesCanvas(t *testing.T) { canvas.Label("Viva", gfx.Rect{X: 2, Y: 2, Width: 40, Height: 12}, gfx.TextStyle{Size: 12}) painter := newTestPainter(t, &canvas, Config{Title: "test", Width: 100, Height: 100}) - if len(painter.renderer.Rectangles()) != 1 { - t.Fatalf("renderer rectangles = %+v", painter.renderer.Rectangles()) + if len(painter.frame.Rectangles()) != 1 { + t.Fatalf("renderer rectangles = %+v", painter.frame.Rectangles()) } - if len(painter.labels) != 1 || painter.labels[0].Value != "Viva" { - t.Fatalf("labels = %+v", painter.labels) + if len(painter.frame.Labels()) != 1 || painter.frame.Labels()[0].Value != "Viva" { + t.Fatalf("labels = %+v", painter.frame.Labels()) } } @@ -716,8 +716,8 @@ func TestRepaintShrinkingListRemovesSceneNodes(t *testing.T) { if !frame.Update.Empty() { t.Fatalf("resize after initial shrink produced work: %+v", frame.Update) } - if len(painter.renderer.Rectangles()) != 1 { - t.Fatalf("renderer kept %d rectangles", len(painter.renderer.Rectangles())) + if len(painter.frame.Rectangles()) != 1 { + t.Fatalf("renderer kept %d rectangles", len(painter.frame.Rectangles())) } } @@ -1158,8 +1158,8 @@ func TestScrollClampsAtZeroAndRepaints(t *testing.T) { if paints != 2 { t.Fatalf("productive scroll repainted %d times, want initial + 1", paints) } - if len(painter.clipped) != 1 || painter.clipped[0].Bounds.Y != -14 { - t.Fatalf("scrolled rectangle = %+v", painter.clipped) + if len(painter.frame.ClippedRectangles()) != 1 || painter.frame.ClippedRectangles()[0].Bounds.Y != -14 { + t.Fatalf("scrolled rectangle = %+v", painter.frame.ClippedRectangles()) } } @@ -1176,7 +1176,7 @@ func TestClipKeepsCutRectanglesWholeAndDropsHiddenShapesAndText(t *testing.T) { canvas.Fill(gfx.Rect{X: 80, Y: 40, Width: 10, Height: 10}, gfx.Color{Alpha: 1}) painter := newTestPainter(t, &canvas, Config{Title: "test", Width: 100, Height: 100}) - instances := painter.renderer.Rectangles() + instances := painter.frame.Rectangles() if len(instances) != 3 { t.Fatalf("renderer holds %d rectangles, want the cut one, the inside one and the unclipped one: %+v", len(instances), instances) } @@ -1188,8 +1188,8 @@ func TestClipKeepsCutRectanglesWholeAndDropsHiddenShapesAndText(t *testing.T) { t.Errorf("rectangle %d carries a clip it does not need: %+v", index, instances[index]) } } - if len(painter.clippedTexts) != 1 || painter.clippedTexts[0].Value != "visible" { - t.Fatalf("clipped texts = %+v", painter.clippedTexts) + if len(painter.frame.ClippedTexts()) != 1 || painter.frame.ClippedTexts()[0].Value != "visible" { + t.Fatalf("clipped texts = %+v", painter.frame.ClippedTexts()) } } @@ -1209,7 +1209,7 @@ func TestPartlyClippedLabelsCarryTheirClipToThePlatform(t *testing.T) { painter := newTestPainter(t, &canvas, Config{Title: "test", Width: 100, Height: 120}) got := map[string]platform.TextLabel{} - for _, label := range painter.labels { + for _, label := range painter.frame.Labels() { got[label.Value] = label } if _, sent := got["gone"]; sent || len(got) != 4 { @@ -1242,7 +1242,7 @@ func TestClippedStrokeReachesTheRendererWholeWithItsClip(t *testing.T) { painter := newTestPainter(t, &canvas, Config{Title: "test", Width: 100, Height: 100}) painted := canvas.Triangles() - instances := painter.renderer.Rectangles() + instances := painter.frame.Rectangles() if len(painted) != 6 || len(instances) != 4 { t.Fatalf("canvas painted %d triangles and the renderer holds %d, want 6 and 4", len(painted), len(instances)) } @@ -1269,7 +1269,7 @@ func TestVectorFringeKeepsItsClip(t *testing.T) { canvas.DrawPath(gfx.NewPath(10, 10, gfx.MoveTo(x/scale, 2), gfx.LineTo(8, 2), gfx.LineTo(x/scale, 8), gfx.ClosePath()), clip, gfx.PathStyle{Fill: gfx.Color{Alpha: 1}}) canvas.Unclip() painter := newTestPainter(t, &canvas, Config{Title: "test", Width: 10, Height: 10}) - instances := painter.renderer.Rectangles() + instances := painter.frame.Rectangles() if len(instances) == 0 { t.Fatal("visible fringe was culled") } @@ -1755,8 +1755,8 @@ func TestRepaintRecoloringRectanglesBehindShrinkingTrianglesRefreshesEverything( if len(canvas.Triangles()) >= trianglesBefore { t.Fatal("the triangle list did not shrink; the test is not exercising what it claims") } - if painter.resyncs != 0 { - t.Fatalf("the renderer rejected the batch and had to be rebuilt %d times", painter.resyncs) + if painter.frame.Resyncs() != 0 { + t.Fatalf("the renderer rejected the batch and had to be rebuilt %d times", painter.frame.Resyncs()) } want := scene.Color{Red: 0.1, Green: 0.1, Blue: 0.15, Alpha: 1} if len(frame.Rectangles) != len(canvas.Rectangles())+len(canvas.Triangles()) { @@ -1782,14 +1782,14 @@ func TestRepaintRebuildsRenderStateThatDisagreesWithTheScene(t *testing.T) { } painter := newTestPainter(t, &canvas, config) - painter.renderer = render.Store{} // forget every node the scene believes was published + *painter.frame.Store() = render.Store{} // forget every node the scene believes was published tint = gfx.Color{Red: 0.2, Green: 0.4, Blue: 0.6, Alpha: 1} frame, err := painter.repaint() if err != nil { t.Fatalf("repaint: %v", err) } - if painter.resyncs != 1 { - t.Fatalf("resyncs = %d, want exactly one rebuild", painter.resyncs) + if painter.frame.Resyncs() != 1 { + t.Fatalf("resyncs = %d, want exactly one rebuild", painter.frame.Resyncs()) } if !frame.Update.Rebuild || len(frame.Rectangles) != 2 { t.Fatalf("update=%+v instances=%d, want a full rebuild of both rectangles", frame.Update, len(frame.Rectangles)) @@ -2313,7 +2313,7 @@ func TestShadowsReachTheRendererAndRepaintWithoutChangePerformsNoWork(t *testing paint(&canvas, gfx.Size{}) painter := newTestPainter(t, &canvas, Config{Title: "test", Width: 100, Height: 100, Paint: paint}) - instances := painter.renderer.Rectangles() + instances := painter.frame.Rectangles() if len(instances) != 5 { t.Fatalf("renderer holds %d instances, want the page, the two layers of the large shadow, the surface and the shadow that reaches in: %+v", len(instances), instances) } @@ -2364,7 +2364,7 @@ func TestAShapeBecomingAShadowKeepsItsPlace(t *testing.T) { if err != nil { t.Fatal(err) } - instances := painter.renderer.Rectangles() + instances := painter.frame.Rectangles() if len(instances) != 3 || instances[1].Kind != want { t.Fatalf("instances = %+v, want the middle one to be kind %d", instances, want) } @@ -2502,8 +2502,8 @@ func TestPainterDropsLabelsWithoutAreaOrFontSize(t *testing.T) { canvas.Label("visible", gfx.Rect{Width: 40, Height: 12}, gfx.TextStyle{Size: 12}) } painter := newTestPainter(t, &canvas, config) - if len(painter.labels) != 1 || painter.labels[0].Value != "visible" { - t.Fatalf("labels = %+v, want only the visible one", painter.labels) + if len(painter.frame.Labels()) != 1 || painter.frame.Labels()[0].Value != "visible" { + t.Fatalf("labels = %+v, want only the visible one", painter.frame.Labels()) } if _, err := painter.repaint(); err != nil { t.Fatalf("repaint failed: %v", err) @@ -2531,11 +2531,11 @@ func TestPainterDropsSubpixelAndClippedImages(t *testing.T) { canvas.DrawBitmap(bitmap, gfx.Rect{X: 10, Y: 10, Width: 20, Height: 20}) } painter := newTestPainter(t, &canvas, config) - if len(painter.labels) != 1 { - t.Fatalf("labels count = %d, want 1; labels = %+v", len(painter.labels), painter.labels) + if len(painter.frame.Labels()) != 1 { + t.Fatalf("labels count = %d, want 1; labels = %+v", len(painter.frame.Labels()), painter.frame.Labels()) } - if painter.labels[0].Width <= 0 || painter.labels[0].Height <= 0 { - t.Fatalf("visible image label has non-positive dimensions: %+v", painter.labels[0]) + if painter.frame.Labels()[0].Width <= 0 || painter.frame.Labels()[0].Height <= 0 { + t.Fatalf("visible image label has non-positive dimensions: %+v", painter.frame.Labels()[0]) } if _, err := painter.repaint(); err != nil { t.Fatalf("repaint failed: %v", err) @@ -2692,3 +2692,30 @@ func TestGridLinesDrawBoxArcsAsStrokesNotText(t *testing.T) { t.Fatalf("no stroked ring in %+v", frame.Rectangles) } } + +// Removing one shape is a suffix shrink, not a full renderer rebuild. +func TestRepaintShrinksWhenAShapeIsRemoved(t *testing.T) { + removed := -1 + config := Config{Title: "shrink", Width: 200, Height: 100} + config.Paint = func(canvas *gfx.Canvas, _ gfx.Size) { + for index := 0; index < 3; index++ { + if index == removed { + continue + } + canvas.Fill(gfx.Rect{X: float32(index) * 20, Width: 10, Height: 10}, gfx.Color{Alpha: 1}) + } + } + var canvas gfx.Canvas + painter := newTestPainter(t, &canvas, config) + removed = 1 + frame, err := painter.repaint() + if err != nil { + t.Fatal(err) + } + if frame.Update.Rebuild || !frame.Update.Shrink || frame.Update.Count != 1 || frame.Update.First != 1 { + t.Fatalf("shrink update = %+v", frame.Update) + } + if len(frame.Rectangles) != 2 { + t.Fatalf("rectangles = %d, want 2", len(frame.Rectangles)) + } +} diff --git a/app/quad_clip_test.go b/app/quad_clip_test.go index 21330b2f..eca3f718 100644 --- a/app/quad_clip_test.go +++ b/app/quad_clip_test.go @@ -31,11 +31,11 @@ func TestQuadClippingPreservesBothBackendPlacements(t *testing.T) { Tint: [4]gfx.Color{white, white, white, white}, }, gfx.TextStyle{Size: 14, Color: white}) painter := newTestPainter(t, &canvas, Config{Title: "quad clip", Width: 200, Height: 100}) - if (len(painter.labels) != 0) != test.visible { - t.Fatalf("visible=%t, labels=%+v", test.visible, painter.labels) + if (len(painter.frame.Labels()) != 0) != test.visible { + t.Fatalf("visible=%t, labels=%+v", test.visible, painter.frame.Labels()) } - if test.visible && (painter.labels[0].Clipped != test.cut || test.cut && painter.labels[0].Clip != clip) { - t.Fatalf("clip cut=%t, label=%+v", test.cut, painter.labels[0]) + if test.visible && (painter.frame.Labels()[0].Clipped != test.cut || test.cut && painter.frame.Labels()[0].Clip != clip) { + t.Fatalf("clip cut=%t, label=%+v", test.cut, painter.frame.Labels()[0]) } }) } diff --git a/app/run_canvas.go b/app/run_canvas.go index 784dbe0e..385c6e2e 100644 --- a/app/run_canvas.go +++ b/app/run_canvas.go @@ -175,8 +175,8 @@ func nativeWindowConfig(normalized *Config, painter *painter) (platform.Config, }, Web: normalized.Web.bind(), NativeViews: slices.Clone(painter.lastViews), - Rectangles: painter.renderer.Rectangles(), - TextLabels: painter.labels, + Rectangles: painter.frame.Rectangles(), + TextLabels: painter.frame.Labels(), Accessibility: painter.accessibility, OnResize: resizeHandler, OnFrameChange: frameChangeHandler(normalized.OnFrameChange), diff --git a/app/run_canvas_js.go b/app/run_canvas_js.go index 1991db33..36f24254 100644 --- a/app/run_canvas_js.go +++ b/app/run_canvas_js.go @@ -42,8 +42,8 @@ func RunCanvas(config Config, canvas *gfx.Canvas) error { }, Paint: normalized.Paint, OnPointer: normalized.OnPointer, OnKey: normalized.OnKey, OnShortcut: normalized.OnShortcut, OnScroll: normalized.OnScroll, OnModifierTap: normalized.OnModifierTap, - OnFileDrop: normalized.OnFileDrop, - OnResize: normalized.OnResize, OnMinimize: normalized.OnMinimize, + OnFileDrop: normalized.OnFileDrop, ForwardWheel: normalized.ForwardWheel, + OnResize: normalized.OnResize, OnMinimize: normalized.OnMinimize, OnFullscreen: normalized.OnFullscreen, OnCloseRequest: normalized.OnCloseRequest, OnClosed: normalized.OnClosed, OnActivate: normalized.OnActivate, TextInput: webTextInput(normalized.TextInput), diff --git a/app/run_canvas_js_test.go b/app/run_canvas_js_test.go index f5b0578f..3d95a4db 100644 --- a/app/run_canvas_js_test.go +++ b/app/run_canvas_js_test.go @@ -26,10 +26,12 @@ func TestRunCanvasHandsTheApplicationToThePage(t *testing.T) { var invalidator Invalidator canvas := &gfx.Canvas{} woken := false + forwarded := [2]float32{} err := RunCanvas(Config{ Title: "Notes", Tree: &tree, Invalidator: &invalidator, OnWake: func() { woken = true }, - Paint: func(*gfx.Canvas, gfx.Size) {}, - TextInput: func(TextInputContext) *TextInput { return nil }, + Paint: func(*gfx.Canvas, gfx.Size) {}, + TextInput: func(TextInputContext) *TextInput { return nil }, + ForwardWheel: func(deltaX, deltaY float32) { forwarded = [2]float32{deltaX, deltaY} }, }, canvas) if err != nil { t.Fatal(err) @@ -43,6 +45,13 @@ func TestRunCanvasHandsTheApplicationToThePage(t *testing.T) { if got.Paint == nil || got.TextInput == nil { t.Error("Paint and TextInput must reach the page") } + if got.ForwardWheel == nil { + t.Fatal("ForwardWheel must reach the page") + } + got.ForwardWheel(1.5, -2.5) + if forwarded != [2]float32{1.5, -2.5} { + t.Errorf("the page forwarded %v, want the application's callback", forwarded) + } if got.Waker == nil { t.Fatal("an Invalidator must reach the page as its waker") } diff --git a/app/store_consistency_test.go b/app/store_consistency_test.go index 21882d27..7b2c7af0 100644 --- a/app/store_consistency_test.go +++ b/app/store_consistency_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/framebuild" "github.com/vivaui/viva/internal/scene" ) @@ -15,36 +16,36 @@ func storeMatchesCanvas(t *testing.T, painter *painter, painted []gfx.Color, ste t.Helper() var rects, triangles int var order []gfx.Color - for _, primitive := range painter.renderer.Rectangles() { + for _, primitive := range painter.frame.Rectangles() { var color gfx.Color if primitive.Kind == scene.KindTriangle { - if triangles >= len(painter.clippedPaths) { - t.Fatalf("step %d: the store holds more triangles than the canvas painted (%d)", step, len(painter.clippedPaths)) + if triangles >= len(painter.frame.ClippedTriangles()) { + t.Fatalf("step %d: the store holds more triangles than the canvas painted (%d)", step, len(painter.frame.ClippedTriangles())) } - want := sceneTriangle(painter.clippedPaths[triangles]) + want := framebuild.SceneTriangle(painter.frame.ClippedTriangles()[triangles]) if primitive.Points != want.Points || primitive.Color != want.Color { t.Fatalf("step %d: stored triangle %d = %+v, canvas painted %+v", step, triangles, primitive.Points, want.Points) } triangles++ - color = painter.clippedPaths[triangles-1].Color + color = painter.frame.ClippedTriangles()[triangles-1].Color } else { - if rects >= len(painter.clipped) { - t.Fatalf("step %d: the store holds more rectangles than the canvas painted (%d)", step, len(painter.clipped)) + if rects >= len(painter.frame.ClippedRectangles()) { + t.Fatalf("step %d: the store holds more rectangles than the canvas painted (%d)", step, len(painter.frame.ClippedRectangles())) } - want := sceneRectangle(painter.clipped[rects]) + want := framebuild.SceneRectangle(painter.frame.ClippedRectangles()[rects]) if primitive.Bounds != want.Bounds || primitive.Color != want.Color || primitive.Radius != want.Radius { t.Fatalf("step %d: stored rectangle %d = %+v, canvas painted %+v", step, rects, primitive.Bounds, want.Bounds) } rects++ - color = painter.clipped[rects-1].Color + color = painter.frame.ClippedRectangles()[rects-1].Color } if len(order) == 0 || order[len(order)-1] != color { order = append(order, color) } } - if rects != len(painter.clipped) || triangles != len(painter.clippedPaths) { + if rects != len(painter.frame.ClippedRectangles()) || triangles != len(painter.frame.ClippedTriangles()) { t.Fatalf("step %d: store has %d rectangles and %d triangles, canvas painted %d and %d", - step, rects, triangles, len(painter.clipped), len(painter.clippedPaths)) + step, rects, triangles, len(painter.frame.ClippedRectangles()), len(painter.frame.ClippedTriangles())) } // Every shape was painted in a color of its own, so the colors in store // order, one per run, are the shapes in store order. @@ -166,22 +167,22 @@ func TestInsertingAShapeMidPageTouchesOnlyThatShape(t *testing.T) { } } painter := newTestPainter(t, &canvas, config) - shapes := len(painter.order) + shapes := painter.frame.OrderLen() for _, want := range []bool{true, false, true} { highlighted = want if _, err := painter.resize(size(800, 600)); err != nil { t.Fatal(err) } - if len(painter.changes) != 1 { - t.Fatalf("highlighted=%v: %d scene changes for one shape among %d", want, len(painter.changes), shapes) + if len(painter.frame.Changes()) != 1 { + t.Fatalf("highlighted=%v: %d scene changes for one shape among %d", want, len(painter.frame.Changes()), shapes) } total := shapes if highlighted { total++ } - if len(painter.renderer.Rectangles()) != total { - t.Fatalf("highlighted=%v: renderer holds %d shapes, want %d", highlighted, len(painter.renderer.Rectangles()), total) + if len(painter.frame.Rectangles()) != total { + t.Fatalf("highlighted=%v: renderer holds %d shapes, want %d", highlighted, len(painter.frame.Rectangles()), total) } } } diff --git a/base/accessors.go b/base/accessors.go index 873c60ca..9a3c93a4 100644 --- a/base/accessors.go +++ b/base/accessors.go @@ -263,6 +263,10 @@ func (x *Extra) GetHit() gfx.HitOptions { return x.hit } // GetHitOut reads the hitOut of Extra for the styled painting layer. func (x *Extra) GetHitOut() [4]float32 { return x.hitOut } +// GetHitExact reads whether a styled control targets its laid-out rectangle for +// the styled painting layer. +func (x *Extra) GetHitExact() bool { return x.hitExact } + // GetIcon reads the icon of Extra for the styled painting layer. func (x *Extra) GetIcon() gfx.Icon { return x.icon } @@ -757,9 +761,6 @@ func (x *Page) GetHeld() [2]armedButton { return x.held } // GetHoverArea reads the hoverArea of Page for the styled painting layer. func (x *Page) GetHoverArea() gfx.ID { return x.hoverArea } -// GetIcons reads the icons of Page for the styled painting layer. -func (x *Page) GetIcons() []gfx.Icon { return x.icons } - // GetIntKeys reads the intKeys of Page for the styled painting layer. func (x *Page) GetIntKeys() map[intKey]keyEntry { return x.intKeys } @@ -1210,6 +1211,9 @@ func (x *TableState) GetSortColumn() int32 { return x.sortColumn } // GetLabels reads the labels of TabsDecl for the styled painting layer. func (x *TabsDecl) GetLabels() []string { return x.labels } +// GetIcon reads the icon function of TabsDecl for the styled painting layer. +func (x *TabsDecl) GetIcon() func(index int) gfx.Icon { return x.icon } + // GetLine reads the line of TabsDecl for the styled painting layer. func (x *TabsDecl) GetLine() bool { return x.line } @@ -1456,6 +1460,14 @@ func (x *drawerState) GetLayer() uint16 { return x.layer } // GetSpec reads the spec of drawerState for the styled painting layer. func (x *drawerState) GetSpec() DrawerDeclaration { return x.spec } +// GetVerticalValue reads the accessible value of a scroll area's vertical bar for +// the styled painting layer. +func (x *ScrollState) GetVerticalValue() string { return x.verticalValue } + +// GetHorizontalValue reads the accessible value of a scroll area's horizontal bar +// for the styled painting layer. +func (x *ScrollState) GetHorizontalValue() string { return x.horizontalValue } + // GetViewport reads the area the drawer covers, the frame less its spec's Inset. func (x *drawerState) GetViewport() Rect { return x.viewport } diff --git a/base/bases.go b/base/bases.go index b4da6923..ba4b7ec1 100644 --- a/base/bases.go +++ b/base/bases.go @@ -88,6 +88,18 @@ func (f *Frame) ComboboxBase(ID gfx.ID, Label, Value string, open bool) Box { return b.HitWith(ID, Label, gfx.HitOptions{Role: gfx.RoleCombobox, Value: Value, Expanded: open, Expandable: true}) } +// DisclosureBase adds a disclosure header without a look: a row that reports Clicked and, +// to assistive technology, is a button that is expanded or not. The caller paints the +// trigger and owns the content under it; DisclosureBase itself adds no chevron, surface +// or content. +func (f *Frame) DisclosureBase(ID gfx.ID, Label string, open bool) Box { + b := f.Row().Center() + if open { + f.Nodes[b.i].Flags |= flagOpen + } + return b.HitWith(ID, Label, gfx.HitOptions{Role: gfx.RoleButton, Expanded: open, Expandable: true}) +} + // SwitchBase adds a switch without a look: the size of the shadcn track, that reports // Clicked and is a switch in the given state to assistive technology, with the pointer // region reaching beyond the track as the shadcn control's does. The track and the thumb diff --git a/base/box.go b/base/box.go index 71e4bd62..4329ea81 100644 --- a/base/box.go +++ b/base/box.go @@ -509,6 +509,17 @@ func (b Box) HitOutset(top, right, bottom, left float32) Box { return b } +// HitExact makes a styled control's pointer target its laid-out rectangle +// instead of the enlarged desktop target its component paints: a Checkbox in a +// 22x24 slot is clicked across the whole slot, not a 40x32 region around it. The +// painted geometry is unchanged, and it has no effect on controls whose target +// is already their rectangle. +func (b Box) HitExact() Box { + b.N() + b.f.Extra(b.i).hitExact = true + return b +} + // Chosen reports which item this paint is delivering a click on: the option of a // Segmented control, or the page item of a Pagination. It is false in every other // paint, like Clicked for the whole control: diff --git a/base/color.go b/base/color.go index 82188e11..b77f9399 100644 --- a/base/color.go +++ b/base/color.go @@ -16,7 +16,8 @@ func (s *ColorPickerState) SetHexText(value string) { // ColorSwatch adds a circular color choice, a radio button in a group of them: color is // what it shows (a transparent color is "no color", drawn as a slash), selected rings // it, and label names it for assistive technology. A click is Clicked; the application -// owns the choice. It is as wide and tall as its Size, 28 when it has none. +// owns the choice. It is as wide and tall as its Size, 28 when it has none. Disabled +// makes it dimmed and inert, as it does for the other controls. // // if ui.ColorSwatch(c.Key(name), color, m.color == color, name).Clicked() { m.color = color } func ColorSwatch(c C, Color Color, selected bool, Label string) Box { @@ -58,6 +59,7 @@ func (b Box) TabStop(on bool) Box { // closed. type ColorPickerState struct { open, restoreFocus, applied bool + showAlpha bool draft ColorPickerValue hexEditor text.Editor hex Field @@ -72,6 +74,10 @@ type ColorPickerState struct { // Open reports whether the picker's panel is open. func (s *ColorPickerState) Open() bool { return s.open } +// ShowsAlpha reports whether the picker offers an opacity bar and reads and writes +// #RRGGBBAA, as ShowAlpha set it. +func (s *ColorPickerState) ShowsAlpha() bool { return s.showAlpha } + // Draft is the color being staged while the panel is open, which follows the plane, the // hue bar and the hex field as they change and is not yet the application's: a preview // that tracks the drag reads it. It reports false when the panel is closed. @@ -104,7 +110,8 @@ type ColorPickerLook struct { // color is staged while the panel is open and written to *color on Apply (Enter in the // hex field); Cancel, Escape and a press outside leave it as it was. A transparent // *color is no color, which Clear sets. The box is the 32 pixel trigger; Applied -// reports a change. RoundTrigger, TriggerIcon, NoColor and PanelLabels change how it looks. +// reports a change. RoundTrigger, TriggerIcon, NoColor and PanelLabels change how it +// looks, and ShowAlpha adds an opacity bar and #RRGGBBAA input. // // ui.ColorPicker(c, &m.picker, &m.accent, "Accent") // if m.picker.Applied() { m.save() } @@ -178,8 +185,8 @@ func (b Box) NoColor(empty bool) Box { } // PanelLabels overrides the words of a ColorPicker's panel: its title, the plane, the hue -// bar, the hex field and the buttons. A label left empty keeps its default. Other -// elements ignore it. +// bar, the alpha bar, the hex field and the buttons. A label left empty keeps its +// default. Other elements ignore it. func (b Box) PanelLabels(labels ColorPickerLabels) Box { if extra := b.pickerExtra(); extra != nil { extra.pickerLook.labels = labels @@ -187,6 +194,16 @@ func (b Box) PanelLabels(labels ColorPickerLabels) Box { return b } +// ShowAlpha makes a ColorPicker offer an opacity bar and read and write #RRGGBBAA, +// so the chosen color keeps its alpha; without it a picked color is opaque. Other +// elements ignore it. +func (b Box) ShowAlpha(show bool) Box { + if extra := b.pickerExtra(); extra != nil { + extra.picker.showAlpha = show + } + return b +} + func (b Box) pickerExtra() *Extra { n := b.N() if n.Ext == 0 || b.f.Exts[n.Ext].picker == nil { @@ -221,7 +238,7 @@ func (s *ColorPickerState) ApplyDraft() { func (s *ColorPickerState) SetDraftValue(v ColorPickerValue) { s.draft = v var buf [9]byte - value := string(v.AppendHex(buf[:0], false)) + value := string(v.AppendHex(buf[:0], s.showAlpha)) if s.hexEditor.String() != value { s.hexEditor = text.Editor{} s.hexEditor.Insert(value) @@ -280,7 +297,7 @@ func (s *ColorPickerState) syncHex() { return } s.seen = value - color, valid := ParseColorHex(value, false) + color, valid := ParseColorHex(value, s.showAlpha) s.invalid = !valid if valid { s.draft = s.draft.WithColor(color) diff --git a/base/combobox.go b/base/combobox.go index 7e9622ad..5b10335f 100644 --- a/base/combobox.go +++ b/base/combobox.go @@ -5,6 +5,7 @@ import ( "unsafe" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/text" "github.com/vivaui/viva/window" ) @@ -21,7 +22,8 @@ import ( // Clearable adds a button that clears the choice, Empty says what the list shows // when nothing matches, and Creatable offers what was typed as a new choice, which // Created reports for the application to add. Describe gives choices a detail, text to -// search by and a disabled state. +// search by and a disabled state. InitiallyOpen and InitialQuery start the list open +// with a search, once; Invalid marks the field as one whose value is wrong. // // Not inside a Memo. func Combobox[T comparable](c C, Value *T, choices []T, nameOf func(T) string, Label string) Box { @@ -120,6 +122,7 @@ func combobox[T comparable](c C, Value *T, choices []T, nameOf func(T) string, L // Clearable, Empty and Creatable say these again for this paint, after the clicks // were taken with what the last paint showed. state.clearable, state.empty, state.list.AllowCreate, state.createPrefix = false, "", false, "" + state.Invalid = false state.layer = f.WidgetLayer() + 1 // The field declares its own hits as it paints; the element only places it, as // wide as its container, a control tall. @@ -155,10 +158,15 @@ type ComboState struct { Node int32 gen uint32 Label, placeholder, empty string - clearLabel, clearLabelOf string // "Clear