diff --git a/README.md b/README.md index ce30626ce..e215009cd 100644 --- a/README.md +++ b/README.md @@ -11,9 +11,10 @@ Viva 交流群

-Viva is a Go-first, GPU-native desktop framework. Applications draw through -the platform's own window and GPU APIs — Cocoa and Metal, Win32 and Direct3D 11, -XCB and Vulkan — with no WebView, no browser engine, and no bundled runtime. It +Viva is a Go-first desktop framework. Applications draw through the platform's +own window and GPU APIs — Cocoa and Metal, Win32 and Direct3D 11, XCB and +Vulkan — and, on a machine with no graphics device, with Viva's own CPU +rasterizer. There is no WebView, no browser engine, and no bundled runtime. It is aimed at small binaries, low idle resource usage, and direct access to native platform capabilities. An application that needs web content can host the system's own web view beside Viva's drawing (WebKitGTK, WKWebView, WebView2): it @@ -50,7 +51,8 @@ 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, +Viva reaches Cocoa and Metal through cgo (a Mac with no Metal device, like an +Intel virtual machine, draws on the CPU); on Linux, X11 with the system XCB, Pango and Cairo libraries (the opt-in GTK 3 shell, `-tags vivagtk`, is a native Wayland client and needs the system's GTK 3), and a Vulkan loader and driver for GPU acceleration (a machine without them draws on the CPU); on Windows, Win32 with Direct3D 11 @@ -170,6 +172,9 @@ WebView and no bundled rendering runtime. - A separate retained semantic accessibility tree. - Direct CoreText shaping, system-font fallback, GPU-composited text textures, and a bounded measurement cache. +- A CPU renderer for a Mac with no Metal device (an Intel virtual machine): the + window and headless screenshots are drawn by the same retained scene and + CoreText rasterizer, and `VIVA_SOFTWARE_RENDERING=1` asks for it on any Mac. - Experimental Windows shell with Win32 events, D3D11 retained rendering, embedded DXBC shaders, DirectWrite measurement, and bounded GDI label textures; native builds do not load a shader compiler. diff --git a/README.zh-CN.md b/README.zh-CN.md index 1ec501f76..e0e0b1e0c 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -11,7 +11,7 @@ Viva 交流群

-Viva 是一个 Go 优先、GPU 原生的桌面框架。应用通过操作系统自己的窗口和 GPU API 绘制——Cocoa 与 Metal、Win32 与 Direct3D 11、XCB 与 Vulkan——不使用 WebView,不捆绑浏览器引擎,也不捆绑运行时。它追求小的二进制产物、低的空闲资源占用,以及对原生平台能力的直接访问。需要展示网页内容的应用可以在 Viva 的绘制旁边承载系统自带的网页视图(WebKitGTK、WKWebView、WebView2):它是可选的,第一个页面打开时才加载,不捆绑任何东西。 +Viva 是一个 Go 优先的桌面框架。应用通过操作系统自己的窗口和 GPU API 绘制——Cocoa 与 Metal、Win32 与 Direct3D 11、XCB 与 Vulkan——在没有图形设备的机器上,则用 Viva 自带的 CPU 光栅器绘制。它不使用 WebView,不捆绑浏览器引擎,也不捆绑运行时。它追求小的二进制产物、低的空闲资源占用,以及对原生平台能力的直接访问。需要展示网页内容的应用可以在 Viva 的绘制旁边承载系统自带的网页视图(WebKitGTK、WKWebView、WebView2):它是可选的,第一个页面打开时才加载,不捆绑任何东西。 下面的状态列表是今天实际能跑的东西。 @@ -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、Pango 和 Cairo 库的 X11(可选的 GTK 3 外壳用 `-tags vivagtk` 构建,是原生 Wayland 客户端,需要系统的 GTK 3),Vulkan 加载库和驱动用于 GPU 加速,缺失时窗口用 CPU 渲染;Windows 上需要 Win32、Direct3D 11 和 DirectWrite。Viva 在运行时加载系统库,自身不捆绑任何一个。 +环境要求:Go 1.26 或更新版本(缺失时 viva 会自己下载)。macOS 上需要 Xcode 命令行工具,因为 Viva 通过 cgo 访问 Cocoa 和 Metal(没有 Metal 设备的 Mac,例如 Intel 虚拟机,用 CPU 绘制);Linux 上需要带系统 XCB、Pango 和 Cairo 库的 X11(可选的 GTK 3 外壳用 `-tags vivagtk` 构建,是原生 Wayland 客户端,需要系统的 GTK 3),Vulkan 加载库和驱动用于 GPU 加速,缺失时窗口用 CPU 渲染;Windows 上需要 Win32、Direct3D 11 和 DirectWrite。Viva 在运行时加载系统库,自身不捆绑任何一个。 当前版本是 `v0.6.9`;要固定版本就写明(`@v0.6.9`)。指南、API 参考和带实时预览的组件目录在 [`website/`](website/) 里,本地用 `npm run dev` 运行;也已经发布在 [vivaui.dev](https://vivaui.dev/zh/)。 @@ -48,6 +48,7 @@ Viva 面向 macOS、Windows 和 Linux 上的原生桌面应用,同时把 WebAs - macOS 原生窗口与事件循环。 - 直接 Metal 清屏与呈现。 +- 没有 Metal 设备的 Mac(例如 Intel 虚拟机)由 CPU 渲染器绘制窗口和无头截图:与 GPU 路径共用同一套保留场景,文字由 CoreText 给出;`VIVA_SOFTWARE_RENDERING=1` 可在任何 Mac 上强制使用它。 - 扁平的分代保留式场景,节点标识稳定。 - 合并后的 O(1) 局部矩形更新,热路径零分配。 - 预编译 Metal 着色器与实例化矩形渲染。 diff --git a/app/accessibility.go b/app/accessibility.go index 80e5ecb36..e7b565406 100644 --- a/app/accessibility.go +++ b/app/accessibility.go @@ -5,6 +5,7 @@ import ( "unicode/utf8" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/frametrace" "github.com/vivaui/viva/internal/input" "github.com/vivaui/viva/internal/interaction" "github.com/vivaui/viva/internal/platform" @@ -21,15 +22,19 @@ func (painter *painter) accessibilityHandler(config *Config) platform.Accessibil } // accessibleHit finds the control a request names. Labels share their control's -// ID and are not controls, and a region declared by Container has no ID. +// ID and are not controls, a region declared by Container has no ID, and a +// control behind an open modal is not there for assistive technology. func (painter *painter) accessibleHit(id gfx.ID) (gfx.Hit, bool) { - return interaction.Control(painter.canvas.Hits(), id) + return interaction.Control(painter.canvas.Hits(), painter.canvas.TrappedFocusScope(), id) } // accessibilityRequest carries out one request the way the keyboard or the // mouse would, through the same paths, so a control cannot tell assistive // technology from a person. func (painter *painter) accessibilityRequest(request platform.AccessibilityRequest, present func(platform.Frame) error) (bool, error) { + if painter.trace != nil { + painter.trace.Event(frametrace.Accessibility, "") + } hit, ok := painter.accessibleHit(request.Node) if !ok || (hit.Disabled && !(request.Action == platform.AccessibilityFocus && hit.FocusableDisabled)) { return false, nil @@ -154,7 +159,7 @@ func (painter *painter) editText(hit gfx.Hit, request platform.AccessibilityRequ } func (painter *painter) presentRepaint(present func(platform.Frame) error) error { - frame, err := painter.repaint() + frame, err := painter.repaint(frametrace.Accessibility) if err != nil { return err } diff --git a/app/accessibility_test.go b/app/accessibility_test.go index 421128af3..699fa3d45 100644 --- a/app/accessibility_test.go +++ b/app/accessibility_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/frametrace" "github.com/vivaui/viva/internal/platform" "github.com/vivaui/viva/text" ) @@ -16,6 +17,35 @@ func (p *presented) present(frame platform.Frame) error { return nil } +func TestTerminalPublishesSelectedTextAndItsChangingBounds(t *testing.T) { + var canvas gfx.Canvas + selection := &gfx.TextSelection{Text: "界a", Bounds: []gfx.Rect{{X: 8, Y: 12, Width: 24, Height: 16}}} + secure := false + config := Config{Width: 200, Height: 100} + config.Paint = func(canvas *gfx.Canvas, size gfx.Size) { + canvas.HitWithOptions(gfx.Item(1), gfx.Rect{Width: size.Width, Height: size.Height}, "Terminal", + gfx.HitOptions{Role: gfx.RoleTerminal, Autofocus: true, Secure: secure, TextSelection: selection}) + } + p := newTestPainter(t, &canvas, config) + first := p.accessibility[0] + if first.Value != "界a" || !first.ReadOnly || first.TextSelection != selection || + first.Selection != (platform.AccessibilitySelection{End: 2, Valid: true}) { + t.Fatalf("selected terminal text = %+v", first) + } + selection = &gfx.TextSelection{Text: "界a", Bounds: []gfx.Rect{{X: 8, Y: 44, Width: 24, Height: 16}}} + frame, err := p.repaint(frametrace.Invalidate) + if err != nil || len(frame.Accessibility) == 0 || frame.Accessibility[0].TextSelection != selection || + platform.DiffAccessibility(first, frame.Accessibility[0])&platform.ChangedSelection == 0 { + t.Fatalf("moving the selection to the same word on another line did not publish it: %v, %v", frame.Accessibility, err) + } + secure = true + frame, err = p.repaint(frametrace.Invalidate) + if err != nil || len(frame.Accessibility) == 0 || frame.Accessibility[0].TextSelection != nil || + frame.Accessibility[0].Value != "" || frame.Accessibility[0].Selection.Valid { + t.Fatalf("secure terminal exposed a selection: %v, %v", frame.Accessibility, err) + } +} + func TestAccessibilityNodesCarryWhatAssistiveTechnologyNeeds(t *testing.T) { var canvas gfx.Canvas config := Config{Title: "a11y", Width: 200, Height: 120} @@ -254,7 +284,7 @@ func TestSyncSemanticsUpdatesZeroIDContainerOnIncrementalPaint(t *testing.T) { width = 904 role = gfx.RoleGroup label = "Article A" - if err := driver.redraw(); err != nil { + if err := driver.redraw(frametrace.Invalidate); err != nil { t.Fatal(err) } nodes := driver.Accessibility() diff --git a/app/accessnodes.go b/app/accessnodes.go index eb77c3e37..74c583a42 100644 --- a/app/accessnodes.go +++ b/app/accessnodes.go @@ -2,6 +2,7 @@ package app import ( "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/platform" "github.com/vivaui/viva/internal/semantic" ) @@ -39,6 +40,10 @@ type AccessNode struct { // Expandable marks a control that opens and closes something, whatever its // state now. Expandable bool + // MultiSelectable marks a list whose items can be chosen several at once. + MultiSelectable bool + // Sort is how a column header orders the rows of its table. + Sort gfx.SortDirection // Level is a heading's level or a tree item's depth; zero when not stated. Level uint8 @@ -81,13 +86,98 @@ func (driver *Driver) Accessibility() []AccessNode { Selected: node.Selected, Expanded: node.Expanded, Multiline: node.Multiline, 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, + Live: node.Live, Range: node.Range, Sort: node.Sort, MultiSelectable: node.MultiSelectable, Selection: AccessSelection{Start: node.Selection.Start, End: node.Selection.End, Valid: node.Selection.Valid}, } } return out } +// AccessAction is something assistive technology asks a node to do: the +// actions every platform adapter (UI Automation patterns, AT-SPI actions and +// values, NSAccessibility actions) turns its own requests into. +type AccessAction uint8 + +const ( + // AccessPress is the node's default action: click a button or a link, + // toggle a checkbox or a switch, choose a radio, a tab, an option or a menu + // item, open or close a disclosure; on a text field it places the caret. + AccessPress AccessAction = iota + 1 + // AccessFocus gives the node the keyboard. + AccessFocus + // AccessIncrement and AccessDecrement move a slider by one step. + AccessIncrement + AccessDecrement + // AccessSetNumber moves a slider to AccessRequest.Number. + AccessSetNumber + // AccessSetText replaces the text of a text field with AccessRequest.Text. + AccessSetText + // AccessSetSelection selects the span AccessRequest.Start..End (code + // points) of a text field's text, a caret when they are equal. + AccessSetSelection +) + +// AccessRequest is one request from assistive technology to the node Node +// names (AccessNode.ID). +type AccessRequest struct { + Node gfx.ID + Action AccessAction + // Number is the value of AccessSetNumber. + Number float64 + // Text is the value of AccessSetText. + Text string + // Start and End are the span of AccessSetSelection, in code points. + Start, End int32 +} + +// platformAction is the request's action as the platform adapters deliver it. +func (action AccessAction) platformAction() (platform.AccessibilityAction, bool) { + switch action { + case AccessPress: + return platform.AccessibilityPress, true + case AccessFocus: + return platform.AccessibilityFocus, true + case AccessIncrement: + return platform.AccessibilityIncrement, true + case AccessDecrement: + return platform.AccessibilityDecrement, true + case AccessSetNumber: + return platform.AccessibilitySetNumber, true + case AccessSetText: + return platform.AccessibilitySetText, true + case AccessSetSelection: + return platform.AccessibilitySetSelection, true + } + return 0, false +} + +// PerformAccess carries out request as a screen reader or another assistive +// technology would: it is handed to the same handler a window's platform +// adapter calls, so a modal that hides the node, a disabled control, a +// read-only or secure field and a role that does not take the action refuse it +// as they do on every platform. handled is false when the node is gone or +// refused; err is a failure of the repaint it caused. Background work posted +// before it is applied first, as for any other input. +func (driver *Driver) PerformAccess(request AccessRequest) (handled bool, err error) { + if err := driver.Pump(); err != nil { + return false, err + } + action, ok := request.Action.platformAction() + if !ok { + return false, nil + } + handler := driver.painter.accessibilityHandler(&driver.config) + if handler == nil { + return false, nil + } + // A window hands each repaint to the screen; the driver keeps only the + // painter's state, as it does for a key or a click. + return handler(platform.AccessibilityRequest{ + Node: request.Node, Action: action, Number: request.Number, + Text: request.Text, Start: request.Start, End: request.End, + }, func(platform.Frame) error { return nil }) +} + // accessRole maps the semantic role the platform adapters receive back to the // gfx.Role the application declared. Roles that have no gfx counterpart (a // text, an image, the application itself) are zero. @@ -135,6 +225,8 @@ func accessRole(role semantic.Role) gfx.Role { return gfx.RoleSeparator case semantic.RoleProgress: return gfx.RoleProgressBar + case semantic.RoleColumnHeader: + return gfx.RoleColumnHeader } return 0 } diff --git a/app/app.go b/app/app.go index 1e363c2b4..7e4fecf26 100644 --- a/app/app.go +++ b/app/app.go @@ -115,6 +115,12 @@ type Config struct { // Without one, a WindowPanel is centered on the screen. Anchor StatusAnchor ClearColor Color + // D3D11LowMemoryUploads uses a reusable upload buffer for rectangles and + // maps drawing constants and mutable label textures. This can reduce the + // private working set on some Windows graphics drivers. The default uses + // UpdateSubresource. Windows reads this option when the window opens. + // Other platforms ignore it. + D3D11LowMemoryUploads bool // Transparent composites the window over the desktop: the part of the canvas // left at ClearColor's alpha shows what is behind the window. It makes a // ClearColor of zero mean fully transparent instead of the default fill, and diff --git a/app/application.go b/app/application.go index 024bea73f..159801ccd 100644 --- a/app/application.go +++ b/app/application.go @@ -117,6 +117,9 @@ type Window struct { control WindowControl closed atomic.Bool hidden atomic.Bool + // active mirrors what the platform last reported through OnActivate and + // OnDeactivate. A hidden or minimized window is not active. + active atomic.Bool // onShow is Config.OnShow, run when Show brings back a hidden window. onShow func() // minimized mirrors what the platform last reported through OnMinimize. @@ -159,6 +162,7 @@ func (window *Window) Hide() { if window == nil || window.closed.Load() || window.hidden.Swap(true) { return } + window.active.Store(false) window.control.Hide() } @@ -214,6 +218,40 @@ func (window *Window) Maximized() bool { return window != nil && window.maximized.Load() } +// attentionControl is what a window control offers when its platform can ask +// the desktop to draw the user's attention to the window. +type attentionControl interface { + RequestAttention() error +} + +// RequestAttention asks the desktop to draw the user's attention to the window +// when it is in the background: the Dock tile bounces on macOS, the taskbar +// button flashes on Windows, and the taskbar entry asks for attention on Linux. +// It is meant for something that waits on the user, such as a confirmation, and +// does nothing for the window that already has the user's attention. The call +// may come from any goroutine. +// +// macOS asks for the application, not for one window: while another window of +// the application is frontmost the call returns nil and nothing is shown. A +// window that has not yet received its first activation counts as being in the +// background. +// +// An error wrapping ErrUnsupported means this platform cannot ask. A closed +// window reports that it is closed. +func (window *Window) RequestAttention() error { + if window == nil || window.closed.Load() { + return fmt.Errorf("app: window is closed") + } + if window.active.Load() && !window.minimized.Load() { + return nil + } + control, ok := window.control.(attentionControl) + if !ok { + return fmt.Errorf("%w: window attention", ErrUnsupported) + } + return control.RequestAttention() +} + // shortcutCapturer is what a window control offers when its platform can take the system's // shortcuts for the window. type shortcutCapturer interface { @@ -289,17 +327,29 @@ func (application *Application) OpenWindow(config Config, canvas *gfx.Canvas) (* } onActivate := config.OnActivate config.OnActivate = func() { + window.active.Store(true) application.setActive(window) if onActivate != nil { onActivate() } } + onDeactivate := config.OnDeactivate + config.OnDeactivate = func() gfx.EventResult { + window.active.Store(false) + if onDeactivate != nil { + return onDeactivate() + } + return gfx.EventResult{} + } // The runtime tracks the minimize state for every window, so Window.Minimized // answers even when the application did not ask for OnMinimize. There is no // minimize event during OpenWindow, so the zero value is the initial state. onMinimize := config.OnMinimize config.OnMinimize = func(minimized bool) { window.minimized.Store(minimized) + if minimized { + window.active.Store(false) + } if onMinimize != nil { onMinimize(minimized) } diff --git a/app/application_native.go b/app/application_native.go index ee285d7a3..ce432868a 100644 --- a/app/application_native.go +++ b/app/application_native.go @@ -7,6 +7,7 @@ import ( "runtime" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/frametrace" "github.com/vivaui/viva/internal/platform" "github.com/vivaui/viva/keymap" ) @@ -107,6 +108,7 @@ var _ shortcutCapturer = resultWindow{} var _ titleControl = resultWindow{} var _ watermarkControl = resultWindow{} var _ windowIconControl = resultWindow{} +var _ attentionControl = resultWindow{} var _ platform.WindowMover = resultWindow{} // What OpenWindow looks for in a host's window control. @@ -169,6 +171,14 @@ func (window resultWindow) SetIcon(icon WindowIcon) error { return control.SetIcon(icon.platform()) } +func (window resultWindow) RequestAttention() error { + control, ok := window.WindowControl.(attentionControl) + if !ok { + return fmt.Errorf("%w: window attention", ErrUnsupported) + } + return control.RequestAttention() +} + func (window resultWindow) SetAlwaysOnTop(enabled bool) error { control, ok := window.WindowControl.(alwaysOnTopControl) if !ok { @@ -209,7 +219,7 @@ func (window resultWindow) applyResult(result gfx.EventResult) bool { func (window resultWindow) requestRedraw() { if window.waker != nil { - window.waker.Wake() + window.waker.WakeFor(frametrace.Menu) } } diff --git a/app/application_test.go b/app/application_test.go index 7461ad1ff..efee0808b 100644 --- a/app/application_test.go +++ b/app/application_test.go @@ -32,6 +32,7 @@ type fakeWindow struct { config Config closed func() hides, shows int + attentions int done bool // focused is the control that holds the keyboard, which a menu shortcut // aims at before the entry's own action. @@ -51,6 +52,8 @@ func (window *fakeWindow) Close() { func (window *fakeWindow) Hide() { window.hides++ } func (window *fakeWindow) Show() { window.shows++ } +func (window *fakeWindow) RequestAttention() error { window.attentions++; return nil } + func (window *fakeWindow) applyResult(result gfx.EventResult) bool { window.applied = append(window.applied, result) return !result.Focus.IsZero() @@ -215,6 +218,57 @@ func TestWindowTracksTheMinimizeThePlatformReports(t *testing.T) { } } +func TestRequestAttentionSkipsTheActiveWindow(t *testing.T) { + host := &fakeHost{} + useHost(t, host) + var window *Window + if err := RunApplication(func(application *Application) error { + var err error + window, err = application.OpenWindow(Config{Title: "main"}, nil) + return err + }); err != nil { + t.Fatal(err) + } + attention := func() int { return host.windows[0].attentions } + + if err := window.RequestAttention(); err != nil { + t.Fatal(err) + } + if attention() != 1 { + t.Fatalf("a background window asked %d times, want 1", attention()) + } + // The platform reports the window taking the user's attention through the + // config it was opened with; an active window must not flash or bounce. + host.windows[0].config.OnActivate() + if err := window.RequestAttention(); err != nil { + t.Fatal(err) + } + if attention() != 1 { + t.Fatalf("the active window asked %d times, want 1", attention()) + } + host.windows[0].config.OnDeactivate() + if err := window.RequestAttention(); err != nil { + t.Fatal(err) + } + if attention() != 2 { + t.Fatalf("the deactivated window asked %d times, want 2", attention()) + } + // A minimized window is not the one the user works in, even if the platform + // reports the focus before the minimize. + host.windows[0].config.OnActivate() + host.windows[0].config.OnMinimize(true) + if err := window.RequestAttention(); err != nil { + t.Fatal(err) + } + if attention() != 3 { + t.Fatalf("the minimized window asked %d times, want 3", attention()) + } + window.Close() + if err := window.RequestAttention(); err == nil { + t.Fatal("a closed window asked for attention") + } +} + func TestWindowFollowsPlatformMaximize(t *testing.T) { host := &fakeHost{} useHost(t, host) diff --git a/app/d3d11_uploads_windows_test.go b/app/d3d11_uploads_windows_test.go new file mode 100644 index 000000000..f6b865382 --- /dev/null +++ b/app/d3d11_uploads_windows_test.go @@ -0,0 +1,21 @@ +package app + +import ( + "runtime" + "testing" +) + +func TestPreparedWindowKeepsD3D11UploadMode(t *testing.T) { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + for _, lowMemory := range []bool{true, false} { + native, _, cleanup, err := prepareNativeWindow(Config{D3D11LowMemoryUploads: lowMemory}, nil) + if err != nil { + t.Fatal(err) + } + cleanup() + if native.D3D11LowMemoryUploads != lowMemory { + t.Errorf("native D3D11LowMemoryUploads = %t, want %t", native.D3D11LowMemoryUploads, lowMemory) + } + } +} diff --git a/app/desktop_settings_linux.go b/app/desktop_settings_linux.go index b0972d9ed..85d2cad19 100644 --- a/app/desktop_settings_linux.go +++ b/app/desktop_settings_linux.go @@ -4,6 +4,7 @@ package app import ( "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/frametrace" "github.com/vivaui/viva/internal/platform" ) @@ -20,7 +21,7 @@ func watchDesktopSettings(canvas *gfx.Canvas, waker *platform.Waker) (stop func( canvas.SetTextEngine(nativeTextEngine()) } if waker != nil { - waker.Wake() + waker.WakeFor(frametrace.Settings) } }) return func() { platform.SetDesktopObserver(nil) } diff --git a/app/driver.go b/app/driver.go index 860d3c75d..78287af85 100644 --- a/app/driver.go +++ b/app/driver.go @@ -12,6 +12,7 @@ import ( "unicode/utf8" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/frametrace" "github.com/vivaui/viva/internal/input" "github.com/vivaui/viva/internal/platform" "github.com/vivaui/viva/internal/scene" @@ -67,8 +68,11 @@ type Driver struct { now time.Duration animating bool frameDue time.Duration // virtual time the next requested frame is due - wake atomic.Bool - wakeSent chan struct{} + // frameReasons are the reasons of the frame requests the due frame answers, + // for the frame trace. + frameReasons frametrace.Reason + wake atomic.Bool + wakeSent chan struct{} // modifierKeys is the modifier keys KeyDown holds, one bit per // gfx.KeyShiftLeft..ui.KeyMetaRight. @@ -96,12 +100,12 @@ type Driver struct { clipboardGeneration uint64 system driverSystem - openFilesResponses [driverOpenFilesQueueSize]driverOpenFilesResponse + openFilesResponses [driverOpenFilesQueueSize]driverOpenPathsResponse openFilesHead int openFilesCount int lastOpenFilesRequest OpenFileOptions hasOpenFilesRequest bool - openDirectoryResponses [driverOpenDirectoryQueueSize]driverOpenDirectoryResponse + openDirectoryResponses [driverOpenDirectoryQueueSize]driverOpenPathsResponse openDirectoryHead int openDirectoryCount int lastOpenDirectoryRequest OpenDirectoryOptions @@ -170,12 +174,13 @@ func NewDriver(config Config, canvas *gfx.Canvas) (*Driver, error) { driver.painter.enableTextMenu(true) driver.painter.setCursor = func(Cursor) error { return nil } driver.painter.setCursorImage = func(*gfx.CursorImage) error { return nil } - driver.painter.scheduleFrame = func(delay time.Duration) { + driver.painter.scheduleFrame = func(delay time.Duration, reason frametrace.Reason) { due := driver.now + delay if !driver.animating || due < driver.frameDue { driver.frameDue = due } driver.animating = true + driver.frameReasons |= reason } driver.painter.scheduleIfAnimating() if err := driver.registerSystem(); err != nil { @@ -197,6 +202,9 @@ func (driver *Driver) Close() { return } driver.closed = true + if driver.painter != nil && driver.painter.trace != nil { + driver.painter.trace.Closed() + } liveDrivers.Release() if driver.appearanceOpen { leaveDriverAppearance() @@ -235,15 +243,19 @@ func (driver *Driver) Pump() error { if !driver.wake.Swap(false) { return nil } - return driver.redraw() + var reasons frametrace.Reason + if invalidator := driver.config.Invalidator; invalidator != nil { + reasons = invalidator.waker.Redrawing() + } + return driver.redraw(reasons) } -// redraw is the window's redraw handler: OnWake, then a repaint. -func (driver *Driver) redraw() error { +// redraw is the window's redraw handler: OnWake, then a repaint for reasons. +func (driver *Driver) redraw(reasons frametrace.Reason) error { if driver.config.OnWake != nil { driver.config.OnWake() } - _, err := driver.painter.repaint() + _, err := driver.painter.repaint(reasons) return err } @@ -265,7 +277,7 @@ func (driver *Driver) Paint() error { if err := driver.Pump(); err != nil { return err } - return driver.redraw() + return driver.redraw(frametrace.Invalidate) } // Advance moves virtual time forward by duration, repainting at frame cadence @@ -281,9 +293,11 @@ func (driver *Driver) Advance(duration time.Duration) error { } if driver.animating && driver.now >= driver.frameDue { driver.animating = false + reasons := driver.frameReasons + driver.frameReasons = 0 // A due frame reaches the application the way the window's timer // does: OnWake first, then the repaint. - if err := driver.redraw(); err != nil { + if err := driver.redraw(reasons); err != nil { return err } } @@ -915,14 +929,14 @@ func (driver *Driver) textKey(key gfx.Key, modifiers gfx.Modifiers) error { // presentation changed. func (driver *Driver) textEvent(event platform.TextEvent) error { previous := driver.painter.nativeText.State - next, err := driver.painter.applyTextEvent(event) + next, err := driver.painter.onTextEvent(event) if err != nil { return err } if !platform.TextInputPresentationChanged(driver.painter.nativeText.Terminal, previous, next) { return nil } - return driver.redraw() + return driver.redraw(frametrace.Text) } // Type inserts text into the focused text field, replacing its selection. diff --git a/app/driver_keys_test.go b/app/driver_keys_test.go index 350e3a059..bab8166ba 100644 --- a/app/driver_keys_test.go +++ b/app/driver_keys_test.go @@ -7,6 +7,7 @@ import ( "testing" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/frametrace" "github.com/vivaui/viva/internal/platform" ) @@ -234,7 +235,7 @@ func TestStoppingTheRequestForReleasesReleasesHeldKeys(t *testing.T) { t.Fatal(err) } probe.keys, probe.releases = nil, false - if err := driver.redraw(); err != nil { + if err := driver.redraw(frametrace.Invalidate); err != nil { t.Fatal(err) } if got := summary(probe.keys); !reflect.DeepEqual(got, []string{"left up"}) { diff --git a/app/driver_system.go b/app/driver_system.go index 575297903..b5e3ac832 100644 --- a/app/driver_system.go +++ b/app/driver_system.go @@ -60,16 +60,11 @@ type driverSaveFileResponse struct { err error } -type driverOpenFilesResponse struct { +type driverOpenPathsResponse struct { paths []string err error } -type driverOpenDirectoryResponse struct { - path string - err error -} - var activeDriverSystem atomic.Pointer[driverSystem] // A worker may finish after a driver closes, or before a tool's first driver @@ -491,13 +486,13 @@ func driverOpenFiles(options OpenFileOptions) ([]string, error, bool) { return paths, err, true } -func driverOpenDirectory(options OpenDirectoryOptions) (string, error, bool) { +func driverOpenDirectories(options OpenDirectoryOptions) ([]string, error, bool) { system := activeDriverSystem.Load() if system == nil { - return "", nil, false + return nil, nil, false } - path, err := system.driver.openDirectory(options) - return path, err, true + paths, err := system.driver.openDirectories(options) + return paths, err, true } func driverSaveFile(options SaveFileOptions) (string, error, bool) { @@ -576,7 +571,7 @@ func (driver *Driver) QueueOpenFiles(paths []string, err error) error { return fmt.Errorf("app: open-files response queue is full") } index := (driver.openFilesHead + driver.openFilesCount) % len(driver.openFilesResponses) - driver.openFilesResponses[index] = driverOpenFilesResponse{paths: append([]string(nil), paths...), err: err} + driver.openFilesResponses[index] = driverOpenPathsResponse{paths: append([]string(nil), paths...), err: err} driver.openFilesCount++ return nil } @@ -594,7 +589,7 @@ func (driver *Driver) openFiles(options OpenFileOptions) ([]string, error) { return nil, ErrNoDriverResponse } response := driver.openFilesResponses[driver.openFilesHead] - driver.openFilesResponses[driver.openFilesHead] = driverOpenFilesResponse{} + driver.openFilesResponses[driver.openFilesHead] = driverOpenPathsResponse{} driver.openFilesHead = (driver.openFilesHead + 1) % len(driver.openFilesResponses) driver.openFilesCount-- return response.paths, response.err @@ -603,14 +598,27 @@ func (driver *Driver) openFiles(options OpenFileOptions) ([]string, error) { // QueueOpenDirectory queues the result returned by the next OpenDirectory // call made while driver is active. func (driver *Driver) QueueOpenDirectory(path string, err error) error { - if err == nil && path == "" { - return fmt.Errorf("app: queued open-directory path is empty") + if path == "" { + return driver.QueueOpenDirectories(nil, err) + } + return driver.QueueOpenDirectories([]string{path}, err) +} + +// QueueOpenDirectories queues a directory picker result and copies the paths. +func (driver *Driver) QueueOpenDirectories(paths []string, err error) error { + if err == nil && len(paths) == 0 { + return fmt.Errorf("app: queued open-directory paths are empty") + } + for _, path := range paths { + if path == "" { + return fmt.Errorf("app: queued open-directory path is empty") + } } if driver.openDirectoryCount == len(driver.openDirectoryResponses) { return fmt.Errorf("app: open-directory response queue is full") } index := (driver.openDirectoryHead + driver.openDirectoryCount) % len(driver.openDirectoryResponses) - driver.openDirectoryResponses[index] = driverOpenDirectoryResponse{path: path, err: err} + driver.openDirectoryResponses[index] = driverOpenPathsResponse{paths: append([]string(nil), paths...), err: err} driver.openDirectoryCount++ return nil } @@ -621,17 +629,17 @@ func (driver *Driver) LastOpenDirectoryRequest() (OpenDirectoryOptions, bool) { return driver.lastOpenDirectoryRequest, driver.hasOpenDirectoryRequest } -func (driver *Driver) openDirectory(options OpenDirectoryOptions) (string, error) { +func (driver *Driver) openDirectories(options OpenDirectoryOptions) ([]string, error) { driver.lastOpenDirectoryRequest = options driver.hasOpenDirectoryRequest = true if driver.openDirectoryCount == 0 { - return "", ErrNoDriverResponse + return nil, ErrNoDriverResponse } response := driver.openDirectoryResponses[driver.openDirectoryHead] - driver.openDirectoryResponses[driver.openDirectoryHead] = driverOpenDirectoryResponse{} + driver.openDirectoryResponses[driver.openDirectoryHead] = driverOpenPathsResponse{} driver.openDirectoryHead = (driver.openDirectoryHead + 1) % len(driver.openDirectoryResponses) driver.openDirectoryCount-- - return response.path, response.err + return response.paths, response.err } // QueueSaveFile queues the result returned by the next SaveFile call made diff --git a/app/driver_system_test.go b/app/driver_system_test.go index 4334eead3..ee08d72fd 100644 --- a/app/driver_system_test.go +++ b/app/driver_system_test.go @@ -362,6 +362,12 @@ func TestDriverInterceptsOpenDirectory(t *testing.T) { t.Fatalf("queued OpenDirectory = %q, %v; want %q", path, err, want) } } + if err := driver.QueueOpenDirectories([]string{"/tmp/first", "/tmp/second"}, nil); err != nil { + t.Fatal(err) + } + if _, err := OpenDirectory(OpenDirectoryOptions{}); err == nil { + t.Fatal("single-directory picker accepted multiple paths") + } } func BenchmarkDriverOpenDirectory(b *testing.B) { diff --git a/app/driver_system_unsupported.go b/app/driver_system_unsupported.go index d9839a367..52675c872 100644 --- a/app/driver_system_unsupported.go +++ b/app/driver_system_unsupported.go @@ -52,8 +52,8 @@ func driverOpenFiles(OpenFileOptions) ([]string, error, bool) { return nil, nil, false } -func driverOpenDirectory(OpenDirectoryOptions) (string, error, bool) { - return "", nil, false +func driverOpenDirectories(OpenDirectoryOptions) ([]string, error, bool) { + return nil, nil, false } func driverSaveFile(SaveFileOptions) (string, error, bool) { diff --git a/app/driver_terminal_test.go b/app/driver_terminal_test.go index b5d6dbd6c..c733ec21e 100644 --- a/app/driver_terminal_test.go +++ b/app/driver_terminal_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/frametrace" "github.com/vivaui/viva/internal/platform" "github.com/vivaui/viva/text" ) @@ -72,7 +73,7 @@ func TestDriverHonorsATerminalsAltSendsEscapePolicy(t *testing.T) { } probe.altMeta = true - if err := driver.redraw(); err != nil { + if err := driver.redraw(frametrace.Invalidate); err != nil { t.Fatal(err) } if err := driver.Chord(gfx.ModifierAlt, "X"); err != nil { diff --git a/app/frame_clock_test.go b/app/frame_clock_test.go index 153fb5a39..28fe20617 100644 --- a/app/frame_clock_test.go +++ b/app/frame_clock_test.go @@ -5,6 +5,7 @@ import ( "time" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/frametrace" "github.com/vivaui/viva/internal/platform" ) @@ -19,7 +20,7 @@ func TestFrameTimerMeasuresFromTheFrameStart(t *testing.T) { frames.setInterval(20 * time.Millisecond) frames.redrawing() // the frame starts at start now = start.Add(15 * time.Millisecond) - frames.request(0) + frames.request(0, frametrace.Animation) want := start.Add(20 * time.Millisecond) if !frames.due.Equal(want) { t.Fatalf("due = %v, want the frame start + 20ms, %v", frames.due, want) @@ -38,7 +39,7 @@ func TestFrameTimerWithPresentPacedInterval(t *testing.T) { frames.now = func() time.Time { return now } frames.setInterval(0) frames.redrawing() - frames.request(0) + frames.request(0, frametrace.Animation) if frames.armed.Load() { t.Fatal("a present-paced frame asked for its successor before presenting") } @@ -62,7 +63,7 @@ func TestFrameTimerArmsOutsideAFrame(t *testing.T) { start := time.Unix(300, 0) frames.now = func() time.Time { return start } frames.setInterval(0) - frames.request(0) + frames.request(0, frametrace.Animation) if want := start.Add(minFrameInterval); !frames.due.Equal(want) { t.Fatalf("due = %v, want %v", frames.due, want) } @@ -91,8 +92,8 @@ func TestFrameTimerDelayedRequestWaitsFromThePresent(t *testing.T) { frames.now = func() time.Time { return start } frames.setInterval(0) frames.redrawing() - frames.request(125 * time.Millisecond) - frames.request(0) + frames.request(125*time.Millisecond, frametrace.Animation) + frames.request(0, frametrace.Animation) frames.presented() if want := start.Add(minFrameInterval); !frames.due.Equal(want) { t.Fatalf("due = %v, want the soonest request, %v", frames.due, want) @@ -103,7 +104,7 @@ func TestFrameTimerDelayedRequestWaitsFromThePresent(t *testing.T) { frames.now = func() time.Time { return start } frames.setInterval(0) frames.redrawing() - frames.request(125 * time.Millisecond) + frames.request(125*time.Millisecond, frametrace.Animation) frames.presented() if want := start.Add(125 * time.Millisecond); !frames.due.Equal(want) { t.Fatalf("due = %v, want the delayed request from the present, %v", frames.due, want) @@ -121,7 +122,7 @@ func TestFrameTimerWithDisplayIntervalArmsWhilePainting(t *testing.T) { frames.setInterval(20 * time.Millisecond) frames.redrawing() now = start.Add(5 * time.Millisecond) - frames.request(0) + frames.request(0, frametrace.Animation) if want := start.Add(20 * time.Millisecond); !frames.due.Equal(want) { t.Fatalf("due = %v, want the frame start + 20ms, %v", frames.due, want) } @@ -138,7 +139,7 @@ func BenchmarkFramePresentedFrame(b *testing.B) { b.ReportAllocs() for range b.N { frames.redrawing() - frames.request(0) + frames.request(0, frametrace.Animation) now = now.Add(time.Millisecond) frames.presented() frames.timer.Stop() @@ -157,7 +158,7 @@ func TestCoalescedPointerEventLeavesThePaintToTheFrameClock(t *testing.T) { painter := newTestPainter(t, &canvas, config) painter.coalesceInput = true requests := 0 - painter.scheduleFrame = func(time.Duration) { requests++ } + painter.scheduleFrame = func(time.Duration, frametrace.Reason) { requests++ } frame, err := painter.pointerEvent(platform.PointerEvent{Kind: platform.PointerMove, X: 10, Y: 10}) if err != nil { @@ -174,7 +175,7 @@ func TestCoalescedPointerEventLeavesThePaintToTheFrameClock(t *testing.T) { } // The frame clock's repaint publishes the hover. - if _, err := painter.repaint(); err != nil { + if _, err := painter.repaint(frametrace.Invalidate); err != nil { t.Fatal(err) } if got := painter.canvas.Hovered(); got != gfx.Item(1) { diff --git a/app/frame_timer.go b/app/frame_timer.go index f00e20003..200cf35e1 100644 --- a/app/frame_timer.go +++ b/app/frame_timer.go @@ -3,6 +3,8 @@ package app import ( "sync/atomic" "time" + + "github.com/vivaui/viva/internal/frametrace" ) // frameInterval is the interval the frame timer starts with, for a workspace @@ -33,6 +35,13 @@ const minFrameInterval = time.Second / 240 // next frame starts from an event loop that has read its input. type frameTimer struct { wake func() + // note, set when the window is traced, hands the reasons of a wake-up to the + // redraw it causes (platform.Waker.Note). reasons gathers the reasons of the + // requests the armed timer answers, and pendingReasons those of the request + // held until the present; both are kept only while note is set. + note func(frametrace.Reason) + reasons atomic.Uint32 + pendingReasons frametrace.Reason // interval is the display period, zero when presentation blocks. It is // written by the adapter on the window thread and read by request there. interval time.Duration @@ -84,6 +93,10 @@ func (frames *frameTimer) presented() { } delay := frames.pendingDelay frames.pending = false + if frames.note != nil { + frames.reasons.Or(uint32(frames.pendingReasons)) + frames.pendingReasons = 0 + } frames.arm(delay, frames.now()) } @@ -94,23 +107,29 @@ func (frames *frameTimer) setInterval(interval time.Duration) { frames.interval = max(interval, 0) } -// request asks for the next frame after delay. A presentation-paced window +// request asks for the next frame after delay, for reason. A presentation-paced window // holds the request until presented, so the next frame's message is posted to // an event loop that has drained; otherwise it arms the timer at once, never // sooner than one display frame, unless a wake-up is already pending. A pending // wake-up that is later than the one asked for is brought forward, so an // animation that starts while a slow tick is waiting is not held back by it. It // must be called from the window thread, which is the timer's only writer. -func (frames *frameTimer) request(delay time.Duration) { +func (frames *frameTimer) request(delay time.Duration, reason frametrace.Reason) { if frames.stopped.Load() { return } if frames.painting && frames.interval <= 0 { + if frames.note != nil { + frames.pendingReasons |= reason + } if !frames.pending || delay < frames.pendingDelay { frames.pending, frames.pendingDelay = true, max(delay, 0) } return } + if frames.note != nil { + frames.reasons.Or(uint32(reason)) + } now := frames.now() base := frames.last if base.IsZero() { @@ -135,6 +154,8 @@ func (frames *frameTimer) arm(delay time.Duration, base time.Time) { if !frames.armed.CompareAndSwap(false, true) { // Stop reports whether the timer was still waiting; if it already // fired the wake-up is on its way and the repaint it causes asks again. + // The reasons of a request that joins a wake-up already on its way + // stay behind; the redraw it causes takes them (orphans). if due.Before(frames.due) && frames.timer.Stop() { frames.due = due frames.timer.Reset(wait) @@ -150,12 +171,32 @@ func (frames *frameTimer) arm(delay time.Duration, base time.Time) { } func (frames *frameTimer) fire() { + // The reasons are taken before the timer is disarmed: a request made after + // this either finds the timer still armed, and the redraw this wake-up + // causes takes its reasons (orphans), or arms the timer again for its own. + var reasons frametrace.Reason + if frames.note != nil { + reasons = frametrace.Reason(frames.reasons.Swap(0)) + } frames.armed.Store(false) if !frames.stopped.Load() { + if frames.note != nil { + frames.note(reasons) + } frames.wake() } } +// orphans takes the reasons of requests that joined a wake-up already on its way +// while the timer is disarmed: no later wake-up will carry them, so the redraw +// running now answers them. It must run on the window thread. +func (frames *frameTimer) orphans() frametrace.Reason { + if frames.note == nil || frames.armed.Load() { + return 0 + } + return frametrace.Reason(frames.reasons.Swap(0)) +} + // stop cancels any pending wake-up. Later requests are ignored. func (frames *frameTimer) stop() { frames.stopped.Store(true) diff --git a/app/frame_trace_test.go b/app/frame_trace_test.go new file mode 100644 index 000000000..ba07958b5 --- /dev/null +++ b/app/frame_trace_test.go @@ -0,0 +1,142 @@ +package app + +import ( + "bytes" + "io" + "strings" + "testing" + "time" + + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/frametrace" +) + +// tracedDriver opens a driver on a page with one button and traces it into out. +func tracedDriver(t *testing.T, config Config) (*Driver, *bytes.Buffer) { + t.Helper() + config.Title, config.Width, config.Height = "trace", 200, 80 + config.Paint = func(canvas *gfx.Canvas, size gfx.Size) { + components.BeginButton(canvas, gfx.LightTheme(), gfx.Item(1), gfx.Rect{X: 10, Y: 10, Width: 90}).Default("Save") + } + var canvas gfx.Canvas + driver, err := NewDriver(config, &canvas) + if err != nil { + t.Fatal(err) + } + t.Cleanup(driver.Close) + out := &bytes.Buffer{} + driver.painter.trace = frametrace.NewWindow(out) + return driver, out +} + +// frameLines are the trace's frame lines. +func frameLines(out *bytes.Buffer) []string { + var lines []string + for line := range strings.Lines(out.String()) { + if strings.Contains(line, " frame ") { + lines = append(lines, line) + } + } + return lines +} + +// An idle window writes nothing: no frame, no wake, however long it is left. +func TestFrameTraceOfAnIdleWindowIsEmpty(t *testing.T) { + driver, out := tracedDriver(t, Config{}) + if err := driver.Advance(10 * time.Second); err != nil { + t.Fatal(err) + } + if out.Len() != 0 { + t.Fatalf("an idle window traced:\n%s", out) + } +} + +// A frame painted for a pointer event says so, after the event's own line. +func TestFrameTraceAttributesAFrameToTheInputThatCausedIt(t *testing.T) { + driver, out := tracedDriver(t, Config{}) + if err := driver.Move(20, 20); err != nil { + t.Fatal(err) + } + lines := frameLines(out) + if len(lines) == 0 { + t.Fatalf("hovering a button painted no traced frame:\n%s", out) + } + if !strings.Contains(lines[0], " reason=pointer ") { + t.Fatalf("the hover frame is not attributed to the pointer: %q", lines[0]) + } + event := strings.Index(out.String(), " event pointer move") + if event < 0 || event > strings.Index(out.String(), lines[0]) { + t.Fatalf("the pointer event is not traced before its frame:\n%s", out) + } +} + +// A frame an Invalidator asked for from another goroutine is attributed to it. +func TestFrameTraceAttributesAWakeToItsInvalidator(t *testing.T) { + invalidator := &Invalidator{} + driver, out := tracedDriver(t, Config{Invalidator: invalidator}) + done := make(chan struct{}) + go func() { + invalidator.Invalidate() + close(done) + }() + <-done + if err := driver.Pump(); err != nil { + t.Fatal(err) + } + lines := frameLines(out) + if len(lines) != 1 || !strings.Contains(lines[0], " reason=invalidate ") { + t.Fatalf("an invalidated frame traced as %q", lines) + } + // The page did not change, which is what makes the frame redundant. + if !strings.HasSuffix(strings.TrimSpace(lines[0]), " empty") { + t.Fatalf("an unchanged frame is not marked empty: %q", lines[0]) + } +} + +// The frame timer hands the reasons of the requests it answers to the wake-up +// it posts. +func TestFrameTimerCarriesTheReasonsOfItsRequests(t *testing.T) { + woken := make(chan frametrace.Reason, 1) + var noted frametrace.Reason + frames := newFrameTimer(func() { woken <- noted }) + defer frames.stop() + frames.note = func(reason frametrace.Reason) { noted |= reason } + frames.request(0, frametrace.Animation) + frames.request(time.Second, frametrace.Timer) + select { + case got := <-woken: + if got != frametrace.Animation|frametrace.Timer { + t.Fatalf("the wake-up carried %v, want animation and timer", got) + } + case <-time.After(5 * time.Second): + t.Fatal("the frame timer never woke") + } +} + +// BenchmarkMidFlightFrame measures a frame of a running transition with the +// trace off and on. +func BenchmarkMidFlightFrame(b *testing.B) { + for _, traced := range []bool{false, true} { + name := "off" + if traced { + name = "on" + } + b.Run(name, func(b *testing.B) { + harness := newMotionHarness(b) + if traced { + harness.painter.trace = frametrace.NewWindow(io.Discard) + } + harness.theme.Transition.Duration = 10 * time.Minute + harness.click(b) + b.ReportAllocs() + b.ResetTimer() + for b.Loop() { + harness.now += 8 * time.Millisecond + if _, err := harness.painter.repaint(frametrace.Animation); err != nil { + b.Fatal(err) + } + } + }) + } +} diff --git a/app/fullscreen_native.go b/app/fullscreen_native.go index 515a1f5b7..f39cd7354 100644 --- a/app/fullscreen_native.go +++ b/app/fullscreen_native.go @@ -2,8 +2,19 @@ package app +import "github.com/vivaui/viva/internal/frametrace" + func (painter *painter) fullscreenHandler(callback func(bool)) func(bool) { return func(fullscreen bool) { + if painter.trace != nil { + detail := "leave" + if fullscreen { + detail = "enter" + } + painter.trace.Event(frametrace.Resize, detail) + // The platform repaints a change of full screen itself. + painter.trace.Note(frametrace.Resize) + } painter.fullscreen = fullscreen if callback != nil { callback(fullscreen) diff --git a/app/hit_gate_test.go b/app/hit_gate_test.go index d5a5c91b7..8f573c4e0 100644 --- a/app/hit_gate_test.go +++ b/app/hit_gate_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/frametrace" "github.com/vivaui/viva/internal/input" "github.com/vivaui/viva/internal/platform" "github.com/vivaui/viva/text" @@ -28,7 +29,7 @@ func TestRepaintReusesRegionsAndSemanticsWhenTheHitsAreUnchanged(t *testing.T) { painter := newTestPainter(t, &canvas, config) reused := painter.reusedHits - frame, err := painter.repaint() + frame, err := painter.repaint(frametrace.Invalidate) if err != nil { t.Fatal(err) } @@ -52,7 +53,7 @@ func TestRepaintReusesRegionsButPublishesAChangedLabel(t *testing.T) { regions := append([]input.Region(nil), painter.focus.Router().Regions()...) page.label = "Save and close" - frame, err := painter.repaint() + frame, err := painter.repaint(frametrace.Invalidate) if err != nil { t.Fatal(err) } @@ -77,7 +78,7 @@ func TestRepaintPublishesABoundsChangeAfterTheGateOpens(t *testing.T) { painter := newTestPainter(t, &canvas, config) page.bounds = gfx.Rect{X: 100, Width: 80, Height: 20} - if _, err := painter.repaint(); err != nil { + if _, err := painter.repaint(frametrace.Invalidate); err != nil { t.Fatal(err) } if target, ok := painter.focus.Router().HitTest(140, 10); !ok || target != gfx.Item(1) { @@ -175,7 +176,7 @@ func TestRepaintReleasesFocusWhenThePaintAsksWithoutChangingHits(t *testing.T) { t.Fatalf("focused = %v, want the only control", painter.focus.Focused()) } release = true - if _, err := painter.repaint(); err != nil { + if _, err := painter.repaint(frametrace.Invalidate); err != nil { t.Fatal(err) } if !painter.focus.Focused().IsZero() { @@ -194,7 +195,7 @@ func TestRepaintComparesLabelsByText(t *testing.T) { painter := newTestPainter(t, &canvas, config) page.label = fresh("Clicked 3 times") - frame, err := painter.repaint() + frame, err := painter.repaint(frametrace.Invalidate) if err != nil { t.Fatal(err) } @@ -203,7 +204,7 @@ func TestRepaintComparesLabelsByText(t *testing.T) { } page.label = fresh("Clicked 4 times") - frame, err = painter.repaint() + frame, err = painter.repaint(frametrace.Invalidate) if err != nil { t.Fatal(err) } diff --git a/app/interface_font_test.go b/app/interface_font_test.go index 3d75e8bfc..1d1553e62 100644 --- a/app/interface_font_test.go +++ b/app/interface_font_test.go @@ -7,6 +7,7 @@ import ( "testing" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/frametrace" ) const interfaceFontSample = "The quick brown fox 0123" @@ -149,7 +150,7 @@ func TestAFamilyChangeSendsTheSameTextToTheRendererAgain(t *testing.T) { return painter.frame.Labels()[0].FontGeneration, painter.frame.Labels()[1].FontGeneration } before, _ := generation() - frame, err := painter.repaint() + frame, err := painter.repaint(frametrace.Invalidate) if err != nil { t.Fatal(err) } @@ -157,7 +158,7 @@ func TestAFamilyChangeSendsTheSameTextToTheRendererAgain(t *testing.T) { t.Fatal("an unchanged repaint sent its text again") } SetInterfaceFontFamily(family) - frame, err = painter.repaint() + frame, err = painter.repaint(frametrace.Invalidate) if err != nil { t.Fatal(err) } @@ -171,7 +172,7 @@ func TestAFamilyChangeSendsTheSameTextToTheRendererAgain(t *testing.T) { if fixedPitch != 0 { t.Fatalf("fixed-pitch text follows the interface font: generation %d", fixedPitch) } - if frame, err = painter.repaint(); err != nil || frame.TextLabels != nil { + if frame, err = painter.repaint(frametrace.Invalidate); err != nil || frame.TextLabels != nil { t.Fatalf("a repaint after the change sent its text again (%v)", err) } } diff --git a/app/invalidator.go b/app/invalidator.go index 390f5df95..afa06bef6 100644 --- a/app/invalidator.go +++ b/app/invalidator.go @@ -3,6 +3,7 @@ package app import ( "sync" + "github.com/vivaui/viva/internal/frametrace" "github.com/vivaui/viva/internal/platform" "github.com/vivaui/viva/window" ) @@ -34,7 +35,7 @@ var _ window.Invalidator = (*Invalidator)(nil) // Invalidate requests one repaint on the window thread. It is safe to call // from any goroutine and never blocks on the application. func (invalidator *Invalidator) Invalidate() { - invalidator.waker.Wake() + invalidator.waker.WakeFor(frametrace.Invalidate) } // postLimit bounds the updates waiting for one window. @@ -143,16 +144,31 @@ func (invalidator *Invalidator) closePosts() { // // The waker is told the redraw has begun before OnWake reads anything, which is what puts // the next wake on the frame grid. A window the gate says nobody can see runs OnWake and -// skips the repaint. -func wakeHandler(waker *platform.Waker, gate *visibilityGate, onWake func(), repaint platform.RedrawHandler) platform.RedrawHandler { +// skips the repaint. The repaint is given the reasons of the wakes it answers; a traced +// window (trace not nil) also takes those of frame requests that joined a wake already on +// its way, and reports a skipped repaint. +func wakeHandler(waker *platform.Waker, gate *visibilityGate, onWake func(), repaint func(frametrace.Reason) (platform.Frame, error), trace *wakeTrace) platform.RedrawHandler { return func() (platform.Frame, error) { - waker.Redrawing() + reasons := waker.Redrawing() + if trace != nil && trace.frames != nil { + reasons |= trace.frames.orphans() + } if onWake != nil { onWake() } if gate != nil && gate.skipPaint() { + if trace != nil { + trace.window.Skipped(reasons) + } return platform.Frame{}, nil } - return repaint() + return repaint(reasons) } } + +// wakeTrace is where the redraw of a traced window finds its frame trace and the +// frame requests whose reasons it may answer. +type wakeTrace struct { + window *frametrace.Window + frames *frameTimer +} diff --git a/app/invalidator_test.go b/app/invalidator_test.go index 3b7fbd32c..87388fc4b 100644 --- a/app/invalidator_test.go +++ b/app/invalidator_test.go @@ -5,6 +5,7 @@ import ( "sync/atomic" "testing" + "github.com/vivaui/viva/internal/frametrace" "github.com/vivaui/viva/internal/platform" ) @@ -50,11 +51,11 @@ func TestInvalidatorAcceptsConcurrentCallers(t *testing.T) { func TestWakeHandlerAppliesBackgroundResultsBeforeRepainting(t *testing.T) { var order []string - repaint := func() (platform.Frame, error) { + repaint := func(frametrace.Reason) (platform.Frame, error) { order = append(order, "repaint") return platform.Frame{}, nil } - handler := wakeHandler(&platform.Waker{}, nil, func() { order = append(order, "onwake") }, repaint) + handler := wakeHandler(&platform.Waker{}, nil, func() { order = append(order, "onwake") }, repaint, nil) if _, err := handler(); err != nil { t.Fatal(err) } @@ -63,7 +64,7 @@ func TestWakeHandlerAppliesBackgroundResultsBeforeRepainting(t *testing.T) { } order = order[:0] - if _, err := wakeHandler(&platform.Waker{}, nil, nil, repaint)(); err != nil { + if _, err := wakeHandler(&platform.Waker{}, nil, nil, repaint, nil)(); err != nil { t.Fatal(err) } if len(order) != 1 || order[0] != "repaint" { @@ -77,10 +78,10 @@ func TestAWindowNobodyCanSeeRunsOnWakeButDoesNotPaintUntilItShows(t *testing.T) waker.Bind(func() { posted++ }) gate := &visibilityGate{waker: &waker} var wakes, paints int - handler := wakeHandler(&waker, gate, func() { wakes++ }, func() (platform.Frame, error) { + handler := wakeHandler(&waker, gate, func() { wakes++ }, func(frametrace.Reason) (platform.Frame, error) { paints++ return platform.Frame{}, nil - }) + }, nil) gate.changed(false) for range 3 { diff --git a/app/label_replace_test.go b/app/label_replace_test.go index fe64ee72e..b5680381d 100644 --- a/app/label_replace_test.go +++ b/app/label_replace_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/frametrace" ) // A keystroke in a grid-shaped page re-sends every row's label; the rows that @@ -36,7 +37,7 @@ func BenchmarkPainterBorderedRowsOneChanged(b *testing.B) { values[changed] = "┌────┤ title ├────┐ padding" } changed = (changed + 1) % rows - if _, err := painter.repaint(); err != nil { + if _, err := painter.repaint(frametrace.Invalidate); err != nil { b.Fatal(err) } } diff --git a/app/labels_bench_test.go b/app/labels_bench_test.go index 11fbdef83..7a37366e2 100644 --- a/app/labels_bench_test.go +++ b/app/labels_bench_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/frametrace" ) // A labelled page used to cost O(controls*hits) in nameFromLabels. This keeps @@ -25,7 +26,7 @@ func BenchmarkPainterLabelledPage(b *testing.B) { b.ReportAllocs() b.ResetTimer() for b.Loop() { - if _, err := painter.repaint(); err != nil { + if _, err := painter.repaint(frametrace.Invalidate); err != nil { b.Fatal(err) } } @@ -59,7 +60,7 @@ func BenchmarkPainterLabelledPageChanged(b *testing.B) { } else { label = "odd" } - if _, err := painter.repaint(); err != nil { + if _, err := painter.repaint(frametrace.Invalidate); err != nil { b.Fatal(err) } } @@ -97,7 +98,7 @@ func BenchmarkPainterLabelledPageOneChanged(b *testing.B) { } else { label = "odd" } - if _, err := painter.repaint(); err != nil { + if _, err := painter.repaint(frametrace.Invalidate); err != nil { b.Fatal(err) } } diff --git a/app/labels_test.go b/app/labels_test.go index 292011ec2..13f946367 100644 --- a/app/labels_test.go +++ b/app/labels_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/frametrace" ) func accessibilityLabel(t *testing.T, painter *painter, id gfx.ID) string { @@ -113,7 +114,7 @@ func TestOneChangedLabelOnALargePageUpdatesOnlyItsControl(t *testing.T) { t.Fatalf("initial label = %q", got) } changed = "second" - if _, err := painter.repaint(); err != nil { + if _, err := painter.repaint(frametrace.Invalidate); err != nil { t.Fatal(err) } if got := accessibilityLabel(t, painter, gfx.Item(4)); got != "second" { @@ -145,7 +146,7 @@ func TestOneChangedValueOnALargePageUpdatesOnlyItsControl(t *testing.T) { t.Fatalf("initial value = %q", got) } changed = "after" - if _, err := painter.repaint(); err != nil { + if _, err := painter.repaint(frametrace.Invalidate); err != nil { t.Fatal(err) } if got := accessibilityValue(t, painter, gfx.Item(8)); got != "after" { @@ -182,7 +183,7 @@ func TestAllLabelsChangedOnALargePageUpdatesEveryControl(t *testing.T) { } painter := labelledPainter(t, paint) words = "second" - if _, err := painter.repaint(); err != nil { + if _, err := painter.repaint(frametrace.Invalidate); err != nil { t.Fatal(err) } for _, id := range []gfx.ID{gfx.Item(1), gfx.Item(64), gfx.Item(controls)} { diff --git a/app/painter.go b/app/painter.go index 4f7e16317..8de715de1 100644 --- a/app/painter.go +++ b/app/painter.go @@ -8,10 +8,12 @@ import ( "slices" "time" "unicode" + "unicode/utf8" "unsafe" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/internal/framebuild" + "github.com/vivaui/viva/internal/frametrace" "github.com/vivaui/viva/internal/input" "github.com/vivaui/viva/internal/interaction" "github.com/vivaui/viva/internal/platform" @@ -28,7 +30,9 @@ type painter struct { touch touchState // customTitlebar says the page draws the window's titlebar strip itself // (WindowCustomTitlebar), so the window buttons cover part of it. + // titlebarStrip is that strip's height (Config.TitlebarHeight). customTitlebar bool + titlebarStrip float32 paint func(canvas *gfx.Canvas, size gfx.Size) onPointer func(gfx.PointerEvent) gfx.EventResult onKey func(gfx.KeyEvent) gfx.EventResult @@ -141,7 +145,11 @@ type painter struct { scrollY float32 // scheduleFrame asks the runtime for one more frame, after at least the // delay, while a transition is in flight or the application asked for one. - scheduleFrame func(delay time.Duration) + // The reason is what the frame trace reports the frame for. + scheduleFrame func(delay time.Duration, reason frametrace.Reason) + // trace writes the window's events and frames to standard error; nil unless + // VIVA_TRACE is set, which leaves every trace call behind a nil check. + trace *frametrace.Window // noteFrameStart records that a frame is beginning, so the timer measures // its interval from the start of the paint rather than from its end. noteFrameStart func() @@ -195,8 +203,13 @@ func newPainterWithClock(canvas *gfx.Canvas, config *Config, clock func() time.D size: gfx.Size{Width: float32(config.Width), Height: float32(config.Height)}, frame: framebuild.New(canvas), accessibility: make([]platform.AccessibilityNode, 0, len(canvas.Hits())+1), + trace: frametrace.NewStderrWindow(), } painter.onTextEvent = painter.applyTextEvent + if painter.trace != nil { + painter.trace.Opened(config.Title, config.Width, config.Height) + painter.onTextEvent = painter.tracedTextEvent + } painter.clipboardText = func() string { active := painter.activeText if active == nil || active.CopyText == nil { @@ -213,8 +226,11 @@ func newPainterWithClock(canvas *gfx.Canvas, config *Config, clock func() time.D return value } painter.customTitlebar = config.WindowMode == WindowCustomTitlebar - if painter.customTitlebar && controlsDrawnByViva { - painter.controls = newWindowControls(config) + if painter.customTitlebar { + painter.titlebarStrip = (platform.Config{TitlebarHeight: config.TitlebarHeight}).TitlebarStrip() + if controlsDrawnByViva { + painter.controls = newWindowControls(config) + } } if _, err := painter.publish(); err != nil { return nil, err @@ -223,7 +239,7 @@ func newPainterWithClock(canvas *gfx.Canvas, config *Config, clock func() time.D // Repaint once with the injected measurer so the initial frame and // every later repaint agree on text widths; a pre-painted canvas from // the caller would otherwise embed estimated widths. - if _, err := painter.repaint(); err != nil { + if _, err := painter.repaint(frametrace.Open); err != nil { return nil, err } } @@ -235,12 +251,19 @@ func newPainterWithClock(canvas *gfx.Canvas, config *Config, clock func() time.D func (painter *painter) resize(size platform.Size) (platform.Frame, error) { next := gfx.Size{Width: size.Width, Height: size.Height} changed := next != painter.size + reason := frametrace.Resize + if size.Scale != painter.scale { + reason |= frametrace.Scale + } + if painter.trace != nil { + painter.trace.Resized(size.Width, size.Height, size.Scale) + } painter.size, painter.scale = next, size.Scale painter.pointerNeedsHit = painter.pointerNeedsHit || changed if changed && painter.onResize != nil { painter.onResize(next) } - return painter.repaint() + return painter.repaint(reason) } // pressAt tells a custom-titlebar window what a press at a window point does: @@ -261,6 +284,9 @@ func (painter *painter) pressAt(x, y float32) platform.PressKind { // backdrop would, and the second is the same press aimed at what the overlay // was covering, once the paint has taken it away. func (painter *painter) pointerEvent(event platform.PointerEvent) (platform.Frame, error) { + if painter.trace != nil { + painter.trace.Event(frametrace.Pointer, pointerKindNames[event.Kind]) + } if event.Device == gfx.PointerTouch && touchRuntime.event != nil { return touchRuntime.event(painter, event) } @@ -311,7 +337,7 @@ func (painter *painter) pointerInputOf(event platform.PointerEvent, handled *boo if !painter.updateHover(false, false) { return platform.Frame{}, nil } - return painter.repaintAfterInput() + return painter.repaintAfterInput(frametrace.Pointer) } beforeHovered, beforePressed := painter.pointer.Hovered(), painter.pointer.Pressed() beforeRole, beforeSurface := painter.pointer.HoveredRole(), painter.onSurface @@ -381,7 +407,16 @@ func (painter *painter) pointerInputOf(event platform.PointerEvent, handled *boo } return platform.Frame{}, nil } - return painter.repaintAfterInput() + return painter.repaintAfterInput(frametrace.Pointer) +} + +// fileDropPhaseNames are the steps of a drag of files in the frame trace. +var fileDropPhaseNames = [...]string{platform.FileDropOver: "over", platform.FileDropLeave: "leave", platform.FileDropDrop: "drop"} + +// pointerKindNames are the pointer events' names in the frame trace. +var pointerKindNames = [...]string{ + platform.PointerDown: "down", platform.PointerMove: "move", platform.PointerUp: "up", + platform.PointerExit: "exit", platform.PointerCancel: "cancel", } // pointerStep is one pass of a pointer event through hit testing, the press @@ -638,6 +673,9 @@ func (painter *painter) shortcutHandler(config *Config) platform.ShortcutHandler } func (painter *painter) shortcut(event platform.KeyEvent) (platform.Frame, bool, error) { + if painter.trace != nil { + painter.trace.Event(frametrace.Key, "shortcut") + } painter.tap.Cancel() if painter.onShortcut == nil { return platform.Frame{}, false, nil @@ -651,7 +689,7 @@ func (painter *painter) shortcut(event platform.KeyEvent) (platform.Frame, bool, if !focusChanged && !response.Repaint { return platform.Frame{}, response.Handled, nil } - frame, err := painter.repaint() + frame, err := painter.repaint(frametrace.Key) return frame, response.Handled, err } @@ -695,6 +733,13 @@ func (painter *painter) keysWanted() bool { // Releases and modifier keys exist only for a terminal that asked for them; // they never reach a handler otherwise. func (painter *painter) key(event platform.KeyEvent) (platform.Frame, error) { + if painter.trace != nil { + detail := "down" + if event.Release { + detail = "up" + } + painter.trace.Event(frametrace.Key, detail) + } if event.Release { return painter.keyRelease(event) } @@ -742,7 +787,7 @@ func (painter *painter) key(event platform.KeyEvent) (platform.Frame, error) { // An input method owns Escape while it is composing: the key cancels // the composition instead of dismissing the overlay behind the field. painter.deliverClick(painter.focus.EscapeTarget(), gfx.ClickInfo{}) - return painter.repaint() + return painter.repaint(frametrace.Key) } result := input.Result{Target: input.Target(painter.focus.Focused())} if !response.Handled { @@ -760,7 +805,7 @@ func (painter *painter) key(event platform.KeyEvent) (platform.Frame, error) { if painter.focus.Focused() == before && !activated && painter.focus.KeyboardFocus() == beforeKeyboard && !focusChanged && !response.Repaint { return platform.Frame{}, nil } - return painter.repaint() + return painter.repaint(frametrace.Key) } // afterKeyResponse applies the result of a key handler that has no focus @@ -769,7 +814,7 @@ func (painter *painter) afterKeyResponse(response gfx.EventResult) (platform.Fra if !painter.applyEventResult(response) && !response.Repaint { return platform.Frame{}, nil } - return painter.repaint() + return painter.repaint(frametrace.Key) } // keyRelease delivers the end of a key the handler saw go down, with the @@ -787,7 +832,7 @@ func (painter *painter) keyRelease(event platform.KeyEvent) (platform.Frame, err if err != nil || painted || !tapRepaint { return frame, err } - return painter.repaint() + return painter.repaint(frametrace.Key) } // releaseHeldKey is keyRelease for the key the handler saw go down. @@ -809,7 +854,7 @@ func (painter *painter) releaseHeldKey(event platform.KeyEvent) (frame platform. if !painter.applyEventResult(response) && !response.Repaint { return platform.Frame{}, false, nil } - frame, err = painter.repaint() + frame, err = painter.repaint(frametrace.Key) return frame, true, err } @@ -871,9 +916,12 @@ func (painter *painter) deactivateHandler() platform.DeactivateHandler { // meanwhile (a text caret), before the application hears of it. func (painter *painter) activateHandler(next func()) func() { return func() { + if painter.trace != nil { + painter.trace.Event(frametrace.Focus, "activate") + } painter.canvas.SetWindowActive(true) if painter.scheduleFrame != nil { - painter.scheduleFrame(0) + painter.scheduleFrame(0, frametrace.Focus) } if next != nil { next() @@ -882,6 +930,9 @@ func (painter *painter) activateHandler(next func()) func() { } func (painter *painter) deactivate() (platform.Frame, error) { + if painter.trace != nil { + painter.trace.Event(frametrace.Focus, "deactivate") + } painter.canvas.SetWindowActive(false) painter.tap.Cancel() repaint := painter.releaseKeys() @@ -897,10 +948,13 @@ func (painter *painter) deactivate() (platform.Frame, error) { if !repaint { return platform.Frame{}, nil } - return painter.repaint() + return painter.repaint(frametrace.Focus) } func (painter *painter) focusLost() (platform.Frame, error) { + if painter.trace != nil { + painter.trace.Event(frametrace.Focus, "keyboard-lost") + } painter.tap.Cancel() repaint := painter.releaseKeys() // A window manager's grab (Alt+Tab, a compositor gesture) takes the @@ -915,7 +969,7 @@ func (painter *painter) focusLost() (platform.Frame, error) { if !repaint { return platform.Frame{}, nil } - return painter.repaint() + return painter.repaint(frametrace.Focus) } // noteKeyboardTarget records, after a paint, whether the held keys still have a @@ -933,6 +987,9 @@ func (painter *painter) fileDrop(event platform.FileDropEvent) (platform.Frame, if painter.onFileDrop == nil { return platform.Frame{}, false, nil } + if painter.trace != nil { + painter.trace.Event(frametrace.Drop, fileDropPhaseNames[event.Phase]) + } target := gfx.ID{} if event.Phase != platform.FileDropLeave { if hit, ok := painter.focus.Router().HitTest(event.X, event.Y); ok { @@ -947,17 +1004,20 @@ func (painter *painter) fileDrop(event platform.FileDropEvent) (platform.Frame, if !response.Repaint && !focusChanged { return platform.Frame{}, response.Handled, nil } - frame, err := painter.repaintAfterInput() + frame, err := painter.repaintAfterInput(frametrace.Drop) return frame, response.Handled, err } func (painter *painter) scroll(event platform.ScrollEvent) (platform.Frame, error) { + if painter.trace != nil { + painter.trace.Event(frametrace.Scroll, "") + } painter.tap.Cancel() painter.touch.StopFling() // a wheel or a touchpad takes over from a fling if !painter.applyScroll(event) { return platform.Frame{}, nil } - return painter.repaintAfterInput() + return painter.repaintAfterInput(frametrace.Scroll) } // applyScroll gives a scroll to the application, or scrolls the page itself when @@ -1089,8 +1149,14 @@ func (painter *painter) deliverPointer(event gfx.PointerEvent) bool { } // repaint reruns the paint callback with current interaction state and -// synchronizes the result with the retained renderer. -func (painter *painter) repaint() (platform.Frame, error) { +// synchronizes the result with the retained renderer. The reason is what the +// frame is painted for, as the frame trace reports it. +func (painter *painter) repaint(reason frametrace.Reason) (platform.Frame, error) { + if painter.trace != nil { + // A touch step below may paint the frame itself, through a repaint of + // its own: the reason goes with whichever paints it. + painter.trace.Note(reason) + } if touchRuntime.advance != nil { if frame, done, err := touchRuntime.advance(painter); done { return frame, err @@ -1101,26 +1167,46 @@ func (painter *painter) repaint() (platform.Frame, error) { } painter.paintCanvas() painter.settleInteraction() + var published time.Time + if painter.trace != nil { + published = time.Now() + } frame, err := painter.publish() if err != nil { return platform.Frame{}, err } + if painter.trace != nil { + painter.traceFrame(frame, time.Since(published)) + } if painter.keys.TakeDue() && painter.releaseKeys() && painter.scheduleFrame != nil { - painter.scheduleFrame(0) + painter.scheduleFrame(0, frametrace.Key) } painter.scheduleIfAnimating() return frame, nil } +// traceFrame writes the frame line of a frame just published. +func (painter *painter) traceFrame(frame platform.Frame, publish time.Duration) { + labels := -1 + if frame.TextLabels != nil { + labels = len(frame.TextLabels) + } + painter.trace.Frame(publish, frametrace.Frame{ + Instances: len(frame.Rectangles), Changed: frame.Update.Count, Rebuild: frame.Update.Rebuild, Shrink: frame.Update.Shrink, + Labels: labels, Accessibility: frame.Accessibility != nil, TextInput: frame.TextInput.Changed, + NativeViews: frame.NativeViews != nil, + }) +} + // repaintAfterInput is repaint for a pointer or wheel event: a window that // coalesces input asks its frame clock for the next frame instead, so a burst // of events costs one paint and lands on the display's own cadence. -func (painter *painter) repaintAfterInput() (platform.Frame, error) { +func (painter *painter) repaintAfterInput(reason frametrace.Reason) (platform.Frame, error) { if painter.coalesceInput && painter.scheduleFrame != nil { - painter.scheduleFrame(0) + painter.scheduleFrame(0, reason) return platform.Frame{}, nil } - return painter.repaint() + return painter.repaint(reason) } // titlebarInsets is how much of the titlebar strip the page draws the window @@ -1133,6 +1219,16 @@ func (painter *painter) titlebarInsets() (leading, trailing float32) { return platformTitlebarInsets() } +// titlebarHeight is the height of the titlebar strip the window buttons sit on +// now: zero for a window whose titlebar is the system's, and zero in full screen, +// where the buttons are not shown on the strip. +func (painter *painter) titlebarHeight() float32 { + if !painter.customTitlebar || painter.fullscreen { + return 0 + } + return painter.titlebarStrip +} + // focusSettlement is what a paint decided about the focus: nothing yet, synced // with the canvas, or kept because the canvas asks for nothing the focus and the // input regions do not already reflect. @@ -1212,13 +1308,21 @@ func (painter *painter) paintCanvas() { painter.canvas.SetHoveredDisabled(painter.pointer.HoveredDisabled()) painter.canvas.SetPointerOnSurface(painter.onSurface) painter.canvas.SetTitlebarInsets(painter.titlebarInsets()) + painter.canvas.SetTitlebarHeight(painter.titlebarHeight()) painter.canvas.SetScroll(painter.scrollX, painter.scrollY) + var started time.Time + if painter.trace != nil { + started = time.Now() + } painter.canvas.BeginFrame() painter.paint(painter.canvas, painter.size) if painter.controls != nil && !painter.fullscreen { painter.controls.paint(painter.canvas, painter.size) } painter.canvas.EndFrame() + if painter.trace != nil { + painter.trace.Painted(time.Since(started)) + } } // scheduleIfAnimating asks for exactly one more frame when the last paint left @@ -1230,7 +1334,11 @@ func (painter *painter) scheduleIfAnimating() { return } if delay, ok := painter.canvas.NextFrame(); ok { - painter.scheduleFrame(delay) + reason := frametrace.Animation + if delay > 0 { + reason = frametrace.Timer + } + painter.scheduleFrame(delay, reason) } } @@ -1621,6 +1729,15 @@ func (painter *painter) disableTextInput() platform.TextInputUpdate { return platform.TextInputUpdate{Changed: true} } +// tracedTextEvent is applyTextEvent for a traced window: the platform asks for +// the frame a text event needs through a redraw after it, so the reason is +// noted for that frame. +func (painter *painter) tracedTextEvent(event platform.TextEvent) (platform.TextState, error) { + painter.trace.Event(frametrace.Text, "") + painter.trace.Note(frametrace.Text) + return painter.applyTextEvent(event) +} + func (painter *painter) applyTextEvent(event platform.TextEvent) (platform.TextState, error) { painter.tap.Cancel() active := painter.activeText @@ -2064,33 +2181,42 @@ func (painter *painter) syncSemantics(incremental bool) (changed bool) { // accessibilityNode is the payload entry for one hit. func (painter *painter) accessibilityNode(hit *gfx.Hit, focused gfx.ID) platform.AccessibilityNode { node := platform.AccessibilityNode{ - ID: hit.ID, - Role: uint8(semanticRole(hit.Role)), - X: hit.Bounds.X, - Y: hit.Bounds.Y, - Width: hit.Bounds.Width, - Height: hit.Bounds.Height, - Label: hit.Label, - Value: hit.Value, - Hint: hit.Hint, - Focused: !hit.ID.IsZero() && hit.ID == focused, - Disabled: hit.Disabled, - Checked: hit.Checked, - Mixed: hit.Mixed, - Selected: hit.Selected, - Expanded: hit.Expanded, - Multiline: hit.Multiline, - ReadOnly: hit.ReadOnly, - Invalid: hit.Invalid, - Secure: hit.Secure, - Focusable: hit.Focusable, - Expandable: hit.Expandable, - Description: hit.Description, - Level: hit.Level, - PosInSet: hit.PosInSet, - SetSize: hit.SetSize, - Live: hit.Live, - Range: hit.Range, + ID: hit.ID, + Role: uint8(semanticRole(hit.Role)), + X: hit.Bounds.X, + Y: hit.Bounds.Y, + Width: hit.Bounds.Width, + Height: hit.Bounds.Height, + Label: hit.Label, + Value: hit.Value, + Hint: hit.Hint, + Focused: !hit.ID.IsZero() && hit.ID == focused, + Disabled: hit.Disabled, + Checked: hit.Checked, + Mixed: hit.Mixed, + Selected: hit.Selected, + Expanded: hit.Expanded, + Sort: hit.Sort, + + MultiSelectable: hit.MultiSelectable, + Multiline: hit.Multiline, + ReadOnly: hit.ReadOnly, + Invalid: hit.Invalid, + Secure: hit.Secure, + Focusable: hit.Focusable, + Expandable: hit.Expandable, + Description: hit.Description, + Level: hit.Level, + PosInSet: hit.PosInSet, + SetSize: hit.SetSize, + Live: hit.Live, + Range: hit.Range, + } + if selected := hit.TextSelection; node.Focused && hit.Role == gfx.RoleTerminal && !hit.Secure && selected != nil { + node.TextSelection = selected + node.Value = selected.Text + node.ReadOnly = true + node.Selection = platform.AccessibilitySelection{End: int32(utf8.RuneCountInString(selected.Text)), Valid: true} } if node.Focused && !hit.ID.IsZero() && painter.activeText != nil && !hit.Secure && (hit.Role == gfx.RoleTextField || hit.Role == gfx.RoleCombobox) && painter.activeText.State.Value == hit.Value { @@ -2182,6 +2308,8 @@ func semanticRole(role gfx.Role) semantic.Role { return semantic.RoleSeparator case gfx.RoleProgressBar: return semantic.RoleProgress + case gfx.RoleColumnHeader: + return semantic.RoleColumnHeader default: return semantic.RoleButton } diff --git a/app/painter_bitmap_test.go b/app/painter_bitmap_test.go index 1d3da252a..5bd6206d9 100644 --- a/app/painter_bitmap_test.go +++ b/app/painter_bitmap_test.go @@ -7,6 +7,7 @@ import ( "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/internal/framebuild" + "github.com/vivaui/viva/internal/frametrace" "github.com/vivaui/viva/internal/platform" ) @@ -33,7 +34,7 @@ func TestBitmapPaintIsRetainedAndClippedWithoutPixelCopies(t *testing.T) { 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) } - frame, err := painter.repaint() + frame, err := painter.repaint(frametrace.Invalidate) if err != nil { t.Fatal(err) } @@ -41,7 +42,7 @@ func TestBitmapPaintIsRetainedAndClippedWithoutPixelCopies(t *testing.T) { t.Fatal("unchanged bitmap was uploaded again") } caption = "two" - frame, err = painter.repaint() + frame, err = painter.repaint(frametrace.Invalidate) if err != nil { t.Fatal(err) } @@ -87,7 +88,7 @@ func TestBitmapPixelsFollowTheLabelAndNotThePictureOrder(t *testing.T) { // the viewport, so the picture list grows by one. showIcon = true aboutClip = gfx.Rect{X: 0, Y: 200, Width: 40, Height: 5} - if _, err := painter.repaint(); err != nil { + if _, err := painter.repaint(frametrace.Invalidate); err != nil { t.Fatal(err) } previous := append([]int32(nil), painter.frame.LastLabelImages()...) @@ -96,7 +97,7 @@ func TestBitmapPixelsFollowTheLabelAndNotThePictureOrder(t *testing.T) { // one image place, while the labels keep the places the text gives them. showIcon = false aboutClip = gfx.Rect{X: 0, Y: 200, Width: 40, Height: 20} - frame, err := painter.repaint() + frame, err := painter.repaint(frametrace.Invalidate) if err != nil { t.Fatal(err) } @@ -125,7 +126,7 @@ func TestBitmapPixelsFollowTheLabelAndNotThePictureOrder(t *testing.T) { // A later frame that changes only text sends the bitmaps again, in the same // places; their textures are reused and their pixels stay home. line = "line two" - frame, err = painter.repaint() + frame, err = painter.repaint(frametrace.Invalidate) if err != nil { t.Fatal(err) } @@ -168,7 +169,7 @@ func TestInitialBitmapUploadAfterPreparationPaint(test *testing.T) { test.Fatal("initial frame omitted the bitmap") } caption = "updated" - frame, err := painter.repaint() + frame, err := painter.repaint(frametrace.Invalidate) if err != nil { test.Fatal(err) } @@ -210,7 +211,7 @@ func BenchmarkBitmapStartup(bench *testing.B) { } bench.ReportAllocs() for bench.Loop() { - if _, err := painter.repaint(); err != nil { + if _, err := painter.repaint(frametrace.Invalidate); err != nil { bench.Fatal(err) } } @@ -260,7 +261,7 @@ func TestBackdropIsBeneathEveryLayerAndShiftsThemOnlyWhilePresent(t *testing.T) } backdrop = false - frame, err := painter.repaint() + frame, err := painter.repaint(frametrace.Invalidate) if err != nil { t.Fatal(err) } @@ -279,7 +280,7 @@ func TestBackdropIsBeneathEveryLayerAndShiftsThemOnlyWhilePresent(t *testing.T) } backdrop = true - frame, err = painter.repaint() + frame, err = painter.repaint(frametrace.Invalidate) if err != nil { t.Fatal(err) } @@ -308,7 +309,7 @@ func BenchmarkRepaintWithBackdrop(b *testing.B) { } b.ReportAllocs() for b.Loop() { - if _, err := painter.repaint(); err != nil { + if _, err := painter.repaint(frametrace.Invalidate); err != nil { b.Fatal(err) } } @@ -339,7 +340,7 @@ func TestOnlyChangedBitmapsCrossTheNativeBoundary(t *testing.T) { } // A patch inside the first tile: one upload, the other five stay on the GPU. surface.Update(10, 10, 8, 8, make([]byte, 8*8*4), 8*4) - frame, err := painter.repaint() + frame, err := painter.repaint(frametrace.Invalidate) if err != nil { t.Fatal(err) } @@ -348,7 +349,7 @@ func TestOnlyChangedBitmapsCrossTheNativeBoundary(t *testing.T) { } // A frame that changes only text uploads none. caption = "two" - frame, err = painter.repaint() + frame, err = painter.repaint(frametrace.Invalidate) if err != nil { t.Fatal(err) } diff --git a/app/painter_leak_test.go b/app/painter_leak_test.go index 6f194c284..1cdb1d83b 100644 --- a/app/painter_leak_test.go +++ b/app/painter_leak_test.go @@ -5,6 +5,7 @@ import ( "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/frametrace" ) // Showing a busy page and then an empty one must give back what the page held: the @@ -28,7 +29,7 @@ func TestAPageThatIsRemovedLeavesNothingRetained(t *testing.T) { settle := func(count int) { t.Helper() rowCount = count - if _, err := painter.repaint(); err != nil { + if _, err := painter.repaint(frametrace.Invalidate); err != nil { t.Fatal(err) } } @@ -67,7 +68,7 @@ func TestALargePageThenASmallOneReleasesSlots(t *testing.T) { settle := func(count int) { t.Helper() rowCount = count - if _, err := painter.repaint(); err != nil { + if _, err := painter.repaint(frametrace.Invalidate); err != nil { t.Fatal(err) } } diff --git a/app/painter_motion_test.go b/app/painter_motion_test.go index 1c6b35921..b4ef5e2be 100644 --- a/app/painter_motion_test.go +++ b/app/painter_motion_test.go @@ -1,12 +1,14 @@ package app import ( + "io" "sync/atomic" "testing" "time" "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/frametrace" "github.com/vivaui/viva/internal/platform" ) @@ -21,7 +23,7 @@ type motionHarness struct { theme gfx.Theme } -func newMotionHarness(t *testing.T) *motionHarness { +func newMotionHarness(t testing.TB) *motionHarness { t.Helper() harness := &motionHarness{canvas: &gfx.Canvas{}, now: time.Second, theme: gfx.LightTheme()} config := Config{Title: "motion", Width: 120, Height: 60} @@ -31,22 +33,22 @@ func newMotionHarness(t *testing.T) *motionHarness { onClick(&config, func(id gfx.ID) { harness.checked = !harness.checked }) harness.painter = newTestPainter(t, harness.canvas, config) harness.canvas.SetClock(func() time.Duration { return harness.now }) - harness.painter.scheduleFrame = func(time.Duration) { harness.requests++ } + harness.painter.scheduleFrame = func(time.Duration, frametrace.Reason) { harness.requests++ } return harness } // frame plays the role of the platform's redraw callback. -func (harness *motionHarness) frame(t *testing.T, advance time.Duration) platform.Frame { +func (harness *motionHarness) frame(t testing.TB, advance time.Duration) platform.Frame { t.Helper() harness.now += advance - frame, err := harness.painter.repaint() + frame, err := harness.painter.repaint(frametrace.Invalidate) if err != nil { t.Fatal(err) } return frame } -func (harness *motionHarness) click(t *testing.T) platform.Frame { +func (harness *motionHarness) click(t testing.TB) platform.Frame { t.Helper() var frame platform.Frame for _, kind := range []platform.PointerEventKind{platform.PointerMove, platform.PointerDown, platform.PointerUp} { @@ -114,19 +116,26 @@ func TestClickSchedulesFramesUntilTransitionSettles(t *testing.T) { } } +// Mid-flight frames allocate nothing with the frame trace off, the default, and +// nothing either while it writes a line for each of them. func TestMidFlightFramesDoNotAllocate(t *testing.T) { - harness := newMotionHarness(t) - harness.theme.Transition.Duration = 10 * time.Minute - harness.click(t) - harness.frame(t, time.Second) - allocations := testing.AllocsPerRun(200, func() { - harness.now += 8 * time.Millisecond - if _, err := harness.painter.repaint(); err != nil { - t.Fatal(err) + for _, traced := range []bool{false, true} { + harness := newMotionHarness(t) + if traced { + harness.painter.trace = frametrace.NewWindow(io.Discard) + } + harness.theme.Transition.Duration = 10 * time.Minute + harness.click(t) + harness.frame(t, time.Second) + allocations := testing.AllocsPerRun(200, func() { + harness.now += 8 * time.Millisecond + if _, err := harness.painter.repaint(frametrace.Animation); err != nil { + t.Fatal(err) + } + }) + if allocations != 0 || !harness.canvas.Animating() { + t.Fatalf("traced=%v: mid-flight frames allocated %v times (animating=%v)", traced, allocations, harness.canvas.Animating()) } - }) - if allocations != 0 || !harness.canvas.Animating() { - t.Fatalf("mid-flight frames allocated %v times (animating=%v)", allocations, harness.canvas.Animating()) } } @@ -154,7 +163,7 @@ func TestFrameTimerCoalescesRequestsIntoOneWake(t *testing.T) { defer frames.stop() for range 10 { - frames.request(0) + frames.request(0, frametrace.Animation) } waitForWake(t, woken) if wakes.Load() != 1 { @@ -167,7 +176,7 @@ func TestFrameTimerCoalescesRequestsIntoOneWake(t *testing.T) { t.Fatal("timer re-armed itself without a request") case <-time.After(4 * frameInterval): } - frames.request(0) + frames.request(0, frametrace.Animation) waitForWake(t, woken) if wakes.Load() != 2 { t.Fatalf("second request produced %d total wakes", wakes.Load()) @@ -177,9 +186,9 @@ func TestFrameTimerCoalescesRequestsIntoOneWake(t *testing.T) { func TestFrameTimerStopCancelsPendingWake(t *testing.T) { var wakes atomic.Int32 frames := newFrameTimer(func() { wakes.Add(1) }) - frames.request(0) + frames.request(0, frametrace.Animation) frames.stop() - frames.request(0) + frames.request(0, frametrace.Animation) time.Sleep(6 * frameInterval) if wakes.Load() != 0 { t.Fatalf("stopped timer woke the loop %d times", wakes.Load()) @@ -199,7 +208,7 @@ func TestFrameLoopRunsThroughRealTimerAndSettles(t *testing.T) { redraws := 0 for harness.canvas.Animating() { waitForWake(t, woken) - if _, err := harness.painter.repaint(); err != nil { + if _, err := harness.painter.repaint(frametrace.Invalidate); err != nil { t.Fatal(err) } redraws++ @@ -243,7 +252,7 @@ func BenchmarkPainterAnimatedSwitchFrame(b *testing.B) { b.Fatal(err) } harness.canvas.SetClock(func() time.Duration { return harness.now }) - harness.painter.scheduleFrame = func(time.Duration) {} + harness.painter.scheduleFrame = func(time.Duration, frametrace.Reason) {} b.ReportAllocs() b.ResetTimer() for index := range b.N { @@ -251,7 +260,7 @@ func BenchmarkPainterAnimatedSwitchFrame(b *testing.B) { if index%20 == 0 { harness.checked = !harness.checked } - if _, err := harness.painter.repaint(); err != nil { + if _, err := harness.painter.repaint(frametrace.Invalidate); err != nil { b.Fatal(err) } } @@ -271,13 +280,13 @@ func TestPainterSchedulesADelayedFrameWithItsDelay(t *testing.T) { } painter := newTestPainter(t, &canvas, config) var delays []time.Duration - painter.scheduleFrame = func(delay time.Duration) { delays = append(delays, delay) } + painter.scheduleFrame = func(delay time.Duration, _ frametrace.Reason) { delays = append(delays, delay) } - if _, err := painter.repaint(); err != nil { + if _, err := painter.repaint(frametrace.Invalidate); err != nil { t.Fatal(err) } asked = false - if _, err := painter.repaint(); err != nil { + if _, err := painter.repaint(frametrace.Invalidate); err != nil { t.Fatal(err) } if len(delays) != 1 || delays[0] != 125*time.Millisecond { @@ -292,7 +301,7 @@ func TestFrameTimerWaitsForTheRequestedDelay(t *testing.T) { const delay = 60 * time.Millisecond start := time.Now() - frames.request(delay) + frames.request(delay, frametrace.Animation) waitForWake(t, woken) if elapsed := time.Since(start); elapsed < delay { t.Fatalf("woke after %v, before the %v asked for", elapsed, delay) @@ -306,15 +315,15 @@ func TestFrameTimerBringsAPendingWakeForward(t *testing.T) { defer frames.stop() start := time.Now() - frames.request(5 * time.Second) - frames.request(0) + frames.request(5*time.Second, frametrace.Animation) + frames.request(0, frametrace.Animation) waitForWake(t, woken) if elapsed := time.Since(start); elapsed > time.Second { t.Fatalf("the immediate request waited %v behind a 5s tick", elapsed) } // And a later request does not push a sooner pending wake back. - frames.request(0) - frames.request(5 * time.Second) + frames.request(0, frametrace.Animation) + frames.request(5*time.Second, frametrace.Animation) start = time.Now() waitForWake(t, woken) if elapsed := time.Since(start); elapsed > time.Second { diff --git a/app/painter_presence_test.go b/app/painter_presence_test.go index 9d4e0d38c..b448405da 100644 --- a/app/painter_presence_test.go +++ b/app/painter_presence_test.go @@ -6,6 +6,7 @@ import ( "time" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/frametrace" "github.com/vivaui/viva/text" ) @@ -41,18 +42,18 @@ func TestPresenceExitPublishesLabelsPastTheWindowEdge(t *testing.T) { } now += 200 * time.Millisecond - if _, err := painter.repaint(); err != nil { + if _, err := painter.repaint(frametrace.Invalidate); err != nil { t.Fatal(err) } 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 { + if _, err := painter.repaint(frametrace.Invalidate); err != nil { t.Fatal(err) } now += 50 * time.Millisecond - frame, err := painter.repaint() + frame, err := painter.repaint(frametrace.Invalidate) if err != nil { t.Fatal(err) } @@ -71,7 +72,7 @@ func TestPresenceExitPublishesLabelsPastTheWindowEdge(t *testing.T) { } now += 100 * time.Millisecond - frame, err = painter.repaint() + frame, err = painter.repaint(frametrace.Invalidate) if err != nil { t.Fatal(err) } @@ -120,7 +121,7 @@ func TestPresenceCarriesNativeTextInputWithTheDrawer(t *testing.T) { if err != nil { t.Fatal(err) } - if _, err := painter.repaint(); err != nil { + if _, err := painter.repaint(frametrace.Invalidate); err != nil { t.Fatal(err) } if painter.focus.Focused() != gfx.Item(2) { @@ -135,7 +136,7 @@ func TestPresenceCarriesNativeTextInputWithTheDrawer(t *testing.T) { } now += 100 * time.Millisecond - if _, err := painter.repaint(); err != nil { + if _, err := painter.repaint(frametrace.Invalidate); err != nil { t.Fatal(err) } if painter.nativeText.X != field.X || painter.nativeText.CaretX != caret.X { diff --git a/app/painter_test.go b/app/painter_test.go index e71ff1131..b289b24a9 100644 --- a/app/painter_test.go +++ b/app/painter_test.go @@ -6,6 +6,7 @@ import ( "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/frametrace" "github.com/vivaui/viva/internal/input" "github.com/vivaui/viva/internal/platform" "github.com/vivaui/viva/internal/render" @@ -123,7 +124,7 @@ func TestFocusTrapEscapeDismissesAndRestoresFocus(t *testing.T) { } open = true - if _, err := painter.repaint(); err != nil { + if _, err := painter.repaint(frametrace.Invalidate); err != nil { t.Fatal(err) } if painter.focus.Router().ActiveScope() != gfx.Item(99) || !painter.focus.Focused().IsZero() { @@ -261,7 +262,7 @@ func TestTextInputRestoresStaticLabelInBlurFrame(t *testing.T) { if len(frame.TextLabels) != 1 || frame.TextLabels[0].Value != input.State.Value { t.Fatalf("blur frame lost the edited label: %+v", frame.TextLabels) } - idle, err := painter.repaint() + idle, err := painter.repaint(frametrace.Invalidate) if err != nil || !idle.Update.Empty() || idle.TextLabels != nil || idle.TextInput.Changed { t.Fatalf("unchanged blurred repaint did work: %+v, %v", idle, err) } @@ -328,7 +329,7 @@ func TestPainterTextSetSelectionPreservesRuneIndicesAndSynchronizesOwner(t *test if next != wantNative || painter.nativeText.State != wantNative { t.Fatalf("native result = %+v, state = %+v, want %+v", next, painter.nativeText.State, wantNative) } - frame, err = painter.repaint() + frame, err = painter.repaint(frametrace.Invalidate) if err != nil { t.Fatal(err) } @@ -481,12 +482,12 @@ func TestRepaintWithOnlyTheClipChangedRepublishesTheLabel(t *testing.T) { canvas.Unclip() } painter := newTestPainter(t, &canvas, config) - if frame, err := painter.repaint(); err != nil || frame.TextLabels != nil { + if frame, err := painter.repaint(frametrace.Invalidate); err != nil || frame.TextLabels != nil { t.Fatalf("unchanged repaint = %+v, %v; want no labels", frame.TextLabels, err) } clip.Height = 8 - frame, err := painter.repaint() + frame, err := painter.repaint(frametrace.Invalidate) if err != nil { t.Fatal(err) } @@ -508,7 +509,7 @@ func TestRepaintLayerOnlyChangePublishesCompositingUpdate(t *testing.T) { painter := newTestPainter(t, &canvas, config) layer = 5 - frame, err := painter.repaint() + frame, err := painter.repaint(frametrace.Invalidate) if err != nil { t.Fatal(err) } @@ -550,7 +551,7 @@ func TestRepaintLayersFollowPrimitivesWhenRectanglesGrowAfterTriangles(t *testin painter := newTestPainter(t, &canvas, config) overlay = true - frame, err := painter.repaint() + frame, err := painter.repaint(frametrace.Invalidate) if err != nil { t.Fatal(err) } @@ -584,7 +585,7 @@ func TestRepaintLayersFollowPrimitivesWhenRectanglesGrowAfterTriangles(t *testin // Closing and reopening exercises both removal and re-insertion. for _, open := range []bool{false, true, false} { overlay = open - frame, err = painter.repaint() + frame, err = painter.repaint(frametrace.Invalidate) if err != nil { t.Fatal(err) } @@ -807,7 +808,7 @@ func TestStationaryPointerFollowsNewHitGeometry(t *testing.T) { } covered = true - if _, err := painter.repaint(); err != nil { + if _, err := painter.repaint(frametrace.Invalidate); err != nil { t.Fatal(err) } check(gfx.ID{}, 0, CursorArrow, true) @@ -815,7 +816,7 @@ func TestStationaryPointerFollowsNewHitGeometry(t *testing.T) { t.Fatalf("scroll and repaints sent pointer events, got %d events", events) } before := paints - if _, err := painter.repaint(); err != nil { + if _, err := painter.repaint(frametrace.Invalidate); err != nil { t.Fatal(err) } if paints != before+1 { @@ -823,7 +824,7 @@ func TestStationaryPointerFollowsNewHitGeometry(t *testing.T) { } covered = false - if _, err := painter.repaint(); err != nil { + if _, err := painter.repaint(frametrace.Invalidate); err != nil { t.Fatal(err) } check(gfx.Item(8), gfx.RoleTextField, CursorText, false) @@ -840,7 +841,7 @@ func TestStationaryPointerFollowsNewHitGeometry(t *testing.T) { covered = false // An exit carries no useful coordinates. A later paint must not treat // its zero position as a pointer that moved onto the exposed item. - if _, err := painter.repaint(); err != nil { + if _, err := painter.repaint(frametrace.Invalidate); err != nil { t.Fatal(err) } check(gfx.ID{}, 0, CursorArrow, false) @@ -1545,7 +1546,7 @@ func TestModalOpenMovesFocusInsideWithinTheSameFrameAndCloseRestoresIt(t *testin // Steady state: the scope is already open, so repainting must neither // pull focus back nor paint twice. before := paints - if _, err := painter.repaint(); err != nil { + if _, err := painter.repaint(frametrace.Invalidate); err != nil { t.Fatal(err) } if paints != before+1 || painter.focus.Focused() != gfx.Item(int(field)) { @@ -1590,21 +1591,21 @@ func TestDialogShowsInitialButtonFocusUntilAPointerPress(t *testing.T) { t.Fatal(err) } open = true - if _, err := painter.repaint(); err != nil { + if _, err := painter.repaint(frametrace.Invalidate); err != nil { t.Fatal(err) } if canvas.Focused() != initial || (canvas.FocusVisible() == initial) != (role == gfx.RoleButton) { t.Fatalf("initial role %v: focus %v, visible %v", role, canvas.Focused(), canvas.FocusVisible()) } open = false - if _, err := painter.repaint(); err != nil { + if _, err := painter.repaint(frametrace.Invalidate); err != nil { t.Fatal(err) } if canvas.Focused() != opener || !canvas.FocusVisible().IsZero() { t.Fatalf("closing restored focus %v, visible %v", canvas.Focused(), canvas.FocusVisible()) } open = true - if _, err := painter.repaint(); err != nil { + if _, err := painter.repaint(frametrace.Invalidate); err != nil { t.Fatal(err) } if _, err := painter.pointerEvent(platform.PointerEvent{Kind: platform.PointerDown, X: target.X + 1, Y: target.Y + 1}); err != nil { @@ -1640,7 +1641,7 @@ func BenchmarkPainterModalToggle(b *testing.B) { b.ResetTimer() for range b.N { open = !open - if _, err := painter.repaint(); err != nil { + if _, err := painter.repaint(frametrace.Invalidate); err != nil { b.Fatal(err) } } @@ -1674,7 +1675,7 @@ func TestPressAtReportsControlsMoveRegionsAndTheClientArea(t *testing.T) { t.Fatal("a press outside every move region must stay the application's") } modal = true - if _, err := painter.repaint(); err != nil { + if _, err := painter.repaint(frametrace.Invalidate); err != nil { t.Fatal(err) } if painter.pressAt(310, 16) == platform.PressControl { @@ -1818,7 +1819,7 @@ func TestRepaintRecoloringEveryPrimitiveRefreshesEveryInstance(t *testing.T) { background = gfx.Color{Red: 0.97, Green: 0.97, Blue: 0.98, Alpha: 1} tint = gfx.Color{Red: 0.1, Green: 0.1, Blue: 0.15, Alpha: 1} - frame, err := painter.repaint() + frame, err := painter.repaint(frametrace.Invalidate) if err != nil { t.Fatal(err) } @@ -1867,7 +1868,7 @@ func TestRepaintRecoloringWhileTheTriangleCountChangesRefreshesEveryInstance(t * second = long tint = gfx.Color{Red: 0.1, Green: 0.1, Blue: 0.15, Alpha: 1} - frame, err := painter.repaint() + frame, err := painter.repaint(frametrace.Invalidate) if err != nil { t.Fatal(err) } @@ -1908,14 +1909,14 @@ func TestRepaintRecoloringRectanglesBehindShrinkingTrianglesRefreshesEverything( painter := newTestPainter(t, &canvas, config) extra = 3 // new rectangle nodes, appended behind the triangles - if _, err := painter.repaint(); err != nil { + if _, err := painter.repaint(frametrace.Invalidate); err != nil { t.Fatal(err) } trianglesBefore := len(canvas.Triangles()) icon = short tint = gfx.Color{Red: 0.1, Green: 0.1, Blue: 0.15, Alpha: 1} - frame, err := painter.repaint() + frame, err := painter.repaint(frametrace.Invalidate) if err != nil { t.Fatalf("repaint: %v", err) } @@ -1951,7 +1952,7 @@ func TestRepaintRebuildsRenderStateThatDisagreesWithTheScene(t *testing.T) { *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() + frame, err := painter.repaint(frametrace.Invalidate) if err != nil { t.Fatalf("repaint: %v", err) } @@ -1969,7 +1970,7 @@ func TestRepaintRebuildsRenderStateThatDisagreesWithTheScene(t *testing.T) { // And it keeps working incrementally afterwards. tint = gfx.Color{Red: 0.6, Green: 0.4, Blue: 0.2, Alpha: 1} - frame, err = painter.repaint() + frame, err = painter.repaint(frametrace.Invalidate) if err != nil || frame.Update.Empty() || frame.Rectangles[0].Color.Red != 0.6 { t.Fatalf("incremental repaint after recovery: update=%+v err=%v", frame.Update, err) } @@ -2061,12 +2062,12 @@ func TestNativeTextInputKeepsDeclaredFontWeight(t *testing.T) { t.Fatalf("native text weight = %+v, want %v", frame.TextInput.Input, weight) } weight = gfx.WeightMedium - frame, err = painter.repaint() + frame, err = painter.repaint(frametrace.Invalidate) if err != nil || !frame.TextInput.Changed || frame.TextInput.Input == nil || frame.TextInput.Input.Weight != weight { t.Fatalf("weight update = %+v, %v", frame.TextInput, err) } override = true - frame, err = painter.repaint() + frame, err = painter.repaint(frametrace.Invalidate) if err != nil || !frame.TextInput.Changed || frame.TextInput.Input == nil || frame.TextInput.Input.Weight != gfx.WeightBold { t.Fatalf("explicit weight = %+v, %v", frame.TextInput, err) } @@ -2414,7 +2415,7 @@ func TestTerminalAltPolicyIsPublishedAndUpdated(t *testing.T) { } altSendsEscape = true - frame, err := painter.repaint() + frame, err := painter.repaint(frametrace.Invalidate) if err != nil { t.Fatal(err) } @@ -2422,14 +2423,14 @@ func TestTerminalAltPolicyIsPublishedAndUpdated(t *testing.T) { t.Fatalf("Alt policy update = %+v", frame.TextInput) } monoFace = gfx.MonoClassic - frame, err = painter.repaint() + frame, err = painter.repaint(frametrace.Invalidate) if err != nil { t.Fatal(err) } if !frame.TextInput.Changed || frame.TextInput.Input == nil || frame.TextInput.Input.MonoFace != gfx.MonoClassic { t.Fatalf("mono face update = %+v", frame.TextInput) } - if frame, err = painter.repaint(); err != nil || frame.TextInput.Changed { + if frame, err = painter.repaint(frametrace.Invalidate); err != nil || frame.TextInput.Changed { t.Fatalf("unchanged Alt policy republished = %+v, %v", frame.TextInput, err) } } @@ -2629,7 +2630,7 @@ func TestPopoverInitialFocusIsHonoredOnce(t *testing.T) { if painter.focus.Focused() == gfx.Item(5) { t.Fatal("Tab could not leave the open popover") } - if _, err := painter.repaint(); err != nil { + if _, err := painter.repaint(frametrace.Invalidate); err != nil { t.Fatal(err) } if painter.focus.Focused() == gfx.Item(5) { @@ -2649,7 +2650,7 @@ func TestPainterAppendsOneShapeWithoutRebuild(t *testing.T) { } }}) count = 2 - frame, err := painter.repaint() + frame, err := painter.repaint(frametrace.Invalidate) if err != nil { t.Fatal(err) } @@ -2672,7 +2673,7 @@ func TestPainterDropsLabelsWithoutAreaOrFontSize(t *testing.T) { 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 { + if _, err := painter.repaint(frametrace.Invalidate); err != nil { t.Fatalf("repaint failed: %v", err) } } @@ -2704,7 +2705,7 @@ func TestPainterDropsSubpixelAndClippedImages(t *testing.T) { 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 { + if _, err := painter.repaint(frametrace.Invalidate); err != nil { t.Fatalf("repaint failed: %v", err) } } @@ -2747,7 +2748,7 @@ func TestPainterDisablesTextInputOnSubpixelBounds(t *testing.T) { // Shrink the text field bounds to subpixel (< 0.5) to simulate extreme resize compression fieldWidth = 0.3 - frame, err := painter.repaint() + frame, err := painter.repaint(frametrace.Invalidate) if err != nil { t.Fatalf("repaint failed when field is subpixel: %v", err) } @@ -2760,7 +2761,7 @@ func TestPainterDisablesTextInputOnSubpixelBounds(t *testing.T) { // Expand the text field bounds back to normal fieldWidth = 100 - frame, err = painter.repaint() + frame, err = painter.repaint(frametrace.Invalidate) if err != nil { t.Fatalf("repaint failed after restoring field bounds: %v", err) } @@ -2800,7 +2801,9 @@ func TestGridLinesDrawBlockElementsAsRectanglesNotText(t *testing.T) { t.Fatalf("the platform was given %+v, want the blocks as blank cells", frame.TextLabels) } label := frame.TextLabels[0] - if len(label.Runs) != 4 || label.Runs[1].Bytes != 1 || label.Runs[2].Column != 2 { + // The columns are the label's own, which starts a cell before the line (see + // framebuild.overhangCells), so they are compared with each other. + if len(label.Runs) != 4 || label.Runs[1].Bytes != 1 || label.Runs[2].Column-label.Runs[0].Column != 2 { t.Fatalf("runs after replacing the blocks = %+v", label.Runs) } var blocks int @@ -2875,7 +2878,7 @@ func TestRepaintShrinksWhenAShapeIsRemoved(t *testing.T) { var canvas gfx.Canvas painter := newTestPainter(t, &canvas, config) removed = 1 - frame, err := painter.repaint() + frame, err := painter.repaint(frametrace.Invalidate) if err != nil { t.Fatal(err) } diff --git a/app/reload_worker.go b/app/reload_worker.go index c75c8228e..102947232 100644 --- a/app/reload_worker.go +++ b/app/reload_worker.go @@ -37,6 +37,8 @@ func newReloadWorkerConfig(config Config, canvas *gfx.Canvas) reloadwire.WorkerC HasKey: config.OnKey != nil, HasShortcut: config.OnShortcut != nil, HasScroll: config.OnScroll != nil, HasModifierTap: config.OnModifierTap != nil, HasClose: config.OnCloseRequest != nil, HasSnapshot: config.Reload.Snapshot != nil, HasRestore: config.Reload.Restore != nil, + + D3D11LowMemoryUploads: config.D3D11LowMemoryUploads, }, Canvas: canvas, Paint: config.Paint, Pointer: config.OnPointer, Key: config.OnKey, Shortcut: config.OnShortcut, Scroll: config.OnScroll, ModifierTap: config.OnModifierTap, diff --git a/app/run.go b/app/run.go index 9c74ba81b..f82629b58 100644 --- a/app/run.go +++ b/app/run.go @@ -47,6 +47,7 @@ func Run(config Config) error { Blue: normalized.ClearColor.Blue, Alpha: normalized.ClearColor.Alpha, }, - WindowBorderColor: borderColorHandler(normalized.WindowBorderColor), + WindowBorderColor: borderColorHandler(normalized.WindowBorderColor), + D3D11LowMemoryUploads: normalized.D3D11LowMemoryUploads, }) } diff --git a/app/run_canvas.go b/app/run_canvas.go index e08b1ed64..8c557c15f 100644 --- a/app/run_canvas.go +++ b/app/run_canvas.go @@ -10,6 +10,7 @@ import ( "time" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/frametrace" "github.com/vivaui/viva/internal/platform" ) @@ -108,6 +109,56 @@ func maximizeHandler(callback func(bool)) platform.MaximizeHandler { return platform.MaximizeHandler(callback) } +// traceVisibility reports the window's visibility changes in its frame trace +// before handler, which may be nil; an untraced window gets handler itself. +func traceVisibility(trace *frametrace.Window, handler platform.VisibilityHandler) platform.VisibilityHandler { + if trace == nil { + return handler + } + return func(visible bool) { + detail := "hidden" + if visible { + detail = "shown" + } + trace.Event(frametrace.Visibility, detail) + if handler != nil { + handler(visible) + } + } +} + +// traceMinimize reports minimizing and restoring in the window's frame trace +// before handler, which may be nil; an untraced window gets handler itself. +func traceMinimize(trace *frametrace.Window, handler platform.MinimizeHandler) platform.MinimizeHandler { + if trace == nil { + return handler + } + return func(minimized bool) { + detail := "restore" + if minimized { + detail = "minimize" + } + trace.Event(frametrace.Visibility, detail) + if handler != nil { + handler(minimized) + } + } +} + +// traceClosed writes the window's last trace line before handler, which may be +// nil; an untraced window gets handler itself. +func traceClosed(trace *frametrace.Window, handler func()) func() { + if trace == nil { + return handler + } + return func() { + trace.Closed() + if handler != nil { + handler() + } + } +} + // nativeWindowConfig is the window a platform adapter opens: the painter's // initial scene, input and text state, plus the callbacks that keep it current. // It reads no native API, so the wiring can be assembled and driven without the @@ -127,6 +178,9 @@ func nativeWindowConfig(normalized *Config, painter *painter) (platform.Config, waker = &platform.Waker{} } frames = newFrameTimer(waker.Wake) + if painter.trace != nil { + frames.note = waker.Note + } painter.scheduleFrame = frames.request painter.noteFrameStart = frames.redrawing painter.coalesceInput = true @@ -136,6 +190,13 @@ func nativeWindowConfig(normalized *Config, painter *painter) (platform.Config, var framePresented func() if frames != nil { framePresented = frames.presented + if trace := painter.trace; trace != nil { + trace.AwaitPresent() + framePresented = func() { + frames.presented() + trace.Presented() + } + } setFrameInterval = func(interval time.Duration) { frames.setInterval(interval) if waker != nil { @@ -148,7 +209,8 @@ func nativeWindowConfig(normalized *Config, painter *painter) (platform.Config, var pointerHandler platform.PointerHandler var keyHandler platform.KeyHandler var scrollHandler platform.ScrollHandler - var redrawHandler platform.RedrawHandler = painter.repaint + // A redraw without a waker is one the platform asked for. + redrawHandler := func() (platform.Frame, error) { return painter.repaint(frametrace.System) } var gate *visibilityGate if normalized.Paint != nil || painter.controls != nil || normalized.OnResize != nil || normalized.OnFullscreen != nil { resizeHandler = painter.resize @@ -169,7 +231,11 @@ func nativeWindowConfig(normalized *Config, painter *painter) (platform.Config, if waker != nil { waker.SetSpacing(frameInterval) gate = &visibilityGate{waker: waker} - redrawHandler = wakeHandler(waker, gate, normalized.OnWake, painter.repaint) + var trace *wakeTrace + if painter.trace != nil { + trace = &wakeTrace{window: painter.trace, frames: frames} + } + redrawHandler = wakeHandler(waker, gate, normalized.OnWake, painter.repaint, trace) } var closeHandler platform.CloseRequestHandler if normalized.OnCloseRequest != nil { @@ -202,8 +268,8 @@ func nativeWindowConfig(normalized *Config, painter *painter) (platform.Config, Accessibility: painter.accessibility, OnResize: resizeHandler, OnFrameChange: frameChangeHandler(normalized.OnFrameChange), - OnMinimize: minimizeHandler(normalized.OnMinimize), - OnVisibility: gate.handler(), + OnMinimize: traceMinimize(painter.trace, minimizeHandler(normalized.OnMinimize)), + OnVisibility: traceVisibility(painter.trace, gate.handler()), OnMaximize: maximizeHandler(normalized.OnMaximize), OnFullscreen: painter.fullscreenHandler(normalized.OnFullscreen), OnReopen: normalized.onReopen, @@ -224,8 +290,10 @@ func nativeWindowConfig(normalized *Config, painter *painter) (platform.Config, FramePresented: framePresented, Waker: waker, OnCloseRequest: closeHandler, - OnClosed: normalized.OnClosed, + OnClosed: traceClosed(painter.trace, normalized.OnClosed), DynamicTextInput: normalized.TextInput != nil, + + D3D11LowMemoryUploads: normalized.D3D11LowMemoryUploads, } if normalized.TextInput != nil { config.ReadOnlyTextFocused = func() bool { diff --git a/app/singleinstance/singleinstance.go b/app/singleinstance/singleinstance.go index 1cd17d14f..cd1cbc708 100644 --- a/app/singleinstance/singleinstance.go +++ b/app/singleinstance/singleinstance.go @@ -42,10 +42,23 @@ func (claim *Instance) Close() { // directories their shells set. An error means the claim could not be made // either way; the caller may carry on as an unclaimed copy. func SingleInstance(id string, args []string, onLaunch func(args []string)) (claim *Instance, primary bool, err error) { + return SingleInstanceWithOptions(id, args, onLaunch, Options{}) +} + +// Options controls the handoff from a second launch to the running instance. +type Options struct { + // AllowForeground lets the running copy bring a window forward on Windows + // if the calling process has permission. It does not activate a window. + // Leave it false for background launches. + AllowForeground bool +} + +// SingleInstanceWithOptions is SingleInstance with a choice of handoff options. +func SingleInstanceWithOptions(id string, args []string, onLaunch func(args []string), options Options) (claim *Instance, primary bool, err error) { if onLaunch == nil { return nil, false, errors.New("singleinstance: a launch handler is required") } - inner, primary, err := instance.Claim(id, args, onLaunch) + inner, primary, err := instance.Claim(id, args, options.AllowForeground, onLaunch) if err != nil || !primary { return nil, false, err } diff --git a/app/system.go b/app/system.go index 82d5668c4..da839bd5b 100644 --- a/app/system.go +++ b/app/system.go @@ -187,10 +187,28 @@ func OpenFiles(options OpenFileOptions) ([]string, error) { // OpenDirectory asks the user to choose one existing local directory. The Web // target cannot expose a directory path and returns ErrUnsupported. func OpenDirectory(options OpenDirectoryOptions) (string, error) { - if path, err, handled := driverOpenDirectory(options); handled { - return path, err + paths, err := openDirectories(options, false) + if err == nil && len(paths) != 1 { + return "", fmt.Errorf("app: expected one directory, got %d", len(paths)) + } + if len(paths) == 0 { + return "", err + } + return paths[0], err +} + +// OpenDirectories asks the user to choose one or more existing local directories. +// Cancellation returns ErrCanceled. On Linux the KDialog fallback can select +// one directory per call. The Web target returns ErrUnsupported. +func OpenDirectories(options OpenDirectoryOptions) ([]string, error) { + return openDirectories(options, true) +} + +func openDirectories(options OpenDirectoryOptions, multiple bool) ([]string, error) { + if paths, err, handled := driverOpenDirectories(options); handled { + return paths, err } - return nativeOpenDirectory(options) + return nativeOpenDirectories(options, multiple) } // SaveFile presents the platform's save-file picker. The Web target returns diff --git a/app/system_darwin.go b/app/system_darwin.go index 716e1e104..457d399d6 100644 --- a/app/system_darwin.go +++ b/app/system_darwin.go @@ -71,12 +71,12 @@ func nativeOpenFiles(options OpenFileOptions) ([]string, error) { return paths, err } -func nativeOpenDirectory(options OpenDirectoryOptions) (string, error) { - path, canceled, err := darwinplatform.OpenDirectory(darwinplatform.OpenDirectoryOptions{Title: options.Title, InitialDirectory: options.InitialDirectory}) +func nativeOpenDirectories(options OpenDirectoryOptions, multiple bool) ([]string, error) { + paths, canceled, err := darwinplatform.OpenDirectories(darwinplatform.OpenDirectoryOptions{Title: options.Title, InitialDirectory: options.InitialDirectory}, multiple) if canceled { - return "", ErrCanceled + return nil, ErrCanceled } - return path, err + return paths, err } func nativeSaveFile(options SaveFileOptions) (string, error) { diff --git a/app/system_js.go b/app/system_js.go index c7e3c54ec..456dd0d76 100644 --- a/app/system_js.go +++ b/app/system_js.go @@ -74,8 +74,8 @@ func nativeOpenFiles(OpenFileOptions) ([]string, error) { return paths, webSystemError("open files", err) } -func nativeOpenDirectory(OpenDirectoryOptions) (string, error) { - return "", ErrUnsupported +func nativeOpenDirectories(OpenDirectoryOptions, bool) ([]string, error) { + return nil, ErrUnsupported } func nativeSaveFile(SaveFileOptions) (string, error) { diff --git a/app/system_linux.go b/app/system_linux.go index 2c6260bec..86db66963 100644 --- a/app/system_linux.go +++ b/app/system_linux.go @@ -87,12 +87,12 @@ func nativeOpenFiles(options OpenFileOptions) ([]string, error) { return paths, linuxSystemError(err) } -func nativeOpenDirectory(options OpenDirectoryOptions) (string, error) { - path, canceled, err := linuxplatform.OpenDirectory(linuxplatform.OpenDirectoryOptions{Title: options.Title, InitialDirectory: options.InitialDirectory}) +func nativeOpenDirectories(options OpenDirectoryOptions, multiple bool) ([]string, error) { + paths, canceled, err := linuxplatform.OpenDirectories(linuxplatform.OpenDirectoryOptions{Title: options.Title, InitialDirectory: options.InitialDirectory}, multiple) if canceled { - return "", ErrCanceled + return nil, ErrCanceled } - return path, linuxSystemError(err) + return paths, linuxSystemError(err) } func nativeSaveFile(options SaveFileOptions) (string, error) { diff --git a/app/system_unsupported.go b/app/system_unsupported.go index 98c2dada5..30091dbed 100644 --- a/app/system_unsupported.go +++ b/app/system_unsupported.go @@ -23,8 +23,10 @@ func nativeOnClipboardChange(func()) error { return ErrUns func nativeSetCursor(Cursor) error { return ErrUnsupported } func nativeSetCursorImage(*gfx.CursorImage) error { return ErrUnsupported } func nativeOpenFiles(OpenFileOptions) ([]string, error) { return nil, ErrUnsupported } -func nativeOpenDirectory(OpenDirectoryOptions) (string, error) { return "", ErrUnsupported } -func nativeSaveFile(SaveFileOptions) (string, error) { return "", ErrUnsupported } +func nativeOpenDirectories(OpenDirectoryOptions, bool) ([]string, error) { + return nil, ErrUnsupported +} +func nativeSaveFile(SaveFileOptions) (string, error) { return "", ErrUnsupported } func nativeSaveFileWithCheckbox(SaveFileOptions, SaveFileCheckbox) (SaveFileSelection, error) { return SaveFileSelection{}, ErrUnsupported } diff --git a/app/system_windows.go b/app/system_windows.go index f7be5cd68..1a3a3fb53 100644 --- a/app/system_windows.go +++ b/app/system_windows.go @@ -62,12 +62,12 @@ func nativeOpenFiles(options OpenFileOptions) ([]string, error) { return paths, err } -func nativeOpenDirectory(options OpenDirectoryOptions) (string, error) { - path, canceled, err := windowsplatform.OpenDirectory(windowsplatform.OpenDirectoryOptions{Title: options.Title, InitialDirectory: options.InitialDirectory}) +func nativeOpenDirectories(options OpenDirectoryOptions, multiple bool) ([]string, error) { + paths, canceled, err := windowsplatform.OpenDirectories(windowsplatform.OpenDirectoryOptions{Title: options.Title, InitialDirectory: options.InitialDirectory}, multiple) if canceled { - return "", ErrCanceled + return nil, ErrCanceled } - return path, err + return paths, err } func nativeSaveFile(options SaveFileOptions) (string, error) { filters := make([]windowsplatform.FileFilter, len(options.Filters)) diff --git a/app/text_input_test.go b/app/text_input_test.go index 2cf895baa..270cb5f99 100644 --- a/app/text_input_test.go +++ b/app/text_input_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/frametrace" "github.com/vivaui/viva/internal/platform" "github.com/vivaui/viva/internal/semantic" "github.com/vivaui/viva/text" @@ -358,11 +359,11 @@ func TestFocusedTextFieldRepaintDoesNotAllocate(t *testing.T) { if !painter.textEnabled { t.Fatal("the text field did not take focus") } - if _, err := painter.repaint(); err != nil { + if _, err := painter.repaint(frametrace.Invalidate); err != nil { t.Fatal(err) } allocs := testing.AllocsPerRun(100, func() { - if _, err := painter.repaint(); err != nil { + if _, err := painter.repaint(frametrace.Invalidate); err != nil { t.Fatal(err) } }) diff --git a/app/text_menu.go b/app/text_menu.go index da5cc7156..3d3b7b470 100644 --- a/app/text_menu.go +++ b/app/text_menu.go @@ -6,6 +6,7 @@ import ( "slices" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/frametrace" "github.com/vivaui/viva/internal/platform" ) @@ -51,7 +52,7 @@ func (painter *painter) requestTextMenu(event platform.PointerEvent) (platform.F return platform.Frame{}, nil, false } painter.textMenuAt = &pointToMenu{x: event.X, y: event.Y, at: painter.pointer.Hovered()} - frame, err := painter.repaint() + frame, err := painter.repaint(frametrace.Pointer) return frame, err, true } @@ -95,6 +96,9 @@ func (painter *painter) textMenuItems() []platform.TextMenuItem { // performTextMenu runs a command chosen from the menu as the keyboard's chord of // the same name would, and returns the frame it caused. func (painter *painter) performTextMenu(command platform.TextMenuCommand) (platform.Frame, error) { + if painter.trace != nil { + painter.trace.Event(frametrace.Menu, "text") + } var err error switch command { case platform.TextMenuCut: @@ -111,7 +115,7 @@ func (painter *painter) performTextMenu(command platform.TextMenuCommand) (platf if err != nil { return platform.Frame{}, err } - return painter.repaint() + return painter.repaint(frametrace.Menu) } func (painter *painter) readClipboardText() (string, error) { diff --git a/app/titlebar_insets_test.go b/app/titlebar_insets_test.go index a0121a5e4..35cb55ab0 100644 --- a/app/titlebar_insets_test.go +++ b/app/titlebar_insets_test.go @@ -6,6 +6,7 @@ import ( "testing" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/frametrace" ) // The page reads how much of its titlebar strip the window buttons cover from @@ -19,7 +20,7 @@ func TestTitlebarInsetsFollowTheWindow(t *testing.T) { config.Paint = func(canvas *gfx.Canvas, size gfx.Size) { leading, trailing = canvas.TitlebarInsets() } painter := newTestPainter(t, &canvas, config) painter.fullscreenHandler(nil)(fullscreen) - if _, err := painter.repaint(); err != nil { + if _, err := painter.repaint(frametrace.Invalidate); err != nil { t.Fatal(err) } return leading, trailing diff --git a/app/touch.go b/app/touch.go index 20fa2e06a..2c857b84f 100644 --- a/app/touch.go +++ b/app/touch.go @@ -2,6 +2,7 @@ package app import ( "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/frametrace" "github.com/vivaui/viva/internal/input" "github.com/vivaui/viva/internal/interaction" "github.com/vivaui/viva/internal/platform" @@ -122,24 +123,24 @@ func (painter *painter) carryTouch(step interaction.TouchStep) (platform.Frame, t.FlingBlocked() // at the end of what it scrolls step.Wake = false } else if !t.advancing { - frame, err = painter.repaintAfterInput() + frame, err = painter.repaintAfterInput(frametrace.Scroll) } } if step.ScrollEnds { // The finger lifted: content held past an end springs back, and the frames // that does it come from the layout asking for them. if painter.applyScroll(platform.ScrollEvent{Phase: gfx.ScrollPhaseEnd, X: step.ScrollAtX, Y: step.ScrollAtY}) && !t.advancing { - frame, err = painter.repaintAfterInput() + frame, err = painter.repaintAfterInput(frametrace.Scroll) } } if step.Pinch != interaction.PinchNone { phase := gfx.PinchPhase(step.Pinch) if painter.applyPinch(phase, step.PinchX, step.PinchY, step.PinchScale, step.PinchDelta, t.modifiers) && !t.advancing { - frame, err = painter.repaintAfterInput() + frame, err = painter.repaintAfterInput(frametrace.Scroll) } } if step.Wake && painter.scheduleFrame != nil { - painter.scheduleFrame(step.WakeAfter) + painter.scheduleFrame(step.WakeAfter, frametrace.Pointer) } return frame, err } diff --git a/app/visibility.go b/app/visibility.go index bc7f528e0..eac1b15b8 100644 --- a/app/visibility.go +++ b/app/visibility.go @@ -1,6 +1,9 @@ package app -import "github.com/vivaui/viva/internal/platform" +import ( + "github.com/vivaui/viva/internal/frametrace" + "github.com/vivaui/viva/internal/platform" +) // visibilityGate keeps a window nobody can see from painting. The platform says when the window // is hidden, minimized, covered or on a desktop that is not showing; while it is, a wake still @@ -18,7 +21,7 @@ type visibilityGate struct { func (gate *visibilityGate) changed(visible bool) { gate.hidden = !visible if visible && gate.missed { - gate.waker.Wake() + gate.waker.WakeFor(frametrace.Visibility) } } diff --git a/app/web.go b/app/web.go index 0d443f710..a1ae14ff3 100644 --- a/app/web.go +++ b/app/web.go @@ -9,6 +9,7 @@ import ( "sync/atomic" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/frametrace" "github.com/vivaui/viva/internal/platform" ) @@ -72,7 +73,7 @@ func (host *WebHost) repaintWith(painter *painter) { if host != nil { host.repaint = func() { if painter.scheduleFrame != nil { - painter.scheduleFrame(0) + painter.scheduleFrame(0, frametrace.Invalidate) } } } diff --git a/app/web_test.go b/app/web_test.go index 0f9b17c2e..a6d9a08f9 100644 --- a/app/web_test.go +++ b/app/web_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/frametrace" "github.com/vivaui/viva/internal/platform" ) @@ -22,22 +23,22 @@ func TestNativeViewsReachThePlatformWhenTheyChange(t *testing.T) { } }} painter := newTestPainter(t, &canvas, config) - frame, err := painter.repaint() + frame, err := painter.repaint(frametrace.Invalidate) if err != nil || frame.NativeViews != nil { t.Fatalf("with no view: %+v, %v", frame.NativeViews, err) } declare = true - if frame, err = painter.repaint(); err != nil { + if frame, err = painter.repaint(frametrace.Invalidate); err != nil { t.Fatal(err) } if len(frame.NativeViews) != 1 || frame.NativeViews[0].ID != 4 || frame.NativeViews[0].Bounds.Width != 140 { t.Fatalf("declared view = %+v, want id 4 cut to the clip", frame.NativeViews) } - if frame, err = painter.repaint(); err != nil || frame.NativeViews != nil { + if frame, err = painter.repaint(frametrace.Invalidate); err != nil || frame.NativeViews != nil { t.Fatalf("an unchanged view was sent again: %+v, %v", frame.NativeViews, err) } declare = false - if frame, err = painter.repaint(); err != nil { + if frame, err = painter.repaint(frametrace.Invalidate); err != nil { t.Fatal(err) } if frame.NativeViews == nil || len(frame.NativeViews) != 0 { diff --git a/app/window_controls_test.go b/app/window_controls_test.go index a380350d0..cc06c556b 100644 --- a/app/window_controls_test.go +++ b/app/window_controls_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/frametrace" "github.com/vivaui/viva/internal/platform" ) @@ -44,7 +45,7 @@ func newControlsFixture(t testing.TB, mutate func(*Config)) *controlsFixture { actions.ToggleMaximize = func() { fixture.toggles++; fixture.maximized = !fixture.maximized } actions.RequestClose = func() { fixture.shut++ } actions.Maximized = func() bool { return fixture.maximized } - if _, err := painter.repaint(); err != nil { + if _, err := painter.repaint(frametrace.Invalidate); err != nil { t.Fatal(err) } fixture.painter = painter @@ -132,7 +133,7 @@ func TestMaximizeButtonShowsTheOppositeActionAndFollowsTheWindowState(t *testing } idle := len(fixture.canvas.Triangles()) + len(fixture.canvas.Rectangles()) fixture.maximized = true - if _, err := fixture.painter.repaint(); err != nil { + if _, err := fixture.painter.repaint(frametrace.Invalidate); err != nil { t.Fatal(err) } if hit, _ := fixture.hit(windowControlMaximize); hit.Label != "Restore" { @@ -216,7 +217,7 @@ func TestDesktopThemeStyling(t *testing.T) { // Adwaita theme produces circular rounded buttons. fixture.painter.controls.theme = desktopAdwaita - if _, err := fixture.painter.repaint(); err != nil { + if _, err := fixture.painter.repaint(frametrace.Invalidate); err != nil { t.Fatal(err) } var adwaitaRect *gfx.Rectangle @@ -233,7 +234,7 @@ func TestDesktopThemeStyling(t *testing.T) { // Breeze theme also produces circular rounded buttons. fixture.painter.controls.theme = desktopBreeze - if _, err := fixture.painter.repaint(); err != nil { + if _, err := fixture.painter.repaint(frametrace.Invalidate); err != nil { t.Fatal(err) } var breezeRect *gfx.Rectangle @@ -276,7 +277,7 @@ func TestWindowControlsStyleIsReadAtEveryPaintAndDefaultsFollowTheClearColor(t * t.Fatalf("glyph color = %+v, want the first style", got) } dark = false - if _, err := fixture.painter.repaint(); err != nil { + if _, err := fixture.painter.repaint(frametrace.Invalidate); err != nil { t.Fatal(err) } if got := glyphColor(); got.Blue != 1 { @@ -349,7 +350,7 @@ func TestWindowActionsExistOnlyWhereVivaDrawsTheButtons(t *testing.T) { func TestSteadyStatePaintOfTheWindowButtonsDoesNotAllocate(t *testing.T) { fixture := newControlsFixture(t, nil) - if _, err := fixture.painter.repaint(); err != nil { + if _, err := fixture.painter.repaint(frametrace.Invalidate); err != nil { t.Fatal(err) } allocations := testing.AllocsPerRun(200, func() { diff --git a/base/accessors.go b/base/accessors.go index 8d0ceca05..1c5219b6e 100644 --- a/base/accessors.go +++ b/base/accessors.go @@ -880,6 +880,11 @@ func (x *Page) GetShortcutRoute() func(*Page, gfx.KeyEvent) (gfx.EventResult, bo return x.shortcutRoute } +// GetPointerShortcutRoute reads the pointerShortcutRoute of Page for the styled painting layer. +func (x *Page) GetPointerShortcutRoute() func(*Page, gfx.PointerEvent) (gfx.EventResult, bool) { + return x.pointerShortcutRoute +} + // GetShortcuts reads the shortcuts of Page for the styled painting layer. func (x *Page) GetShortcuts() []shortcutEntry { return x.shortcuts } @@ -1232,9 +1237,6 @@ func (x *TableState) GetRows() int32 { return x.rows } // GetScope reads the scope of TableState for the styled painting layer. func (x *TableState) GetScope() gfx.Scope { return x.scope } -// GetSelected reads the selected of TableState for the styled painting layer. -func (x *TableState) GetSelected() int32 { return x.selected } - // GetSortColumn reads the sortColumn of TableState for the styled painting layer. func (x *TableState) GetSortColumn() int32 { return x.sortColumn } @@ -1672,9 +1674,6 @@ func (x *listInternals) GetScope() gfx.Scope { return x.scope } // GetScrollX reads the scrollX of listInternals for the styled painting layer. func (x *listInternals) GetScrollX() float32 { return x.scrollX } -// GetSelected reads the selected of listInternals for the styled painting layer. -func (x *listInternals) GetSelected() int32 { return x.selected } - // GetSubmitted reads the submitted of listInternals for the styled painting layer. func (x *listInternals) GetSubmitted() bool { return x.submitted } @@ -1882,6 +1881,9 @@ func (x *segmented) GetOptions() []style.SegmentOption { return x.options } // GetSelected reads the selected of segmented for the styled painting layer. func (x *segmented) GetSelected() gfx.ID { return x.selected } +// GetButton reads the button of shortcutEntry for the styled painting layer. +func (x *shortcutEntry) GetButton() gfx.PointerButton { return x.button } + // GetChar reads the char of shortcutEntry for the styled painting layer. func (x *shortcutEntry) GetChar() byte { return x.char } diff --git a/base/attrcheck_dev.go b/base/attrcheck_dev.go index 5b552a2d2..4505f00d5 100644 --- a/base/attrcheck_dev.go +++ b/base/attrcheck_dev.go @@ -433,7 +433,6 @@ func (f *Frame) checkWidgetAttributes(n *Node, name string) { rejectChildren() rejectVariant() rejectSize() - rejectLabel() rejectDisabled() case kindInputGroup: rejectPad() diff --git a/base/box.go b/base/box.go index 2c7eb2da8..9e5d27242 100644 --- a/base/box.go +++ b/base/box.go @@ -85,10 +85,15 @@ func (b Box) Clicked() bool { } // Hit makes the element's whole rectangle a pointer target named id, with the -// accessibility label given, so a row or a card can be clicked or hovered. +// accessibility label given, so a row or a card can be clicked or hovered. On a +// Splitter it renames the divider, and the arrow keys of the focused divider +// follow the new name. func (b Box) Hit(ID gfx.ID, Label string) Box { n := b.N() n.ID, n.Label = ID, Label + if n.Kind == kindSplitter { + WidgetsOf(b.f).splits[n.Aux].state.ID = ID + } n.Flags = n.Flags&^flagLabelFor | flagHasHit n.markAttr(attrHit) return b diff --git a/base/control.go b/base/control.go index 81f20a51f..c066535a8 100644 --- a/base/control.go +++ b/base/control.go @@ -20,6 +20,8 @@ type Handlers struct { // control for. Zero is a group. RoleTextField or RoleTerminal make it a target // of typing, given to Text. Role gfx.Role + // TextSelection is the selected output of a RoleTerminal control. + TextSelection *gfx.TextSelection // Cursor is the pointer shown over the control while the pointer is over // it, and while a press it took is still held. Zero is the platform's // arrow; a control of text the user selects, such as an editor or a @@ -90,7 +92,7 @@ func Control(c C, Label string, h *Handlers) Box { } theme := &c.f.Palette // What the text service is given when Text leaves it unset: the page's body text. - return c.f.Slot().HitWith(id, Label, gfx.HitOptions{Role: role, Cursor: h.Cursor, + return c.f.Slot().HitWith(id, Label, gfx.HitOptions{Role: role, Cursor: h.Cursor, TextSelection: h.TextSelection, TextSize: theme.Metrics.FontSizeM, TextColor: theme.Foreground}) } diff --git a/base/drawer.go b/base/drawer.go index bb1271b42..ddef7e3df 100644 --- a/base/drawer.go +++ b/base/drawer.go @@ -197,7 +197,9 @@ type drawerState struct { // drawer declares a Drawer's root: an element over the whole frame holding the // body and footer at the rectangles components.Drawer gives them. The drawer -// itself covers the frame less its spec's Inset. +// itself covers the frame less its spec's Inset; under a custom titlebar its +// header starts below the strip the window buttons cover (see +// components.DrawerOptions.HeaderInset). func (f *Frame) Drawer(spec DrawerDeclaration, footer bool) Box { layer := f.WidgetLayer() + 2 viewport := f.bounds.Inset(spec.Inset) diff --git a/base/elements.go b/base/elements.go index 660163446..41c38b68c 100644 --- a/base/elements.go +++ b/base/elements.go @@ -257,9 +257,11 @@ func Splitter(c C, state *SplitterState) Box { // Table is a Table; its Rows and Header scopes are made from state when spec leaves // them zero. It is a whole control as declared: the page gives it the keys that -// move its selection (TableState.Key), a click on a row selects that row as a -// List's does, TableState.Changed reports either in the paint that delivers it, -// and a table none of whose columns has a width shares its width between them. +// move its selection (TableState.Key) and Primary+A, a click on a row selects +// that row as a List's does (and, with TableState.Selection, extends or toggles +// the choice with Shift or Primary), TableState.Changed reports any of them in +// the paint that delivers it, and a table none of whose columns has a width +// shares its width between them. func Table(c C, state *TableState, spec TableSpec) Box { p := c.page if spec.Rows == 0 || spec.Header == 0 { @@ -274,12 +276,19 @@ func Table(c C, state *TableState, spec TableSpec) Box { if p.tableKeyRoute == nil { p.keyRoute, p.tableKeyRoute = (*Page).RouteKey, (*Page).tableKey } + if p.typeRoute == nil { + p.typeRoute = (*Page).TypeKey // Primary+A, offered as a shortcut + } if state.changedAt != p.epoch { state.changed = false } b := c.f.Table(state, spec) + if state.ticked { + state.markChanged(p.epoch) + } if row, ok := b.RowClicked(); ok { - state.choose(row, p.epoch) + info, _ := c.f.Surface.ClickInfo() + state.click(row, info.Modifiers, p.epoch) } return b } diff --git a/base/leaves_test.go b/base/leaves_test.go index b80931300..bd26ed3d6 100644 --- a/base/leaves_test.go +++ b/base/leaves_test.go @@ -175,6 +175,29 @@ func TestSplitterRatioPlacesTheFirstPaneOnTheFirstLayout(t *testing.T) { } } +// A divider renamed with Hit takes its arrow keys under the new name, and no +// longer under the one the splitter was declared with. +func TestARenamedSplitterTakesItsArrowKeysUnderTheNewName(t *testing.T) { + var view View + state := SplitterState{Pos: 200} + canvas := testCanvas() + renamed := gfx.Item(77) + view.Draw(canvas, gfx.LightTheme(), gfx.Rect{Width: 400, Height: 100}, func(f *Frame) { + f.Row().Fill().Children(func() { + f.Column().Width(state.Pos).Children(func() { f.Text("left") }) + f.Splitter(splitID, &state).Mins(100, 150).Hit(renamed, "Resize") + f.Column().Grow(1).Children(func() { f.Text("right") }) + }) + }) + if got := state.Key(gfx.KeyEvent{Key: gfx.KeyRight, Target: splitID}); got.Handled { + t.Error("the divider still took keys under its declared name") + } + before := state.Pos + if got := state.Key(gfx.KeyEvent{Key: gfx.KeyRight, Target: renamed}); !got.Handled || state.Pos != before+splitterStep { + t.Errorf("Right under the new name: handled=%v pos=%v, want %v", got.Handled, state.Pos, before+splitterStep) + } +} + func TestSplitterKeepsItsPositionInRangeWhenTheWindowShrinksAndTakesArrowKeys(t *testing.T) { var view View state := SplitterState{Pos: 300} diff --git a/base/list.go b/base/list.go index 069fe9fc6..89cf3179d 100644 --- a/base/list.go +++ b/base/list.go @@ -3,12 +3,10 @@ package base import ( "math" "runtime" - "strings" "time" "unsafe" "github.com/vivaui/viva/gfx" - "github.com/vivaui/viva/keymap" ) // ListState is what a List knows of its rows between paints: the height of each row @@ -91,9 +89,7 @@ type listInternals struct { n int scope gfx.Scope // the list's place in the page rows gfx.Scope // the identities of its rows, rows.At(key) - selected int32 // 1 + the row the keys are on, or 0 - Anchor int32 // 1 + the row a Shift range starts at, or 0 - Span int32 // where the last Shift range ended, from the anchor + choice rowChoice // the row the keys are on, and the anchor of a Shift range changed bool changedAt uint32 // the paint Changed is reported in submitted bool @@ -121,6 +117,12 @@ type listInternals struct { scrollX float32 // how far the rows are scrolled sideways, as the user left it View Rect // the area as painted, for the drag and the width of the rows drag listDrag + // anchorRow is 1 + the row at the top of the viewport in the last paint, or 0, and + // anchorAt where that paint chose the offset for it to start. Measuring rows above it + // changes where the list computes it to start; the next paint moves the offset by + // as much, so what the user is reading stays where it was (see keepAnchor). + anchorRow int32 + anchorAt float32 } // listDeclRow is a row a List or a Tree declared in the last paint: its element @@ -169,27 +171,26 @@ const ( ) // Selected is the row the user chose last, or the keys are on, or -1. -func (s *ListState) Selected() int { return int(s.list.selected) - 1 } +func (s *ListState) Selected() int { return s.list.choice.Selected() } -// Select chooses row as if the user had clicked it without a modifier; a negative -// row clears the choice. It does not report Changed, and it scrolls nothing: see +// Select makes row the selected row, where the keys move from and a Shift range +// starts; a negative row clears it. It leaves the Selection of a list that +// chooses several to the application, selecting the row it is on already +// changes nothing, it does not report Changed, and it scrolls nothing: see // ScrollIntoView. func (s *ListState) Select(row int) { - row = min(max(row, -1), max(s.list.n-1, -1)) - s.list.selected = int32(row + 1) - s.list.Anchor, s.list.Span = s.list.selected, 0 + s.list.choice.set(min(max(row, -1), max(s.list.n-1, -1))) +} + +// choiceRows is what the list's choice is made over. +func (s *ListState) choiceRows() choiceRows { + return choiceRows{n: s.list.n, selection: s.Selection, key: s.Key, header: s.Header} } // Chosen reports whether row is in the choice: in the Selection when the list has // one, else the selected row. func (s *ListState) Chosen(row int) bool { - if row < 0 || row >= s.list.n { - return false - } - if s.Selection != nil { - return s.Selection.Has(s.key(row)) - } - return s.Selected() == row + return s.list.choice.chosen(s.choiceRows(), row) } // Changed reports whether the paint that declared the list delivered a choice the @@ -266,15 +267,7 @@ func (s *ListState) AtEnd() bool { // one identity and a click on any of them would reach them all. A paint asks it of // every row it declares, so it stays within the inliner's budget, which a message // naming the key would exceed. -func (s *ListState) key(i int) int { - if s.Key != nil { - i = s.Key(i) - } - if uint(i) > math.MaxInt32 { - panic("ui: a List row's key is outside 0 to 2^31-1, the numbers gfx.Index names; give ListState.Key the items' numbers, not hashes") - } - return i -} +func (s *ListState) key(i int) int { return rowKey(s.Key, i) } // markChanged records a choice the user made in epoch, the paint its reader sees // it in. @@ -289,77 +282,15 @@ func (s *ListState) submit(row int, epoch uint32) { // chooseRow makes row the choice, alone, and shows it. func (s *ListState) chooseRow(row int, epoch uint32) { - if s.Selection != nil { - k := s.key(row) - if s.Selection.Len() != 1 || !s.Selection.Has(k) { - s.Selection.Clear() - s.Selection.Add(k) - s.markChanged(epoch) - } - } - if s.Selected() != row { - s.list.selected = int32(row + 1) + if s.list.choice.choose(s.choiceRows(), row) { s.markChanged(epoch) } - s.list.Anchor, s.list.Span = int32(row+1), 0 s.revealRow(row) } // toggleRow adds row to the choice or takes it out, and shows it. func (s *ListState) toggleRow(row int, epoch uint32) { - s.Selection.set(s.key(row), !s.Selection.Has(s.key(row))) - s.markChanged(epoch) - s.list.selected = int32(row + 1) - s.list.Anchor, s.list.Span = int32(row+1), 0 - s.revealRow(row) -} - -// extendRow chooses the rows from the anchor to row, as Shift does: on macOS in -// place of those it chose last, elsewhere in place of all others unless keep. -func (s *ListState) extendRow(row int, keep bool, epoch uint32) { - sel := s.Selection - pivot := int(s.list.Anchor) - 1 - if pivot < 0 || pivot >= s.list.n { - s.chooseRow(row, epoch) - return - } - lo, hi := min(pivot, row), max(pivot, row) - changed := false - if runtime.GOOS == "darwin" { - last := min(max(pivot+int(s.list.Span), 0), s.list.n-1) - for j := min(pivot, last); j <= max(pivot, last); j++ { - if (j < lo || j > hi) && !s.isHeader(j) && sel.set(s.key(j), false) { - changed = true - } - } - } else if !keep { - in := 0 - for j := lo; j <= hi; j++ { - if !s.isHeader(j) && sel.Has(s.key(j)) { - in++ - } - } - if sel.Len() > in { - sel.Clear() - changed = true - } - } - for j := lo; j <= hi; j++ { - if !s.isHeader(j) && sel.set(s.key(j), true) { - changed = true - } - } - if changed { - s.markChanged(epoch) - } - s.list.Span = int32(row - pivot) - s.leadRow(row, epoch) -} - -// leadRow makes row the one the keys move from, without choosing it. -func (s *ListState) leadRow(row int, epoch uint32) { - if s.Selected() != row { - s.list.selected = int32(row + 1) + if s.list.choice.toggle(s.choiceRows(), row) { s.markChanged(epoch) } s.revealRow(row) @@ -367,12 +298,7 @@ func (s *ListState) leadRow(row int, epoch uint32) { // selectAll chooses every row, and reports whether that changed the choice. func (s *ListState) selectAll(epoch uint32) bool { - changed := false - for i := 0; i < s.list.n; i++ { - if !s.isHeader(i) && s.Selection.set(s.key(i), true) { - changed = true - } - } + changed := s.list.choice.selectAll(s.choiceRows()) if changed { s.markChanged(epoch) } @@ -610,6 +536,23 @@ func (s *ListState) afterLayout() { } } +// keepAnchor moves the offset by as much as the row at the top of the viewport in the +// last paint moved in content space since: rows above it measured at other heights +// than the list estimated, or the estimate of the rows still unmeasured changing with +// them. Without it, a wheel that brings rows in from above (a log opened at its end +// and read upward) makes the rows on screen jump by the difference, sometimes by +// more than the viewport. A scroll by the wheel or the keys between the paints moved +// the offset itself and stays in it. A request to scroll (ScrollTo) places the offset +// where it asks instead, and a scrollbar drag puts it under the pointer. +func (s *ListState) keepAnchor(scroll *ScrollState) { + in := &s.list + row := int(in.anchorRow) - 1 + if row < 0 || row >= in.n || in.pending != listScrollNone || scroll.Dragging() { + return + } + scroll.Offset += s.top(row) - in.anchorAt +} + // scrollTarget is where the request kind puts row as the list knows the heights now: // the offset to scroll to, and whether the end of the content is what it scrolls to, // which only a layout can place. @@ -784,6 +727,9 @@ type listDecl struct { rows, until int32 // the List's rows in Page.listRows pinned int32 // the element of the pinned header, or -1 pinnedRow int + anchor int // the row at the top of the viewport, or -1 when the list does not keep one + anchorAt float32 // where the offset was chosen for the anchor to start, in content space + spacer float32 // the height above the first row declared: where the list placed it } // listOverscan is how many rows a List declares beyond what is visible each way, so @@ -845,12 +791,7 @@ func List(c C, state *ListState, n int, row func(ListRow)) Box { in := &state.list in.n, in.f = n, c.f in.declared = in.declared[:0] - if int(in.selected) > n { - in.selected = 0 - } - if int(in.Anchor) > n { - in.Anchor = 0 - } + in.choice.clamp(n) if in.changedAt != p.epoch { in.changed = false } @@ -939,24 +880,30 @@ func (p *Page) ListArea(c C, state *ListState, n int, horizontal bool, row func( if viewport <= 0 { viewport = c.f.bounds.Height } - if pinned || scroll.pinned() { + atEnd := pinned || scroll.pinned() + if atEnd { // The layout puts the area at its end, which the rows that arrived since the // last paint moved: the rows are placed for that end, not for the offset the // area had, which would leave the paint that adds them blank. scroll.Offset = max(state.top(n)-viewport, 0) } else { + state.keepAnchor(scroll) // Measuring the previous paint can shorten the estimated content. Choose // rows against that extent before layout clamps the old offset; otherwise // the rows declared at the old end are outside the new viewport. scroll.Offset = min(max(scroll.Offset, 0), max(state.top(n)-viewport, 0)) } + in.anchorRow = 0 // The rows are placed and hit-tested on whole logical pixels, as the layout // applies them, so a label's native texture survives a fractional scroll. offset := snapScroll(scroll.Offset) c.f.Nodes[area.i].Scroll = offset first := max(state.rowAt(offset)-listOverscan, 0) + anchor := -1 if in.n == 0 { first = 0 + } else if !atEnd { + anchor = min(state.rowAt(offset), in.n-1) } bottom := offset + viewport last := first @@ -1034,7 +981,8 @@ func (p *Page) ListArea(c C, state *ListState, n int, horizontal bool, row func( } }) in.pinned, in.pinnedRow = pinnedNode, pin - p.lists = append(p.lists, listDecl{state: state, First: first, rows: int32(start), until: int32(len(p.listRows)), pinned: pinnedNode, pinnedRow: pin}) + p.lists = append(p.lists, listDecl{state: state, First: first, rows: int32(start), until: int32(len(p.listRows)), pinned: pinnedNode, pinnedRow: pin, + anchor: anchor, anchorAt: state.top(max(anchor, 0)), spacer: state.top(first)}) return area } @@ -1051,7 +999,7 @@ func listRowBox(c C, horizontal bool) Box { // first one shown that is not a header. func (s *ListState) tabRow() int { in := &s.list - if cur := int(in.selected) - 1; cur >= in.First && cur <= in.Last && !s.isHeader(cur) { + if cur := in.choice.Selected(); cur >= in.First && cur <= in.Last && !s.isHeader(cur) { return cur } for i := in.First; i <= in.Last; i++ { @@ -1121,42 +1069,10 @@ func (s *ListState) clickRow(p *Page, row int, info gfx.ClickInfo) { if info.DoubleClick() { s.submit(row, epoch) } - switch { - case s.Selection == nil: - s.chooseRow(row, epoch) - case info.Modifiers&gfx.ModifierShift != 0: - s.extendRow(row, info.Modifiers&keymap.Primary != 0, epoch) - case info.Modifiers&keymap.Primary != 0: - s.toggleRow(row, epoch) - default: - s.chooseRow(row, epoch) - } -} - -// listMove is how a key moves the choice: choosing the row it reaches, extending -// from the anchor with Shift, or moving the keys' row without choosing with Primary -// in a list that chooses several. -type listMove uint8 - -const ( - listChoose listMove = iota + 1 - listExtend - listCursor -) - -// moveOf says how event moves the choice, if it is a key that does. -func moveOf(event gfx.KeyEvent, multi bool) (listMove, bool) { - switch event.Modifiers { - case 0: - return listChoose, true - case gfx.ModifierShift: - return listExtend, true - case keymap.Primary: - if multi { - return listCursor, true - } + if s.list.choice.click(s.choiceRows(), row, info.Modifiers) { + s.markChanged(epoch) } - return 0, false + s.revealRow(row) } // listKey moves through a List from the row that has the focus: the arrows and @@ -1246,13 +1162,8 @@ func (p *Page) ListKey(event gfx.KeyEvent) (gfx.EventResult, bool) { target = row } } - switch how { - case listChoose: - s.chooseRow(target, p.epoch+1) - case listExtend: - s.extendRow(target, false, p.epoch+1) - case listCursor: - s.leadRow(target, p.epoch+1) + if s.list.choice.move(s.choiceRows(), how, target) { + s.markChanged(p.epoch + 1) } s.revealRow(target) return listFocus(s, target), true @@ -1306,12 +1217,16 @@ func listFocus(s *ListState, row int) gfx.EventResult { } // typeKey is the OnShortcut handler for printable keys no field is typing in: an -// open Menu's typeahead, then a Tree's, then a List's and its Primary+A. +// open Menu's typeahead, then a Tree's, then a List's and its Primary+A, then a +// Table's Primary+A. func (p *Page) TypeKey(event gfx.KeyEvent) (gfx.EventResult, bool) { if result, ok := p.TreeType(event); ok { return result, true } - return p.ListType(event) + if result, ok := p.ListType(event); ok { + return result, true + } + return p.tableType(event) } // rowSlotHeight is the room a row takes in the list: its rectangle and the @@ -1326,8 +1241,23 @@ func rowSlotHeight(node *Node) float32 { // measureLists records the heights the layout gave the rows the Lists declared. func (p *Page) measureLists() { for _, list := range p.lists { + in := &list.state.list + at := list.spacer // where the layout placed each row, from the first declared for k, node := range p.listRows[list.rows:list.until] { - list.state.measured(list.First+k, rowSlotHeight(&p.ctx.f.Nodes[node])) + h := rowSlotHeight(&p.ctx.f.Nodes[node]) + if list.First+k == list.anchor { + // The paint after this one keeps the anchor where the offset was chosen + // for it, not where the rows above it measured in this paint put it. + in.anchorRow, in.anchorAt = int32(list.anchor+1), list.anchorAt + if moved := at - list.anchorAt; moved > 0.5 || moved < -0.5 { + // Rows declared above it to fill the overscan measured at other + // heights than estimated, so this paint shows it moved: paint + // again with the offset kept rather than show that for a frame. + p.retry = true + } + } + at += h + list.state.measured(list.First+k, h) } if list.pinned >= 0 { list.state.measured(list.pinnedRow, rowSlotHeight(&p.ctx.f.Nodes[list.pinned])) @@ -1355,7 +1285,7 @@ func (p *Page) ListType(event gfx.KeyEvent) (gfx.EventResult, bool) { continue } epoch := p.epoch + 1 - if s.Selection != nil && event.Modifiers == keymap.Primary && strings.EqualFold(text, "a") { + if s.Selection != nil && isSelectAll(event) { s.selectAll(epoch) return gfx.EventResult{Handled: true, Repaint: true}, true } diff --git a/base/page.go b/base/page.go index 9fe13af7e..e752e7635 100644 --- a/base/page.go +++ b/base/page.go @@ -39,6 +39,7 @@ import ( "unsafe" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/frametrace" "github.com/vivaui/viva/window" ) @@ -356,20 +357,22 @@ type Page struct { pointerRoute func(*Page, gfx.PointerEvent) (gfx.EventResult, bool) areaKey func(*Field, gfx.KeyEvent) gfx.EventResult shortcutRoute func(*Page, gfx.KeyEvent) (gfx.EventResult, bool) - menuRoute func(*Page, gfx.KeyEvent) (gfx.EventResult, bool) - roveRoute func(*Page, gfx.KeyEvent) (gfx.EventResult, bool) // arrow keys in a Choice or Tabs - groupRoute func(*Page, gfx.KeyEvent) (gfx.EventResult, bool) // arrow keys in a FocusGroup - sliderRoute func(*Page, gfx.KeyEvent) (gfx.EventResult, bool) // the keys of a Slider - splitRoute func(*Page, gfx.KeyEvent) (gfx.EventResult, bool) // the keys of a Splitter - tableKeyRoute func(*Page, gfx.KeyEvent) (gfx.EventResult, bool) // moves the selection of a Table - selectRoute func(*Page, gfx.KeyEvent) (gfx.EventResult, bool) // opens and moves the list of a Select - comboRoute func(*Page, gfx.KeyEvent) (gfx.EventResult, bool) - treeRoute func(*Page, gfx.KeyEvent) (gfx.EventResult, bool) - listRoute func(*Page, gfx.KeyEvent) (gfx.EventResult, bool) // moves and chooses rows of a List - wheelXRoute func(*Page, gfx.ScrollEvent) (moved, only bool) // the sideways wheel of a List with RowWidth - typeRoute func(*Page, gfx.KeyEvent) (gfx.EventResult, bool) // a Tree's typeahead, from OnShortcut - wheelRoute func(*Page, gfx.ScrollEvent) (gfx.EventResult, bool) - textRoute func(*Page, gfx.ID) *window.TextInput + // pointerShortcutRoute is set by the first mouse button's Shortcut. + pointerShortcutRoute func(*Page, gfx.PointerEvent) (gfx.EventResult, bool) + menuRoute func(*Page, gfx.KeyEvent) (gfx.EventResult, bool) + roveRoute func(*Page, gfx.KeyEvent) (gfx.EventResult, bool) // arrow keys in a Choice or Tabs + groupRoute func(*Page, gfx.KeyEvent) (gfx.EventResult, bool) // arrow keys in a FocusGroup + sliderRoute func(*Page, gfx.KeyEvent) (gfx.EventResult, bool) // the keys of a Slider + splitRoute func(*Page, gfx.KeyEvent) (gfx.EventResult, bool) // the keys of a Splitter + tableKeyRoute func(*Page, gfx.KeyEvent) (gfx.EventResult, bool) // moves the selection of a Table + selectRoute func(*Page, gfx.KeyEvent) (gfx.EventResult, bool) // opens and moves the list of a Select + comboRoute func(*Page, gfx.KeyEvent) (gfx.EventResult, bool) + treeRoute func(*Page, gfx.KeyEvent) (gfx.EventResult, bool) + listRoute func(*Page, gfx.KeyEvent) (gfx.EventResult, bool) // moves and chooses rows of a List + wheelXRoute func(*Page, gfx.ScrollEvent) (moved, only bool) // the sideways wheel of a List with RowWidth + typeRoute func(*Page, gfx.KeyEvent) (gfx.EventResult, bool) // a Tree's typeahead, from OnShortcut + wheelRoute func(*Page, gfx.ScrollEvent) (gfx.EventResult, bool) + textRoute func(*Page, gfx.ID) *window.TextInput } // protoNode is a container of the frame: where it is named (in the container at @@ -630,6 +633,8 @@ func (p *Page) onPointer(event gfx.PointerEvent) gfx.EventResult { var result gfx.EventResult if done, ok := p.dropPointer(event); ok { result = done + } else if done, ok := p.routePointerShortcut(event); ok { + result = done } else if p.pointerRoute != nil { if routed, ok := p.pointerRoute(p, event); ok { result = routed @@ -644,6 +649,15 @@ func (p *Page) onPointer(event gfx.PointerEvent) gfx.EventResult { return result } +// routePointerShortcut gives a press of a mouse button to the Shortcut it makes, +// before the element under the pointer has it. +func (p *Page) routePointerShortcut(event gfx.PointerEvent) (gfx.EventResult, bool) { + if p.pointerShortcutRoute == nil { + return gfx.EventResult{}, false + } + return p.pointerShortcutRoute(p, event) +} + // hoverPlaceAt names the innermost scroll area or self-scrolling table under a // point; the zero ID means none. func (p *Page) hoverPlaceAt(x, y float32) gfx.ID { @@ -829,6 +843,7 @@ func (p *Page) Draw(Surface *gfx.Canvas, bounds Rect, View func(C)) { if !p.retry || try > 0 || !Surface.Rewind(start) { break } + frametrace.Retry() } p.retry = false p.settleHeld() diff --git a/base/rowchoice.go b/base/rowchoice.go new file mode 100644 index 000000000..64cacbbd5 --- /dev/null +++ b/base/rowchoice.go @@ -0,0 +1,238 @@ +package base + +import ( + "math" + "runtime" + "strings" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/keymap" +) + +// rowChoice is the choice of rows a List and a Table share: the row the keys are +// on and, in one that lets the user choose several (a Selection), where a Shift +// range starts and how far the last one reached. Both widgets keep one, so a click, +// a Shift or Primary click, the keys that move and Primary+A choose the same way in +// either, as the platform's own lists and tables do. +type rowChoice struct { + selected int32 // 1 + the row the keys are on, or 0 + anchor int32 // 1 + the row a Shift range starts at, or 0 + span int32 // where the last Shift range ended, from the anchor +} + +// choiceRows is what a choice is made over in one paint: how many rows, the +// Selection when several can be chosen, how a row is keyed in it (nil: by its +// index) and which rows head a section and are never chosen (nil: none). +type choiceRows struct { + n int + selection *Selection + key func(int) int + header func(int) bool +} + +// rowKey is row i's key given a Key function: its index without one. A key +// outside 0 to 2^31-1 panics: gfx.Index names every such number as it names item +// 0, so those rows would share one identity and a click on any of them would +// reach them all. +func rowKey(key func(int) int, i int) int { + if key != nil { + i = key(i) + } + if uint(i) > math.MaxInt32 { + panic("ui: a row's key is outside 0 to 2^31-1, the numbers gfx.Index names; give ListState.Key the items' numbers, not hashes") + } + return i +} + +func (rows choiceRows) keyOf(i int) int { return rowKey(rows.key, i) } + +func (rows choiceRows) isHeader(i int) bool { + return rows.header != nil && i >= 0 && i < rows.n && rows.header(i) +} + +// Selected is the row the keys are on, or -1. +func (c *rowChoice) Selected() int { return int(c.selected) - 1 } + +// clamp forgets a row and an anchor past the last of n rows. +func (c *rowChoice) clamp(n int) { + if int(c.selected) > n { + c.selected = 0 + } + if int(c.anchor) > n { + c.anchor = 0 + } +} + +// set makes row the one the keys are on and where a Shift range starts, as the +// program asks; a negative row clears it. Setting the row it is on already +// changes nothing, so an application that hands the widget its own idea of the +// row every paint does not lose the anchor of the range the user is making. +func (c *rowChoice) set(row int) { + selected := int32(max(row, -1) + 1) + if selected == c.selected { + return + } + c.selected = selected + c.anchor, c.span = selected, 0 +} + +// chosen reports whether row is in the choice: in the Selection when there is +// one, else the row the keys are on. +func (c *rowChoice) chosen(rows choiceRows, row int) bool { + if row < 0 || row >= rows.n { + return false + } + if rows.selection != nil { + return rows.selection.Has(rows.keyOf(row)) + } + return c.Selected() == row +} + +// choose makes row the choice, alone, and reports whether that changed anything +// the user would see as their choice. +func (c *rowChoice) choose(rows choiceRows, row int) bool { + changed := false + if sel := rows.selection; sel != nil { + k := rows.keyOf(row) + if sel.Len() != 1 || !sel.Has(k) { + sel.Clear() + sel.Add(k) + changed = true + } + } + if c.Selected() != row { + c.selected = int32(row + 1) + changed = true + } + c.anchor, c.span = int32(row+1), 0 + return changed +} + +// toggle adds row to the Selection or takes it out, and makes it the row the keys +// are on and where the next Shift range starts. It always changes the choice. +func (c *rowChoice) toggle(rows choiceRows, row int) bool { + k := rows.keyOf(row) + rows.selection.set(k, !rows.selection.Has(k)) + c.selected = int32(row + 1) + c.anchor, c.span = int32(row+1), 0 + return true +} + +// extend chooses the rows from the anchor to row, as Shift does: on macOS in +// place of those the last Shift range chose, elsewhere in place of all others +// unless keep (Primary held with Shift). Without a Selection, or without an +// anchor, it chooses row alone, as Shift with a key does in a list that chooses +// one row. +func (c *rowChoice) extend(rows choiceRows, row int, keep bool) bool { + sel := rows.selection + pivot := int(c.anchor) - 1 + if sel == nil || pivot < 0 || pivot >= rows.n { + return c.choose(rows, row) + } + lo, hi := min(pivot, row), max(pivot, row) + changed := false + if runtime.GOOS == "darwin" { + last := min(max(pivot+int(c.span), 0), rows.n-1) + for j := min(pivot, last); j <= max(pivot, last); j++ { + if (j < lo || j > hi) && !rows.isHeader(j) && sel.set(rows.keyOf(j), false) { + changed = true + } + } + } else if !keep { + in := 0 + for j := lo; j <= hi; j++ { + if !rows.isHeader(j) && sel.Has(rows.keyOf(j)) { + in++ + } + } + if sel.Len() > in { + sel.Clear() + changed = true + } + } + for j := lo; j <= hi; j++ { + if !rows.isHeader(j) && sel.set(rows.keyOf(j), true) { + changed = true + } + } + c.span = int32(row - pivot) + return c.lead(row) || changed +} + +// lead makes row the one the keys move from, without choosing it. +func (c *rowChoice) lead(row int) bool { + if c.Selected() == row { + return false + } + c.selected = int32(row + 1) + return true +} + +// selectAll chooses every row, and reports whether that changed the choice. +func (c *rowChoice) selectAll(rows choiceRows) bool { + changed := false + for i := 0; i < rows.n; i++ { + if !rows.isHeader(i) && rows.selection.set(rows.keyOf(i), true) { + changed = true + } + } + return changed +} + +// click chooses row as a click with modifiers does: alone, or, in a choice of +// several, extending from the anchor with Shift (keeping the rest with Primary as +// well, off macOS) or adding or taking out the row with Primary. +func (c *rowChoice) click(rows choiceRows, row int, modifiers gfx.Modifiers) bool { + switch { + case rows.selection == nil: + return c.choose(rows, row) + case modifiers&gfx.ModifierShift != 0: + return c.extend(rows, row, modifiers&keymap.Primary != 0) + case modifiers&keymap.Primary != 0: + return c.toggle(rows, row) + } + return c.choose(rows, row) +} + +// rowMove is how a key moves the choice: choosing the row it reaches, extending +// from the anchor with Shift, or moving the keys' row without choosing with Primary +// in a choice of several. +type rowMove uint8 + +const ( + moveChoose rowMove = iota + 1 + moveExtend + moveCursor +) + +// moveOf says how event moves the choice, if it is a key that does. +func moveOf(event gfx.KeyEvent, multi bool) (rowMove, bool) { + switch event.Modifiers { + case 0: + return moveChoose, true + case gfx.ModifierShift: + return moveExtend, true + case keymap.Primary: + if multi { + return moveCursor, true + } + } + return 0, false +} + +// move moves the choice to target as how says, and reports whether it changed. +func (c *rowChoice) move(rows choiceRows, how rowMove, target int) bool { + switch how { + case moveExtend: + return c.extend(rows, target, false) + case moveCursor: + return c.lead(target) + } + return c.choose(rows, target) +} + +// isSelectAll reports whether event is Primary+A, which chooses every row of a +// choice of several. +func isSelectAll(event gfx.KeyEvent) bool { + return event.Modifiers == keymap.Primary && strings.EqualFold(event.Text, "a") +} diff --git a/base/shortcut.go b/base/shortcut.go index 328b6c0b0..dd8fee224 100644 --- a/base/shortcut.go +++ b/base/shortcut.go @@ -24,16 +24,23 @@ type shortcutEntry struct { modifiers gfx.Modifiers char byte key gfx.Key + button gfx.PointerButton ID gfx.ID focus gfx.ID scope gfx.Scope rows gfx.Scope // a List's or a Tree's rows, which its box's Shortcut also covers + // own is the identity of a container that names a place and has a hit of its + // own, as a tab holding an icon and a close button does: the focus or a press + // on the container itself is on the element, though its identity is not in + // the place it names. + own gfx.ID } // Shortcut reports whether this paint delivers the chord modifiers+key pressed // anywhere in the page: a window's Save or Find, declared next to what it does. -// key is a character ("s", "/") or a key's name ("enter", "escape", "delete", -// "f2", "up"; see keymap.Parse). +// key is a character ("s", "/"), a key's name ("enter", "escape", "delete", +// "f2", "up") or a mouse button's ("mouse_middle", "mouse_back", +// "mouse_forward"; see keymap.Parse). // // if ui.Shortcut(c, ui.Primary, "s") { // m.save() @@ -46,6 +53,11 @@ type shortcutEntry struct { // field, Combobox or terminal being typed in. While an overlay is open , a page-wide Shortcut does not act // (the overlay has the keyboard); Box.Shortcut on an element in it does. Not inside // a Memo. +// +// A mouse button's Shortcut acts on the press of the button, anywhere in the page, +// before the press reaches the element under the pointer: a page-wide +// "mouse_back" goes back wherever the pointer is. While an overlay is open it +// does not act. func Shortcut(c C, modifiers gfx.Modifiers, key string) bool { return c.page.shortcut(c, modifiers, key, gfx.ID{}, 0, 0) } @@ -61,13 +73,20 @@ func Shortcut(c C, modifiers gfx.Modifiers, key string) bool { // if list.Shortcut(0, "delete") { // m.removeSelected() // } +// +// A mouse button's Shortcut on an element acts on a press of the button on the +// element or in it, where the keyboard focus is does not matter: a tab's +// "mouse_middle" closes the tab pressed. It wins over a page-wide one of the same +// chord, and the innermost of nested ones acts. func (b Box) Shortcut(modifiers gfx.Modifiers, key string) bool { p := b.f.page if p == nil { panic("ui: Box.Shortcut needs a page: declare it with a ui.C") } if int(b.i) < len(p.Nodes) && p.Nodes[b.i].named { - return p.shortcut(&p.ctx, modifiers, key, gfx.ID{}, p.resolve(b.i), p.listRowScope(b.i)) + ok := p.shortcut(&p.ctx, modifiers, key, gfx.ID{}, p.resolve(b.i), p.listRowScope(b.i)) + p.shortcuts[len(p.shortcuts)-1].own = b.N().ID + return ok } if id := b.N().ID; !id.IsZero() { return p.shortcut(&p.ctx, modifiers, key, id, 0, 0) @@ -82,8 +101,12 @@ func (p *Page) shortcut(c C, modifiers gfx.Modifiers, key string, focus gfx.ID, panic("ui: Shortcut " + key + ": not a key keymap.Parse names, nor one character") } id := p.ControlID(pkShortcut) - p.shortcuts = append(p.shortcuts, shortcutEntry{modifiers: chord.Modifiers, char: chord.Char, key: chord.Key, ID: id, focus: focus, scope: scope, rows: rows}) - if p.shortcutRoute == nil { + p.shortcuts = append(p.shortcuts, shortcutEntry{modifiers: chord.Modifiers, char: chord.Char, key: chord.Key, button: chord.Button, ID: id, focus: focus, scope: scope, rows: rows}) + if chord.Button != gfx.PointerButtonNone { + if p.pointerShortcutRoute == nil { + p.pointerShortcutRoute = (*Page).matchPointerShortcut + } + } else if p.shortcutRoute == nil { p.keyRoute, p.shortcutRoute = (*Page).RouteKey, (*Page).matchShortcut } return c.f.Surface != nil && c.f.Surface.Clicked(id) @@ -102,14 +125,33 @@ func (p *Page) matchShortcut(event gfx.KeyEvent) (gfx.EventResult, bool) { if chord.Modifiers&(keymap.Primary|gfx.ModifierControl|gfx.ModifierAlt) == 0 && p.typing(event.Target) { return gfx.EventResult{}, false // the key types, or edits, in the field } - target := event.Target - // A page-wide Shortcut acts with the focus in the page, or with none in a window - // the page fills; not while an overlay has the keyboard. + return p.deliverShortcut(chord, event.Target) +} + +// matchPointerShortcut finds the mouse button's Shortcut a press makes where it +// lands, and returns the result that delivers it. +func (p *Page) matchPointerShortcut(event gfx.PointerEvent) (gfx.EventResult, bool) { + if event.Kind != gfx.PointerDown || len(p.shortcuts) == 0 { + return gfx.EventResult{}, false + } + chord, ok := keymap.FromPointer(event) + if !ok { + return gfx.EventResult{}, false + } + return p.deliverShortcut(chord, event.Target) +} + +// deliverShortcut finds the Shortcut of chord nearest target, the focus for a key +// and the element pressed for a mouse button, and returns the result that +// delivers it. +func (p *Page) deliverShortcut(chord keymap.Chord, target gfx.ID) (gfx.EventResult, bool) { + // A page-wide Shortcut acts with the target in the page, or with none in a + // window the page fills; not while an overlay has the keyboard. pageWide := !p.overlay && (p.owns(target) || target.IsZero() && p.window) best := -1 for i := range p.shortcuts { entry := &p.shortcuts[i] - if entry.modifiers != chord.Modifiers || entry.char != chord.Char || entry.key != chord.Key { + if entry.modifiers != chord.Modifiers || entry.char != chord.Char || entry.key != chord.Key || entry.button != chord.Button { continue } switch { @@ -118,7 +160,7 @@ func (p *Page) matchShortcut(event gfx.KeyEvent) (gfx.EventResult, bool) { continue } case entry.scope != 0: - if target.IsZero() || !p.shortcutCovers(entry, target.Scope()) { + if target.IsZero() || target != entry.own && !p.shortcutCovers(entry, target.Scope()) { continue } case !pageWide: diff --git a/base/table.go b/base/table.go index 74f39a681..69c4a0e59 100644 --- a/base/table.go +++ b/base/table.go @@ -2,6 +2,7 @@ package base import ( "math" + "runtime" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/style" @@ -48,14 +49,15 @@ type TableSpec struct { // width still fits. It applies to the preferred width and to painting. FitHeadings bool Source TableSource - // Checked, when set, gives the table a leading column of checkboxes, one for each - // row, and a checkbox in the header that checks or clears every row: the rows - // checked are the keys of the Selection, the application's to read and to change. - // It is separate from the row the user has selected (TableState.Selected), as the - // ticks of a file list are from its highlighted row. The column is not one of - // Columns: the indexes of Source.Cell, Header and TableState.SortBy stay those of - // Columns. - Checked *Selection + // Checkboxes, in a table whose state has a Selection, gives it a leading column + // with a checkbox for each row, ticked while the row is chosen, and one in the + // header that chooses every row or none: the checkboxes show the Selection and + // change it, as a Primary click on the row would, so a ticked row and a chosen + // one are the same thing. Space ticks or unticks the row the keys are on. The + // column is not one of Columns: the indexes of Source.Cell, Header and + // TableState.SortBy stay those of Columns. A table without a Selection has no + // column of checkboxes. + Checkboxes bool // SelectAllLabel and SelectRowLabel are the accessible names of the header's // checkbox and of a row's, "Select all rows" and "Select row" when empty. SelectAllLabel, SelectRowLabel string @@ -121,14 +123,26 @@ type tableRoute struct { // selected row, the sort, and, when the table has a height of its own, how far it is // scrolled. The zero value is a table with nothing selected, unsorted, at the top. type TableState struct { + // Selection, when set, lets the user choose several rows, which it holds by + // their indexes in Source, as a List's Selection does: a click chooses one, + // Primary (Command on macOS, Control elsewhere) with a click adds a row or + // takes it out, Shift with a click or the arrow keys chooses those from the + // row last chosen, and Primary+A chooses all. On Linux and Windows Control + // with the keys moves without choosing, and Control+Space adds the row there + // or takes it out. Selected, set as well, is the row last chosen, where the + // keys move from. The indexes are the rows' places in Source: an application + // that reorders or removes rows moves or takes out the keys with them. Nil, the + // default, chooses one row at a time. + Selection *Selection + // Scroll is the scroll position of a table with a height of its own (a Height, // Fill or Grow that is less than its rows need), and, when its explicit column // widths are wider than it, how far across it is scrolled. Give config.OnScroll // state.Wheel, or call it for the table under the pointer. A table in a // ScrollArea is as tall as its rows, as wide as its area makes it, and needs // none of it. - Scroll ScrollState - selected int32 // 1 + the row, or 0 + Scroll ScrollState + choice rowChoice // the selected row, and where a Shift range starts // changed is a selection the user made, reported by Changed in the paint // changedAt: the one a click is delivered in, or the one after a key. changed bool @@ -138,12 +152,18 @@ type TableState struct { reveal bool // scroll the selected row into view at the next paint rows, page int32 // as of the last paint: how many rows, how many fit at once lead int32 // 1 when the last paint had a column of checkboxes in front - // checkedChanged is whether the paint being declared delivered a tick or untick: - // see CheckedChanged. - checkedChanged bool + // ticked is whether the paint being declared applied a click on one of its + // checkboxes, which the page reports through Changed. + ticked bool // checkDone is the checkbox whose click this paint has already applied, so a // table painted in two passes (frozen columns) applies it once. checkDone gfx.ID + // checkboxes is whether the last paint showed a column of checkboxes, so + // Space ticks the row the keys are on. + checkboxes bool + // tabRows is the identities of the rows and checkboxes of the last paint, to + // make them one stop of Tab. It keeps its capacity across frames. + tabRows []gfx.ID // headerY and headerHeight are where the header was painted last, for HeaderRect. headerY, headerHeight float32 rowFirst, rowEnd int32 // the declared source rows: rowFirst <= i < rowEnd @@ -157,63 +177,123 @@ type TableState struct { cellRowHeight float32 } -// Selected is the selected row, or -1. -func (s *TableState) Selected() int { return int(s.selected) - 1 } +// Selected is the selected row, or -1: in a table with a Selection, the row last +// chosen, where the keys move from. +func (s *TableState) Selected() int { return s.choice.Selected() } + +// Chosen reports whether row is in the choice: in the Selection when the table has +// one, else the selected row. +func (s *TableState) Chosen(row int) bool { return s.choice.chosen(s.choiceRows(), row) } -// Changed reports whether the paint that declared the table delivered a row the -// user chose: a click on a row, or a key that moved the selection. It is true in -// the paint that delivers it, and in the one after a key between paints, and -// false again in the next, as ListState.Changed is. Select by the program does -// not set it. +// Changed reports whether the paint that declared the table delivered a choice the +// user made: a click on a row or a checkbox, a key that moved the selection or +// changed the Selection. It is true in the paint that delivers it, and in the one +// after a key between paints, and false again in the next, as ListState.Changed +// is. Select by the program does not set it. func (s *TableState) Changed() bool { return s.changed } -// choose selects row as the user's choice, reported by Changed in epoch. -func (s *TableState) choose(row int, epoch uint32) { - if s.Selected() != row { - s.changed, s.changedAt = true, epoch +// choiceRows is what the table's choice is made over, as of the last paint. +func (s *TableState) choiceRows() choiceRows { + return choiceRows{n: int(s.rows), selection: s.Selection} +} + +// markChanged records a choice the user made, reported by Changed in epoch. +func (s *TableState) markChanged(epoch uint32) { s.changed, s.changedAt = true, epoch } + +// click chooses row as a click with modifiers does, reported by Changed in epoch. +func (s *TableState) click(row int, modifiers gfx.Modifiers, epoch uint32) { + if s.choice.click(s.choiceRows(), row, modifiers) { + s.markChanged(epoch) } - s.Select(row) } -// Select selects a row; a negative row clears the selection. -func (s *TableState) Select(row int) { s.selected = int32(max(row, -1) + 1) } +// Select makes row the selected row, where the keys move from and a Shift range +// starts; a negative row clears it. It leaves the Selection of a table that +// chooses several to the application, and selecting the row it is on already +// changes nothing. +func (s *TableState) Select(row int) { s.choice.set(row) } // Sort is the sorted column and its direction; ok is false when nothing is sorted. func (s *TableState) Sort() (column int, descending, ok bool) { return int(s.sortColumn) - 1, s.descending, s.sortColumn > 0 } -// SortBy is what a click on a column's header does: sort by it ascending, or reverse -// it when it is the sorted one already. The application orders its rows by what Sort -// says. +// SortBy is what a click on a column's header does: sort by it ascending, then +// descending when it is sorted ascending already, then leave the rows unsorted +// when it is sorted descending, as a native table's header and a data table's +// sorter cycle. The application orders its rows by what Sort says, and back in +// their own order when Sort says nothing is sorted. func (s *TableState) SortBy(column int) { - if int(s.sortColumn) == column+1 { - s.descending = !s.descending - return + switch { + case int(s.sortColumn) != column+1: + s.sortColumn, s.descending = int32(column)+1, false + case !s.descending: + s.descending = true + default: + s.ClearSort() } - s.sortColumn, s.descending = int32(column)+1, false } // ClearSort leaves no column sorted. func (s *TableState) ClearSort() { s.sortColumn, s.descending = 0, false } +// GetSortDirection is how the header of column shows its sort to assistive +// technology, for the styled painting layer. +func (s *TableState) GetSortDirection(column int) gfx.SortDirection { + switch { + case int(s.sortColumn) != column+1: + return gfx.SortNone + case s.descending: + return gfx.SortDescending + } + return gfx.SortAscending +} + // Wheel applies a scroll event to a table that scrolls itself; see ScrollState.Wheel. func (s *TableState) Wheel(event gfx.ScrollEvent) gfx.EventResult { return s.Scroll.Wheel(event) } // Key moves the selection when a row of the table has the keyboard: Up and Down by a // row, PageUp and PageDown by what is on screen, Home and End to the first and last // row. The new row is selected, takes the keyboard focus and is scrolled into view -// (in the table's own scroll position, or in the nearest ScrollArea around it). A -// page routes a declared Table its keys; a host that paints a table without a page -// gives Key to Config.OnKey. It ignores every other key and any other focus, and -// reports Handled only for the keys it used. +// (in the table's own scroll position, or in the nearest ScrollArea around it). In a +// table with a Selection, Shift with those keys chooses the rows from the anchor, +// Primary moves without choosing, Control+Space (off macOS) adds the row the keys +// are on or takes it out, and Space does so in a table with Checkboxes. A page +// routes a declared Table its keys, and gives it Primary+A, which chooses every +// row; a host that paints a table without a page gives Key to Config.OnKey. It +// ignores every other key and any other focus, and reports Handled only for the +// keys it used. func (s *TableState) Key(event gfx.KeyEvent) gfx.EventResult { - if s.rows == 0 || event.Modifiers&(gfx.ModifierControl|gfx.ModifierMeta|gfx.ModifierAlt) != 0 { - return gfx.EventResult{} + result, _ := s.key(event) + return result +} + +// key is Key, and whether it changed the choice. +func (s *TableState) key(event gfx.KeyEvent) (gfx.EventResult, bool) { + if s.rows == 0 { + return gfx.EventResult{}, false } at, ok := event.Target.In(s.scope) + if !ok || at < 0 || at >= int(s.rows) { + return gfx.EventResult{}, false + } + rows := s.choiceRows() + if rows.selection != nil && isSelectAll(event) { + return gfx.EventResult{Handled: true, Repaint: true}, s.choice.selectAll(rows) + } + if event.Key == gfx.KeySpace && rows.selection != nil { + toggles := s.checkboxes && event.Modifiers == 0 || + runtime.GOOS != "darwin" && event.Modifiers == gfx.ModifierControl + if !toggles { + // Not the row's activation, which would choose it alone. + return gfx.EventResult{Handled: event.Modifiers == 0}, false + } + s.choice.toggle(rows, at) + return s.focusRow(at), true + } + how, ok := moveOf(event, rows.selection != nil) if !ok { - return gfx.EventResult{} + return gfx.EventResult{}, false } last, page := int(s.rows)-1, max(int(s.page)-1, 1) row := at @@ -231,10 +311,16 @@ func (s *TableState) Key(event gfx.KeyEvent) gfx.EventResult { case gfx.KeyEnd: row = last default: - return gfx.EventResult{} + return gfx.EventResult{}, false } row = min(max(row, 0), last) - s.Select(row) + changed := s.choice.move(rows, how, row) + return s.focusRow(row), changed +} + +// focusRow is the result that gives row the keyboard focus, visibly, and scrolls +// it into view at the next paint. +func (s *TableState) focusRow(row int) gfx.EventResult { s.reveal = true return gfx.EventResult{Handled: true, Repaint: true, Focus: s.scope.At(row), FocusVisible: true} } @@ -247,10 +333,9 @@ func (p *Page) tableKey(event gfx.KeyEvent) (gfx.EventResult, bool) { } for i := range p.tables { state := p.tables[i].state - before := state.Selected() - if result := state.Key(event); result.Handled { - if state.Selected() != before { - state.changed, state.changedAt = true, p.epoch+1 + if result, changed := state.key(event); result.Handled { + if changed { + state.markChanged(p.epoch + 1) } return result, true } @@ -258,6 +343,15 @@ func (p *Page) tableKey(event gfx.KeyEvent) (gfx.EventResult, bool) { return gfx.EventResult{}, false } +// tableType gives Primary+A, which a window offers as a shortcut, to the Table +// whose row has the keyboard. +func (p *Page) tableType(event gfx.KeyEvent) (gfx.EventResult, bool) { + if !isSelectAll(event) { + return gfx.EventResult{}, false + } + return p.tableKey(event) +} + type TableDecl struct { spec TableSpec state *TableState @@ -319,7 +413,11 @@ func (f *Frame) Table(state *TableState, spec TableSpec) Box { rows = max(spec.Source.Len(), 0) } decl := TableDecl{spec: spec, state: state, rows: rows, userColumns: spec.Columns} - state.checkedChanged, state.checkDone = false, gfx.ID{} + state.ticked, state.checkDone = false, gfx.ID{} + // The choice is made over the rows of this paint: a click it delivers and the + // keys before the next one see as many as the application declared. + state.rows = int32(rows) + state.choice.clamp(rows) if index < cap(*decls) { // Reuse the titles, and the fitted columns of a table that fits or shares, // of this table from the last paint even though the fit itself waits for @@ -331,7 +429,7 @@ func (f *Frame) Table(state *TableState, spec TableSpec) Box { } } *decls = append(*decls, decl) - if spec.Checked != nil { + if spec.Checkboxes && state.Selection != nil { f.applyCheckClick(&(*decls)[index]) } return b @@ -385,7 +483,7 @@ const tableCheckWidth = 40 // that goes with it in front of the titles, for a table given Checked. func (t *TableDecl) addLead() { t.lead = 0 - if t.spec.Checked == nil { + if !t.spec.Checkboxes || t.state.Selection == nil { return } t.lead = 1 @@ -593,7 +691,7 @@ func (f *Frame) paintTable(n *Node) { if !sideways { s.OffsetX = 0 // an outer ScrollArea owns the table's geometry instead } - t.state.rows, t.state.scope = int32(t.rows), t.spec.Rows + t.state.rows, t.state.scope, t.state.checkboxes = int32(t.rows), t.spec.Rows, t.lead > 0 if t.state.reveal { f.RevealSelected(n, t, body, rowHeight, headerHeight, scrolls) } @@ -657,6 +755,10 @@ func (f *Frame) paintTable(n *Node) { // bottom rule needing room below it. f.paintTableHeader(t, Rect{X: left, Y: r.Y, Width: contentWidth, Height: r.Height}, body, headerHeight, rowHeight, sideways && frozenWidth == 0, frozenWidth) } + // The rows are one list for assistive technology, named by the element's + // Label, of which the user chooses several when the table has a Selection. + canvas.ContainerWithOptions(body, gfx.RoleListBox, n.Label, gfx.HitOptions{MultiSelectable: t.state.Selection != nil}) + rowsMark := canvas.Mark() if last > first { extra := float32(0) if top+float32(last)*rowHeight < r.Y+r.Height { @@ -691,6 +793,14 @@ func (f *Frame) paintTable(n *Node) { if sideways && frozenWidth > 0 { canvas.Fill(Rect{X: seam - tableFrozenSeparator, Y: top + float32(first)*rowHeight, Width: tableFrozenSeparator, Height: float32(last-first)*rowHeight + extra}, f.Palette.Border) } + // The rows, and their checkboxes, are one stop of Tab, as a native + // table is: the row that has the keyboard, else the selected row, else + // the first on screen. The arrows move between them. + var stop gfx.ID + if row := t.state.Selected(); row >= first && row < last { + stop = t.spec.Rows.At(row) + } + _, t.state.tabRows = canvas.OneTabStop(rowsMark, stop, t.state.tabRows[:0]) } if scrolls || sticky { if headerHeight > 0 { diff --git a/base/table_check.go b/base/table_check.go index e0ea132f5..c882ee099 100644 --- a/base/table_check.go +++ b/base/table_check.go @@ -2,30 +2,24 @@ package base import "github.com/vivaui/viva/gfx" -// CheckedChanged reports whether the paint being declared delivered a tick or an -// untick in the table's column of checkboxes (TableSpec.Checked). Like Changed, it -// is true in the paint that finds the click and false in the paint after it. -func (s *TableState) CheckedChanged() bool { return s.checkedChanged } - // GetLead is 1 when the table has a column of checkboxes in front of its columns. func (t *TableDecl) GetLead() int { return t.lead } -// ToggleRow ticks a row that is not ticked and unticks one that is. +// ToggleRow ticks a row that is not ticked and unticks one that is: it adds the +// row to the Selection or takes it out, as a Primary click on the row does, and +// makes it the selected row. func (t *TableDecl) ToggleRow(id gfx.ID, row int) { - if sel := t.spec.Checked; sel != nil && t.state.checkDone != id { - t.state.checkDone = id - if sel.Has(row) { - sel.Remove(row) - } else { - sel.Add(row) - } - t.state.checkedChanged = true + if t.state.Selection == nil || t.state.checkDone == id { + return } + t.state.checkDone = id + t.state.choice.toggle(t.state.choiceRows(), row) + t.state.ticked = true } -// ToggleAll ticks every row when some are not ticked, and clears them when all are. +// ToggleAll chooses every row when some are not chosen, and none when all are. func (t *TableDecl) ToggleAll(id gfx.ID) { - sel := t.spec.Checked + sel := t.state.Selection if sel == nil || t.state.checkDone == id { return } @@ -33,22 +27,23 @@ func (t *TableDecl) ToggleAll(id gfx.ID) { if t.AllChecked() { sel.Clear() } else { - for row := 0; row < t.rows; row++ { - sel.Add(row) - } + t.state.choice.selectAll(t.state.choiceRows()) } - t.state.checkedChanged = true + t.state.ticked = true } -// AllChecked reports whether the table has rows and every one is ticked: the +// AllChecked reports whether the table has rows and every one is chosen: the // Selection holds as many keys as there are rows. The keys of a table's Selection // are its row numbers, and the application takes the ones of rows that are gone out. func (t *TableDecl) AllChecked() bool { - return t.spec.Checked != nil && t.rows > 0 && t.spec.Checked.Len() >= t.rows + sel := t.state.Selection + return sel != nil && t.rows > 0 && sel.Len() >= t.rows } -// SomeChecked reports whether any row is ticked. -func (t *TableDecl) SomeChecked() bool { return t.spec.Checked != nil && t.spec.Checked.Len() > 0 } +// SomeChecked reports whether any row is chosen. +func (t *TableDecl) SomeChecked() bool { + return t.state.Selection != nil && t.state.Selection.Len() > 0 +} // checks is the scope of a table's checkboxes, inside the scope of its rows: the // header's is item 0 and the checkbox of row r is item r+1. diff --git a/base/table_test.go b/base/table_test.go index 1520f8544..5dc11ef6c 100644 --- a/base/table_test.go +++ b/base/table_test.go @@ -333,6 +333,19 @@ func TestTableHeaderClicksSortAndShowTheArrow(t *testing.T) { if column, descending, ok := state.Sort(); column != 0 || !descending || !ok { t.Errorf("a second click gives %d %v %v, want a descending sort of column 0", column, descending, ok) } + state.SortBy(0) + if _, _, ok := state.Sort(); ok { + t.Error("a third click on the sorted column left it sorted; it unsorts the rows") + } + state.SortBy(0) + if column, descending, ok := state.Sort(); column != 0 || descending || !ok { + t.Errorf("a fourth click gives %d %v %v, want an ascending sort of column 0 again", column, descending, ok) + } + state.SortBy(1) + if column, descending, ok := state.Sort(); column != 1 || descending || !ok { + t.Errorf("a click on another column gives %d %v %v, want it sorted ascending", column, descending, ok) + } + state.ClearSort() canvas = testCanvas() canvas.BeginEventPass(tableScope.At(1), gfx.ClickInfo{}) if _, row := draw(canvas); row != 1 { @@ -347,6 +360,14 @@ func TestTableAllocatesNothingOnceWarm(t *testing.T) { rows := &countingRows{n: 10000} var state TableState state.SortBy(1) + // A table that chooses several rows paints the same: the rows it shows ask + // the Selection whether they are chosen. + var chosen Selection + for _, row := range []int{3, 500, 501, 9999} { + chosen.Add(row) + } + state.Selection = &chosen + state.Select(500) columns := titledColumns(tableColumns, tableTitles, allSortable) run := func() { canvas.Reset() @@ -501,3 +522,40 @@ func TestTableInAScrollAreaKeepsItsHeaderAndKeysScrollTheArea(t *testing.T) { t.Errorf("selected row %d is at y=%v in a 200 tall area scrolled to %v, want it fully visible below the header", selected, rowY, view.ScrollState(listID).Offset) } } + +// The header of a sortable column is a column header that says how the rows are +// sorted, as a header click cycles it: by it ascending, descending, then not. +func TestTableHeaderReportsItsSort(t *testing.T) { + theme := gfx.LightTheme() + data := TableRows{{"b", "2"}, {"a", "1"}} + var state TableState + header := func() gfx.Hit { + t.Helper() + canvas := testCanvas() + var view View + view.Draw(canvas, theme, gfx.Rect{Width: 300, Height: 200}, func(f *Frame) { + f.Column().Children(func() { + f.Table(&state, TableSpec{Rows: tableScope, Header: headerScope, Columns: titledColumns(tableColumns[:2], []string{"Name", "N"}, []bool{true, true}), Source: &data}) + }) + }) + for _, hit := range canvas.Hits() { + if hit.ID == headerScope.At(0) { + return hit + } + } + t.Fatal("no header hit for the Name column") + return gfx.Hit{} + } + for step, want := range []gfx.SortDirection{gfx.SortNone, gfx.SortAscending, gfx.SortDescending, gfx.SortNone} { + if step > 0 { + state.SortBy(0) + } + hit := header() + if hit.Role != gfx.RoleColumnHeader || !hit.Focusable { + t.Fatalf("step %d: the header is role %v, focusable %v; want a focusable column header", step, hit.Role, hit.Focusable) + } + if hit.Sort != want { + t.Fatalf("after %d clicks the header reports sort %v, want %v", step, hit.Sort, want) + } + } +} diff --git a/components/drawer.go b/components/drawer.go index 9f0a86cf9..598bb73d6 100644 --- a/components/drawer.go +++ b/components/drawer.go @@ -45,6 +45,12 @@ type DrawerOptions struct { // DrawerSwipe.Offset reports it: Layout and Begin place every part that much // closer to closed, and the scrim fades with it. Offset float32 + // HeaderInset is where the header must start at the earliest: the bottom + // edge, from the window's top, of the strip the window buttons of a custom + // titlebar cover. The panel and the scrim still cover the strip, as a + // sidebar runs under the traffic lights; the title and the close button + // begin under it, as far as the panel reaches into it. Zero is nothing. + HeaderInset float32 } func absFloat32(value float32) float32 { @@ -177,8 +183,20 @@ func (drawer Drawer) layout(scratch *overlayLines, description string) (DrawerLa padding := metrics.PadSurface lines := overlayWrap(drawer.canvas, scratch, description, metrics.FontSizeM, gfx.WeightRegular, drawer.contentWidth()-2*padding) headerHeight := drawerHeaderHeight(metrics, len(lines)) + // The close button is a control's height; a one-line title is shorter, and + // the header takes the taller of the two so the button stays above the body. + if !drawer.options.CloseID.IsZero() { + headerHeight = max(headerHeight, metrics.ControlHeight) + } content := drawer.contentBounds(headerHeight) inner := content.Inset(gfx.All(padding)) + // The panel runs under the titlebar's buttons; only its header keeps clear + // of them, starting at the strip's bottom edge as far as the panel's top + // lies within the strip. + if overlap := drawer.options.HeaderInset - inner.Y; overlap > 0 { + inner.Y += min(overlap, inner.Height) + inner.Height = max(0, inner.Height-overlap) + } layout := DrawerLayout{Content: content} if drawer.showHandle { layout.Handle = drawer.handleBounds(content) @@ -196,7 +214,7 @@ func (drawer Drawer) layout(scratch *overlayLines, description string) (DrawerLa layout.Body = gfx.Rect{X: inner.X, Y: layout.Header.Y + layout.Header.Height + metrics.GapItem, Width: inner.Width, Height: max(0, layout.Footer.Y-layout.Header.Y-layout.Header.Height-metrics.GapItem*2)} if !drawer.options.CloseID.IsZero() { closeSize := metrics.ControlHeight - layout.Close = gfx.Rect{X: content.X + content.Width - padding - closeSize, Y: content.Y + padding, Width: closeSize, Height: closeSize} + layout.Close = gfx.Rect{X: content.X + content.Width - padding - closeSize, Y: inner.Y, Width: closeSize, Height: closeSize} } return layout, lines } diff --git a/components/input.go b/components/input.go index 86b8f7d58..b93bf3b36 100644 --- a/components/input.go +++ b/components/input.go @@ -225,9 +225,8 @@ func inputPaintLine(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, value, // bounds, and those should describe the glyph line the field draws. It is moved // with the caret, on the same offset the caret and selection take. lineTop, lineHeight := inputLineBox(bounds, fontSize) - glyphs := gfx.Rect{X: bounds.X, Y: lineTop, Width: bounds.Width, Height: lineHeight} - glyphs.X -= scroll - canvas.LabelAligned(value, glyphs, style, snapshot.Alignment) + glyphs := inputLineFrame(bounds, origin, lineTop, lineHeight) + canvas.LabelAligned(value, glyphs, style, gfx.AlignLeft) for _, selection := range selections { if selection.Width <= 0 { continue @@ -239,7 +238,7 @@ func inputPaintLine(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, value, } selected := textStyle selected.Color = selectedColor - canvas.LabelAligned(value, glyphs, selected, snapshot.Alignment) + canvas.LabelAligned(value, glyphs, selected, gfx.AlignLeft) canvas.Unclip() } canvas.Unclip() @@ -315,6 +314,15 @@ func inputLineBox(bounds gfx.Rect, fontSize float32) (top, height float32) { return bounds.Y + (bounds.Height-height)/2, height } +// inputLineFrame is the box a line of value is drawn in, from origin, the left end where +// the line stands: it reaches the field's right edge. A platform rasterizes a label only +// within its box, so a box no wider than the field would blank the end of a line scrolled +// past the field's left edge, while the caret sat at the field's edge. The part of the line +// past the field's edge is clipped anyway, so the box need not be the line's full width. +func inputLineFrame(bounds gfx.Rect, origin, top, height float32) gfx.Rect { + return gfx.Rect{X: origin, Y: top, Width: max(bounds.Width, bounds.X+bounds.Width-origin), Height: height} +} + // inputLineBand is the vertical band a line of text of fontSize occupies in a // field of bounds: the room a selection fills, the caret sits in and a // composition is underlined at the foot of. It is centered in the field and diff --git a/components/input_scroll_test.go b/components/input_scroll_test.go index 61ac7c93f..02585202d 100644 --- a/components/input_scroll_test.go +++ b/components/input_scroll_test.go @@ -176,3 +176,34 @@ func TestInputScrollOffsetIsBoundedByTheLine(t *testing.T) { t.Fatalf("the line scrolls by %v, want its most %v", got, most) } } + +// The line of a scrolled field is drawn in a box that covers the field: a platform +// rasterizes a label only within its box, so a box that stopped short of the field's right +// edge would blank the end of the line while the caret sat at that edge. +func TestInputScrolledLineBoxCoversTheField(t *testing.T) { + const cell = 10 + theme := gfx.LightTheme() + bounds := gfx.Rect{X: 0, Y: 0, Width: 100, Height: 32} + value := "0123456789abcdefghij" // 20 cells, twice the field + scroll := new(base.InputScroll) + + canvas := fixedWidth(cell) + PaintInputContent(canvas, theme, bounds, bounds, InputSnapshot{ + ID: gfx.Item(1), Label: "Filter", Value: value, Focused: true, ShowCaret: true, + Caret: len(value), HideEditorText: true, Scroll: scroll, + }) + var label gfx.Text + for _, text := range canvas.Texts() { + if text.Value == value { + label = text + break + } + } + if label.Value == "" { + t.Fatal("the line was not painted") + } + left, right := label.Bounds.X, label.Bounds.X+label.Bounds.Width + if left > bounds.X || right < bounds.X+bounds.Width { + t.Fatalf("the line's box spans %v..%v, not the field's %v..%v: the end of the scrolled line is not drawn", left, right, bounds.X, bounds.X+bounds.Width) + } +} diff --git a/components/table.go b/components/table.go index 307f9bd75..7d84f2b2b 100644 --- a/components/table.go +++ b/components/table.go @@ -440,7 +440,9 @@ func (table *Table) paintRow(id gfx.ID, cells []string, state TableRowState, kin remaining -= width } if kind == tableRowBody && !id.IsZero() { - table.canvas.HitWithLabel(id, rowBounds, tableRowLabel(cells)) + // A body row is an item the user chooses, as a native table's row is: it + // says whether it is chosen, as its surface shows. + table.canvas.HitWithOptions(id, rowBounds, tableRowLabel(cells), gfx.HitOptions{Role: gfx.RoleOption, Selected: state.Selected}) } table.y += height if table.y < bottom { diff --git a/docs/README.md b/docs/README.md index 995a6e74b..f7ea64e49 100644 --- a/docs/README.md +++ b/docs/README.md @@ -46,7 +46,8 @@ mentions every exported method and theme field. - [web-deployment.md](web-deployment.md) — the browser build, its capability matrix, lifecycle mapping, static-hosting headers and security limits. - [diagnostics.md](diagnostics.md) — the structured event stream, its slog - adapters, the recent-event ring and fault context. + adapters, the recent-event ring and fault context, and the `VIVA_TRACE` + frame trace for finding redundant redraws. - [upgrading.md](upgrading.md) — moving an application to a newer Viva, and the call-site changes each release asks for. - [updating.md](updating.md) — the signed feed, the client API, and what each diff --git a/docs/accessibility.md b/docs/accessibility.md index 8ae83f600..b32c7f6f4 100644 --- a/docs/accessibility.md +++ b/docs/accessibility.md @@ -13,7 +13,10 @@ Role, bounds, name (`Label`), `Value`, `Hint`, `Description`, the states (`Focused`, `Disabled`, `Checked`, `Mixed`, `Selected`, `Expanded`, `ReadOnly`, `Secure`), `Focusable`, `Expandable`, a heading `Level`, `PosInSet` and `SetSize`, a `Live` setting, a numeric `Range` for sliders and labelled -progress bars, and, for the focused text field, its `Selection` in code points. +progress bars, `MultiSelectable` for a list whose items can be chosen several at +once, the `Sort` of a column header (`gfx.SortNone`, `SortAscending`, +`SortDescending`), and, for the focused text field, its `Selection` in code +points. Components set the extras through `gfx.HitOptions` (and `Canvas.ContainerWithOptions` for regions). @@ -35,7 +38,10 @@ taking no pointer or focus from the row that holds it. | Carried out as | focus, then a completed click (`Clicked`) | focus | Up / Down on the focused slider | Home / End / Up / Down | a native text event over the whole text | a native selection event | A field with no native editor, a read-only or secure field, and a disabled -control refuse. Each repaint a request causes is presented in order. +control refuse. While a modal holds the focus trap, a node outside it is left +out of the tree and a request that still names it (queued or held from before +the modal opened) is refused. Each repaint a request causes is presented in +order. ## Platforms @@ -50,6 +56,22 @@ A progress bar maps to `NSAccessibilityProgressIndicatorRole` on macOS, UIA's `role="progressbar"` on Web; its 0–100 range is exposed as a read-only `RangeValue`. +### Tables + +`ui.Table` declares its body as a list (`RoleListBox`, named by the element's +`Label`) and each row as an option whose `Selected` is whether it is chosen, so a +table reads as a native list view's details mode does. The list is +`MultiSelectable` when the table has a `TableState.Selection`. A sortable +column's header is a `RoleColumnHeader` that presses like a button and carries +the sort: + +| | macOS | Windows | Linux | Web | +|---|---|---|---|---| +| Column header | `AXButton`, subrole `AXSortButton` (as an `NSTableView` header) | `HeaderItem` (50035), Invoke | `ROLE_COLUMN_HEADER`, action `click` | `role="columnheader"` | +| Sort direction | `AXSortDirection` ascending, descending or unknown | `AriaProperties` `sort=ascending`/`descending`/`none`; `ItemStatus` `ascending`/`descending` while sorted | object attribute `sort` (`ascending`/`descending`/`none`); `AttributesChanged` when it changes | `aria-sort`, left off while unsorted | +| Several items chosen | not exposed: AppKit has no such attribute | `Selection.CanSelectMultiple` | state `MULTISELECTABLE`; `state-changed` when it changes | `aria-multiselectable` | +| Item chosen | `AXSelected` | `SelectionItem.IsSelected` | state `SELECTED` | `aria-selected` | + Cost when nobody is listening: - Windows builds no element until a client first asks (`WM_GETOBJECT`), keeping @@ -65,15 +87,46 @@ Cost when nobody is listening: - The tree is flat in paint order. A client sees containers (lists, grids, menus) as parents on Linux; Windows and macOS list every node under the window. -- Text ranges are in code points. Windows `GetBoundingRectangles` and AT-SPI - character extents answer with the field's rectangle, and `RangeFromPoint` with - the caret: the adapters cannot ask the text layout for a glyph's place. A line - is a hard line (up to `\n`); soft-wrapped rows are not known to them. -- AT-SPI sentences are lines. `Selection` pattern support is for lists only. +- Text ranges are in code points. For a terminal that publishes its selected + text and visible row bounds, Windows `GetBoundingRectangles` returns one + screen rectangle per visible selected row. `GetVisibleRanges` returns the + selected excerpt if any of its rows are visible, and an empty array if all + its rows are offscreen. Partially visible excerpts have no per-character + bounds or offsets for just the visible part. Other fields and AT-SPI + character extents report the field's rectangle. `RangeFromPoint` reports the + caret. A line is a hard line + (up to `\n`); text navigation does not expose soft-wrapped rows. +- AT-SPI sentences are lines. `Selection` pattern support is for lists only. A + client reads which items are chosen and whether several can be, but selecting + an item, `AddToSelection` included, presses it, which chooses it alone as a + plain click does; adding to or taking out of a choice of several is the + keyboard's (Shift and Primary with the arrows, Control+Space, Primary+A). - No `Table`/`Grid` patterns, no `Drag`, no `Transform`; no Windows UIA on arm64 (the callbacks need a floating-point thunk that exists for amd64 only). - The `viva dev` reload worker does not carry requests from assistive technology. +## Testing + +A test reads the tree with `Driver.Accessibility` (`headless.Session.Access`, +`AccessByRole`, `AccessByName`) and makes requests with `Driver.PerformAccess` +(`Session.PerformAccess`), which takes an `app.AccessRequest`: `AccessPress`, +`AccessFocus`, `AccessIncrement`, `AccessDecrement`, `AccessSetNumber`, +`AccessSetText` or `AccessSetSelection`. It calls the handler a window's +platform adapter calls, so modal, disabled, read-only and role refusals are +the ones a screen reader meets. `Session.LocateNode` finds a node by the +headless selector (`button:Save`, `id:home/save`, a name) without hit testing, +so a covered node, or one a modal hides, is still named and its refusal +observed: + +```go +save, _ := session.LocateNode("button:Save") +handled, err := session.PerformAccess(app.AccessRequest{Node: save.ID, Action: app.AccessPress}) +``` + +The line protocol has the same requests as `access press|focus|increment|decrement SEL`, +`access set SEL VALUE` (a number on a slider, text on a field) and +`access select SEL START END`, answered `ok handled` or `ok refused`. + ## Verification - Pure logic (roles, states, patterns, text units, the AT-SPI object model and diff --git a/docs/benchmarks/2026-12-01-cpu-fallback-darwin.md b/docs/benchmarks/2026-12-01-cpu-fallback-darwin.md new file mode 100644 index 000000000..db33cfc2f --- /dev/null +++ b/docs/benchmarks/2026-12-01-cpu-fallback-darwin.md @@ -0,0 +1,76 @@ +# CPU renderer: offscreen frames and a window without Metal + +Measured 2026-12-01. The CPU renderer (`internal/raster`, driven by +`internal/softscene`) draws a window on a macOS machine with no Metal device and +draws headless screenshots on any machine with `VIVA_SOFTWARE_RENDERING=1`. The +numbers below say what a frame costs; they are evidence for budgets, not a +comparison across machines. + +## Machines + +| Machine | Renderer | Notes | +| --- | --- | --- | +| Apple M2 Pro (macOS 15, arm64) | CPU, headless | Development host | +| Intel macOS 14.8.5 virtual machine (4 vCPU) | CPU, headless and window | VMware SVGA, no Metal device; the case the fallback exists for | + +## Offscreen frames + +The benchmarks render a 1000x700 logical-pixel scene at scale 1 and include the +pixel copy `Render` returns. They run on the development host: + +```sh +go test -tags vivahead ./internal/platform/darwin -run '^$' \ + -bench 'BenchmarkCPUOffscreen' -benchtime 2s -count=2 +``` + +| Scene | Contents | M2 Pro | Intel VM | +| --- | --- | --- | --- | +| Page | 200 rectangles, 20 proportional labels | 0.48 ms | 1.2–1.5 ms | +| Terminal | 1 rectangle, 40 fixed-pitch lines | 1.67 ms | 3.0 ms | + +The benchmarks report 2.8 MB and one allocation per frame: the copy of the +canvas `Render` returns. Painting a steady frame allocates nothing; the scene +keeps each label's picture while its content and scale are unchanged. + +On the Intel VM the same scenes were also timed with a small program built from +the same package, sixty steady frames per run: + +| Scene | Create | First frame | Steady frame | +| --- | --- | --- | --- | +| Page | 0.06–0.43 ms | 1.7–2.5 ms | 1.21–1.53 ms | +| Terminal | 0.35–0.66 ms | 4.8–6.5 ms | 2.96–3.03 ms | + +The first steady run on a cold process took 23 ms for its first frame; later runs +showed the numbers above. + +## A window without Metal + +A Motty window at 1400x900 logical pixels (1x) was driven on the Intel VM while +the app printed the time each present took, split into painting the damaged +region and handing the canvas to the view. The app decides when to redraw, so +present intervals here are its pacing, not a renderer limit: it coalesces +terminal output and repaints the caret every ~530 ms. + +| Stretch | Presents | Present time p50 | p95 | max | Paint p50 | +| --- | --- | --- | --- | --- | --- | +| Terminal output and typing | 29 | 3.7 ms | 7.2 ms | 16.8 ms | 1.7 ms | +| Scrollback scrolling | 9 | 3.3 ms | 3.4 ms | 4.2 ms | 1.2 ms | + +Present time is paint plus building the layer's image and copying the damaged +rectangle into it. A frame of this size (1.26 M device pixels) stays within a +60 Hz budget on a 4-vCPU virtual machine without a GPU. + +## Headless end to end + +The `-tags vivahead` build of Motty renders on the same Intel VM without Metal: +`texts`, `layout` and `shot` at scale 2 (2800x1800) returned the window's scene +and a screenshot identical in structure to the window's. + +## Limits + +- The Intel VM has four cores and no GPU; its numbers do not describe a + supported Mac. +- The window probe was a temporary instrumentation of the present path. It + measures paint and presentation, not compositor latency or input-to-screen + delay. +- Offscreen numbers include the screenshot copy; a window does not pay it. diff --git a/docs/benchmarks/2026-12-01-windows-d3d11-first-frame.csv b/docs/benchmarks/2026-12-01-windows-d3d11-first-frame.csv new file mode 100644 index 000000000..e4d3e4a3f --- /dev/null +++ b/docs/benchmarks/2026-12-01-windows-d3d11-first-frame.csv @@ -0,0 +1,53 @@ +mode,pair,position,build,process_to_scene_ns,scene_to_present_call_ns,present_call_ns,scene_to_present_return_ns,process_to_present_return_ns,private_ws_before_bytes,private_ws_after_bytes,private_commit_before_bytes,private_commit_after_bytes,go_total_alloc_before_bytes,go_total_alloc_after_bytes,go_mallocs_before,go_mallocs_after +time,0,1,optimized,820900600,40644100,3001100,43645200,864545800,,,,,,,, +time,0,2,main,724797900,35118400,2597300,37715700,762513600,,,,,,,, +time,1,1,main,669070000,29060400,2352800,31413200,700483200,,,,,,,, +time,1,2,optimized,737451000,21091300,1500800,22592100,760043100,,,,,,,, +time,2,1,optimized,710583100,22509900,1999800,24509700,735092800,,,,,,,, +time,2,2,main,652774500,33451200,2170600,35621800,688396300,,,,,,,, +time,3,1,main,764387700,28275900,2505500,30781400,795169100,,,,,,,, +time,3,2,optimized,738652600,27618200,2025500,29643700,768296300,,,,,,,, +time,4,1,optimized,693545000,20000200,1147700,21147900,714692900,,,,,,,, +time,4,2,main,768909900,31728100,2497800,34225900,803135800,,,,,,,, +time,5,1,main,694926900,30545700,2239200,32784900,727711800,,,,,,,, +time,5,2,optimized,668499800,23145700,1723500,24869200,693369000,,,,,,,, +time,6,1,optimized,647154000,36651400,3499800,40151200,687305200,,,,,,,, +time,6,2,main,658776000,29026400,2591500,31617900,690393900,,,,,,,, +time,7,1,main,873106000,34080900,1660800,35741700,908847700,,,,,,,, +time,7,2,optimized,679147400,19292000,2479000,21771000,700918400,,,,,,,, +time,8,1,optimized,672671200,20390200,1502100,21892300,694563500,,,,,,,, +time,8,2,main,871975900,33791000,1459000,35250000,907225900,,,,,,,, +time,9,1,main,896594600,34499600,1643500,36143100,932737700,,,,,,,, +time,9,2,optimized,803202200,21877900,2013600,23891500,827093700,,,,,,,, +time,10,1,optimized,660220600,24055500,999700,25055200,685275800,,,,,,,, +time,10,2,main,666951200,29015500,2004000,31019500,697970700,,,,,,,, +time,11,1,main,760189400,26567400,1006000,27573400,787762800,,,,,,,, +time,11,2,optimized,682074100,19500100,2001000,21501100,703575200,,,,,,,, +time,12,1,optimized,660033100,22019800,2000300,24020100,684053200,,,,,,,, +time,12,2,main,709224700,29337400,1540100,30877500,740102200,,,,,,,, +time,13,1,main,740073700,28369300,2882500,31251800,771325500,,,,,,,, +time,13,2,optimized,653681100,21857900,1999800,23857700,677538800,,,,,,,, +time,14,1,optimized,675600100,18979300,1999800,20979100,696579200,,,,,,,, +time,14,2,main,703380000,30501000,2603000,33104000,736484000,,,,,,,, +time,15,1,main,650594700,27114400,1124900,28239300,678834000,,,,,,,, +time,15,2,optimized,691877700,22923400,2010500,24933900,716811600,,,,,,,, +time,16,1,optimized,703304700,18864200,1500500,20364700,723669400,,,,,,,, +time,16,2,main,663438600,27362800,3543100,30905900,694344500,,,,,,,, +memory,0,1,optimized,727235100,20554400,1999600,22554000,749789100,47955968,59613184,115941376,130101248,81138168,83644344,4281482,4282244 +memory,0,2,main,697392400,27383100,1966100,29349200,726741600,43962368,122044416,111747072,192032768,81257640,83763808,4281501,4282262 +memory,1,1,main,670850800,29089300,1999700,31089000,701939800,43929600,122339328,111616000,192524288,81201208,83708192,4281504,4282266 +memory,1,2,optimized,666539500,39234400,2822700,42057100,708596600,46403584,57917440,113999872,128507904,81336936,83843880,4281513,4282274 +memory,2,1,optimized,669671400,18074300,1499300,19573600,689245000,47525888,58978304,114851840,128827392,81131848,83638808,4281489,4282250 +memory,2,2,main,722171700,32508200,2499200,35007400,757179100,47652864,125431808,115445760,195395584,81201152,83708472,4281509,4282271 +memory,3,1,main,636863100,29112300,2499400,31611700,668474800,46002176,123715584,113278976,193363968,81140776,83646944,4281523,4282284 +memory,3,2,optimized,728792200,19766000,2048200,21814200,750606400,46186496,58847232,114335744,129589248,81266984,83774304,4281517,4282280 +memory,4,1,optimized,718921500,20128100,1294500,21422600,740344100,46497792,58695680,113979392,128909312,81133632,83639792,4281519,4282280 +memory,4,2,main,703342200,29027700,1999800,31027500,734369700,45162496,124051456,112963584,194019328,81138248,83645568,4281525,4282287 +memory,5,1,main,653467800,31422700,3459500,34882200,688350000,46387200,124424192,113389568,193679360,81138384,83644552,4281528,4282289 +memory,5,2,optimized,686065200,17001000,2508700,19509700,705574900,45428736,57012224,112861184,127074304,81204096,83711040,4281531,4282292 +memory,6,1,optimized,710498900,23449900,2521600,25971500,736470400,44818432,56905728,112979968,127385600,81137088,83644400,4281538,4282300 +memory,6,2,main,665087200,28876000,1531600,30407600,695494800,46997504,124751872,114905088,195145728,81138776,83646128,4281539,4282302 +memory,7,1,main,653345200,25065400,2241600,27307000,680652200,46485504,124432384,114159616,194306048,81137192,83643008,4281542,4282302 +memory,7,2,optimized,702911600,17092000,1500300,18592300,721503900,47599616,59068416,115609600,129622016,81136304,83643600,4281559,4282321 +memory,8,1,optimized,651465200,20078500,865700,20944200,672409400,47087616,59338752,114638848,129314816,81207640,83713448,4281558,4282318 +memory,8,2,main,655612700,27891600,1499600,29391200,685003900,48394240,126115840,115757056,195788800,81139968,83647304,4281557,4282320 diff --git a/docs/benchmarks/2026-12-01-windows-d3d11-first-frame.md b/docs/benchmarks/2026-12-01-windows-d3d11-first-frame.md new file mode 100644 index 000000000..3381fb31a --- /dev/null +++ b/docs/benchmarks/2026-12-01-windows-d3d11-first-frame.md @@ -0,0 +1,67 @@ +# D3D11 memory and timing at Motty's first frame on Windows + +With a fresh Motty profile on an Intel Iris Xe, changing how Viva uploads +rectangles, constants and label textures reduced the median private working +set immediately after the first `Present` from **118.66 MiB to 56.05 MiB**. +At entry to the renderer for that scene, both builds used about 44.3 MiB. + +Both builds used [Motty `2aab32b6`](https://github.com/t8y2/motty/commit/2aab32b627b2352ef405ffbd630e2f85eea83a5e). +The table compares Viva main (`db30adab`) with the upload change (measured +as `7fbfb134`, with the same source tree as `32156655`). +All values are per-build medians. Each interval is calculated per launch before +taking its median. + +To select the optimized path for a new Windows window, set +`config.D3D11LowMemoryUploads = true` on its `app.Config` before opening it. +The default (`false`) uses D3D11's `UpdateSubresource`. Each window keeps +its choice through device recovery. Hardware and WARP both support the option. + +| Timing, 16 pairs | Main | Optimized | +| --- | ---: | ---: | +| Process creation to first scene entering the renderer | 706.30 ms | 680.61 ms | +| Scene entry to first DXGI `Present` call | 29.20 ms | 21.87 ms | +| Time inside the first `Present` call | 2.20 ms | 2.00 ms | +| Scene entry to first successful `Present` return | 31.52 ms | 23.87 ms | +| Process creation to first successful `Present` return | 738.29 ms | 702.25 ms | + +The scene-to-return interval was shorter in 15 of 16 pairs. The median of the +paired reductions was 8.37 ms. Total startup was shorter in 12 of 16 pairs, +with individual differences ranging from 212.66 ms faster to 59.56 ms slower. +Much of the difference in total startup preceded the first scene. + +| Memory, 8 separate pairs | Main | Optimized | +| --- | ---: | ---: | +| Private working set at scene entry | 44.29 MiB | 44.30 MiB | +| Private working set at first `Present` return | 118.66 MiB | 56.05 MiB | +| Private working set increase over that interval | 74.26 MiB | 11.29 MiB | +| Private committed memory at first `Present` return | 185.17 MiB | 122.90 MiB | +| Go heap bytes allocated over the interval | 2.39 MiB | 2.39 MiB | +| Go heap allocations over the interval | 762 | 761 | + +The optimized build used 61.44–64.70 MiB less private working set at first +`Present` return in each of the eight pairs. + +## Measurement method + +- Windows 10 22H2 (build 19045), windows/amd64, Go 1.26.11, Intel Iris Xe + driver 27.20.100.9664. Each launch used D3D11 hardware and DirectComposition. + The first draw in every run was 1400 × 900, with 4,503 rectangles and 21 labels. +- Build the same Motty checkout with each Viva revision, using + `go build -buildvcs=false -trimpath -ldflags=-H=windowsgui ./cmd/motty`. + Use the same probes in both builds. For each launch, use a fresh empty + `MOTTY_DATA_DIR` and show the window with `SW_SHOWNOACTIVATE`. Leave OS + caches warm. In each batch, warm up each build once and then alternate the + order of the two builds in consecutive pairs. +- Record `time.Now()` at the first nonempty window scene entering + `renderer.apply`, immediately before the swap chain's `Present` call in + `renderer.presentWithSync`, and immediately after it succeeds. Use the + creation time from `GetProcessTimes` for elapsed time since process creation. + The endpoint measures submission to DXGI. Display scanout occurs separately. +- In a separate batch, read `PROCESS_MEMORY_COUNTERS_EX2.PrivateWorkingSetSize` + and `PrivateUsage` with `K32GetProcessMemoryInfo` at scene entry and at + `Present` return. Read `runtime.MemStats.TotalAlloc` and `Mallocs` at the same + points. Keeping these reads out of the timing batch avoids timing their overhead. + +[Per-launch data in nanoseconds, bytes and allocation counts](./2026-12-01-windows-d3d11-first-frame.csv). +Pair 0 in each batch contains the excluded warm-ups. Position gives the run +order within a pair. diff --git a/docs/conformance.md b/docs/conformance.md index 6d2d7f941..ac080677a 100644 --- a/docs/conformance.md +++ b/docs/conformance.md @@ -162,13 +162,20 @@ GPU when the desktop asks for it and the window is opaque, and in grayscale othe a compositing desktop it also draws the transparent frame margin (shadow and round corners) of a custom-titlebar window. If the CPU renderer cannot start either, `OpenWindow` fails with an error that wraps `app.ErrNoGraphics` and names what to install. -macOS always has Metal. A server with no display at all (most cloud machines) cannot open -a window on any platform: give it a virtual display (Xvfb or Xvnc on Linux) or use the -headless build (`-tags vivahead`), which renders offscreen. -The Linux headless renderer needs no Vulkan driver: with none it draws on the CPU -(`internal/raster`), within a few levels of the Vulkan pipelines per channel (checked -against lavapipe), with the same LCD text antialiasing when the desktop asks for it and -the target is opaque. +macOS draws with Metal when the machine has a device. A Mac without one (an Intel virtual +machine is the common case) draws its window with the same CPU scene: `internal/softscene` +shared with the Linux path, labels rasterized by CoreText, the canvas presented in a plain +layer, and the native text editor composited in its layer. `VIVA_SOFTWARE_RENDERING=1` +asks for it on a Mac that does have Metal. A server with no display at all (most cloud +machines) cannot open a window on any platform: give it a virtual display (Xvfb or Xvnc on +Linux) or use the headless build (`-tags vivahead`), which renders offscreen. +The headless renderer needs no graphics driver of its own: with no Vulkan driver on Linux, +or no Metal device on macOS, it draws on the CPU (`internal/raster`), within a few levels +of the GPU pipelines per channel (checked against lavapipe on Linux), with the same LCD +text antialiasing when the desktop asks for it and the target is opaque. On macOS the CPU +headless renderer also draws the native text editor, as the window does. +`VIVA_SOFTWARE_RENDERING=1` asks for the CPU renderer in headless builds on Linux and +macOS, so the CPU pipelines can be exercised on a machine that has a device. The Linux test machine is a virtual display plus lavapipe. The case of no Vulkan loader at all is covered by a unit test and by the CPU renderer's live X11 test run with the loader hidden, not by a machine that physically lacks the library. diff --git a/docs/diagnostics.md b/docs/diagnostics.md index db5d009bf..4cf26c26f 100644 --- a/docs/diagnostics.md +++ b/docs/diagnostics.md @@ -147,7 +147,78 @@ A panic the application recovers itself enters the stream with - No timer, goroutine, file descriptor or connection is created by either package. - Nothing is written to stderr unless the application's handler does it. The - few platform messages that still go to stderr are independent of this stream. + few platform messages that still go to stderr, and the frame trace below, are + independent of this stream. + +## Frame trace + +`VIVA_TRACE=1` makes every window write one line to stderr for each event it +receives and each frame it paints, so a developer can see why a frame was +painted and find redundant redraws and idle wake-ups. A window left alone +prints nothing; a line that keeps coming while nobody touches the window is +the bug. It works the same in a real window and in the headless driver. Any +value but empty and `0` turns it on; it is read once, at start. + +```text +viva trace: w1 open "Editor" 900x600 +viva trace: w1 frame 1 reason=open passes=1 retries=0 paint=3.100ms publish=0.840ms instances=412 changed=all labels=37 accessibility +viva trace: w1 event pointer move +viva trace: w1 frame 2 reason=pointer passes=1 retries=0 paint=0.410ms publish=0.060ms instances=412 changed=3 present=1.920ms +viva trace: w1 frame 3 reason=timer passes=1 retries=0 paint=0.380ms publish=0.030ms instances=412 changed=1 present=1.700ms +viva trace: w1 frame 4 reason=invalidate passes=1 retries=0 paint=0.400ms publish=0.020ms instances=412 changed=0 empty present=0.110ms +viva trace: w1 event visibility hidden +viva trace: w1 skip hidden reason=invalidate +viva trace: w1 close +``` + +`w1` numbers the process's windows in the order they opened. An `event` line +names the kind of event and a detail: `pointer down|move|up|exit|cancel`, +`key down|up|shortcut`, `text`, `scroll`, `drop over|leave|drop`, `menu text`, +`accessibility`, `resize x@`, `resize enter|leave` (full +screen), `focus activate|deactivate|keyboard-lost`, `visibility +shown|hidden|minimize|restore`. + +A `frame` line has these fields, in this order: + +| Field | Meaning | +| --- | --- | +| `reason` | why the frame was painted; several reasons are joined by commas when one frame answers several requests | +| `passes` | runs of the page's paint function since the previous frame: settling the focus and hover after a layout change, and the event passes input delivers to controls, are counted | +| `retries` | paints a `ui` page took back and did again inside those passes, because a memoized part or a container query did not fit | +| `paint` | time in the paint function for those passes; layout is value code inside it, so it is included | +| `publish` | time reconciling the painted canvas with the retained scene, the input regions and the accessibility tree | +| `instances` | retained render instances after the frame | +| `changed` | instances the renderer uploads again, `all` for a rebuild; `shrink` follows when the list got shorter | +| `labels` | text labels handed over again; absent when they were kept | +| `accessibility`, `text-input`, `native-views` | present when the frame changed the accessibility tree, the platform's text editor or the native views | +| `empty` | the frame gave the platform nothing to do: it was redundant | +| `present` | time from handing the frame over to the platform reporting it presented; absent where the platform does not report it | + +The reasons are: + +| Reason | Requested by | +| --- | --- | +| `open` | the first frame | +| `resize`, `scale` | a new window size or full-screen state; a new display scale | +| `visibility` | a window shown again, painting the frame it skipped while hidden | +| `focus` | the window gaining or losing the activation or the keyboard | +| `pointer`, `key`, `text`, `scroll`, `drop` | input: mouse, pen and finger; keys and shortcuts; text input and input methods; wheel, touchpad and pinch; files dragged from the system | +| `menu`, `accessibility` | a menu command; a request from assistive technology | +| `animation` | a transition in flight, asking for the next frame | +| `timer` | a frame the page asked for later, such as a caret's next blink | +| `invalidate` | the application from outside a paint: `Invalidator.Invalidate` or `Post`, an embedded web view, `Driver.Paint` | +| `settings` | a change of the desktop's fonts or motion preference | +| `system` | a redraw the platform asked for with no cause recorded in Viva, such as an exposed window | + +A wake of a window nobody can see runs `OnWake` but skips the paint; it writes a +`skip hidden` line with the reasons it was woken for, so a background producer +that keeps waking a hidden window shows up too. + +The trace is not part of the diagnostic stream: frames are not failures, a busy +window paints a hundred a second, and they would push the events a capture ring +exists for out of it. Its cost when off is a nil check per traced call site; the +frame requests carry their reason as a bit set, which costs nothing measurable, +and a steady frame allocates nothing with the trace off or on. ## What this is not @@ -157,5 +228,6 @@ A panic the application recovers itself enters the stream with batching. Sending diagnostics somewhere is an application decision, made visible in its handler. - Not a tracing system: no spans, no correlation IDs. A handler that wants them - can add attributes of its own. + can add attributes of its own. The frame trace above is a developer switch, + not a stream. - Not backpressure-aware: a handler that blocks blocks the reporter. diff --git a/docs/skills/building-with-viva/SKILL.md b/docs/skills/building-with-viva/SKILL.md index e1bd4269d..580e598c4 100644 --- a/docs/skills/building-with-viva/SKILL.md +++ b/docs/skills/building-with-viva/SKILL.md @@ -68,7 +68,7 @@ func (m *model) page(c ui.C) { ### Lists, tables and trees - A long list is `ui.List(c, &m.list, n, func(row ui.ListRow) { ... })`: only the rows on screen are declared. The row's container is `row.Element`, its content is declared with `row.C`. `Selected()`, `Changed()`, `Submitted()`, `ListState.Label` (typeahead), `Selection` (multi-select), `ScrollTo`/`ScrollIntoView`/`Visible`, `Header` (pinned sections), `Reorder` (drag rows), `RowWidth` (sideways scrolling), `ClickModifiers()`. Key rows that hold a `Button`: `ui.Row(c.KeyInt(item.ID))`. -- A table is `ui.Table(c, &m.table, ui.TableSpec{Columns, Source})`, where each `ui.TableColumn` has a `Title`, `Width`, `Alignment` and `Sortable`; the data is a `ui.TableRows` (`[][]string`) or your own `Len() int` / `Cell(row, col int) string`. `RowClicked()`, `HeaderClicked()`, `SortBy`, `Select`. +- A table is `ui.Table(c, &m.table, ui.TableSpec{Columns, Source})`, where each `ui.TableColumn` has a `Title`, `Width`, `Alignment` and `Sortable`; the data is a `ui.TableRows` (`[][]string`) or your own `Len() int` / `Cell(row, col int) string`. `RowClicked()`, `HeaderClicked()`, `SortBy` (ascending, descending, unsorted), `Select`, `Changed()`; `TableState.Selection` (multi-select, as a List's) and `TableSpec.Checkboxes` (a checkbox column showing that Selection). - A tree is `ui.Tree(c, &m.tree, n, label, content)` with a `TreeState.Node` per visible row; `Toggled()` and `Chosen()` report the user's action; a branch whose children are being fetched sets `TreeNode.Loading` (a spinner in place of its chevron); `CanDrop` + `Dropped()` for drag and drop. `RowID(i)` is a row's identity; a part of a row is `ui.Text(c, name).LabelFor(m.tree.RowID(i))`. - A part that rarely changes is `ui.Memo(c, *row, fn)`: it copies the declaration while that value compares equal. Pass the row (or what the function reads), not a counter. - Scrolling: `area := ui.Scroll(c).Grow(1)`; `area.ScrollState()` has `Offset`, `Content`, `Viewport`, `Max()`, `AtEnd()`, `Pinned()`, `ScrollTo`, `ScrollToEnd`; `.Follow(true)` keeps a log or chat at its end; `.Sideways()` and `.Scrollbars()` add horizontal movement and bars. @@ -136,7 +136,7 @@ A component is a function of the page: `func Name(c ui.C) ui.Box`, declared wher Do not open a real window unless the user agrees; it interrupts them and depends on which display it lands on. Use these in order of cost. 1. **A Go test with `app.Driver`.** `driver, err := app.NewDriver(ui.NewPage(ui.PageConfig{View: m.page}).Config(base), nil)` runs the real painter, router and focus rules. Drive it with `Click`, `Key`, `Type`, `Scroll`, `Resize`, `Advance`, and read `driver.Snapshot()` for the labels, hit regions and focus. Find controls by their accessible name (`Hit.Label`), not by pixel. See `examples/guides/hello/main_test.go`. -2. **The headless line protocol.** Import `github.com/vivaui/viva/headless/auto` from a file guarded by `//go:build vivahead`, build with `-tags vivahead`, and start the program with `VIVA_HEADLESS=1` and a throwaway `HOME`. It reads one command per line: `click "Label"`, `type`, `key`, `waitfor`, `shot`, `texts`, `layout`, `tree`, `focus`, `expect`. Each reply ends in `ok` or `error`. The full command list is the comment above `Serve` in [`headless/control.go`](https://github.com/vivaui/viva/blob/main/headless/control.go); do not copy it elsewhere. +2. **The headless line protocol.** Import `github.com/vivaui/viva/headless/auto` from a file guarded by `//go:build vivahead`, build with `-tags vivahead`, and start the program with `VIVA_HEADLESS=1` and a throwaway `HOME`. It reads one command per line: `click "Label"`, `type`, `key`, `waitfor`, `shot`, `texts`, `layout`, `tree`, `focus`, `expect`, and `access` for what a screen reader asks of a control. Each reply ends in `ok` or `error`. The full command list is the comment above `Serve` in [`headless/control.go`](https://github.com/vivaui/viva/blob/main/headless/control.go); do not copy it elsewhere. 3. **Read the frame.** - `layout` lists text that is clipped, spills or overlaps. - `tree` lists every control with its role, identity, name, value and state (`focused`, `disabled`, `covered` ...). diff --git a/docs/system-integrations.md b/docs/system-integrations.md index 2eff9a43f..3f90e24b9 100644 --- a/docs/system-integrations.md +++ b/docs/system-integrations.md @@ -31,6 +31,7 @@ synchronous forms report `ErrAsyncRequired`, `ErrSecretStoreUnavailable` or | Font registration (`RegisterFontAsync`) | CoreText process registration | DirectWrite process registration | Fontconfig process registration | `FontFace` loaded from the application's data; family, weight and italic come from the sfnt tables | | Font enumeration (`FontFamilies`, `MonospaceFamilies`) | system list | system list | fontconfig list | empty: browsers do not expose installed fonts | | Dock badge (`Application.SetDockBadge`) | `NSDockTile.badgeLabel`: the red label macOS draws at the tile's top corner, and an empty label removes it | nothing to do: the taskbar badge a program can set is a picture, not a label | nothing to do: a launcher entry has no badge | nothing to do | +| Window attention (`Window.RequestAttention`) | `NSApplication.requestUserAttention:NSInformationalRequest`: the Dock tile bounces once; it is per application, so nothing shows while another window of the app is frontmost | `FlashWindowEx` with `FLASHW_ALL` and `FLASHW_TIMERNOFG`: the taskbar button and caption flash until the window comes forward | X11 `_NET_WM_STATE_DEMANDS_ATTENTION`; the GTK shell sets the toplevel's urgency hint | `ErrUnsupported`: a page cannot ask the desktop to highlight its taskbar entry | | File icon (`FileIcon`, returns `gfx.Bitmap`) | `NSWorkspace.iconForFile:`: the icon Finder shows, an application bundle's own included; a missing path answers from the type its extension names | `SHGetFileInfoW`: the icon the shell gives, an existing file or folder's own included; a missing path answers from its extension | `ErrUnsupported` | `ErrUnsupported` | | Preferred languages (`PreferredLanguages`, returns `[]string`) | `NSLocale.preferredLanguages` | `GetUserPreferredUILanguages` | `LANGUAGE`, `LC_ALL`, `LC_MESSAGES`, `LANG`; the C locale reports nothing | `navigator.languages` | | System appearance (`SystemAppearance`, `WatchSystemAppearance`; returns `Appearance`) | the application's effective appearance, watched by KVO | the `AppsUseLightTheme` setting, changes heard as `WM_SETTINGCHANGE` | the settings portal's `org.freedesktop.appearance` `color-scheme`, else the XSETTINGS manager, `GTK_THEME`, GTK's `settings.ini` and KDE's `ColorScheme`; changes heard as the portal's `SettingChanged` (one session-bus connection the event loop polls, open only while something watches) and as the XSETTINGS manager's property change; unknown when none says | `prefers-color-scheme`, watched with `matchMedia` | diff --git a/docs/upgrading.md b/docs/upgrading.md index b94fac3fd..52fcf0f8c 100644 --- a/docs/upgrading.md +++ b/docs/upgrading.md @@ -14,7 +14,7 @@ with its own predecessor, not with whatever the application is on. ## Incompatible changes Newest first. This guide covers the incompatible changes documented here from -v0.2.2 through v0.6.0 and in v0.6.8 and v0.6.9, including package moves as well +v0.2.2 through v0.6.0 and in v0.6.8, v0.6.9 and v0.6.12, including package moves as well as removed members and changed signatures. Read every entry newer than the application's current version, together with the corresponding [release notes](releases/). For a target between or newer than those, also check its @@ -22,6 +22,36 @@ intervening release notes; this page is not a promise that other releases only add API. Releases before v0.2.2 are not covered: the release-note archive begins there. +### v0.6.12 - a `ui.Table`'s checkboxes are its multiple selection + +`TableSpec.Checked` and `TableState.CheckedChanged` are gone. A table chooses +several rows with `TableState.Selection`, a `*ui.Selection` of row indexes, as a +`ListState.Selection` does: Shift and Primary with a click or the arrow keys, +and Primary+A. `TableSpec.Checkboxes` shows that Selection as a leading column +of checkboxes, so a ticked row and a chosen one are the same; `Changed` reports +ticks as well as clicks and keys. + +```go +// Before +ui.Table(c, &m.table, ui.TableSpec{Source: &m.rows, Columns: cols, Checked: &m.ticked}) +if m.table.CheckedChanged() { ... } + +// After +m.table.Selection = &m.ticked +ui.Table(c, &m.table, ui.TableSpec{Source: &m.rows, Columns: cols, Checkboxes: true}) +if m.table.Changed() { ... } +``` + +A click on a row of such a table now chooses that row alone, as it does in a +list of several; it used to leave the ticks alone. + +### v0.6.12 - a sorted `ui.Table` header unsorts on its third click + +`TableState.SortBy` on the column already sorted descending now leaves no column +sorted (ascending, descending, unsorted), where it used to go back to ascending. +An application that orders its rows after `HeaderClicked` puts them back in their +own order when `Sort` reports `ok == false`. + ### v0.6.9 - `app.StartFileDrag` no longer reports the effect `StartFileDrag` returns only an error: the effect the target took is the diff --git a/examples/guides/table/main.go b/examples/guides/table/main.go index 7d07b5b52..294997272 100644 --- a/examples/guides/table/main.go +++ b/examples/guides/table/main.go @@ -11,21 +11,24 @@ import ( ) type model struct { - table ui.TableState - rows ui.TableRows + table ui.TableState + servers ui.TableRows // in the order they were added + rows ui.TableRows // in the order the table shows them } func newModel() *model { - return &model{rows: ui.TableRows{ + m := &model{servers: ui.TableRows{ {"web-01", "Running", "eu-west"}, {"web-02", "Running", "us-east"}, {"db-primary", "Degraded", "eu-west"}, {"cache", "Stopped", "us-east"}, }} + m.sortRows() + return m } -// page declares the table. A header click sorts the rows; a row click and the -// arrow keys select a row, and the table keeps the selection and the scroll +// page declares the table. A header click sorts the rows by that column, up, then +// down, then back in their own order; a row click and the arrow keys select a row, and the table keeps the selection and the scroll // position itself. func (m *model) page(c ui.C) { ui.Column(c).Fill().Pad(24).Gap(12).Children(func() { @@ -49,9 +52,11 @@ func (m *model) page(c ui.C) { }) } -// sortRows orders the rows by the column the table reports as sorted. The table -// paints the arrow; the application owns the data and its order. +// sortRows orders the rows by the column the table reports as sorted, or in their +// own order when none is. The table paints the arrow; the application owns the +// data and its order. func (m *model) sortRows() { + m.rows = append(m.rows[:0], m.servers...) column, descending, ok := m.table.Sort() if !ok { return diff --git a/gfx/canvas.go b/gfx/canvas.go index 3ec6643ae..ba0861b29 100644 --- a/gfx/canvas.go +++ b/gfx/canvas.go @@ -404,6 +404,9 @@ const ( // RoleProgressBar is a read-only progress indicator: it reports a value // between bounds while an operation runs, and activates nothing. RoleProgressBar + // RoleColumnHeader is the header of a table's column that the user can + // press, to sort the rows by it: HitOptions.Sort says how they are sorted. + RoleColumnHeader ) // roleNames are the names of the roles: what a selector or a printed tree calls @@ -414,7 +417,7 @@ var roleNames = [...]string{ RoleTextField: "textfield", RoleSlider: "slider", RoleTerminal: "terminal", RoleGroup: "group", RoleMenu: "menu", RoleMenubar: "menubar", RoleListBox: "listbox", RoleOption: "option", RoleGrid: "grid", RoleGridCell: "gridcell", RoleHeading: "heading", RoleStatus: "status", - RoleSeparator: "separator", RoleProgressBar: "progressbar", + RoleSeparator: "separator", RoleProgressBar: "progressbar", RoleColumnHeader: "columnheader", } // String is the role's name as selectors and printed trees write it, such as @@ -448,6 +451,17 @@ const ( LiveAssertive ) +// SortDirection is how the rows under a column header are ordered by it, for +// assistive technology (aria-sort). The zero value is a column the rows are not +// sorted by. +type SortDirection uint8 + +const ( + SortNone SortDirection = iota + SortAscending + SortDescending +) + // ValueRange is the numeric value of a slider, a progress bar or a spinner: // where it is, the bounds it moves between and the smallest step. Set is false // for a control with no number to report. @@ -482,6 +496,15 @@ const ( PointerCursorImage ) +// TextSelection describes text selected in a custom terminal. Bounds contains +// one rectangle per visible selected row, in window logical pixels. A selection +// entirely outside the viewport has no rectangles. Keep the snapshot immutable +// and reuse it until the selection or its screen position changes. +type TextSelection struct { + Text string + Bounds []Rect +} + // HitOptions describes interaction and accessibility state without a dynamic // property bag. Zero values represent an enabled focusable button. type HitOptions struct { @@ -499,6 +522,9 @@ type HitOptions struct { // cursor, as with CursorImage. CursorImageAt CursorImageFunc Value string + // TextSelection exposes a terminal's selected output independently of its + // native text input, which remains at the typing cursor for input methods. + TextSelection *TextSelection Hint string Disabled bool // FocusableWhenDisabled keeps a disabled control in the Tab order and @@ -514,6 +540,12 @@ type HitOptions struct { // Mixed marks a checkbox in the indeterminate state (aria-checked="mixed"). Mixed bool Selected bool + // MultiSelectable marks a list whose items the user can choose several of + // at once (aria-multiselectable); with Canvas.ContainerWithOptions. + MultiSelectable bool + // Sort is how a column header orders the rows (aria-sort); with + // RoleColumnHeader. + Sort SortDirection Expanded bool // Expandable marks a control that opens and closes something (a disclosure, // an accordion trigger, a menu with a submenu), so assistive technology @@ -633,8 +665,8 @@ type HitOptions struct { // that, CursorImageAt being a function. func (options HitOptions) IsZero() bool { return options.Role == 0 && options.Cursor == 0 && options.CursorImage == nil && options.CursorImageAt == nil && - options.Value == "" && options.Hint == "" && !options.Disabled && !options.FocusableWhenDisabled && !options.SecondaryWhenDisabled && - !options.Checked && !options.Mixed && !options.Selected && !options.Expanded && !options.Expandable && !options.Multiline && !options.ReadOnly && + options.Value == "" && options.TextSelection == nil && options.Hint == "" && !options.Disabled && !options.FocusableWhenDisabled && !options.SecondaryWhenDisabled && + !options.Checked && !options.Mixed && !options.Selected && !options.MultiSelectable && options.Sort == SortNone && !options.Expanded && !options.Expandable && !options.Multiline && !options.ReadOnly && !options.Invalid && !options.Secure && options.Description == "" && options.Level == 0 && options.PosInSet == 0 && options.SetSize == 0 && options.Live == 0 && options.Range == (ValueRange{}) && !options.SkipFocus && !options.SkipTab && !options.Backdrop && !options.PassSecondary && !options.PassPrimary && !options.label && !options.Presentational && !options.Autofocus && @@ -687,7 +719,9 @@ type Hit struct { CursorImageAt int32 // CursorImage is HitOptions.CursorImage. CursorImage *CursorImage - Disabled bool + // TextSelection is the terminal selection supplied in HitOptions. + TextSelection *TextSelection + Disabled bool // FocusableDisabled is HitOptions.FocusableWhenDisabled. FocusableDisabled bool // SecondaryWhenDisabled is HitOptions.SecondaryWhenDisabled. @@ -695,7 +729,10 @@ type Hit struct { Checked bool Mixed bool Selected bool - Expanded bool + // MultiSelectable and Sort are the HitOptions fields of the same names. + MultiSelectable bool + Sort SortDirection + Expanded bool // Expandable is HitOptions.Expandable. Expandable bool Multiline bool @@ -860,8 +897,9 @@ type Canvas struct { // it. A menu row uses it to tell the menu's own padding from the world outside // the menu. onSurface bool - // titlebarLeading and titlebarTrailing are the window's TitlebarInsets. - titlebarLeading, titlebarTrailing float32 + // titlebarLeading and titlebarTrailing are the window's TitlebarInsets, and + // titlebarHeight is the height of its strip (TitlebarHeight). + titlebarLeading, titlebarTrailing, titlebarHeight float32 // touched is set once a finger has touched the window. touched bool // prevHovered is the hit the pointer was on at the end of the previous @@ -1746,7 +1784,9 @@ func (canvas *Canvas) TextOffsetAtStyle(value string, style TextStyle, x float32 // color, weight and slant (TextRun.Italic). A terminal row is one such line, // however many colors it holds, so the number and order of labels stays stable // while its content changes. Bounds is the whole line; its width should be -// columns*cellWidth. +// columns*cellWidth. A glyph wider than its cell may reach a cell past either +// end of the line; the picture has room for it, and only the canvas clip, when +// there is one, cuts it. // runs must cover value (see TextRun); the canvas copies them, so the caller // may reuse the slice as soon as the call returns. func (canvas *Canvas) LabelRuns(value string, bounds Rect, style TextStyle, cellWidth float32, runs []TextRun) { @@ -1853,6 +1893,7 @@ func (canvas *Canvas) HitWithOptions(id ID, bounds Rect, label string, options H focusable := (!options.Disabled || options.FocusableWhenDisabled) && !options.SkipFocus && !options.Presentational if options.Secure { options.Value = "" + options.TextSelection = nil } // The text geometry lives beside the hit so that copying and comparing the // hit list does not carry it. One declaration appends at most one entry, so a @@ -1877,13 +1918,13 @@ func (canvas *Canvas) HitWithOptions(id ID, bounds Rect, label string, options H } canvas.hits = append(canvas.hits, Hit{ ID: id, Bounds: bounds, Label: label, - Value: options.Value, Hint: options.Hint, + Value: options.Value, Hint: options.Hint, TextSelection: options.TextSelection, Scope: canvas.currentFocusScope(), Layer: canvas.currentLayer(), Role: role, Cursor: options.Cursor, CursorImage: options.CursorImage, CursorImageAt: cursorAt, Disabled: options.Disabled, FocusableDisabled: options.Disabled && options.FocusableWhenDisabled, SecondaryWhenDisabled: options.Disabled && options.SecondaryWhenDisabled, Checked: options.Checked, Mixed: options.Mixed, - Selected: options.Selected, Expanded: options.Expanded, Expandable: options.Expandable || options.Expanded, + Selected: options.Selected, Sort: options.Sort, Expanded: options.Expanded, Expandable: options.Expandable || options.Expanded, Multiline: options.Multiline, ReadOnly: options.ReadOnly, Invalid: options.Invalid, Secure: options.Secure, Description: options.Description, Level: options.Level, PosInSet: options.PosInSet, SetSize: options.SetSize, Live: options.Live, Range: options.Range, @@ -1922,8 +1963,9 @@ func (canvas *Canvas) Container(bounds Rect, role Role, label string) { } // ContainerWithOptions is Container with the accessibility detail of a region: -// the Level of a heading, the Live setting of a status area, a Description. -// Other options have no meaning for a region that takes no press. +// the Level of a heading, the Live setting of a status area, a Description, a +// list whose items are MultiSelectable. Other options have no meaning for a region +// that takes no press. func (canvas *Canvas) ContainerWithOptions(bounds Rect, role Role, label string, options HitOptions) { if clip, clipped := canvas.clipSnapshot(); clipped { bounds = intersectCanvasRect(bounds, clip) @@ -1933,7 +1975,7 @@ func (canvas *Canvas) ContainerWithOptions(bounds Rect, role Role, label string, } canvas.hits = append(canvas.hits, Hit{ Bounds: bounds, Label: label, Scope: canvas.currentFocusScope(), Layer: canvas.currentLayer(), - Role: role, Container: true, + Role: role, Container: true, MultiSelectable: options.MultiSelectable, Description: options.Description, Level: options.Level, PosInSet: options.PosInSet, SetSize: options.SetSize, Live: options.Live, Range: options.Range, }) @@ -2348,6 +2390,21 @@ func (canvas *Canvas) SetTitlebarInsets(leading, trailing float32) { canvas.titlebarLeading, canvas.titlebarTrailing = leading, trailing } +// TitlebarHeight is the height in logical pixels of the strip the window buttons +// cover the ends of: the custom titlebar's own height, zero for a window whose +// titlebar is the system's and for one in full screen, where the buttons are not +// shown. An overlay that anchors to the window's top edge starts under it, as a +// sheet attaches below the titlebar. +func (canvas *Canvas) TitlebarHeight() float32 { + return canvas.titlebarHeight +} + +// SetTitlebarHeight records the window's TitlebarHeight; the runtime calls it +// before each paint. +func (canvas *Canvas) SetTitlebarHeight(height float32) { + canvas.titlebarHeight = height +} + // HoverCrossed reports whether pointer input reached a different hit since the // previous paint or moved within a hit that layout moved under the pointer. // Lists use it to move their current row without taking it back from the diff --git a/gfx/replay.go b/gfx/replay.go index 12e741aff..ff5912b41 100644 --- a/gfx/replay.go +++ b/gfx/replay.go @@ -236,6 +236,13 @@ func (canvas *Canvas) moveSince(from Mark, dx, dy float32) { for i := from.hits; i < uint32(len(canvas.hits)); i++ { hit := &canvas.hits[i] hit.Bounds = hit.Bounds.Offset(dx, dy) + if selected := hit.TextSelection; selected != nil && len(selected.Bounds) > 0 { + rows := make([]Rect, len(selected.Bounds)) + for i, row := range selected.Bounds { + rows[i] = row.Offset(dx, dy) + } + hit.TextSelection = &TextSelection{Text: selected.Text, Bounds: rows} + } if hit.Text != 0 { if index := int(hit.Text) - 1; index < len(canvas.hitTexts) { canvas.hitTexts[index].Bounds = canvas.hitTexts[index].Bounds.Offset(dx, dy) diff --git a/gfx/replay_test.go b/gfx/replay_test.go index 03fe48cf2..4b8040d8e 100644 --- a/gfx/replay_test.go +++ b/gfx/replay_test.go @@ -280,6 +280,27 @@ func TestReplayAtMovesAndRewindTakesBack(t *testing.T) { } } +func TestReplayAtMovesTerminalSelectionWithItsHit(t *testing.T) { + var canvas Canvas + canvas.KeepPrevious(true) + row := Rect{X: 4, Y: 8, Width: 20, Height: 16} + selection := &TextSelection{Text: "run", Bounds: []Rect{row}} + var span Span + paintPage(&canvas, 0, func(c *Canvas) { + from := c.Mark() + c.HitWithOptions(Item(1), row, "Terminal", HitOptions{Role: RoleTerminal, TextSelection: selection}) + span = c.SpanSince(from) + }) + paintPage(&canvas, 0, func(c *Canvas) { + if _, ok := c.ReplayAt(span, 8, 32); !ok { + t.Fatal("could not replay terminal") + } + if got := c.Hits()[0].TextSelection.Bounds[0]; got != row.Offset(8, 32) || selection.Bounds[0] != row { + t.Fatalf("replayed row = %v, original = %v", got, selection.Bounds[0]) + } + }) +} + func TestReplayAtRefusesToMoveAcrossAClip(t *testing.T) { var canvas Canvas canvas.KeepPrevious(true) diff --git a/gfx/role_test.go b/gfx/role_test.go index 60c1767d6..aab4727d6 100644 --- a/gfx/role_test.go +++ b/gfx/role_test.go @@ -3,7 +3,7 @@ package gfx import "testing" func TestRoleNamesRoundTrip(t *testing.T) { - for role := RoleButton; role <= RoleProgressBar; role++ { + for role := RoleButton; role <= RoleColumnHeader; role++ { name := role.String() if name == "" || name == "region" { t.Fatalf("role %d has no name", role) diff --git a/headless/access_test.go b/headless/access_test.go new file mode 100644 index 000000000..2fa2d1c5c --- /dev/null +++ b/headless/access_test.go @@ -0,0 +1,224 @@ +//go:build darwin || windows || linux + +package headless + +import ( + "strings" + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/text" +) + +// accessApp is a form a screen reader operates: a button, a disabled button, +// a text field, a slider, and a modal dialog that opens over them. +type accessApp struct { + saves, deletes, oks int + volume float64 + modal bool + editor text.Editor +} + +var accessDialog = gfx.Item(100) + +func (a *accessApp) config() app.Config { + return app.Config{ + Title: "access", Width: 320, Height: 240, + Paint: func(canvas *gfx.Canvas, size gfx.Size) { + canvas.HitWithLabel(gfx.Item(1), gfx.Rect{X: 16, Y: 16, Width: 80, Height: 24}, "Save") + if canvas.Clicked(gfx.Item(1)) { + a.saves++ + } + canvas.HitWithOptions(gfx.Item(2), gfx.Rect{X: 112, Y: 16, Width: 80, Height: 24}, "Delete", gfx.HitOptions{Disabled: true}) + if canvas.Clicked(gfx.Item(2)) { + a.deletes++ + } + canvas.HitWithOptions(gfx.Item(3), gfx.Rect{X: 16, Y: 56, Width: 200, Height: 24}, "Name", + gfx.HitOptions{Role: gfx.RoleTextField, Value: a.editor.String()}) + canvas.HitWithOptions(gfx.Item(4), gfx.Rect{X: 16, Y: 96, Width: 200, Height: 16}, "Volume", gfx.HitOptions{ + Role: gfx.RoleSlider, Range: gfx.ValueRange{Now: a.volume, Min: 0, Max: 100, Step: 10, Set: true}, + }) + if a.modal { + canvas.PushFocusScope(accessDialog) + canvas.TrapFocus(accessDialog) + canvas.Block(gfx.Rect{Width: size.Width, Height: size.Height}) + canvas.HitWithLabel(gfx.Item(5), gfx.Rect{X: 120, Y: 180, Width: 80, Height: 24}, "OK") + if canvas.Clicked(gfx.Item(5)) { + a.oks++ + } + canvas.PopFocusScope() + } + }, + OnKey: func(event gfx.KeyEvent) gfx.EventResult { + switch event.Key { + case gfx.KeyUp: + a.volume = min(a.volume+10, 100) + case gfx.KeyDown: + a.volume = max(a.volume-10, 0) + case gfx.KeyHome: + a.volume = 0 + case gfx.KeyEnd: + a.volume = 100 + default: + return gfx.EventResult{} + } + return gfx.EventResult{Handled: true, Repaint: true} + }, + TextInput: func(app.TextInputContext) *app.TextInput { + return &app.TextInput{Editor: &a.editor, Bounds: gfx.Rect{X: 16, Y: 56, Width: 200, Height: 24}, FontSize: 13} + }, + } +} + +func openAccessApp(t *testing.T) (*Session, *accessApp) { + t.Helper() + target := &accessApp{} + session, err := Open(target.config(), nil, Options{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(session.Close) + return session, target +} + +// perform names a node as a test does, by selector, and makes one request of it. +func perform(t *testing.T, session *Session, selector string, request app.AccessRequest) bool { + t.Helper() + hit, err := session.LocateNode(selector) + if err != nil { + t.Fatal(err) + } + request.Node = hit.ID + handled, err := session.PerformAccess(request) + if err != nil { + t.Fatal(err) + } + return handled +} + +func TestPerformAccessOperatesControlsAsTheirKeysAndClicksDo(t *testing.T) { + session, target := openAccessApp(t) + + if !perform(t, session, "Save", app.AccessRequest{Action: app.AccessPress}) || target.saves != 1 { + t.Fatalf("press: saves = %d", target.saves) + } + if focus, _ := session.AccessByName("Save"); !focus.Focused { + t.Error("a pressed button does not have the keyboard, as a Tab onto it and Space would leave it") + } + + if perform(t, session, "Delete", app.AccessRequest{Action: app.AccessPress}) || target.deletes != 0 { + t.Fatalf("a disabled control took a press: deletes = %d", target.deletes) + } + + if !perform(t, session, "textfield:Name", app.AccessRequest{Action: app.AccessSetText, Text: "web-01"}) { + t.Fatal("set text refused") + } + if got := target.editor.String(); got != "web-01" { + t.Fatalf("editor = %q", got) + } + if node, _ := session.AccessByRole(gfx.RoleTextField, "Name"); node.Value != "web-01" || !node.Focused { + t.Errorf("the tree does not report the new text on the focused field: %+v", node) + } + + before := target.volume + if !perform(t, session, "slider:Volume", app.AccessRequest{Action: app.AccessIncrement}) || target.volume <= before { + t.Fatalf("increment: volume %v -> %v", before, target.volume) + } + if !perform(t, session, "slider:Volume", app.AccessRequest{Action: app.AccessSetNumber, Number: 70}) || target.volume != 70 { + t.Fatalf("set number: volume = %v", target.volume) + } + if node, _ := session.AccessByRole(gfx.RoleSlider, "Volume"); node.Range.Now != target.volume { + t.Errorf("the tree reports %v, the slider holds %v", node.Range.Now, target.volume) + } + + // An action a node's role does not offer is refused, not turned into another. + if perform(t, session, "Save", app.AccessRequest{Action: app.AccessIncrement}) { + t.Error("a button took an increment") + } +} + +func TestPerformAccessDropsRequestsForNodesBehindAModal(t *testing.T) { + session, target := openAccessApp(t) + // Name the node while the page is live, as a screen reader holds it. + save, err := session.LocateNode("Save") + if err != nil { + t.Fatal(err) + } + target.modal = true + if err := session.Frame(); err != nil { + t.Fatal(err) + } + if _, ok := session.AccessByName("Save"); ok { + t.Fatal("the tree still shows a node behind the modal") + } + for _, request := range []app.AccessRequest{ + {Node: save.ID, Action: app.AccessPress}, + {Node: save.ID, Action: app.AccessFocus}, + } { + if handled, err := session.PerformAccess(request); handled || err != nil { + t.Fatalf("request %d behind the modal = %v, %v", request.Action, handled, err) + } + } + if target.saves != 0 { + t.Fatalf("a button behind the modal was pressed %d times", target.saves) + } + if focus := session.Snapshot().Focused; focus == save.ID { + t.Fatal("the keyboard moved behind the modal") + } + if !perform(t, session, "OK", app.AccessRequest{Action: app.AccessPress}) || target.oks != 1 { + t.Fatalf("the dialog's own button: oks = %d", target.oks) + } + + target.modal = false + if err := session.Frame(); err != nil { + t.Fatal(err) + } + if handled, _ := session.PerformAccess(app.AccessRequest{Node: save.ID, Action: app.AccessPress}); !handled || target.saves != 1 { + t.Fatalf("after the modal closed: handled %v, saves %d", handled, target.saves) + } +} + +func TestAccessCommand(t *testing.T) { + session, target := openAccessApp(t) + for _, step := range [][2]string{ + {"access press Save", "ok handled\n"}, + {"access press Delete", "ok refused\n"}, + {`access set textfield:Name "db 02"`, "ok handled\n"}, + {"access increment slider:Volume", "ok handled\n"}, + {"access decrement slider:Volume", "ok handled\n"}, + {"access set slider:Volume 40", "ok handled\n"}, + {"access select textfield:Name 0 2", "ok handled\n"}, + {"access focus Save", "ok handled\n"}, + } { + if reply, _ := execute(session, step[0]); reply != step[1] { + t.Fatalf("%s: %q, want %q", step[0], reply, step[1]) + } + } + if target.saves != 1 || target.deletes != 0 || target.editor.String() != "db 02" || target.volume != 40 { + t.Fatalf("saves %d deletes %d editor %q volume %v", target.saves, target.deletes, target.editor.String(), target.volume) + } + if selection := target.editor.Selection(); selection.Start != 0 || selection.End != 2 { + t.Errorf("selection = %+v", selection) + } + + target.modal = true + if err := session.Frame(); err != nil { + t.Fatal(err) + } + if reply, _ := execute(session, "access press Save"); reply != "ok refused\n" { + t.Fatalf("behind the modal: %q", reply) + } + if target.saves != 1 { + t.Fatalf("saves = %d", target.saves) + } + + for _, command := range []string{ + "access", "access press", "access wave Save", "access set slider:Volume loud", + "access select textfield:Name 1", "access press Save extra", `access press "no such control"`, + } { + if reply, _ := execute(session, command); !strings.HasPrefix(reply, "error ") { + t.Errorf("%s: %q", command, reply) + } + } +} diff --git a/headless/control.go b/headless/control.go index 339049211..a83f5000a 100644 --- a/headless/control.go +++ b/headless/control.go @@ -40,6 +40,12 @@ import ( // key until released. A terminal that asked for key releases // sees the presses and releases; elsewhere keydown acts as key // blur the window loses the keyboard: held keys are released +// access ACTION SEL [VALUE] make the request a screen reader would of the node SEL names +// (a selector as for click, found even where something covers it): +// press | focus | increment | decrement | set SEL VALUE (a number +// on a slider, the text of a field) | select SEL START END (code +// points). It goes where a platform adapter's request goes, so a +// disabled control or one behind a modal refuses: ok handled|refused // type TEXT insert the rest of the line into the focused field // compose [TEXT] set the input-method composition of the focused field to the // rest of the line, as an input method does while a syllable is @@ -107,6 +113,7 @@ import ( // schemehandlers [SCHEME...] declare which custom URL schemes have a registered application (none: clear) // openfiles PATH...|cancel queue the next native open-dialog result // opendirectory PATH|cancel queue the next native directory-dialog result +// opendirectories PATH...|cancel queue selected paths for a directory picker // savefile PATH|cancel queue the next native save-dialog result // quit func Serve(session *Session, in io.Reader, out io.Writer) error { @@ -280,6 +287,14 @@ func execute(session *Session, line string) (reply string, quit bool) { return finish(session.driver.QueueOpenDirectory("", app.ErrCanceled), "") } return finish(session.driver.QueueOpenDirectory(arguments[0], nil), "") + case "opendirectories": + if len(arguments) == 0 { + return finish(fmt.Errorf("opendirectories needs paths or cancel"), "") + } + if len(arguments) == 1 && arguments[0] == "cancel" { + return finish(session.driver.QueueOpenDirectories(nil, app.ErrCanceled), "") + } + return finish(session.driver.QueueOpenDirectories(arguments, nil), "") case "savefile": if len(arguments) != 1 { return finish(fmt.Errorf("savefile needs one path or cancel"), "") @@ -394,6 +409,15 @@ func execute(session *Session, line string) (reply string, quit bool) { return finish(session.KeyUp(arguments[0]), "") case "blur": return finish(session.LoseFocus(), "") + case "access": + handled, err := accessCommand(session, arguments) + if err != nil { + return finish(err, "") + } + if handled { + return finish(nil, " handled") + } + return finish(nil, " refused") case "select": span, err := numbers(2) if err != nil { @@ -638,6 +662,66 @@ func summarizeTexts(snapshot app.Snapshot) string { return strings.Join(values, " | ") } +// accessCommand runs "access ACTION SELECTOR [VALUE...]": the request a screen reader makes of +// the node the selector names (see Session.LocateNode). set takes a number on a slider and text +// on a text field or combobox, as the platforms' value patterns do. +func accessCommand(session *Session, arguments []string) (bool, error) { + if len(arguments) < 2 { + return false, fmt.Errorf("access needs an action (press focus increment decrement set select) and a selector") + } + action, selector, values := arguments[0], arguments[1], arguments[2:] + request := app.AccessRequest{} + switch action { + case "press", "focus", "increment", "decrement": + if len(values) != 0 { + return false, fmt.Errorf("access %s takes one selector", action) + } + switch action { + case "press": + request.Action = app.AccessPress + case "focus": + request.Action = app.AccessFocus + case "increment": + request.Action = app.AccessIncrement + default: + request.Action = app.AccessDecrement + } + case "set": + if len(values) != 1 { + return false, fmt.Errorf("access set needs a selector and one value") + } + case "select": + if len(values) != 2 { + return false, fmt.Errorf("access select needs a selector, START and END") + } + start, startErr := strconv.ParseInt(values[0], 10, 32) + end, endErr := strconv.ParseInt(values[1], 10, 32) + if startErr != nil || endErr != nil { + return false, fmt.Errorf("access select: START and END are whole numbers") + } + request.Action, request.Start, request.End = app.AccessSetSelection, int32(start), int32(end) + default: + return false, fmt.Errorf("access: unknown action %q (press focus increment decrement set select)", action) + } + hit, err := session.LocateNode(selector) + if err != nil { + return false, err + } + request.Node = hit.ID + if action == "set" { + if hit.Role == gfx.RoleSlider { + number, err := strconv.ParseFloat(values[0], 64) + if err != nil { + return false, fmt.Errorf("access set: a slider takes a number, not %q", values[0]) + } + request.Action, request.Number = app.AccessSetNumber, number + } else { + request.Action, request.Text = app.AccessSetText, values[0] + } + } + return session.PerformAccess(request) +} + // splitArguments splits a request tail on spaces, honoring double quotes. func splitArguments(text string) ([]string, error) { var arguments []string diff --git a/headless/control_opendirectory_test.go b/headless/control_opendirectory_test.go index 525bc32f9..d9d2a909a 100644 --- a/headless/control_opendirectory_test.go +++ b/headless/control_opendirectory_test.go @@ -4,6 +4,7 @@ package headless import ( "errors" + "slices" "strings" "testing" @@ -39,3 +40,24 @@ func TestOpenDirectoryControlQueuesPathAndCancel(t *testing.T) { t.Fatalf("missing argument reply = %q", reply) } } + +func TestOpenDirectoriesControlQueuesSeveralFolders(t *testing.T) { + session, err := Open(app.Config{}, nil, Options{}) + if err != nil { + t.Fatal(err) + } + defer session.Close() + + reply, _ := execute(session, `opendirectories "/tmp/项目 A" "/tmp/B"`) + if reply != "ok\n" { + t.Fatalf("queue directories: %q", reply) + } + paths, err := app.OpenDirectories(app.OpenDirectoryOptions{}) + if err != nil || !slices.Equal(paths, []string{"/tmp/项目 A", "/tmp/B"}) { + t.Fatalf("selected directories = %q, %v", paths, err) + } + execute(session, "opendirectories cancel") + if _, err := app.OpenDirectories(app.OpenDirectoryOptions{}); !errors.Is(err, app.ErrCanceled) { + t.Fatalf("canceled picker = %v", err) + } +} diff --git a/headless/controls.go b/headless/controls.go index a0b7bba7f..c146b698e 100644 --- a/headless/controls.go +++ b/headless/controls.go @@ -72,6 +72,9 @@ func (c control) flags(focused gfx.ID) []string { add(c.hit.Checked, "checked") add(c.hit.Mixed, "mixed") add(c.hit.Selected, "selected") + add(c.hit.MultiSelectable, "multiselectable") + add(c.hit.Sort == gfx.SortAscending, "sorted ascending") + add(c.hit.Sort == gfx.SortDescending, "sorted descending") add(c.hit.Expandable && c.hit.Expanded, "expanded") add(c.hit.Expandable && !c.hit.Expanded, "collapsed") add(c.hit.ReadOnly, "readonly") @@ -221,6 +224,30 @@ func (session *Session) Locate(text string) (gfx.Hit, error) { return gfx.Hit{}, session.noControl(text) } +// LocateNode returns the front-most control a selector names (see selector for the forms) the +// way assistive technology reaches it: by its node, not by a press at its center, so a control +// something covers, or one a modal now hides, is found too; whether it takes a request is the +// application's answer (see PerformAccess). A bare name is matched as by the other selectors: +// the exact accessible name first, then any name containing it. +func (session *Session) LocateNode(text string) (gfx.Hit, error) { + s, err := parseSelector(text) + if err != nil { + return gfx.Hit{}, err + } + all := session.controls(session.Snapshot()) + for _, exact := range []bool{true, false} { + for index := len(all) - 1; index >= 0; index-- { + if s.matches(all[index], exact) && !all[index].hit.Container { + return all[index].hit, nil + } + } + if s.byID || s.label == "" { + break + } + } + return gfx.Hit{}, session.noControl(text) +} + // noControl is the error for a selector nothing answers to, with what the frame does offer. func (session *Session) noControl(text string) error { snapshot := session.Snapshot() diff --git a/headless/doc.go b/headless/doc.go index 7bc247602..9fc6cc3c8 100644 --- a/headless/doc.go +++ b/headless/doc.go @@ -50,6 +50,13 @@ // node, ok := session.AccessByRole(gfx.RoleCheckbox, "Auto update") // if !ok || !node.Checked { ... } // +// PerformAccess makes the request a screen reader would (press, focus, increment, set a value +// or a selection) through the handler a window's platform adapter calls, so a disabled control +// or one behind a modal refuses it; LocateNode names the node by selector: +// +// save, _ := session.LocateNode("button:Save") +// handled, err := session.PerformAccess(app.AccessRequest{Node: save.ID, Action: app.AccessPress}) +// // A session has no notification center: Notifications returns the ones the // application sent, in order, instead of showing them. // diff --git a/headless/grid_overhang_darwin_test.go b/headless/grid_overhang_darwin_test.go new file mode 100644 index 000000000..0e9126449 --- /dev/null +++ b/headless/grid_overhang_darwin_test.go @@ -0,0 +1,72 @@ +//go:build darwin && vivahead + +package headless + +import ( + "image" + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" +) + +// A glyph wider than its cell, a color emoji here, reaches past the first and +// last column of a grid line. Without a canvas clip the line's picture has room +// for it on both sides; a clip that is the line itself still cuts it there. +func TestHeadlessGridLineShowsGlyphsOverhangingItsEnds(t *testing.T) { + white := gfx.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1} + style := gfx.TextStyle{Size: 16, Color: white, Mono: true} + const left, top, rowHeight = 40, 0, 24 + for _, test := range []struct { + name string + clipped bool + }{{"unclipped", false}, {"clipped to the line", true}} { + t.Run(test.name, func(t *testing.T) { + var cell float32 + session, err := Open(app.Config{ + Title: "overhang", Width: 160, Height: rowHeight, ClearColor: app.Color{Alpha: 1}, + Paint: func(canvas *gfx.Canvas, _ gfx.Size) { + cell, _ = canvas.MonoCellSize(style.Size, style.MonoFace) + bounds := gfx.Rect{X: left, Y: top, Width: cell, Height: rowHeight} + if test.clipped { + canvas.Clip(bounds) + defer canvas.Unclip() + } + canvas.LabelRuns("\U0001F600", bounds, style, cell, []gfx.TextRun{{Bytes: 4, Cells: 1, Color: white}}) + }, + }, nil, Options{Scale: 1}) + if err != nil { + t.Fatal(err) + } + defer session.Close() + picture, err := session.Image() + if err != nil { + t.Fatal(err) + } + first, last := anyInkColumns(picture, top, top+rowHeight) + if first < 0 { + t.Fatal("the emoji left no ink") + } + spills := first < left || last >= left+int(cell) + if spills == test.clipped { + t.Errorf("clipped=%v: ink spans [%d, %d], the cell [%d, %d)", test.clipped, first, last, left, left+int(cell)) + } + }) + } +} + +func anyInkColumns(picture *image.RGBA, top, bottom int) (first, last int) { + first, last = -1, -1 + for x := 0; x < picture.Bounds().Dx(); x++ { + for y := top; y < bottom; y++ { + if pixel := picture.RGBAAt(x, y); max(pixel.R, pixel.G, pixel.B) > 0x40 { + if first < 0 { + first = x + } + last = x + break + } + } + } + return first, last +} diff --git a/headless/render_darwin.go b/headless/render_darwin.go index 34ed46d59..26f125d8e 100644 --- a/headless/render_darwin.go +++ b/headless/render_darwin.go @@ -3,17 +3,32 @@ package headless import ( + "errors" "image" + "os" "github.com/vivaui/viva/app" "github.com/vivaui/viva/internal/platform" "github.com/vivaui/viva/internal/platform/darwin" + "github.com/vivaui/viva/internal/render" ) +// offscreen is what draws a frame to pixels: the Metal pipelines, or the CPU +// rasterizer on a machine with no Metal device. +type offscreen interface { + Set([]render.Rectangle, []platform.TextLabel, *platform.TextInput) error + Render() ([]byte, int, int, error) + Close() +} + +// softwareRenderingRequested says the caller asked for the CPU renderer even +// where a GPU exists, as VIVA_SOFTWARE_RENDERING=1 asks of a window. +func softwareRenderingRequested() bool { return os.Getenv("VIVA_SOFTWARE_RENDERING") == "1" } + // renderer keeps one Metal offscreen renderer, recreated when the frame's // size, scale or clear color changes. type renderer struct { - offscreen *darwin.Offscreen + offscreen offscreen width, height int scale float64 clear app.Color @@ -30,7 +45,7 @@ const defaultScale = 2 const rendererAvailable = true -func newRenderer() *renderer { return &renderer{} } +func newRenderer(app.Config) *renderer { return &renderer{} } func (r *renderer) close() { if r.offscreen != nil { @@ -42,12 +57,27 @@ func (r *renderer) close() { func (r *renderer) render(snapshot app.Snapshot, scale float64) (*image.RGBA, error) { if r.offscreen == nil || r.width != snapshot.Width || r.height != snapshot.Height || r.scale != scale || r.clear != snapshot.Clear { r.close() - offscreen, err := darwin.NewOffscreen(snapshot.Width, snapshot.Height, scale, platform.Color{ - Red: snapshot.Clear.Red, Green: snapshot.Clear.Green, Blue: snapshot.Clear.Blue, Alpha: snapshot.Clear.Alpha, - }) - if err != nil { - return nil, err + clear := platform.Color{Red: snapshot.Clear.Red, Green: snapshot.Clear.Green, Blue: snapshot.Clear.Blue, Alpha: snapshot.Clear.Alpha} + var target offscreen + if !softwareRenderingRequested() { + gpu, err := darwin.NewOffscreen(snapshot.Width, snapshot.Height, scale, clear) + switch { + case err == nil: + target = gpu + case errors.Is(err, platform.ErrNoGraphics): + // No Metal device: the CPU renderer draws the screenshot. + default: + return nil, err + } + } + if target == nil { + cpu, err := darwin.NewCPUOffscreen(snapshot.Width, snapshot.Height, scale, clear) + if err != nil { + return nil, err + } + target = cpu } + offscreen := target r.offscreen, r.width, r.height, r.scale, r.clear = offscreen, snapshot.Width, snapshot.Height, scale, snapshot.Clear } rectangles, labels, input := scenery(snapshot) diff --git a/headless/render_linux.go b/headless/render_linux.go index 7e6ac99bf..f5a447912 100644 --- a/headless/render_linux.go +++ b/headless/render_linux.go @@ -5,6 +5,7 @@ package headless import ( "errors" "image" + "os" "github.com/vivaui/viva/app" "github.com/vivaui/viva/internal/platform" @@ -20,8 +21,13 @@ type offscreen interface { Close() } +// softwareRenderingRequested says the caller asked for the CPU renderer even +// where a Vulkan driver exists, as VIVA_SOFTWARE_RENDERING=1 asks of a window. +func softwareRenderingRequested() bool { return os.Getenv("VIVA_SOFTWARE_RENDERING") == "1" } + // renderer keeps one offscreen renderer, recreated when the frame's size, scale or clear color -// changes. It draws with Vulkan when there is a driver and with the CPU when there is none. +// changes. It draws with Vulkan when there is a driver and with the CPU when there is none or +// VIVA_SOFTWARE_RENDERING asks for it. type renderer struct { offscreen offscreen width, height int @@ -40,7 +46,7 @@ const defaultScale = 2 const rendererAvailable = true -func newRenderer() *renderer { return &renderer{} } +func newRenderer(app.Config) *renderer { return &renderer{} } func (r *renderer) close() { if r.offscreen != nil { @@ -54,17 +60,23 @@ func (r *renderer) render(snapshot app.Snapshot, scale float64) (*image.RGBA, er r.close() clear := platform.Color{Red: snapshot.Clear.Red, Green: snapshot.Clear.Green, Blue: snapshot.Clear.Blue, Alpha: snapshot.Clear.Alpha} var target offscreen - gpu, err := linux.NewOffscreen(snapshot.Width, snapshot.Height, scale, clear) - if err == nil { - target = gpu - } else if errors.Is(err, platform.ErrNoGraphics) { + var graphicsErr error + if !softwareRenderingRequested() { + gpu, err := linux.NewOffscreen(snapshot.Width, snapshot.Height, scale, clear) + if err == nil { + target = gpu + } else if errors.Is(err, platform.ErrNoGraphics) { + graphicsErr = err + } else { + return nil, err + } + } + if target == nil { cpu, cpuErr := linux.NewCPUOffscreen(snapshot.Width, snapshot.Height, scale, clear) if cpuErr != nil { - return nil, errors.Join(err, cpuErr) + return nil, errors.Join(graphicsErr, cpuErr) } target = cpu - } else { - return nil, err } r.offscreen, r.width, r.height, r.scale, r.clear = target, snapshot.Width, snapshot.Height, scale, snapshot.Clear } diff --git a/headless/render_none.go b/headless/render_none.go index 5874fccd4..eae37993a 100644 --- a/headless/render_none.go +++ b/headless/render_none.go @@ -19,7 +19,7 @@ const ( type renderer struct{} -func newRenderer() *renderer { return &renderer{} } +func newRenderer(app.Config) *renderer { return &renderer{} } func (r *renderer) close() {} diff --git a/headless/render_windows.go b/headless/render_windows.go index 6af1b6a19..4d891d48a 100644 --- a/headless/render_windows.go +++ b/headless/render_windows.go @@ -13,10 +13,11 @@ import ( // renderer keeps one Direct3D offscreen renderer, recreated when the frame's // size, scale or clear color changes. type renderer struct { - offscreen *windows.Offscreen - width, height int - scale float64 - clear app.Color + offscreen *windows.Offscreen + width, height int + scale float64 + clear app.Color + lowMemoryUploads bool } // rendererAvailable says whether this build can draw screenshots. @@ -30,7 +31,9 @@ const defaultScale = 2 const rendererAvailable = true -func newRenderer() *renderer { return &renderer{} } +func newRenderer(config app.Config) *renderer { + return &renderer{lowMemoryUploads: config.D3D11LowMemoryUploads} +} func (r *renderer) close() { if r.offscreen != nil { @@ -42,9 +45,11 @@ func (r *renderer) close() { func (r *renderer) render(snapshot app.Snapshot, scale float64) (*image.RGBA, error) { if r.offscreen == nil || r.width != snapshot.Width || r.height != snapshot.Height || r.scale != scale || r.clear != snapshot.Clear { r.close() - offscreen, err := windows.NewOffscreen(snapshot.Width, snapshot.Height, scale, platform.Color{ - Red: snapshot.Clear.Red, Green: snapshot.Clear.Green, Blue: snapshot.Clear.Blue, Alpha: snapshot.Clear.Alpha, - }) + offscreen, err := windows.NewOffscreenWithConfig(platform.Config{ + Width: snapshot.Width, Height: snapshot.Height, + ClearColor: platform.Color{Red: snapshot.Clear.Red, Green: snapshot.Clear.Green, Blue: snapshot.Clear.Blue, Alpha: snapshot.Clear.Alpha}, + D3D11LowMemoryUploads: r.lowMemoryUploads, + }, scale) if err != nil { return nil, err } diff --git a/headless/scrolled_field_darwin_test.go b/headless/scrolled_field_darwin_test.go new file mode 100644 index 000000000..f29206ba3 --- /dev/null +++ b/headless/scrolled_field_darwin_test.go @@ -0,0 +1,56 @@ +//go:build darwin && vivahead + +package headless + +import ( + "strings" + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/base" + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" +) + +// A field that scrolls its own line keeps the end of the line in view: the glyphs run up +// to the field's edge. The platform rasterizes a label only within its box, so a line +// drawn in a box no wider than the field left its end blank. +func TestHeadlessScreenshotDrawsTheEndOfAScrolledFieldLine(t *testing.T) { + const scale = 2 + theme := gfx.DarkTheme() + bounds := gfx.Rect{X: 20, Y: 20, Width: 265, Height: 36} + value := strings.Repeat("14.66.40.17", 7) + var scroll base.InputScroll + session, err := Open(app.Config{ + Title: "scrolled field", Width: 320, Height: 80, ClearColor: app.Color{Alpha: 1}, + Paint: func(canvas *gfx.Canvas, _ gfx.Size) { + components.PaintInput(canvas, theme, bounds, components.InputSnapshot{ + ID: gfx.Item(1), Label: "Address", Value: value, + Caret: len(value), HideEditorText: true, Scroll: &scroll, + }) + }, + }, nil, Options{Scale: scale}) + if err != nil { + t.Fatal(err) + } + defer session.Close() + picture, err := session.Image() + if err != nil { + t.Fatal(err) + } + // The glyphs sit between the field's border and its last visible column; the band + // leaves out the border rows. + top := int(bounds.Y+8) * scale + bottom := int(bounds.Y+bounds.Height-8) * scale + left := int(bounds.X) * scale + right := int(bounds.X+bounds.Width) * scale + last := -1 + for x := left; x < right; x++ { + if column(picture, x, top, bottom) { + last = x + } + } + if quarter := (right - left) / 4; last < right-quarter { + t.Fatalf("the glyphs end at device column %d, more than a quarter of the field (%d device pixels) short of its edge %d: the end of the scrolled line is blank", last, quarter, right) + } +} diff --git a/headless/session.go b/headless/session.go index cb4cbe90e..940230a23 100644 --- a/headless/session.go +++ b/headless/session.go @@ -217,6 +217,13 @@ func (session *Session) Frame() error { return session.driver.Paint() } // name, value, states and range. func (session *Session) Access() []app.AccessNode { return session.driver.Accessibility() } +// PerformAccess delivers request as assistive technology would, through the handler a window's +// platform adapter calls (see app.Driver.PerformAccess); handled is false when the node is gone +// or refused. LocateNode finds the node a selector names. +func (session *Session) PerformAccess(request app.AccessRequest) (handled bool, err error) { + return session.driver.PerformAccess(request) +} + // AccessByRole returns the first node in the last frame with role and the // accessible name; an empty name matches any node with that role. It is the // query a test uses to assert what assistive technology is told. @@ -432,7 +439,7 @@ func (session *Session) Image() (*image.RGBA, error) { return nil, err } if session.renderer == nil { - session.renderer = newRenderer() + session.renderer = newRenderer(session.config) } snapshot := session.driver.Snapshot() if session.showInput { diff --git a/headless/vector_aa_test.go b/headless/vector_aa_test.go index 02616b5dd..251f677b1 100644 --- a/headless/vector_aa_test.go +++ b/headless/vector_aa_test.go @@ -17,7 +17,7 @@ func TestVectorCoverageAtDeviceScales(t *testing.T) { if !rendererAvailable { t.Skip("native screenshots need the platform headless renderer") } - r := newRenderer() + r := newRenderer(app.Config{}) defer r.close() for _, scale := range []float64{1, 1.1, 1.25, 1.3, 1.5, 1.75, 2, 2.5, 3, 1.25} { t.Run(fmt.Sprintf("%gx", scale), func(t *testing.T) { @@ -111,7 +111,7 @@ func TestVectorStrokeQuadCoverageIsUniform(t *testing.T) { if !rendererAvailable { t.Skip("native screenshots need the platform headless renderer") } - r := newRenderer() + r := newRenderer(app.Config{}) defer r.close() for _, scale := range []float64{1, 1.25, 1.5, 2} { for _, width := range []float64{1, 1.25, 2, 3} { @@ -166,7 +166,7 @@ func TestVectorClippedStrokeCoverage(t *testing.T) { if !rendererAvailable { t.Skip("native screenshots need the platform headless renderer") } - renderer := newRenderer() + renderer := newRenderer(app.Config{}) defer renderer.close() icon := gfx.Icon{ ViewBox: 32, Stroke: 1, Cap: gfx.CapButt, diff --git a/headless/vector_sliver_test.go b/headless/vector_sliver_test.go index 0f3a823b3..cb571b66e 100644 --- a/headless/vector_sliver_test.go +++ b/headless/vector_sliver_test.go @@ -20,7 +20,7 @@ func TestVectorSliverCoverageStaysLocal(t *testing.T) { if !rendererAvailable { t.Skip("native screenshots need the platform headless renderer") } - r := newRenderer() + r := newRenderer(app.Config{}) defer r.close() faces := [][3]gfx.Point{ {{X: 830.1327, Y: 356.20184}, {X: 831.76605, Y: 354.5925}, {X: 832.00903, Y: 354.35315}}, @@ -63,7 +63,7 @@ func TestVectorSliverSharedEdgesAndGradients(t *testing.T) { if !rendererAvailable { t.Skip("native screenshots need the platform headless renderer") } - r := newRenderer() + r := newRenderer(app.Config{}) defer r.close() for _, scale := range []float64{1, 1.1, 1.25, 1.3, 1.5, 1.75, 2, 2.5, 3} { for _, offset := range []gfx.Point{{X: 0, Y: 0}, {X: 401.13, Y: 211.29}, {X: -20.25, Y: -20.25}} { @@ -131,7 +131,7 @@ func TestVectorInvalidFacesStayEmpty(t *testing.T) { // one outright, so nothing reaches the rasterizer to be tested. t.Skip("the Vulkan backend rejects invalid primitives instead of drawing nothing") } - r := newRenderer() + r := newRenderer(app.Config{}) defer r.close() for _, points := range [][3]gfx.Point{ {{X: 4, Y: 4}, {X: 4, Y: 4}, {X: 4, Y: 4}}, @@ -166,7 +166,7 @@ func TestVectorSliverMasksAndClipping(t *testing.T) { // Out-of-range edge masks are a validation error there, not a no-op. t.Skip("the Vulkan backend rejects edge masks above 7") } - r := newRenderer() + r := newRenderer(app.Config{}) defer r.close() for _, scale := range []float64{1, 1.5, 3} { for _, mask := range []uint8{0, 1, 2, 3, 4, 5, 6, 7, 8, 15, 255} { @@ -213,7 +213,7 @@ func BenchmarkVectorFrame(b *testing.B) { for _, mask := range []uint8{1, 7} { for _, height := range []float32{0.01, 20} { b.Run(fmt.Sprintf("mask%d/height%g", mask, height), func(b *testing.B) { - r := newRenderer() + r := newRenderer(app.Config{}) defer r.close() snapshot := app.Snapshot{Width: 640, Height: 480, Clear: app.Color{Alpha: 1}} for i := 0; i < 256; i++ { diff --git a/inspector/inspector.go b/inspector/inspector.go index d0934b22d..83bae2ae7 100644 --- a/inspector/inspector.go +++ b/inspector/inspector.go @@ -169,6 +169,9 @@ func states(canvas *gfx.Canvas, hit *gfx.Hit) string { add(hit.Checked, "checked") add(hit.Mixed, "mixed") add(hit.Selected, "selected") + add(hit.MultiSelectable, "multiselectable") + add(hit.Sort == gfx.SortAscending, "sorted ascending") + add(hit.Sort == gfx.SortDescending, "sorted descending") add(hit.Expandable && hit.Expanded, "expanded") add(hit.Expandable && !hit.Expanded, "collapsed") add(hit.ReadOnly, "readonly") diff --git a/internal/componentdemo/table.go b/internal/componentdemo/table.go index 75d8cb204..5d2f54df4 100644 --- a/internal/componentdemo/table.go +++ b/internal/componentdemo/table.go @@ -139,34 +139,37 @@ ui.Table(c, &m.table, ui.TableSpec{ Source: &bills, }) ui.Text(c, "项目左对齐,状态居中,金额右对齐。").Muted()`}, - {ID: "checked", Title: "勾选列", Description: "Checked 在最左加一列复选框,表头复选框全选或清空,部分勾选时为半选;勾选与选中行互不影响,列索引仍是 Columns 的。", Snippet: `// m.checked is a ui.Selection kept in the model: the rows ticked. + {ID: "checked", Title: "多选与勾选列", Description: "Selection 让用户选多行:Shift 加点击或方向键连选,Primary(macOS 为 Command)加点击增减,Primary+A 全选。Checkboxes 在最左加一列复选框,显示并修改同一个 Selection;表头复选框全选或清空,部分选中时为半选。列索引仍是 Columns 的。", Snippet: `// m.chosen is a ui.Selection kept in the model: the rows chosen. +m.table.Selection = &m.chosen ui.Table(c, &m.table, ui.TableSpec{ - Columns: m.columns, - Source: &m.bills, - Checked: &m.checked, + Columns: m.columns, + Source: &m.bills, + Checkboxes: true, }) -if m.table.CheckedChanged() { - // the user ticked or unticked a row, or the header's checkbox +if m.table.Changed() { + // the user chose rows: a click, Shift or Primary with a click, a checkbox, the keys } -// m.checked.Has(row) says whether a row is ticked; m.checked.Len() how many.`, PageSnippet: `// m.checked is a ui.Selection kept in the model: the rows ticked. +// m.chosen.Has(row) says whether a row is chosen; m.chosen.Len() how many.`, PageSnippet: `// m.chosen is a ui.Selection kept in the model: the rows chosen. +m.table.Selection = &m.chosen ui.Table(c, &m.table, ui.TableSpec{ - Columns: m.columns, - Source: &m.bills, - Checked: &m.checked, + Columns: m.columns, + Source: &m.bills, + Checkboxes: true, }) -if m.table.CheckedChanged() { - // the user ticked or unticked a row, or the header's checkbox +if m.table.Changed() { + // the user chose rows: a click, Shift or Primary with a click, a checkbox, the keys } -// m.checked.Has(row) says whether a row is ticked; m.checked.Len() how many.`, PageSnippetZh: `// m.checked is a ui.Selection kept in the model: the rows ticked. +// m.chosen.Has(row) says whether a row is chosen; m.chosen.Len() how many.`, PageSnippetZh: `// m.chosen is a ui.Selection kept in the model: the rows chosen. +m.table.Selection = &m.chosen ui.Table(c, &m.table, ui.TableSpec{ - Columns: m.columns, - Source: &m.bills, - Checked: &m.checked, + Columns: m.columns, + Source: &m.bills, + Checkboxes: true, }) -if m.table.CheckedChanged() { - // the user ticked or unticked a row, or the header's checkbox +if m.table.Changed() { + // the user chose rows: a click, Shift or Primary with a click, a checkbox, the keys } -// m.checked.Has(row) says whether a row is ticked; m.checked.Len() how many.`}, +// m.chosen.Has(row) says whether a row is chosen; m.chosen.Len() how many.`}, {ID: "filter", Title: "列过滤按钮", Description: "Filterable 在表头末尾加漏斗按钮,Filtered 表示该列已过滤;按钮被按下时 FilterClicked 报告列,用 HeaderRect 定位应用自己的筛选菜单。", Snippet: `// m.columns has Filterable set on the Status column, and Filtered while its filter is on. table := ui.Table(c, &m.table, ui.TableSpec{Columns: m.columns, Source: &m.bills}) if column, ok := table.FilterClicked(); ok { @@ -286,8 +289,9 @@ func (state *State) paintTable(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Siz spec.Columns = columns demo.filterColumns = columns } + demo.state.Selection = nil if state.exampleID == "checked" { - spec.Checked = &demo.checked + demo.state.Selection, spec.Checkboxes = &demo.checked, true spec.SelectAllLabel, spec.SelectRowLabel = state.Text("全选", "Select all rows"), state.Text("选择此行", "Select row") } table := ui.Table(c, &demo.state, spec) diff --git a/internal/devreload/supervisor.go b/internal/devreload/supervisor.go index 8ceb16f82..b5ecbdb2e 100644 --- a/internal/devreload/supervisor.go +++ b/internal/devreload/supervisor.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "io" + "runtime" "sync" "time" @@ -43,6 +44,8 @@ func (value *supervisor) hostConfig() app.Config { Paint: value.paint, OnPointer: value.pointer, OnKey: value.key, OnShortcut: value.shortcut, OnScroll: value.scroll, OnCloseRequest: value.requestClose, Invalidator: &value.invalidator, + + D3D11LowMemoryUploads: value.window.D3D11LowMemoryUploads, } if value.window.HasModifierTap { config.OnModifierTap = value.modifierTap @@ -305,6 +308,7 @@ func (value *supervisor) clearErrorLocked() { value.lastError = "" } func compatibleWindow(current, next reloadwire.WindowConfig) error { if current.Title != next.Title || current.Width != next.Width || current.Height != next.Height || + (runtime.GOOS == "windows" && current.D3D11LowMemoryUploads != next.D3D11LowMemoryUploads) || current.WindowMode != next.WindowMode || current.TitlebarHeight != next.TitlebarHeight || current.TrafficLightScale != next.TrafficLightScale || current.ClearRed != next.ClearRed || current.ClearGreen != next.ClearGreen || current.ClearBlue != next.ClearBlue || current.ClearAlpha != next.ClearAlpha { return fmt.Errorf("candidate changed immutable window configuration; restart viva dev") diff --git a/internal/devreload/supervisor_test.go b/internal/devreload/supervisor_test.go index 84c33477d..a622c7609 100644 --- a/internal/devreload/supervisor_test.go +++ b/internal/devreload/supervisor_test.go @@ -1,12 +1,28 @@ package devreload import ( + "runtime" "testing" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/internal/reloadwire" ) +func TestReloadKeepsTheWindowsUploadMode(t *testing.T) { + host := supervisor{window: reloadwire.WindowConfig{D3D11LowMemoryUploads: true}} + if !host.hostConfig().D3D11LowMemoryUploads { + t.Fatal("the host dropped the window's upload mode") + } + if err := compatibleWindow(host.window, host.window); err != nil { + t.Fatal(err) + } + next := host.window + next.D3D11LowMemoryUploads = false + if err := compatibleWindow(host.window, next); (err != nil) != (runtime.GOOS == "windows") { + t.Errorf("changing the D3D11 upload mode on %s: %v", runtime.GOOS, err) + } +} + func TestSupervisorPaintPreservesRealAndVisibleFocus(t *testing.T) { var canvas gfx.Canvas var supervisor supervisor diff --git a/internal/framebuild/framebuild.go b/internal/framebuild/framebuild.go index 9a1cd1e6a..16be48a9f 100644 --- a/internal/framebuild/framebuild.go +++ b/internal/framebuild/framebuild.go @@ -54,7 +54,11 @@ type Builder struct { // 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 + cellReplace []cellReplaceMemo + // overhangRuns holds, for the frame being built, the runs of every grid + // line whose label was widened by overhangCells (see appendTextLabel). Each + // label's runs are a slice of it; a frame reuses it from the start. + overhangRuns []gfx.TextRun clipRects [4]gfx.Rect clipped []gfx.Rectangle clippedPaths []gfx.Triangle @@ -185,6 +189,7 @@ func (builder *Builder) Trim() { builder.lastRuns = TrimCapacity(builder.lastRuns) builder.lastImages = TrimCapacity(builder.lastImages) builder.labelImage = TrimCapacity(builder.labelImage) + builder.overhangRuns = TrimCapacity(builder.overhangRuns) builder.lastLabelImage = TrimCapacity(builder.lastLabelImage) builder.clipped = TrimCapacity(builder.clipped) builder.clippedPaths = TrimCapacity(builder.clippedPaths) @@ -715,6 +720,7 @@ func (builder *Builder) setRectangle(id scene.ID, rectangle gfx.Rectangle) { func (builder *Builder) syncLabels() { builder.labels = builder.labels[:0] builder.labelImage = builder.labelImage[:0] + builder.overhangRuns = builder.overhangRuns[:0] images := builder.clippedImages texts := builder.clippedTexts fontGeneration := builder.canvas.FontGeneration() @@ -834,6 +840,14 @@ func (builder *Builder) bitmapUpload(image gfx.Image, index int) bool { return !SameImageBitmap(image, builder.lastImages[previous]) } +// overhangCells is how many cells of a fixed-pitch line's picture lie outside +// the line's bounds on each side. A glyph may be wider than its cell, as an +// emoji, an icon font's glyph or an italic one is, and centered in the cell +// its ink then falls past the cell's edge: past the line's first and last +// column the picture would end where the line does and cut the glyph. The +// canvas clip, when there is one, still bounds what shows. +const overhangCells = 1 + // appendTextLabel adds one canvas text to the frame's labels. func (builder *Builder) appendTextLabel(label gfx.Text, fontGeneration uint32, shapesBefore uint32) { width := RoundPixel(label.Bounds.Width) @@ -843,12 +857,27 @@ func (builder *Builder) appendTextLabel(label gfx.Text, fontGeneration uint32, s } // Integer logical-pixel bounds keep the texture exactly one texel per // physical pixel so linear sampling stays crisp on scaled displays. + x, originX := RoundPosition(label.Bounds.X), RoundingRemainder(label.Bounds.X) + grid := label.Style.Mono && label.RunCount > 0 && label.CellWidth > 0 + // A grid line's picture is widened by overhangCells on both sides, and its + // runs moved right by as many columns, so every glyph stays where the line + // put it. A warped line keeps the box its quad maps. + widened := grid && !label.HasQuad + cutBounds := label.Bounds + if widened { + margin := overhangCells * label.CellWidth + left := label.Bounds.X - margin + cutBounds = gfx.Rect{X: left, Y: label.Bounds.Y, Width: label.Bounds.Width + 2*margin, Height: label.Bounds.Height} + leftEdge := RoundPosition(left) + width += x - leftEdge + RoundPixel(margin) + x, originX = leftEdge, RoundingRemainder(left) + } entry := platform.TextLabel{ Value: label.Value, Identity: label.Identity, - X: float32(RoundPosition(label.Bounds.X)), Y: float32(RoundPosition(label.Bounds.Y)), + X: float32(x), Y: float32(RoundPosition(label.Bounds.Y)), Width: float32(width), Height: float32(height), - OriginX: RoundingRemainder(label.Bounds.X), OriginY: RoundingRemainder(label.Bounds.Y), + OriginX: originX, 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), @@ -866,8 +895,13 @@ func (builder *Builder) appendTextLabel(label gfx.Text, fontGeneration uint32, s // The font does not draw the cell glyphs; appendCellGlyphs did. entry.Value, entry.Runs = builder.replaceCellGlyphs(entry.Value, entry.Runs) } + if widened { + entry.Runs = builder.shiftRuns(entry.Runs, overhangCells) + } if label.HasClip { - if textClipCuts(label) { + cut := label + cut.Bounds = cutBounds + if textClipCuts(cut) { // The clip cuts the label partway: the renderers scissor to it. entry.Clip, entry.Clipped = label.ClipOf, true } @@ -887,6 +921,19 @@ func (builder *Builder) appendTextLabel(label gfx.Text, fontGeneration uint32, s builder.labelImage = append(builder.labelImage, -1) } +// shiftRuns appends runs moved columns to the right to the frame's overhang +// runs and returns them. The caller's runs are not changed: they are the +// canvas's own, or the memo's. +func (builder *Builder) shiftRuns(runs []gfx.TextRun, columns int32) []gfx.TextRun { + first := len(builder.overhangRuns) + for _, run := range runs { + run.Column += columns + builder.overhangRuns = append(builder.overhangRuns, run) + } + end := len(builder.overhangRuns) + return builder.overhangRuns[first:end:end] +} + // 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. diff --git a/internal/framebuild/overhang_test.go b/internal/framebuild/overhang_test.go new file mode 100644 index 000000000..d6dbd643d --- /dev/null +++ b/internal/framebuild/overhang_test.go @@ -0,0 +1,176 @@ +package framebuild + +import ( + "fmt" + "math" + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/platform" +) + +var overhangStyle = gfx.TextStyle{Size: 12, Mono: true, Color: gfx.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1}} + +func overhangRuns() []gfx.TextRun { + return []gfx.TextRun{ + {Column: 0, Bytes: 2, Cells: 2, Color: overhangStyle.Color}, + {Column: 3, Bytes: 1, Cells: 1, Color: overhangStyle.Color}, + } +} + +func buildLabels(t *testing.T, paint func(*gfx.Canvas)) []platform.TextLabel { + t.Helper() + var canvas gfx.Canvas + paint(&canvas) + builder := New(&canvas) + if _, err := builder.Build(); err != nil { + t.Fatalf("Build: %v", err) + } + return append([]platform.TextLabel(nil), builder.Labels()...) +} + +// A glyph wider than its cell reaches past the line's first and last column. +// The line's picture must therefore extend past the bounds the application gave +// it, and every glyph must still land where the line put it, whatever +// sub-pixel position and cell width the line has. +func TestGridLineMakesRoomForGlyphsOverhangingItsEnds(t *testing.T) { + for _, bounds := range []gfx.Rect{ + {X: 20, Y: 10, Width: 70, Height: 14}, + {X: 20.4, Y: 10.3, Width: 69.7, Height: 14}, + {X: 19.6, Y: 10, Width: 65.5, Height: 14}, + } { + for _, cell := range []float32{7, 8.5, 6.66} { + t.Run(fmt.Sprintf("x=%v cell=%v", bounds.X, cell), func(t *testing.T) { + runs := overhangRuns() + labels := buildLabels(t, func(canvas *gfx.Canvas) { + canvas.LabelRuns("abcd", bounds, overhangStyle, cell, runs) + }) + if len(labels) != 1 { + t.Fatalf("labels = %d, want 1", len(labels)) + } + got := labels[0] + // The picture covers the line's bounds with a cell to spare at both + // ends, less the rounding of the edges to whole logical pixels. + if got.X > bounds.X-cell+1 || got.X+got.Width < bounds.X+bounds.Width+cell-1 { + t.Errorf("label spans [%v, %v], line [%v, %v] with a cell of %v", got.X, got.X+got.Width, bounds.X, bounds.X+bounds.Width, cell) + } + // Each run's glyphs sit where the line put them. + if len(got.Runs) != len(runs) { + t.Fatalf("runs = %d, want %d", len(got.Runs), len(runs)) + } + for index, run := range got.Runs { + want := bounds.X + float32(runs[index].Column)*cell + at := got.X + got.OriginX + float32(run.Column)*cell + if math.Abs(float64(at-want)) > 1e-3 { + t.Errorf("run %d starts at %v, want %v", index, at, want) + } + if run.Bytes != runs[index].Bytes || run.Cells != runs[index].Cells || run.Color != runs[index].Color { + t.Errorf("run %d changed beyond its column: %+v from %+v", index, run, runs[index]) + } + } + if got.Y != float32(RoundPosition(bounds.Y)) || got.Height != float32(RoundPixel(bounds.Height)) { + t.Errorf("label moved vertically: y=%v height=%v for %+v", got.Y, got.Height, bounds) + } + // The application's runs are its own. + if runs[0].Column != 0 || runs[1].Column != 3 { + t.Errorf("the caller's runs were changed: %+v", runs) + } + }) + } + } +} + +// What the canvas clip leaves of the line is all that shows: a picture that +// reaches past the clip is cut to it, one that stays inside is not. +func TestGridLineOverhangIsCutByTheCanvasClip(t *testing.T) { + bounds := gfx.Rect{X: 40, Y: 10, Width: 70, Height: 14} + const cell = 7 + for _, test := range []struct { + name string + clip gfx.Rect + cut bool + }{ + {"clip is the line", bounds, true}, + {"clip leaves a cell each side", gfx.Rect{X: bounds.X - cell - 1, Y: 0, Width: bounds.Width + 2*cell + 2, Height: 40}, false}, + {"clip leaves a cell on one side", gfx.Rect{X: bounds.X - cell - 1, Y: 0, Width: bounds.Width + cell, Height: 40}, true}, + } { + t.Run(test.name, func(t *testing.T) { + labels := buildLabels(t, func(canvas *gfx.Canvas) { + canvas.Clip(test.clip) + canvas.LabelRuns("abcd", bounds, overhangStyle, cell, overhangRuns()) + canvas.Unclip() + }) + if len(labels) != 1 { + t.Fatalf("labels = %d, want 1", len(labels)) + } + if labels[0].Clipped != test.cut || (test.cut && labels[0].Clip != test.clip) { + t.Errorf("clipped = %v clip = %+v, want clipped = %v to %+v", labels[0].Clipped, labels[0].Clip, test.cut, test.clip) + } + }) + } +} + +// Only a grid line made of cells has glyphs that overhang a cell: other text +// and a warped line keep the box they were given. +func TestOnlyAGridLineIsWidened(t *testing.T) { + bounds := gfx.Rect{X: 20.4, Y: 10, Width: 70, Height: 14} + quad := gfx.Quad{Points: [4]gfx.Point{{X: 20, Y: 10}, {X: 90, Y: 12}, {X: 20, Y: 24}, {X: 90, Y: 26}}, Tint: [4]gfx.Color{overhangStyle.Color, overhangStyle.Color, overhangStyle.Color, overhangStyle.Color}} + labels := buildLabels(t, func(canvas *gfx.Canvas) { + canvas.Label("proportional", bounds, gfx.TextStyle{Size: 12, Color: overhangStyle.Color}) + canvas.LabelQuad("warped", bounds, quad, overhangStyle) + }) + if len(labels) != 2 { + t.Fatalf("labels = %d, want 2", len(labels)) + } + for _, label := range labels { + if label.X != 20 || label.Width != 70 || label.OriginX != RoundingRemainder(bounds.X) { + t.Errorf("%q was widened: x=%v width=%v origin=%v", label.Value, label.X, label.Width, label.OriginX) + } + } +} + +func terminalFrame(canvas *gfx.Canvas, rows int, runs []gfx.TextRun) { + canvas.Reset() + canvas.Clip(gfx.Rect{X: 0, Y: 0, Width: 800, Height: 800}) + for row := 0; row < rows; row++ { + canvas.LabelRunsWithIdentity(gfx.TextIdentity{Owner: 1, Item: uint64(row + 1)}, "abcd", gfx.Rect{X: 10, Y: float32(row * 16), Width: 700, Height: 16}, overhangStyle, 7, runs) + } + canvas.Unclip() +} + +// A terminal repaints every row each frame; widening the rows must not cost an +// allocation once the frame's scratch has grown to it. +func TestWideningGridLinesDoesNotAllocateInSteadyState(t *testing.T) { + var canvas gfx.Canvas + runs := overhangRuns() + builder := New(&canvas) + build := func() { + terminalFrame(&canvas, 40, runs) + if _, err := builder.Build(); err != nil { + t.Fatal(err) + } + } + build() + build() + if allocs := testing.AllocsPerRun(20, build); allocs > 0 { + t.Errorf("building 40 grid rows allocated %v times, want none", allocs) + } +} + +func BenchmarkGridRows(b *testing.B) { + var canvas gfx.Canvas + runs := overhangRuns() + builder := New(&canvas) + terminalFrame(&canvas, 40, runs) + if _, err := builder.Build(); err != nil { + b.Fatal(err) + } + b.ReportAllocs() + b.ResetTimer() + for range b.N { + terminalFrame(&canvas, 40, runs) + if _, err := builder.Build(); err != nil { + b.Fatal(err) + } + } +} diff --git a/internal/frametrace/frametrace.go b/internal/frametrace/frametrace.go new file mode 100644 index 000000000..b5016418e --- /dev/null +++ b/internal/frametrace/frametrace.go @@ -0,0 +1,355 @@ +// Package frametrace writes one line to standard error for each event a window +// receives and each frame it paints, when the environment variable VIVA_TRACE +// is 1. Each frame line says why the frame was painted, how many times the page +// was painted for it and where its time went, so a developer can find redundant +// redraws and idle wake-ups in a running application: a window that is left +// alone prints nothing. +// +// The trace is for developers looking at one process. It is not part of the +// diagnostic stream (internal/diag): a frame is not a failure, a busy window +// paints a hundred of them a second, and a stream handler or capture ring that +// received them would lose the events it exists for. +// +// # Cost when off +// +// A window holds a *Window, nil unless VIVA_TRACE was set when it opened, and +// every trace call is guarded by that nil check: an untraced window makes no +// clock reads, keeps no counters and allocates nothing. The reasons frames are +// requested for travel with the requests themselves as a bit set (Reason), which +// costs a register OR where the request is made. +// +// # Threading +// +// A Window is used on its window's thread only. Reasons recorded from other +// goroutines go through the window's platform.Waker, which owns their lock. +package frametrace + +import ( + "io" + "os" + "strconv" + "sync/atomic" + "time" +) + +// On says whether VIVA_TRACE asked for the trace. It is read once, when the +// program starts; windows opened afterwards are traced when it is set. +var On = enabled(os.Getenv("VIVA_TRACE")) + +// enabled reads the variable's value: anything but empty and "0" turns the +// trace on. +func enabled(value string) bool { return value != "" && value != "0" } + +// Reason is a set of the causes a frame was painted for. The requests a frame +// answers are merged, so one frame can carry several reasons. +type Reason uint32 + +const ( + // Open is the first frame of a window. + Open Reason = 1 << iota + // Resize is a change of the window's size, or of its full-screen state. + Resize + // Scale is a change of the display's pixels per logical pixel. + Scale + // Visibility is a window shown again, painting the frame it missed while + // nobody could see it. + Visibility + // Focus is the window gaining or losing the activation or the keyboard. + Focus + // Pointer is a mouse, pen or finger event. + Pointer + // Key is a key press or release, a shortcut, or a held key's release + // coming due. + Key + // Text is an edit the platform's text input made: typing, an input method's + // composition, a paste. + Text + // Scroll is a wheel, touchpad scroll or pinch. + Scroll + // Drop is a drag of files from the system. + Drop + // Menu is a command from a menu: the application's menu bar or the system's + // text menu. + Menu + // Accessibility is a request from assistive technology. + Accessibility + // Animation is a transition in flight, asking for the next frame at the + // display's cadence. + Animation + // Timer is a frame the page asked for later, such as a caret's next blink + // or a spinner's next step. + Timer + // Invalidate is the application asking from outside a paint: an + // Invalidator's Invalidate or Post, an embedded web view, a test driver's + // Paint. + Invalidate + // Settings is a change of the desktop's preferences, such as its fonts or + // reduced motion. + Settings + // System is a redraw the platform asked for with no cause recorded in Viva, + // such as an exposed window. + System + + reasonCount = iota +) + +var reasonNames = [reasonCount]string{ + "open", "resize", "scale", "visibility", "focus", "pointer", "key", "text", "scroll", "drop", + "menu", "accessibility", "animation", "timer", "invalidate", "settings", "system", +} + +// AppendText appends the reasons' names joined by commas, "system" for none. +func (reasons Reason) AppendText(line []byte) []byte { + if reasons == 0 { + reasons = System + } + first := true + for index, name := range reasonNames { + if reasons&(1< ". +func (window *Window) begin() []byte { + window.flush() + line := append(window.line[:0], "viva trace: w"...) + line = strconv.AppendUint(line, window.id, 10) + return append(line, ' ') +} + +// write ends a line and writes it. +func (window *Window) write(line []byte) { + line = append(line, '\n') + window.line = line + _, _ = window.out.Write(line) +} + +// Opened writes the window's first line: its title and its size in logical +// pixels. +func (window *Window) Opened(title string, width, height int) { + line := append(window.begin(), "open "...) + line = strconv.AppendQuote(line, title) + line = append(line, ' ') + line = strconv.AppendInt(line, int64(width), 10) + line = append(line, 'x') + line = strconv.AppendInt(line, int64(height), 10) + window.write(line) +} + +// Closed writes the window's last line. +func (window *Window) Closed() { + window.write(append(window.begin(), "close"...)) +} + +// Event writes a line for an event the window received: the reason it would +// paint for and a detail such as "down" or "hidden", which may be empty. +func (window *Window) Event(reason Reason, detail string) { + line := append(window.begin(), "event "...) + line = reason.AppendText(line) + if detail != "" { + line = append(line, ' ') + line = append(line, detail...) + } + window.write(line) +} + +// Resized writes the line of a resize event: the new size in logical pixels and +// the display scale, zero when the platform does not report it. +func (window *Window) Resized(width, height, scale float32) { + line := append(window.begin(), "event resize "...) + line = strconv.AppendFloat(line, float64(width), 'f', -1, 32) + line = append(line, 'x') + line = strconv.AppendFloat(line, float64(height), 'f', -1, 32) + if scale > 0 { + line = append(line, '@') + line = strconv.AppendFloat(line, float64(scale), 'f', -1, 32) + } + window.write(line) +} + +// Note records a reason for the next frame: the cause of an event whose frame +// the platform asks for itself, after the event. +func (window *Window) Note(reason Reason) { window.reasons |= reason } + +// Painted records one run of the page's paint, and how long it took. +func (window *Window) Painted(took time.Duration) { + window.passes++ + window.paint += took +} + +// Skipped writes the line of a wake whose paint was skipped because nobody can +// see the window, with the reasons it was woken for. +func (window *Window) Skipped(reasons Reason) { + reasons |= window.reasons + window.reasons = 0 + line := append(window.begin(), "skip hidden reason="...) + window.write(reasons.AppendText(line)) +} + +// Frame writes the line of a painted frame: the reasons noted since the last +// frame, the paints run for it, how long they and the publish took, and what +// it changed. When the platform reports presentation the line waits for +// Presented, which adds the present time. +func (window *Window) Frame(publish time.Duration, frame Frame) { + reasons := window.reasons + retried := retries.Load() + window.frames++ + line := append(window.begin(), "frame "...) + line = strconv.AppendUint(line, window.frames, 10) + line = append(line, " reason="...) + line = reasons.AppendText(line) + line = append(line, " passes="...) + line = strconv.AppendInt(line, int64(window.passes), 10) + line = append(line, " retries="...) + line = strconv.AppendUint(line, retried-window.retries, 10) + line = appendMilliseconds(append(line, " paint="...), window.paint) + line = appendMilliseconds(append(line, " publish="...), publish) + line = append(line, " instances="...) + line = strconv.AppendInt(line, int64(frame.Instances), 10) + line = append(line, " changed="...) + if frame.Rebuild { + line = append(line, "all"...) + } else { + line = strconv.AppendInt(line, int64(frame.Changed), 10) + } + if frame.Shrink { + line = append(line, " shrink"...) + } + if frame.Labels >= 0 { + line = append(line, " labels="...) + line = strconv.AppendInt(line, int64(frame.Labels), 10) + } + if frame.Accessibility { + line = append(line, " accessibility"...) + } + if frame.TextInput { + line = append(line, " text-input"...) + } + if frame.NativeViews { + line = append(line, " native-views"...) + } + if frame.empty() { + line = append(line, " empty"...) + } + window.reasons, window.passes, window.paint, window.retries = 0, 0, 0, retried + if window.awaitPresent { + window.line, window.waiting, window.handed = line, true, time.Now() + return + } + window.write(line) +} + +// Presented completes the waiting frame line with the time from the frame's +// handover to its presentation, and writes it. +func (window *Window) Presented() { + if !window.waiting { + return + } + window.waiting = false + window.write(appendMilliseconds(append(window.line, " present="...), time.Since(window.handed))) +} + +// flush writes a frame line still waiting for a presentation the platform did +// not report, without the present time. +func (window *Window) flush() { + if window.waiting { + window.waiting = false + window.write(window.line) + } +} + +// appendMilliseconds appends a duration in milliseconds with three decimals. +func appendMilliseconds(line []byte, duration time.Duration) []byte { + line = strconv.AppendFloat(line, float64(duration)/float64(time.Millisecond), 'f', 3, 64) + return append(line, "ms"...) +} diff --git a/internal/instance/claim_unix.go b/internal/instance/claim_unix.go index 4a15773d6..1c8da7e61 100644 --- a/internal/instance/claim_unix.go +++ b/internal/instance/claim_unix.go @@ -103,7 +103,7 @@ func listen(address string) (net.Listener, error) { // send hands args to the copy listening on the socket. A socket that nobody // listens on is the stale file of a process that died, and the caller replaces // it after errNobody. -func send(address string, args []string) error { +func send(address string, args []string, _ bool) error { conn, err := net.DialTimeout("unix", address, ioDeadline) if err != nil { return fmt.Errorf("%w: %v", errNobody, err) diff --git a/internal/instance/claim_windows.go b/internal/instance/claim_windows.go index fd7b70a23..fa26b90e3 100644 --- a/internal/instance/claim_windows.go +++ b/internal/instance/claim_windows.go @@ -17,6 +17,10 @@ import ( // pipePrefix is where the named pipes of the machine live. const pipePrefix = `\\.\pipe\` +var allowSetForegroundWindow = windows.NewLazySystemDLL("user32.dll").NewProc("AllowSetForegroundWindow") + +var grantForeground = func(pid uint32) { allowSetForegroundWindow.Call(uintptr(pid)) } + // claimAddress is the pipe the claim lives at. The pipe namespace is // machine-wide, not per user like the Unix claim directory, so the name carries // a digest of the user's SID: two users running the same application must not @@ -43,7 +47,7 @@ func listen(address string) (net.Listener, error) { // fails with ERROR_FILE_NOT_FOUND, which means no copy is running; any other // failure means a copy exists and could not be reached, so its claim is not // taken over. -func send(address string, args []string) error { +func send(address string, args []string, allowForeground bool) error { timeout := ioDeadline conn, err := winio.DialPipe(address, &timeout) if err != nil { @@ -52,6 +56,15 @@ func send(address string, args []string) error { } return fmt.Errorf("instance: the running copy cannot be reached: %w", err) } + if pipe, ok := conn.(interface{ Fd() uintptr }); allowForeground && ok { + // Transfer only to the process serving this connection, before it is + // woken by the arguments. Windows may deny foreground permission; the + // launch must still be delivered in that case. + var pid uint32 + if windows.GetNamedPipeServerProcessId(windows.Handle(pipe.Fd()), &pid) == nil && pid != 0 && pid != ^uint32(0) { + grantForeground(pid) + } + } return sendArgs(conn, args) } diff --git a/internal/instance/instance.go b/internal/instance/instance.go index d8b29187b..a3875681f 100644 --- a/internal/instance/instance.go +++ b/internal/instance/instance.go @@ -50,7 +50,9 @@ type Instance struct { // and reports primary false. When primary, handler is called on its own // goroutine with the arguments of every later launch. The id names the // application; two applications with different ids never meet. -func Claim(id string, args []string, handler func(args []string)) (instance *Instance, primary bool, err error) { +// On Windows, allowForeground permits sharing foreground activation rights +// with the receiving process for this launch. +func Claim(id string, args []string, allowForeground bool, handler func(args []string)) (instance *Instance, primary bool, err error) { if id == "" { return nil, false, errors.New("instance: an application id is required") } @@ -67,7 +69,7 @@ func Claim(id string, args []string, handler func(args []string)) (instance *Ins return instance, true, nil } listenErr = attemptErr - sendErr := send(address, args) + sendErr := send(address, args, allowForeground) if sendErr == nil { return nil, false, nil } diff --git a/internal/instance/instance_test.go b/internal/instance/instance_test.go index 24be62c38..914ab00eb 100644 --- a/internal/instance/instance_test.go +++ b/internal/instance/instance_test.go @@ -13,13 +13,13 @@ import ( func TestSecondLaunchHandsItsArgumentsToTheFirst(t *testing.T) { isolate(t) got := make(chan []string, 4) - first, primary, err := Claim("dev.test.one", []string{"first"}, func(args []string) { got <- args }) + first, primary, err := Claim("dev.test.one", []string{"first"}, false, func(args []string) { got <- args }) if err != nil || !primary { t.Fatalf("first claim: primary %v, err %v", primary, err) } defer first.Close() want := []string{"ssh://user@host:2222/", "", "ünï cödé", "with space"} - second, primary, err := Claim("dev.test.one", want, func([]string) { t.Error("the second process must not serve") }) + second, primary, err := Claim("dev.test.one", want, false, func([]string) { t.Error("the second process must not serve") }) if err != nil || primary || second != nil { t.Fatalf("second claim: primary %v, err %v", primary, err) } @@ -35,20 +35,20 @@ func TestSecondLaunchHandsItsArgumentsToTheFirst(t *testing.T) { func TestDifferentIDsDoNotMeetAndEmptyArgumentsWork(t *testing.T) { isolate(t) - a, primaryA, _ := Claim("dev.test.a", nil, func([]string) {}) - b, primaryB, _ := Claim("dev.test.b", nil, func([]string) {}) + a, primaryA, _ := Claim("dev.test.a", nil, false, func([]string) {}) + b, primaryB, _ := Claim("dev.test.b", nil, false, func([]string) {}) if !primaryA || !primaryB { t.Fatal("two applications should both be primary") } a.Close() b.Close() got := make(chan []string, 1) - c, primary, _ := Claim("dev.test.a", nil, func(args []string) { got <- args }) + c, primary, _ := Claim("dev.test.a", nil, false, func(args []string) { got <- args }) if !primary { t.Fatal("a closed instance left its claim behind") } defer c.Close() - Claim("dev.test.a", nil, nil) + Claim("dev.test.a", nil, false, nil) if args := <-got; len(args) != 0 { t.Fatalf("args = %q", args) } @@ -56,7 +56,7 @@ func TestDifferentIDsDoNotMeetAndEmptyArgumentsWork(t *testing.T) { func TestAClosedClaimIsReclaimed(t *testing.T) { isolate(t) - first, primary, _ := Claim("dev.test.stale", nil, func([]string) {}) + first, primary, _ := Claim("dev.test.stale", nil, false, func([]string) {}) if !primary { t.Fatal("not primary") } @@ -65,7 +65,7 @@ func TestAClosedClaimIsReclaimed(t *testing.T) { // until the next claim replaces it. first.listener.Close() <-first.done - second, primary, err := Claim("dev.test.stale", nil, func([]string) {}) + second, primary, err := Claim("dev.test.stale", nil, false, func([]string) {}) if err != nil || !primary { t.Fatalf("after a crash: primary %v, err %v", primary, err) } @@ -79,7 +79,7 @@ func TestOversizeAndMalformedMessagesAreRefused(t *testing.T) { if err := writeArgs(&strings.Builder{}, []string{"a\x00b"}); err == nil { t.Fatal("NUL in an argument was written") } - if _, primary, err := Claim("", nil, nil); err == nil || primary { + if _, primary, err := Claim("", nil, false, nil); err == nil || primary { t.Fatal("an empty id was accepted") } } @@ -104,7 +104,7 @@ func BenchmarkClaimAndClose(b *testing.B) { isolate(b) b.ReportAllocs() for b.Loop() { - claim, primary, err := Claim("dev.test.bench", nil, func([]string) {}) + claim, primary, err := Claim("dev.test.bench", nil, false, func([]string) {}) if err != nil || !primary { b.Fatalf("claim: primary %v, err %v", primary, err) } diff --git a/internal/instance/instance_unix_test.go b/internal/instance/instance_unix_test.go index c8e6557c1..04391dd7b 100644 --- a/internal/instance/instance_unix_test.go +++ b/internal/instance/instance_unix_test.go @@ -80,12 +80,12 @@ func TestALongClaimDirectoryKeepsTheSocketPathShort(t *testing.T) { t.Cleanup(func() { claimDirectory = previous }) got := make(chan []string, 1) - first, primary, err := Claim("dev.test.deep", nil, func(args []string) { got <- args }) + first, primary, err := Claim("dev.test.deep", nil, false, func(args []string) { got <- args }) if err != nil || !primary { t.Fatalf("claim with a deep directory: primary %v, err %v", primary, err) } defer first.Close() - if second, primary, err := Claim("dev.test.deep", []string{"handoff"}, func([]string) { + if second, primary, err := Claim("dev.test.deep", []string{"handoff"}, false, func([]string) { t.Error("the second process must not serve") }); err != nil || primary || second != nil { t.Fatalf("second claim: primary %v, err %v", primary, err) diff --git a/internal/instance/instance_windows_test.go b/internal/instance/instance_windows_test.go index 0d92d675f..a7ecef711 100644 --- a/internal/instance/instance_windows_test.go +++ b/internal/instance/instance_windows_test.go @@ -2,7 +2,12 @@ package instance -import "testing" +import ( + "os" + "os/exec" + "strconv" + "testing" +) // isolate has nothing to hand out on Windows: a claim is a named pipe, not a // file in a directory, so the tests share the machine's pipe namespace. Each @@ -26,3 +31,36 @@ func TestTheClaimAddressIsAStablePipe(t *testing.T) { t.Fatalf("two applications share the claim address %q", address) } } + +func TestForegroundHandoffGrantsOnlyTheConnectedPrimary(t *testing.T) { + const childPID = "VIVA_TEST_PRIMARY_PID" + const idPrefix = "dev.test.foreground." + if parent := os.Getenv(childPID); parent != "" { + var grants []uint32 + grantForeground = func(pid uint32) { grants = append(grants, pid) } + for _, allow := range []bool{false, true} { + if claim, primary, err := Claim(idPrefix+parent, nil, allow, nil); err != nil || primary || claim != nil { + t.Fatalf("secondary claim: primary=%v err=%v", primary, err) + } + } + if len(grants) != 1 || strconv.Itoa(int(grants[0])) != parent { + t.Fatalf("granted %v; want only the server process %s", grants, parent) + } + return + } + pid := strconv.Itoa(os.Getpid()) + delivered := make(chan struct{}, 2) + claim, primary, err := Claim(idPrefix+pid, nil, false, func([]string) { delivered <- struct{}{} }) + if err != nil || !primary { + t.Fatalf("primary claim: primary=%v err=%v", primary, err) + } + defer claim.Close() + cmd := exec.Command(os.Args[0], "-test.run=^TestForegroundHandoffGrantsOnlyTheConnectedPrimary$") + cmd.Env = append(os.Environ(), childPID+"="+pid) + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("secondary: %v\n%s", err, out) + } + if len(delivered) != 2 { + t.Fatalf("received %d launches, want two", len(delivered)) + } +} diff --git a/internal/interaction/accessibility.go b/internal/interaction/accessibility.go index 88bf67206..c62800b83 100644 --- a/internal/interaction/accessibility.go +++ b/internal/interaction/accessibility.go @@ -3,14 +3,19 @@ package interaction import "github.com/vivaui/viva/gfx" // Control finds the control a request names. Labels share their control's ID -// and are not controls, and a region declared by Container has no ID. -func Control(hits []gfx.Hit, id gfx.ID) (gfx.Hit, bool) { +// and are not controls, and a region declared by Container has no ID. While a +// modal holds the focus trap, a control outside the trapped scope is inert: +// the semantic tree leaves it out, and a request that still names it (one an +// assistive technology queued, or a reference it held, before the modal +// opened) finds nothing. +func Control(hits []gfx.Hit, trap, id gfx.ID) (gfx.Hit, bool) { if id.IsZero() { return gfx.Hit{}, false } for index := len(hits) - 1; index >= 0; index-- { hit := hits[index] - if hit.ID == id && !hit.IsLabel && !hit.Block && !hit.Backdrop && !hit.Container { + if hit.ID == id && !hit.IsLabel && !hit.Block && !hit.Backdrop && !hit.Container && + (trap.IsZero() || hit.Scope == trap) { return hit, true } } diff --git a/internal/platform/accessibility.go b/internal/platform/accessibility.go index 4fa24ef8f..cfaa40d23 100644 --- a/internal/platform/accessibility.go +++ b/internal/platform/accessibility.go @@ -31,6 +31,9 @@ const ( // A11yRoleProgress is a read-only progress indicator: a range value it // reports, never one it accepts. A11yRoleProgress + // A11yRoleColumnHeader is a table column's header that sorts the rows when + // pressed; AccessibilityNode.Sort says how they are sorted. + A11yRoleColumnHeader ) // AccessibilityAction is something assistive technology asks a node to do. @@ -110,7 +113,7 @@ func (patterns AccessibilityPatterns) Has(want AccessibilityPatterns) bool { func (node AccessibilityNode) Patterns() AccessibilityPatterns { var patterns AccessibilityPatterns switch node.Role { - case A11yRoleButton, A11yRoleLink, A11yRoleMenuItem: + case A11yRoleButton, A11yRoleLink, A11yRoleMenuItem, A11yRoleColumnHeader: patterns |= PatternInvoke case A11yRoleCheckbox, A11yRoleSwitch: patterns |= PatternToggle @@ -224,6 +227,10 @@ const ( ChangedSelection ChangedBounds ChangedInvalid + // ChangedSort is a column header's sort direction. + ChangedSort + // ChangedMultiSelectable is whether a list lets several items be chosen. + ChangedMultiSelectable ) // DiffAccessibility returns the properties that differ between old and next. @@ -250,8 +257,10 @@ func DiffAccessibility(old, next AccessibilityNode) AccessibilityChange { set(old.Level != next.Level, ChangedLevel) set(old.PosInSet != next.PosInSet || old.SetSize != next.SetSize, ChangedPosition) set(old.Live != next.Live, ChangedLive) - set(old.Selection != next.Selection, ChangedSelection) + set(old.Selection != next.Selection || old.TextSelection != next.TextSelection, ChangedSelection) set(old.X != next.X || old.Y != next.Y || old.Width != next.Width || old.Height != next.Height, ChangedBounds) set(old.Invalid != next.Invalid, ChangedInvalid) + set(old.Sort != next.Sort, ChangedSort) + set(old.MultiSelectable != next.MultiSelectable, ChangedMultiSelectable) return changes } diff --git a/internal/platform/contract.go b/internal/platform/contract.go index 04abd4070..1b1463dd5 100644 --- a/internal/platform/contract.go +++ b/internal/platform/contract.go @@ -8,6 +8,7 @@ import ( "unicode/utf8" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/frametrace" "github.com/vivaui/viva/internal/input" "github.com/vivaui/viva/internal/render" "github.com/vivaui/viva/text" @@ -52,6 +53,8 @@ type Config struct { TitlebarHeight float32 TrafficLightScale float32 ClearColor Color + // D3D11LowMemoryUploads selects the Windows renderer's upload path at creation. + D3D11LowMemoryUploads bool // Transparent asks for a window composited over the desktop: ClearColor's // alpha is what shows what is behind it. Adapters that cannot composite // ignore it, and app.Config only sets it where they report the capability. @@ -225,6 +228,15 @@ type WindowIconSetter interface { SetIcon(WindowIcon) error } +// WindowAttention is implemented by the windows of an adapter that can ask the +// desktop to draw the user's attention to a window in the background: a Dock +// tile bounce on macOS, a taskbar button flash on Windows, an urgency hint on +// Linux. It is called from any goroutine and a window that is already active +// is not asked. An adapter without a native equivalent leaves it unimplemented. +type WindowAttention interface { + RequestAttention() error +} + // WindowMover is implemented by the windows of an adapter that can put a window // somewhere without the user dragging it. MoveTo puts the top-left of the // content area at origin, in the screen coordinates of Window.Frame. It is @@ -655,6 +667,10 @@ type AccessibilityNode struct { Expanded bool Multiline bool ReadOnly bool + // MultiSelectable marks a list whose items can be chosen several at once. + MultiSelectable bool + // Sort is how a column header orders the rows of its table. + Sort gfx.SortDirection // Invalid marks a control whose value failed validation. Invalid bool Secure bool @@ -675,6 +691,8 @@ type AccessibilityNode struct { Range gfx.ValueRange // Selection is the selected span of the focused text field's Value. Selection AccessibilitySelection + // TextSelection supplies client-coordinate bounds for a terminal's selected output. + TextSelection *gfx.TextSelection } // AccessibilitySelection is a span of a text node's Value in Unicode code @@ -822,9 +840,14 @@ type RedrawHandler func() (Frame, error) // redraw per frame, not one per wake. A wake after a quiet spell is posted at // once, and a window nobody wakes owns no timer. Wakes made after one was posted // and before its redraw began join it. +// +// A wake may say what it is for (WakeFor). The reasons of the wakes a redraw +// answers are merged and handed to it by Redrawing, for the frame trace. type Waker struct { mu sync.Mutex wake func() + // reasons are those of the wakes since the last redraw began. + reasons frametrace.Reason spacing time.Duration // last is when the last redraw began; zero before the first. @@ -858,6 +881,7 @@ func (waker *Waker) Unbind() { waker.mu.Lock() waker.wake = nil waker.posted = false + waker.reasons = 0 waker.dropHeld() waker.mu.Unlock() } @@ -870,17 +894,31 @@ func (waker *Waker) SetSpacing(spacing time.Duration) { waker.mu.Unlock() } -// Redrawing records that a redraw is starting. The caller makes it before it reads what -// background work published, so a wake made after it asks for another redraw, and one held -// from before it is not needed any more: this redraw reads what that wake was for. -func (waker *Waker) Redrawing() { +// Redrawing records that a redraw is starting, and returns the reasons of the wakes it +// answers. The caller makes it before it reads what background work published, so a wake +// made after it asks for another redraw, and one held from before it is not needed any more: +// this redraw reads what that wake was for. +func (waker *Waker) Redrawing() frametrace.Reason { waker.mu.Lock() + reasons := waker.reasons + waker.reasons = 0 if waker.spacing > 0 { waker.last = time.Now() waker.posted = false waker.dropHeld() } waker.mu.Unlock() + return reasons +} + +// Note records a reason for the redraw a wake already on its way will run, without waking +// again. +func (waker *Waker) Note(reason frametrace.Reason) { + waker.mu.Lock() + if waker.wake != nil { + waker.reasons |= reason + } + waker.mu.Unlock() } // dropHeld forgets a held wake; the lock is held. @@ -892,12 +930,16 @@ func (waker *Waker) dropHeld() { } // Wake requests one OnRedraw call on the window thread. -func (waker *Waker) Wake() { +func (waker *Waker) Wake() { waker.WakeFor(0) } + +// WakeFor is Wake for a reason, which the redraw's frame trace reports. +func (waker *Waker) WakeFor(reason frametrace.Reason) { waker.mu.Lock() defer waker.mu.Unlock() if waker.wake == nil { return } + waker.reasons |= reason if waker.spacing == 0 { waker.wake() return diff --git a/internal/platform/darwin/accessibility_frame_darwin_test.go b/internal/platform/darwin/accessibility_frame_darwin_test.go new file mode 100644 index 000000000..30a260385 --- /dev/null +++ b/internal/platform/darwin/accessibility_frame_darwin_test.go @@ -0,0 +1,29 @@ +//go:build !ios + +package darwin + +import ( + "os/exec" + "path/filepath" + "testing" +) + +// An accessibility frame is what a client places the element by. The window +// managers that move a window over the accessibility API read it right after +// the move, so it has to be screen coordinates and follow the window even when +// the application has not painted again. The window is never ordered front, so +// the test opens nothing on screen. +func TestAccessibilityFramesAreScreenCoordinates(t *testing.T) { + executable := filepath.Join(t.TempDir(), "accessibility-frame") + command := exec.Command("xcrun", "clang", "-fno-objc-arc", "-Werror", + "-Wno-deprecated-declarations", "testdata/accessibility_frame.m", "-o", executable, + "-framework", "Cocoa", "-framework", "CoreText", "-framework", "Metal", "-framework", "QuartzCore") + if output, err := command.CombinedOutput(); err != nil { + t.Fatalf("compile native accessibility frame test: %v\n%s", err, output) + } + if output, err := exec.Command(executable).CombinedOutput(); err != nil { + t.Fatalf("native accessibility frame test: %v\n%s", err, output) + } else { + t.Logf("%s", output) + } +} diff --git a/internal/platform/darwin/attention_darwin.go b/internal/platform/darwin/attention_darwin.go new file mode 100644 index 000000000..6f840e50f --- /dev/null +++ b/internal/platform/darwin/attention_darwin.go @@ -0,0 +1,18 @@ +//go:build darwin && !ios + +package darwin + +/* +#include "attention_darwin.h" +*/ +import "C" + +import "fmt" + +func (window *nativeWindow) RequestAttention() error { + if window == nil || window.closed.Load() { + return fmt.Errorf("darwin: window is closed") + } + C.viva_application_request_attention() + return nil +} diff --git a/internal/platform/darwin/attention_darwin.h b/internal/platform/darwin/attention_darwin.h new file mode 100644 index 000000000..891506a58 --- /dev/null +++ b/internal/platform/darwin/attention_darwin.h @@ -0,0 +1,10 @@ +//go:build !ios + +#ifndef VIVA_ATTENTION_DARWIN_H +#define VIVA_ATTENTION_DARWIN_H + +/* Bounces the application's Dock tile once, the system's own way of drawing + * attention when the application is not active. Main thread only. */ +void viva_application_request_attention(void); + +#endif diff --git a/internal/platform/darwin/attention_darwin.m b/internal/platform/darwin/attention_darwin.m new file mode 100644 index 000000000..759cc882b --- /dev/null +++ b/internal/platform/darwin/attention_darwin.m @@ -0,0 +1,24 @@ +//go:build !ios + +#include "attention_darwin.h" + +#import +#include + +void viva_application_request_attention(void) { + void (^work)(void) = ^{ + @autoreleasepool { + /* The informational request bounces the tile once. AppKit ignores + * it while the application is active, which is the window's own + * state to report; the Dock tile belongs to the application, not + * to one window. */ + [NSApp requestUserAttention:NSInformationalRequest]; + } + }; + if ([NSThread isMainThread]) { + work(); + } else { + /* The public API may be called from any goroutine; AppKit may not. */ + dispatch_async(dispatch_get_main_queue(), work); + } +} diff --git a/internal/platform/darwin/attention_darwin_test.go b/internal/platform/darwin/attention_darwin_test.go new file mode 100644 index 000000000..f09bccb5c --- /dev/null +++ b/internal/platform/darwin/attention_darwin_test.go @@ -0,0 +1,27 @@ +//go:build !ios + +package darwin + +import ( + "os/exec" + "path/filepath" + "testing" +) + +// The attention request belongs to the system: this compiles the adapter's own +// function with a program that initializes AppKit first, so the bridge reaches +// a real NSApplication instead of a nil one. +func TestNativeAttentionReachesAppKit(t *testing.T) { + executable := filepath.Join(t.TempDir(), "attention") + command := exec.Command("xcrun", "clang", "-fno-objc-arc", "-Werror", + "-Wno-deprecated-declarations", "testdata/attention.m", "attention_darwin.m", + "-o", executable, "-framework", "Cocoa") + if output, err := command.CombinedOutput(); err != nil { + t.Fatalf("compile native attention test: %v\n%s", err, output) + } + if output, err := exec.Command(executable).CombinedOutput(); err != nil { + t.Fatalf("native attention: %v\n%s", err, output) + } else { + t.Logf("%s", output) + } +} diff --git a/internal/platform/darwin/callback.go b/internal/platform/darwin/callback.go index 7f5ea9b28..b2de63c9a 100644 --- a/internal/platform/darwin/callback.go +++ b/internal/platform/darwin/callback.go @@ -125,8 +125,33 @@ func deliverPointer(state *runState, view unsafe.Pointer, event PointerEvent) { } } +//export vivaCPUSurfaceLost +func vivaCPUSurfaceLost(handle C.uintptr_t, view unsafe.Pointer) { + state := cgo.Handle(handle).Value().(*runState) + if state.cpu == nil { + return + } + if err := state.cpu.surfaceLost(view); err != nil { + state.err = err + C.viva_view_close(view) + } +} + +//export vivaTextOverlayChanged +func vivaTextOverlayChanged(handle C.uintptr_t, view unsafe.Pointer) { + state := cgo.Handle(handle).Value().(*runState) + if state.cpu == nil { + // The window is opening, or was never drawn by the CPU renderer. + return + } + if err := state.cpu.overlayChanged(view); err != nil { + state.err = err + C.viva_view_close(view) + } +} + //export vivaViewResized -func vivaViewResized(handle C.uintptr_t, view unsafe.Pointer, width C.double, height C.double) { +func vivaViewResized(handle C.uintptr_t, view unsafe.Pointer, width C.double, height C.double, scale C.double, live C.int) { state := cgo.Handle(handle).Value().(*runState) defer func() { if recovered := recover(); recovered != nil { @@ -136,14 +161,16 @@ func vivaViewResized(handle C.uintptr_t, view unsafe.Pointer, width C.double, he } }() - frame, err := state.resizeHandler(Size{Width: float32(width), Height: float32(height)}) + frame, err := state.resizeHandler(Size{Width: float32(width), Height: float32(height), Scale: float32(scale)}) if err == nil { - // The layer presents the frame in the same Core Animation transaction as - // the new bounds (see -[VivaMetalView beginLiveResizeRelaxation]), so the - // window never scales the previous frame. Waiting for the frame to be - // scheduled before returning keeps the next AppKit resize step behind - // the frame it belongs to. - err = presentFrame(state, view, frame, true) + // A live resize presents the frame in the same Core Animation transaction + // as the new bounds (see -[VivaMetalView beginLiveResizeRelaxation]), so + // the window never scales the previous frame, and waiting for the frame + // to be scheduled keeps the next AppKit step behind the frame it belongs + // to. A window manager's geometry change is outside any such + // transaction: nothing on screen waits for its frame, and waiting there + // only lets a blocked drawable hold the main thread. + err = presentFrame(state, view, frame, live != 0) } if err == nil && state.web != nil { state.web.layout(true) // the view's height moved the pages with it @@ -635,6 +662,27 @@ func presentFrame(state *runState, view unsafe.Pointer, frame Frame, syncRender return err } +// presentCPUFrame takes a frame into the CPU renderer's scene, keeps the view's +// editor state current, and presents what changed. It never touches Metal. +func presentCPUFrame(state *runState, view unsafe.Pointer, frame Frame) error { + if err := presentTextInput(state, view, frame.TextInput); err != nil { + return err + } + if _, err := state.cpu.apply(frame); err != nil { + return err + } + if frame.Accessibility != nil { + state.nodes = frame.Accessibility + if err := presentAccessibility(view, frame.Accessibility); err != nil { + return err + } + } + if state.web != nil { + state.web.frame(frame) + } + return state.cpu.present(view) +} + // recoverRenderer answers a frame the renderer could not make resources for: it // makes the window's Metal resources again and sends the frame once more as a // rebuild, because the new instance buffers are empty. @@ -673,6 +721,9 @@ func (state *runState) recoverResources(view unsafe.Pointer, cause error) error } func presentFrameOnce(state *runState, view unsafe.Pointer, frame Frame, syncRender bool) error { + if state != nil && state.cpu != nil { + return presentCPUFrame(state, view, frame) + } if state != nil && state.rebuildNextFrame { // The window made its Metal resources again since the last frame, so // the instance buffers hold nothing: a partial update would be diff --git a/internal/platform/darwin/core.h b/internal/platform/darwin/core.h index 4420edbea..1c9e0f31d 100644 --- a/internal/platform/darwin/core.h +++ b/internal/platform/darwin/core.h @@ -139,6 +139,7 @@ typedef struct { - (BOOL)refreshWindowWithDevice:(id)device scale:(CGFloat)scale viewport:(CGSize)viewport; - (void)drawLineInContext:(CGContextRef)context pixelScale:(CGFloat)pixelScale; - (void)drawRunsInContext:(CGContextRef)context pixelScale:(CGFloat)pixelScale; +- (void)drawInContext:(CGContextRef)context pixelScale:(CGFloat)pixelScale; - (id)textureAtIndex:(NSUInteger)index; - (NSUInteger)textureCount; - (CGRect)quadAtIndex:(NSUInteger)index; @@ -293,6 +294,32 @@ CGFloat viva_editor_alignment_inset(viva_editor_line line, CGFloat width, int al CGFloat viva_editor_visible_caret(CGFloat offset, CGFloat width, int alignment, BOOL terminal); CGFloat viva_baseline(CGFloat height, CGFloat fontSize, CGFloat pixelScale); CGFloat viva_fixed_baseline(CGFloat height, CGFloat fromTop, CGFloat pixelScale); +/* viva_text_input_bitmap rasterizes the native editor's current appearance + * (shown text, selection or composition, the caret in its visible phase) into + * a new premultiplied BGRA buffer the caller frees with free(): it is the + * texture's pixels without a Metal device. Returns 0, 1 for invalid + * arguments, or 2 when the editor cannot be rasterized. */ +int viva_text_input_bitmap( + CGFloat scale, + NSString *shown, + CGFloat fontSize, + CGFloat fontWeight, + VivaColor *color, + CGSize frameSize, + NSRange selectedRange, + BOOL hasMarked, + NSRange markedRange, + BOOL caretVisible, + BOOL terminal, + BOOL hideNativeOverlays, + int monoFace, + CGFloat cellWidth, + CGFloat cellBaseline, + int alignment, + unsigned char **pixels, + size_t *pixelWidth, + size_t *pixelHeight +); id viva_text_input_texture( id device, CGFloat scale, @@ -319,6 +346,19 @@ id viva_create_pipeline( NSString *fragmentName, NSError **error ); +/* viva_label_bitmap draws the device columns [skip, skip+width) of a text + * label, height rows tall, into pixels: premultiplied BGRA, width*4 bytes per + * row, the glyphs in the label's own color. It is how the CPU renderer asks + * CoreText for a label's picture without a Metal device. Returns 0 when + * drawn, 1 for invalid arguments, 2 when the label has no picture. */ +int viva_label_bitmap( + const viva_text_label *label, + double scale, + size_t skip, + size_t width, + size_t height, + unsigned char *pixels +); uint64_t viva_hash_bytes(uint64_t hash, const void *data, size_t length); float viva_quantized_origin(float value); uint64_t viva_label_content_hash(viva_text_label config); diff --git a/internal/platform/darwin/core_render.m b/internal/platform/darwin/core_render.m index 121d4fb49..4559c4dd0 100644 --- a/internal/platform/darwin/core_render.m +++ b/internal/platform/darwin/core_render.m @@ -938,11 +938,7 @@ - (BOOL)rebuildWithDevice:(id)device scale:(CGFloat)scale viewport:(C if (textureLeft > 0) { CGContextTranslateCTM(context, -(CGFloat)textureLeft / widthScale, 0); } - if (_runCount > 0) { - [self drawRunsInContext:context pixelScale:pixelScale]; - } else { - [self drawLineInContext:context pixelScale:pixelScale]; - } + [self drawInContext:context pixelScale:pixelScale]; MTLTextureDescriptor *descriptor = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm width:pixelWidth @@ -990,6 +986,16 @@ - (BOOL)rebuildWithDevice:(id)device scale:(CGFloat)scale viewport:(C return YES; } +// drawInContext draws the label's picture at the pixel scale: a fixed-pitch +// line's runs, or an ordinary label's one line. +- (void)drawInContext:(CGContextRef)context pixelScale:(CGFloat)pixelScale { + if (_runCount > 0) { + [self drawRunsInContext:context pixelScale:pixelScale]; + } else { + [self drawLineInContext:context pixelScale:pixelScale]; + } +} + // drawLineInContext draws an ordinary label: one line in one font and color, // vertically centered. - (void)drawLineInContext:(CGContextRef)context pixelScale:(CGFloat)pixelScale { @@ -1309,6 +1315,51 @@ int viva_update_label_layers( return 0; } +// viva_label_bitmap draws the device columns [skip, skip+width) of a label the +// way rebuildWithDevice draws a texture, into a caller's premultiplied BGRA +// buffer: the CPU renderer's picture of the label without a Metal device. +int viva_label_bitmap( + const viva_text_label *config, + double scale, + size_t skip, + size_t width, + size_t height, + unsigned char *pixels +) { + if (config == NULL || pixels == NULL || !(scale > 0) || width < 1 || height < 1 || + width > 16384 || height > 16384 || width > SIZE_MAX / 4 || height > SIZE_MAX / (width * 4)) { + return 1; + } + @autoreleasepool { + VivaTextLayer *layer = [[VivaTextLayer alloc] initWithConfig:*config]; + if (layer == nil) { + return 2; + } + CGFloat pixelScale = MAX(1.0, ceil(scale)); + CGFloat widthScale = [layer rasterWidthScale:scale]; + memset(pixels, 0, width * height * 4); + CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); + CGContextRef context = CGBitmapContextCreate( + pixels, width, height, 8, width * 4, colorSpace, + kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little + ); + CGColorSpaceRelease(colorSpace); + if (context == NULL) { + [layer release]; + return 1; + } + viva_prepare_text_context(context, pixelScale); + CGContextScaleCTM(context, widthScale / pixelScale, 1); + if (skip > 0) { + CGContextTranslateCTM(context, -(CGFloat)skip / widthScale, 0); + } + [layer drawInContext:context pixelScale:pixelScale]; + CGContextRelease(context); + [layer release]; + return 0; + } +} + // viva_label_box_quad writes the four corners of an axis-aligned box in the // order the text vertex shader expects them: top-left, top-right, bottom-left, // bottom-right. diff --git a/internal/platform/darwin/core_text.m b/internal/platform/darwin/core_text.m index ca59194e1..a7a85d98e 100644 --- a/internal/platform/darwin/core_text.m +++ b/internal/platform/darwin/core_text.m @@ -1221,12 +1221,12 @@ int viva_text_line_rasterize( } } -// viva_text_input_texture rasterizes the native editor's current appearance: +// viva_text_input_bitmap rasterizes the native editor's current appearance: // the shown text (bullets for a password), the selection or composition, and -// the caret when it is in its visible phase. It returns a retained texture, or -// nil when the frame cannot be rasterized. -id viva_text_input_texture( - id device, +// the caret when it is in its visible phase. It returns a new premultiplied +// BGRA buffer (free it with free()), or nonzero when the frame cannot be +// rasterized: the CPU renderer's editor picture without a Metal device. +int viva_text_input_bitmap( CGFloat scale, NSString *shown, CGFloat fontSize, @@ -1242,20 +1242,29 @@ int viva_text_line_rasterize( int monoFace, CGFloat cellWidth, CGFloat cellBaseline, - int alignment + int alignment, + unsigned char **pixels_out, + size_t *out_width, + size_t *out_height ) { + if (pixels_out == NULL || out_width == NULL || out_height == NULL || scale <= 0 || !isfinite(scale)) { + return 1; + } + *pixels_out = NULL; + *out_width = 0; + *out_height = 0; size_t pixelWidth = (size_t)MAX(1.0, ceil(frameSize.width * scale)); size_t pixelHeight = (size_t)MAX(1.0, ceil(frameSize.height * scale)); if (pixelWidth > 16384 || pixelHeight > 16384 || pixelWidth > SIZE_MAX / 4) { - return nil; + return 2; } size_t rowBytes = pixelWidth * 4; if (pixelHeight > SIZE_MAX / rowBytes) { - return nil; + return 2; } void *pixels = calloc(pixelHeight, rowBytes); if (pixels == NULL) { - return nil; + return 2; } CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); @@ -1271,7 +1280,7 @@ int viva_text_line_rasterize( CGColorSpaceRelease(colorSpace); if (context == NULL) { free(pixels); - return nil; + return 2; } viva_prepare_text_context(context, scale); @@ -1279,7 +1288,7 @@ int viva_text_line_rasterize( if (!viva_editor_line_made(line)) { CGContextRelease(context); free(pixels); - return nil; + return 2; } CGFloat inset = viva_editor_alignment_inset(line, frameSize.width, alignment, terminal); @@ -1351,6 +1360,44 @@ int viva_text_line_rasterize( CGContextFillRect(context, CGRectMake(caret, baseline - descent, 2.0, ascent + descent)); } + viva_editor_line_free(line); + CGContextRelease(context); + *pixels_out = pixels; + *out_width = pixelWidth; + *out_height = pixelHeight; + return 0; +} + + +// viva_text_input_texture is the bitmap the native editor shows, uploaded to a +// texture, or nil when the frame cannot be rasterized. +id viva_text_input_texture( + id device, + CGFloat scale, + NSString *shown, + CGFloat fontSize, + CGFloat fontWeight, + VivaColor *color, + CGSize frameSize, + NSRange selectedRange, + BOOL hasMarked, + NSRange markedRange, + BOOL caretVisible, + BOOL terminal, + BOOL hideNativeOverlays, + int monoFace, + CGFloat cellWidth, + CGFloat cellBaseline, + int alignment +) { + unsigned char *pixels = NULL; + size_t pixelWidth = 0, pixelHeight = 0; + if (viva_text_input_bitmap(scale, shown, fontSize, fontWeight, color, frameSize, selectedRange, + hasMarked, markedRange, caretVisible, terminal, hideNativeOverlays, + monoFace, cellWidth, cellBaseline, alignment, + &pixels, &pixelWidth, &pixelHeight) != 0) { + return nil; + } MTLTextureDescriptor *descriptor = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm width:pixelWidth @@ -1363,11 +1410,8 @@ int viva_text_line_rasterize( [texture replaceRegion:MTLRegionMake2D(0, 0, pixelWidth, pixelHeight) mipmapLevel:0 withBytes:pixels - bytesPerRow:rowBytes]; + bytesPerRow:pixelWidth * 4]; } - - viva_editor_line_free(line); - CGContextRelease(context); free(pixels); if (texture == nil) { return nil; diff --git a/internal/platform/darwin/cpu.go b/internal/platform/darwin/cpu.go new file mode 100644 index 000000000..5df965235 --- /dev/null +++ b/internal/platform/darwin/cpu.go @@ -0,0 +1,261 @@ +//go:build darwin + +package darwin + +/* +#include +#include "native.h" +// core.h is Objective-C and cannot join a cgo preamble; this is its declaration +// of the label picture the CPU renderer asks CoreText for. +int viva_label_bitmap(const viva_text_label *label, double scale, size_t skip, size_t width, size_t height, unsigned char *pixels); +*/ +import "C" + +import ( + "fmt" + "math" + "unsafe" + + "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/internal/raster" + "github.com/vivaui/viva/internal/render" + "github.com/vivaui/viva/internal/scene" + "github.com/vivaui/viva/internal/softscene" +) + +// cpuWindow draws a window with the CPU rasterizer when the machine has no +// Metal device: the scene is painted on the Go side (internal/softscene and +// internal/raster), the glyphs are CoreText's, and the view shows the canvas +// through a few IOSurfaces it sets as its layer's contents in turn. It is not +// safe for concurrent use, like the rest of the window, and runs on the +// event-loop thread. +// +// The canvas stays the one retained picture of the window and each frame's +// damage is copied into the surface about to be shown, rather than painted +// into the surfaces themselves. A surface that missed frames, or that the +// system emptied while it was purgeable, is then brought up to date by copying +// what it missed, which costs far less than painting it again; the rasterizer, +// which reads the pixels it blends over, never reads memory the system may +// take; and no Go code holds a pointer into a locked surface. The price is the +// canvas's memory next to the surfaces', of which only the one shown is held +// while the window is idle. +type cpuWindow struct { + scene *softscene.Scene + // overlayPixels backs the native editor's picture in the scene, so a repaint + // keeps it without the platform drawing it again. + overlayPixels []byte + // needOverlay says the native editor's picture changed since it was made. + needOverlay bool + // missed is, for each of the view's surfaces, what changed in the canvas + // since the surface was last filled: the damage of the frames shown in the + // others since then, which it must be given before it is shown again. + missed [C.VIVA_CPU_SURFACES]raster.Region + // rects carries a surface's rectangles to the view without allocating. + rects [raster.RegionRects]C.viva_cpu_rect + // lost says the view's shown surface was emptied by the system and must be + // shown again although the canvas did not change. + lost bool +} + +// newCPUWindow makes the CPU renderer of a window whose view has no Metal +// device, with the window's first content. +func newCPUWindow(view unsafe.Pointer, clear platform.Color, rectangles []render.Rectangle, labels []platform.TextLabel, scale float32, width, height int) (*cpuWindow, error) { + sc, err := softscene.New(coreTextRasterizer{}, width, height, scale, + scene.Color{Red: float32(clear.Red), Green: float32(clear.Green), Blue: float32(clear.Blue), Alpha: float32(clear.Alpha)}, + rectangles, labels) + if err != nil { + return nil, err + } + return &cpuWindow{scene: sc, needOverlay: true}, nil +} + +// coreTextRasterizer gives the shared scene the glyphs CoreText draws, through +// the native label picture the Metal path also makes. +type coreTextRasterizer struct{} + +func (coreTextRasterizer) Rasterize(label platform.TextLabel, scale float32, skip, width, height int, allowLCD bool) ([]byte, bool, error) { + if width < 1 || height < 1 || !(scale > 0) { + return nil, false, fmt.Errorf("darwin: invalid label window %dx%d at %g", width, height, scale) + } + memory, strings, count, err := makeNativeTextLabels([]platform.TextLabel{label}) + if err != nil { + return nil, false, err + } + if count == 0 { + freeNativeTextLabels(memory, strings) + return nil, false, nil + } + defer freeNativeTextLabels(memory, strings) + pixels := make([]byte, width*height*4) + status := C.viva_label_bitmap( + (*C.viva_text_label)(memory), + C.double(scale), + C.size_t(skip), + C.size_t(width), + C.size_t(height), + (*C.uchar)(unsafe.Pointer(&pixels[0])), + ) + switch status { + case 0: + // CoreText draws the glyphs in the label's own color, so the picture is + // premultiplied BGRA and never per-channel coverage. + return pixels, false, nil + case 2: + return nil, false, nil + default: + return nil, false, fmt.Errorf("darwin: label bitmap failed with status %d", status) + } +} + +func (coreTextRasterizer) Spans() []softscene.Span { return nil } + +// geometry is the view's content size in device pixels and its scale. +func (c *cpuWindow) geometry(view unsafe.Pointer) (width, height int, scale float32, ok bool) { + var logicalWidth, logicalHeight, viewScale C.double + if C.viva_view_cpu_geometry(view, &logicalWidth, &logicalHeight, &viewScale) == 0 { + return 0, 0, 0, false + } + if !(viewScale >= 1) || !(logicalWidth > 0) || !(logicalHeight > 0) { + return 0, 0, 0, false + } + deviceWidth := int(math.Ceil(float64(logicalWidth) * float64(viewScale))) + deviceHeight := int(math.Ceil(float64(logicalHeight) * float64(viewScale))) + return deviceWidth, deviceHeight, float32(viewScale), deviceWidth > 0 && deviceHeight > 0 +} + +// apply takes a frame into the scene and reports whether the canvas changed. +func (c *cpuWindow) apply(frame Frame) (bool, error) { + if frame.TextInput.Changed { + c.needOverlay = true + } + return c.scene.Apply(frame) +} + +// present draws what changed and shows it: the view picks a surface the window +// server is done with, which is given what changed since it was last filled +// (all of the canvas when it is new or was emptied), and shows it. A frame +// whose content changed nothing still refreshes the editor's picture when it +// asks for one. +func (c *cpuWindow) present(view unsafe.Pointer) error { + width, height, scale, ok := c.geometry(view) + if !ok { + return nil + } + if err := c.scene.SetScale(scale); err != nil { + return err + } + if err := c.scene.Resize(width, height); err != nil { + return err + } + if c.needOverlay { + if err := c.refreshOverlay(view, scale); err != nil { + return err + } + } + damage := c.scene.Paint() + for index := range c.missed { + for _, box := range damage { + c.missed[index].Add(box) + } + } + if len(damage) == 0 && !c.lost { + return nil + } + canvas := c.scene.Canvas + if len(canvas.Pix) == 0 { + return nil + } + var fresh C.int + index := C.viva_view_cpu_acquire(view, C.size_t(canvas.Width), C.size_t(canvas.Height), &fresh) + if index < 0 || int(index) >= len(c.missed) { + // No surface could be made: every one keeps what it missed, and the next + // frame tries again. + return nil + } + missed := &c.missed[index] + if fresh != 0 { + missed.Set(canvas.Bounds()) + } + missed.Limit(canvas.Bounds()) + count := 0 + for _, box := range missed.Rects() { + c.rects[count] = C.viva_cpu_rect{x: C.size_t(box.Left), y: C.size_t(box.Top), width: C.size_t(box.Right - box.Left), height: C.size_t(box.Bottom - box.Top)} + count++ + } + if C.viva_view_cpu_present(view, index, (*C.uchar)(unsafe.Pointer(&canvas.Pix[0])), C.size_t(canvas.Stride), + &c.rects[0], C.size_t(count), C.double(platform.IdleTrimDelay.Seconds())) != 0 { + // The surface could not be written; the view fills it whole next time. + return nil + } + missed.Reset() + c.lost = false + return nil +} + +// surfaceLost shows the canvas again after the system emptied the surface the +// view showed while the window was occluded. The canvas is whole, so this is a +// copy and not a paint. +func (c *cpuWindow) surfaceLost(view unsafe.Pointer) error { + c.lost = true + return c.present(view) +} + +// refreshOverlay takes the native editor's picture from the view and places it +// after the frame's content in its layer, or takes it away when no editor is +// shown. A caret blink and every text change ask for this without a frame. +func (c *cpuWindow) refreshOverlay(view unsafe.Pointer, scale float32) error { + c.needOverlay = false + var pixels *C.uchar + var pixelWidth, pixelHeight C.size_t + if C.viva_view_text_input_bitmap(view, C.double(scale), &pixels, &pixelWidth, &pixelHeight) != 0 || pixels == nil { + c.scene.SetOverlay(raster.Label{}, false) + return nil + } + defer C.free(unsafe.Pointer(pixels)) + var x, y, width, height C.double + var layer C.int + if C.viva_view_text_input_frame(view, &x, &y, &width, &height, &layer) == 0 { + c.scene.SetOverlay(raster.Label{}, false) + return nil + } + if pixelWidth < 1 || pixelHeight < 1 || uint64(pixelWidth)*uint64(pixelHeight) > uint64(math.MaxInt)/4 { + c.scene.SetOverlay(raster.Label{}, false) + return nil + } + size := int(pixelWidth) * int(pixelHeight) * 4 + if cap(c.overlayPixels) < size { + c.overlayPixels = make([]byte, size) + } + c.overlayPixels = c.overlayPixels[:size] + copy(c.overlayPixels, unsafe.Slice((*byte)(unsafe.Pointer(pixels)), size)) + c.scene.SetOverlay(raster.Label{ + Pix: c.overlayPixels, + Stride: int(pixelWidth) * 4, + Width: int(pixelWidth), + Height: int(pixelHeight), + X: platform.DevicePosition(float32(x), 0, scale), + Y: platform.DevicePosition(float32(y), 0, scale), + Layer: uint16(layer), + ShapesBefore: math.MaxUint32, + }, true) + return nil +} + +// overlayChanged repaints the editor's picture after the view redrew it outside +// a frame: a caret blink or a text change. +func (c *cpuWindow) overlayChanged(view unsafe.Pointer) error { + width, _, scale, ok := c.geometry(view) + if !ok || width < 1 { + return nil + } + if err := c.refreshOverlay(view, scale); err != nil { + return err + } + return c.present(view) +} + +// close releases the scene and the overlay's pixels. +func (c *cpuWindow) close() { + c.scene.Close() + c.overlayPixels = nil +} diff --git a/internal/platform/darwin/native.h b/internal/platform/darwin/native.h index c50420746..86a2db9e1 100644 --- a/internal/platform/darwin/native.h +++ b/internal/platform/darwin/native.h @@ -303,6 +303,8 @@ typedef struct { int selection_start; int selection_end; int text_length; + // A column header's sort: 0 none, 1 ascending, 2 descending (gfx.SortDirection). + int sort_direction; } viva_accessibility_node; // What an accessibility client asks of a node (vivaAccessibilityAction). @@ -410,6 +412,8 @@ enum { VIVA_APPLICATION_NOT_MAIN_THREAD = 10 }; int viva_application_check_thread(void); int viva_application_begin(void); int viva_application_last_status(void); +/* The content view of an open window, for the per-frame view functions. */ +void *viva_application_window_view(void *window); void *viva_application_open_window(viva_window_config config); /* Writes x, y, width, height of the window's content area in top-left screen * coordinates and returns 1, or returns 0 when there is no such window. Safe from @@ -498,6 +502,91 @@ int viva_view_update_accessibility( ); void viva_view_render(void *view); void viva_view_render_sync(void *view); +/* The CPU renderer's window: the Go side paints the canvas, width by height + * device pixels of premultiplied BGRA, and the view shows it through a few + * IOSurfaces it sets as its layer's contents in turn. VIVA_CPU_SURFACES is how + * many a view keeps; the Go side remembers, for each, what changed in the + * canvas since it was last filled. */ +#define VIVA_CPU_SURFACES 3 +typedef struct viva_cpu_rect { + size_t x; + size_t y; + size_t width; + size_t height; +} viva_cpu_rect; +/* Picks the surface the next frame is written to: one the window server is + * done with, other than the one shown, made for width by height pixels. fresh + * is set when the surface holds nothing of the canvas -- new, resized, or + * emptied by the system while it was purgeable -- and must be filled whole. + * Returns the surface's index, or -1 when none can be made. */ +int viva_view_cpu_acquire(void *view, size_t width, size_t height, int *fresh); +/* Copies the rectangles of the canvas into the surface acquire returned and + * shows it; returns 0 when it is shown. Once no frame has come for trim_after + * seconds, the surfaces off screen become purgeable. */ +int viva_view_cpu_present( + void *view, + int index, + const unsigned char *pixels, + size_t stride, + const viva_cpu_rect *rects, + size_t count, + double trim_after +); +/* The view's content size in logical pixels and its device scale; 1 when the + * view draws with the CPU renderer, 0 otherwise. */ +int viva_view_cpu_geometry(void *view, double *width, double *height, double *scale); +/* Reports the view's content size and display scale to the application, as a + * resize does, so it can repaint the frame it laid out before the window existed. */ +void viva_view_report_size(void *view); +/* viva_text_input_bitmap_c is the native editor's picture from plain C values: + * the offscreen CPU renderer has no view to ask. The caller frees pixels. */ +int viva_text_input_bitmap_c( + double scale, + const unsigned char *utf8, + size_t utf8_length, + double font_size, + double font_weight, + double red, + double green, + double blue, + double alpha, + double width, + double height, + size_t selected_start, + size_t selected_length, + size_t marked_start, + size_t marked_length, + int has_marked_text, + int caret_visible, + int terminal, + int hide_native_overlays, + int mono_face, + double cell_width, + double cell_baseline, + int alignment, + unsigned char **pixels, + size_t *pixel_width, + size_t *pixel_height +); +/* The native editor's picture at scale, in a new buffer the caller frees; + * 0 when it was drawn, nonzero when no editor is shown or it cannot be. */ +int viva_view_text_input_bitmap( + void *view, + double scale, + unsigned char **pixels, + size_t *width, + size_t *height +); +/* The native editor's frame in logical pixels and the layer it draws in; + * 0 when no editor is shown. */ +int viva_view_text_input_frame( + void *view, + double *x, + double *y, + double *width, + double *height, + int *layer +); void viva_view_close(void *view); // viva_view_popup_text_menu shows a menu of count rows at (x, y) of the view, in // the view's top-left coordinates, and returns once it has closed: the command of diff --git a/internal/platform/darwin/native.m b/internal/platform/darwin/native.m index 0388fc2ba..9694b528a 100644 --- a/internal/platform/darwin/native.m +++ b/internal/platform/darwin/native.m @@ -8,6 +8,7 @@ #include "label_geometry.h" #include "main_menu_darwin.h" #import +#import static uint64_t viva_process_start_ticks; static uint64_t viva_pointer_event_count; @@ -168,6 +169,14 @@ static void viva_place_traffic_lights(NSWindow *window, CGFloat stripHeight, CGF VIVA_SHOW_EVENT = 0x4753, VIVA_QUIT_EVENT = 0x4751, VIVA_STATUS_REMOVE_EVENT = 0x4754, + VIVA_RESIZE_EVENT = 0x4745, +}; + +/* How long a frame may stay un-presented before the view assumes it was dropped + * and draws again. A frame normally reaches the screen within a display refresh; + * one that does not was lost rather than merely late. */ +enum { + VIVA_FRAME_IN_FLIGHT_LIMIT_MS = 2000, }; @@ -295,11 +304,14 @@ extern void vivaPointerEvent( double screenY ); +extern void vivaTextOverlayChanged(uintptr_t callback_handle, void *view); extern void vivaViewResized( uintptr_t callbackHandle, void *view, double width, - double height + double height, + double scale, + int live ); extern void vivaRedrawRequested( @@ -410,6 +422,7 @@ extern void vivaFrameChanged( extern void vivaWindowMinimized(uintptr_t callbackHandle, void *view, int minimized); extern void vivaWindowOccluded(uintptr_t callbackHandle, void *view, int visible); +extern void vivaCPUSurfaceLost(uintptr_t callbackHandle, void *view); extern void vivaWindowFullscreen(uintptr_t callbackHandle, void *view, int fullscreen); extern int vivaWindowReopenRequested(uintptr_t callbackHandle, void *view); @@ -1012,11 +1025,22 @@ - (instancetype)initWithConfig:(viva_accessibility_node)config case 22: self.accessibilityRole = NSAccessibilityStaticTextRole; break; case 23: self.accessibilityRole = NSAccessibilitySplitterRole; break; case 24: self.accessibilityRole = NSAccessibilityProgressIndicatorRole; break; + // A sortable column header is a button, as an NSTableView's header + // cell is: its subrole says it sorts, and AXSortDirection how. + case 25: self.accessibilityRole = NSAccessibilityButtonRole; break; default: self.accessibilityRole = NSAccessibilityGroupRole; break; } if (config.secure) { self.accessibilitySubrole = NSAccessibilitySecureTextFieldSubrole; } + if (config.role == 25) { + self.accessibilitySubrole = NSAccessibilitySortButtonSubrole; + switch (config.sort_direction) { + case 1: self.accessibilitySortDirection = NSAccessibilitySortDirectionAscending; break; + case 2: self.accessibilitySortDirection = NSAccessibilitySortDirectionDescending; break; + default: self.accessibilitySortDirection = NSAccessibilitySortDirectionUnknown; break; + } + } self.accessibilityLabel = _label; NSString *hint = config.hint_length > 0 ? [[[NSString alloc] initWithBytes:config.hint @@ -1064,7 +1088,6 @@ - (instancetype)initWithConfig:(viva_accessibility_node)config self.accessibilitySelectedTextRange = NSMakeRange((NSUInteger)low, (NSUInteger)(high - low)); self.accessibilityNumberOfCharacters = config.text_length; } - self.accessibilityFrame = _frameInWindow; self.accessibilityFocused = _focused; self.accessibilityEnabled = config.disabled == 0; self.accessibilitySelected = config.selected != 0; @@ -1082,6 +1105,21 @@ - (void)dealloc { [super dealloc]; } +/* Accessibility frames are screen coordinates: a client (VoiceOver, an + * automation script, a window manager moving or previewing the window) places + * the element by them and reads them whenever it likes, including after the + * window moved without a repaint. The paint gives a node a rectangle in window + * coordinates, so convert when the frame is read rather than freezing the + * window's origin at the paint. */ +- (NSRect)accessibilityFrame { + NSView *view = (NSView *)_view; + NSWindow *window = view != nil ? view.window : nil; + if (window == nil) { + return _frameInWindow; + } + return [window convertRectToScreen:_frameInWindow]; +} + // perform hands a client's request to the application. The element may be // replaced by the very frame the request causes, so it is kept alive until the // call returns. @@ -1157,6 +1195,33 @@ @interface VivaMetalView : NSView { // What the surface draws: the rectangles, the label layers, the pipelines and // the queue they go through (VivaRenderer, shared with the other surfaces). VivaRenderer *_renderer; + // A machine with no Metal device draws its window with the CPU rasterizer + // instead: the Go side paints the canvas and this view shows it in a plain + // layer whose contents are one of a few IOSurfaces. The one shown is never + // written; a frame is copied into another the window server is done with, + // which is then shown (see acquireCPUSurface and presentCPUSurface). + BOOL _cpuMode; + CALayer *_cpuLayer; + IOSurfaceRef _cpuSurfaces[VIVA_CPU_SURFACES]; + // _cpuShown is the serial of the frame each surface last showed, 0 for none. + uint64_t _cpuShown[VIVA_CPU_SURFACES]; + // _cpuVolatile says a surface is purgeable, and the system may empty it; + // _cpuEmptied says it holds nothing of the canvas and must be filled whole. + BOOL _cpuVolatile[VIVA_CPU_SURFACES]; + BOOL _cpuEmptied[VIVA_CPU_SURFACES]; + size_t _cpuSurfaceWidth; + size_t _cpuSurfaceHeight; + int _cpuFront; // the surface shown, -1 for none + uint64_t _cpuSerial; + // The surfaces off screen become purgeable once no frame has come for + // _cpuTrimAfter seconds, by a one-shot timer a burst of frames arms once, + // and a surface beyond the shown one and the one shown before it as soon as + // the window server lets go of it; while the window is occluded the one + // shown is purgeable too. + CFTimeInterval _cpuLastPresent; + NSTimeInterval _cpuTrimAfter; + BOOL _cpuTrimArmed; + BOOL _cpuOccluded; id _textTexture; NSString *_text; NSRect _textFrame; @@ -1219,6 +1284,16 @@ @interface VivaMetalView : NSView { NSSize _lastReportedSize; BOOL _liveResizeRelaxed; BOOL _reportedSize; + // A geometry change the window manager made waits for the run loop before it + // reaches the application: one animation of the window keeps one layout pass + // (see -scheduleResizeReport). + BOOL _resizePosted; + // Whether a frame handed to the layer is still on its way to the screen. The + // next frame would take the last drawable and block this thread in + // -[CAMetalLayer nextDrawable] until the window server presents one. + BOOL _frameInFlight; + uint64_t _frameInFlightSince; + BOOL _redrawAfterPresent; BOOL _reportedFirstFrame; BOOL _profileEnabled; NSCursor *_cursor; @@ -1254,6 +1329,19 @@ - (void)enableFileDrops; - (void)setModifierTapsEnabled:(BOOL)enabled; - (void)render; - (void)renderWaitingForSchedule:(BOOL)wait; +- (int)acquireCPUSurfaceWidth:(size_t)width height:(size_t)height fresh:(int *)fresh; +- (BOOL)presentCPUSurface:(int)index + pixels:(const unsigned char *)pixels + stride:(size_t)stride + rects:(const viva_cpu_rect *)rects + count:(size_t)count + trimAfter:(double)trimAfter; +- (BOOL)cpuGeometryWidth:(double *)width height:(double *)height scale:(double *)scale; +- (int)textInputBitmapAtScale:(CGFloat)scale + pixels:(unsigned char **)pixels + width:(size_t *)width + height:(size_t *)height; +- (BOOL)textInputFrameX:(double *)x y:(double *)y width:(double *)width height:(double *)height layer:(int *)layer; - (BOOL)recoverResources; - (int)updateRectangles:(const viva_rectangle *)rectangles clips:(const viva_clip *)clips @@ -1282,6 +1370,7 @@ - (void)restartCaretBlink; - (void)stopCaretBlink; - (void)shutdownTextInput; - (void)detachCallbacks; +- (void)trackPresentedDrawable:(id)drawable; - (void)notifyCompositionLost; - (void)endOwnedNativeComposition; - (BOOL)rebuildTextTexture; @@ -1434,29 +1523,48 @@ - (instancetype)initWithFrame:(NSRect)frame _reportedSize = YES; _profileEnabled = viva_profile_enabled(); - _metalLayer = [[CAMetalLayer alloc] init]; - _metalLayer.device = device; - _metalLayer.pixelFormat = MTLPixelFormatBGRA8Unorm; - _metalLayer.framebufferOnly = YES; - /* The renderer writes sRGB values into a non-sRGB-encoded format. An - * untagged layer is sent to the display unmatched, so a panel with a - * non-sRGB profile shows flat tints differently (and can band or - * flicker) from every tagged app; naming the space lets the system - * match it as it does for other windows. */ - CGColorSpaceRef layerSpace = CGColorSpaceCreateWithName(kCGColorSpaceSRGB); - _metalLayer.colorspace = layerSpace; - CGColorSpaceRelease(layerSpace); - /* A transparent clear color must reach the desktop through a frameless - * surface. Opaque titled windows keep the normal fast path. */ - _metalLayer.opaque = clearColor.alpha >= 1.0 && windowMode != VIVA_WINDOW_PANEL && windowMode != VIVA_WINDOW_PREVIEW; - _metalLayer.maximumDrawableCount = 2; - _metalLayer.allowsNextDrawableTimeout = YES; - - self.wantsLayer = YES; - self.layer = _metalLayer; - if (windowMode == VIVA_WINDOW_PANEL || windowMode == VIVA_WINDOW_NOTIFICATION) { - _metalLayer.cornerRadius = VIVA_PANEL_CORNER_RADIUS; - _metalLayer.masksToBounds = YES; + if (device == nil) { + /* The machine has no Metal device: the window is drawn by the CPU + * rasterizer on the Go side and shown in a plain layer. */ + _cpuMode = YES; + _cpuFront = -1; + _cpuLayer = [[CALayer alloc] init]; + _cpuLayer.opaque = clearColor.alpha >= 1.0 && windowMode != VIVA_WINDOW_PANEL && windowMode != VIVA_WINDOW_PREVIEW; + if (windowMode == VIVA_WINDOW_PANEL || windowMode == VIVA_WINDOW_NOTIFICATION) { + _cpuLayer.cornerRadius = VIVA_PANEL_CORNER_RADIUS; + _cpuLayer.masksToBounds = YES; + } + self.wantsLayer = YES; + self.layer = _cpuLayer; + [[NSNotificationCenter defaultCenter] addObserver:self + selector:@selector(cpuOcclusionChanged:) + name:NSWindowDidChangeOcclusionStateNotification + object:nil]; + } else { + _metalLayer = [[CAMetalLayer alloc] init]; + _metalLayer.device = device; + _metalLayer.pixelFormat = MTLPixelFormatBGRA8Unorm; + _metalLayer.framebufferOnly = YES; + /* The renderer writes sRGB values into a non-sRGB-encoded format. An + * untagged layer is sent to the display unmatched, so a panel with a + * non-sRGB profile shows flat tints differently (and can band or + * flicker) from every tagged app; naming the space lets the system + * match it as it does for other windows. */ + CGColorSpaceRef layerSpace = CGColorSpaceCreateWithName(kCGColorSpaceSRGB); + _metalLayer.colorspace = layerSpace; + CGColorSpaceRelease(layerSpace); + /* A transparent clear color must reach the desktop through a frameless + * surface. Opaque titled windows keep the normal fast path. */ + _metalLayer.opaque = clearColor.alpha >= 1.0 && windowMode != VIVA_WINDOW_PANEL && windowMode != VIVA_WINDOW_PREVIEW; + _metalLayer.maximumDrawableCount = 2; + _metalLayer.allowsNextDrawableTimeout = YES; + + self.wantsLayer = YES; + self.layer = _metalLayer; + if (windowMode == VIVA_WINDOW_PANEL || windowMode == VIVA_WINDOW_NOTIFICATION) { + _metalLayer.cornerRadius = VIVA_PANEL_CORNER_RADIUS; + _metalLayer.masksToBounds = YES; + } } [self updateDrawableSize]; /* A panel opens while the application is not the active one, and its @@ -1472,20 +1580,22 @@ - (instancetype)initWithFrame:(NSRect)frame userInfo:nil]; [self addTrackingArea:tracking]; [tracking release]; - _renderer = [[VivaRenderer alloc] initWithLayer:_metalLayer - commandQueue:commandQueue - rectanglePipeline:rectanglePipeline - rectangleBuffer:rectangleBuffer - rectangleCount:rectangleCount - rectangleClips:rectangleClips - textPipeline:textPipeline - textLabels:textLabels - textLabelCount:textLabelCount - clearColor:clearColor - viewport:self.bounds.size]; - if (_renderer == nil) { - [self release]; - return nil; + if (device != nil) { + _renderer = [[VivaRenderer alloc] initWithLayer:_metalLayer + commandQueue:commandQueue + rectanglePipeline:rectanglePipeline + rectangleBuffer:rectangleBuffer + rectangleCount:rectangleCount + rectangleClips:rectangleClips + textPipeline:textPipeline + textLabels:textLabels + textLabelCount:textLabelCount + clearColor:clearColor + viewport:self.bounds.size]; + if (_renderer == nil) { + [self release]; + return nil; + } } _accessibilityElements = [[NSMutableArray alloc] init]; for (NSUInteger index = 0; index < accessibilityCount; index++) { @@ -1523,14 +1633,28 @@ - (void)dealloc { [_textColor release]; [_renderer release]; [_metalLayer release]; + [self releaseCPUSurfaces]; + [_cpuLayer release]; [super dealloc]; } - (BOOL)isOpaque { + if (_cpuMode) { + return _cpuLayer.opaque && _windowMode != VIVA_WINDOW_NOTIFICATION; + } return _metalLayer.isOpaque && _windowMode != VIVA_WINDOW_NOTIFICATION; } +// AppKit answers YES for a view that is not opaque, and then moves the window +// from any press in the title-bar band, taking it from the page: a tab dragged +// out of a transparent window moved the whole window. The page declares where +// the window moves from (a move region, which starts the drag itself), so no +// press here is the system's. +- (BOOL)mouseDownCanMoveWindow { + return NO; +} + - (BOOL)acceptsFirstResponder { return YES; } @@ -2209,6 +2333,33 @@ - (void)updateLayer { [self render]; } +// displayScale is the device pixels per logical pixel of the display the view is +// on: what the application rounds everything that must land on a whole device +// pixel for. A view not in a window yet uses the screen it will open on, and a +// machine where no screen can say gets 1. +- (CGFloat)displayScale { + NSScreen *screen = self.window.screen ?: NSScreen.mainScreen; + return screen != nil ? MAX(screen.backingScaleFactor, 1.0) : 1.0; +} + +// reportSize tells the application the content size and display scale this view +// has. The application laid its first frame out before the window existed, when +// the scale was still unknown, so the window reports both once it is built and +// before it draws; a display change reports the same to repaint for the new scale. +- (void)reportSize { + [self reportSizeLive:NO]; +} + +/* reportSizeLive says whether the frame belongs to the transaction that changes + * the bounds. Only a live resize does (see -resizesInTransaction). */ +- (void)reportSizeLive:(BOOL)live { + if (!_resizeEventsEnabled || _callbackHandle == 0) { + return; + } + vivaViewResized(_callbackHandle, self, self.bounds.size.width, self.bounds.size.height, + [self displayScale], live ? 1 : 0); +} + - (void)setFrameSize:(NSSize)newSize { [super setFrameSize:newSize]; [self updateDrawableSize]; @@ -2219,12 +2370,65 @@ - (void)setFrameSize:(NSSize)newSize { _lastReportedSize = newSize; _reportedSize = YES; viva_resize_event_count++; - vivaViewResized(_callbackHandle, self, newSize.width, newSize.height); + if ([self resizesInTransaction]) { + // A live resize draws the new bounds in the transaction that changes + // them, so the application has to answer it before AppKit's next + // step. + [self reportSizeLive:YES]; + } else { + // A window manager animates a geometry change in many steps and + // every step lands here. Relaying each one would make the + // application layout and draw for sizes the window never stops at, + // and each draw takes a drawable from the layer (see + // -renderWaitingForSchedule:). The report waits for the run loop, so + // an animation costs one layout pass instead of one per step. + [self scheduleResizeReport]; + } } else { [self setNeedsDisplay:YES]; } } +/* resizesInTransaction reports whether the window is changing its geometry in a + * transaction that has to show the frame of the new bounds: the user dragging an + * edge, or a system resize session relaxed for it. A window manager's geometry + * change is neither, and nothing on screen waits for its frame. */ +- (BOOL)resizesInTransaction { + return (self.window != nil && self.window.inLiveResize) || _liveResizeRelaxed; +} + +/* scheduleResizeReport posts the report of a window manager's geometry change to + * the run loop. A change that lands before the report runs only replaces the + * size it will read: the view reads its bounds when the report is delivered. */ +- (void)scheduleResizeReport { + if (_resizePosted || _callbackHandle == 0) { + return; + } + _resizePosted = YES; + @autoreleasepool { + NSEvent *event = [NSEvent otherEventWithType:NSEventTypeApplicationDefined + location:NSZeroPoint + modifierFlags:0 + timestamp:0 + windowNumber:0 + context:nil + subtype:VIVA_RESIZE_EVENT + data1:(NSInteger)_callbackHandle + data2:0]; + [[NSApplication sharedApplication] postEvent:event atStart:NO]; + } +} + +/* reportPendingResize relays the size the window last settled on. It runs from + * the run loop, outside AppKit's layout pass. */ +- (void)reportPendingResize { + if (!_resizePosted || _callbackHandle == 0) { + return; + } + _resizePosted = NO; + [self reportSize]; +} + - (void)beginLiveResizeRelaxation { _liveResizeRelaxed = YES; /* AppKit resizes the layer before the drawable drawn for the new bounds is @@ -2233,7 +2437,9 @@ - (void)beginLiveResizeRelaxation { * in the same Core Animation transaction as the layer's new bounds, so the * window never shows a scaled previous frame. The resize path waits for the * frame to be scheduled before returning. */ - _metalLayer.presentsWithTransaction = YES; + if (!_cpuMode) { + _metalLayer.presentsWithTransaction = YES; + } } - (void)endLiveResizeRelaxation { @@ -2245,7 +2451,9 @@ - (void)endLiveResizeRelaxation { // setNeedsDisplay is not honored without drawRect; render explicitly so // the refreshed textures actually reach the screen. [self render]; - _metalLayer.presentsWithTransaction = NO; + if (!_cpuMode) { + _metalLayer.presentsWithTransaction = NO; + } } - (void)viewDidChangeBackingProperties { @@ -2255,21 +2463,32 @@ - (void)viewDidChangeBackingProperties { [self rebuildTextTexture]; } [self rebuildTextLabels]; - // Moving between displays of different scale lands here with no resize - // and no input, so nothing else would draw the rebuilt frame; and - // setNeedsDisplay is not honored without drawRect. Render explicitly or - // the window shows the old scale's pixels until the next hover. - [self render]; + // Moving between displays of different scale lands here with no resize and + // no input, so nothing else would draw the rebuilt frame; and + // setNeedsDisplay is not honored without drawRect. A window that reports + // sizes repaints from reportSize with the new scale; without one, render + // explicitly or the window shows the old scale's pixels until the next hover. + BOOL reported = _resizeEventsEnabled && _callbackHandle != 0; + [self reportSize]; + if (!reported) { + [self render]; + } } - (BOOL)rebuildTextLabels { + if (_cpuMode) { + return YES; + } return [_renderer rebuildTextLabelsWithViewport:self.bounds.size]; } - (void)updateDrawableSize { - NSScreen *screen = self.window.screen ?: NSScreen.mainScreen; - CGFloat scale = screen != nil ? screen.backingScaleFactor : 1.0; + CGFloat scale = [self displayScale]; NSSize size = self.bounds.size; + if (_cpuMode) { + _cpuLayer.contentsScale = scale; + return; + } _metalLayer.contentsScale = scale; _metalLayer.drawableSize = CGSizeMake(size.width * scale, size.height * scale); } @@ -2341,8 +2560,16 @@ - (viva_editor_line)newTextLine { } - (BOOL)rebuildTextTexture { - if (!_textInputEnabled || _renderer.textPipeline == nil) { - return !_textInputEnabled; + if (!_textInputEnabled) { + return YES; + } + if (_cpuMode) { + // Without a device the editor is one of the pictures the CPU renderer + // reads when it draws (viva_view_text_input_bitmap). + return YES; + } + if (_renderer.textPipeline == nil) { + return NO; } id texture = viva_text_input_texture( _metalLayer.device, MAX(_metalLayer.contentsScale, 1.0), [self displayedText], @@ -2445,18 +2672,355 @@ - (void)shutdownTextInput { - (void)detachCallbacks { // The view can outlive its Go window and receive a final mouseExited:. _callbackHandle = 0; + _resizePosted = NO; + _frameInFlight = NO; + _redrawAfterPresent = NO; + // The window is closing: the layer keeps the surface it shows for as long + // as it is on screen, and the others go now. + [self releaseCPUSurfaces]; [self shutdownTextInput]; } +// releaseCPUSurfaces lets go of the presentation surfaces. The layer keeps the +// one it shows until its contents change, so the window does not go blank. +- (void)releaseCPUSurfaces { + [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(cpuTrimTimerFired) object:nil]; + _cpuTrimArmed = NO; + for (int index = 0; index < VIVA_CPU_SURFACES; index++) { + if (_cpuSurfaces[index] != NULL) { + CFRelease(_cpuSurfaces[index]); + _cpuSurfaces[index] = NULL; + } + _cpuShown[index] = 0; + _cpuVolatile[index] = NO; + _cpuEmptied[index] = NO; + } + _cpuFront = -1; + _cpuSurfaceWidth = 0; + _cpuSurfaceHeight = 0; +} + +// viva_new_cpu_surface makes a presentation surface of premultiplied BGRA. +static IOSurfaceRef viva_new_cpu_surface(size_t width, size_t height) { + /* 0x42475241 is 'BGRA', kCVPixelFormatType_32BGRA. */ + int32_t values[4] = {(int32_t)width, (int32_t)height, 4, 0x42475241}; + CFNumberRef numbers[4]; + for (int index = 0; index < 4; index++) { + numbers[index] = CFNumberCreate(NULL, kCFNumberSInt32Type, &values[index]); + } + const void *keys[4] = {kIOSurfaceWidth, kIOSurfaceHeight, kIOSurfaceBytesPerElement, kIOSurfacePixelFormat}; + CFDictionaryRef properties = CFDictionaryCreate(NULL, keys, (const void **)numbers, 4, + &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); + for (int index = 0; index < 4; index++) { + if (numbers[index] != NULL) { + CFRelease(numbers[index]); + } + } + if (properties == NULL) { + return NULL; + } + IOSurfaceRef surface = IOSurfaceCreate(properties); + CFRelease(properties); + if (surface != NULL) { + /* The rasterizer writes sRGB values, as the Metal path does into its + * sRGB-tagged layer; tagging the surface lets the system match it to a + * display with another profile instead of sending it unmatched. */ + IOSurfaceSetValue(surface, kIOSurfaceColorSpace, kCGColorSpaceSRGB); + } + return surface; +} + +// acquireCPUSurface picks the surface the next frame is written to. The one +// shown is not chosen while another can be had: Core Animation may be reading +// it. Of the others, one the window server no longer uses and that showed a +// frame most recently is best, since it missed the fewest changes; a third is +// made only when the previous one is still in use. A purgeable surface is made +// non-purgeable first, and one the system emptied is reported fresh. +- (int)acquireCPUSurfaceWidth:(size_t)width height:(size_t)height fresh:(int *)fresh { + *fresh = 0; + if (!_cpuMode || width < 1 || height < 1 || width > INT32_MAX || height > INT32_MAX) { + return -1; + } + if (width != _cpuSurfaceWidth || height != _cpuSurfaceHeight) { + [self releaseCPUSurfaces]; + _cpuSurfaceWidth = width; + _cpuSurfaceHeight = height; + } + int chosen = -1; + for (int index = 0; index < VIVA_CPU_SURFACES; index++) { + if (_cpuSurfaces[index] != NULL && index != _cpuFront && !IOSurfaceIsInUse(_cpuSurfaces[index]) && + (chosen < 0 || _cpuShown[index] > _cpuShown[chosen])) { + chosen = index; + } + } + for (int index = 0; chosen < 0 && index < VIVA_CPU_SURFACES; index++) { + if (_cpuSurfaces[index] != NULL) { + continue; + } + _cpuSurfaces[index] = viva_new_cpu_surface(width, height); + if (_cpuSurfaces[index] != NULL) { + _cpuShown[index] = 0; + _cpuVolatile[index] = NO; + _cpuEmptied[index] = YES; + chosen = index; + } + break; + } + if (chosen < 0) { + /* Every other surface is still with the window server, which happens + * only when frames come faster than it composites. The one shown longest + * ago is the least likely to be read; the one shown is the last resort. */ + for (int index = 0; index < VIVA_CPU_SURFACES; index++) { + if (_cpuSurfaces[index] != NULL && index != _cpuFront && (chosen < 0 || _cpuShown[index] < _cpuShown[chosen])) { + chosen = index; + } + } + if (chosen < 0 && _cpuFront >= 0 && _cpuSurfaces[_cpuFront] != NULL) { + chosen = _cpuFront; + } + } + if (chosen < 0) { + return -1; + } + if (_cpuVolatile[chosen]) { + uint32_t old = kIOSurfacePurgeableNonVolatile; + IOSurfaceSetPurgeable(_cpuSurfaces[chosen], kIOSurfacePurgeableNonVolatile, &old); + _cpuVolatile[chosen] = NO; + if (old == kIOSurfacePurgeableEmpty) { + _cpuEmptied[chosen] = YES; + } + } + if (_cpuEmptied[chosen]) { + _cpuEmptied[chosen] = NO; + *fresh = 1; + } + return chosen; +} + +// presentCPUSurface copies the rectangles of the canvas into the surface +// acquireCPUSurface chose and makes it the layer's contents. It reports whether +// the surface is shown. +- (BOOL)presentCPUSurface:(int)index + pixels:(const unsigned char *)pixels + stride:(size_t)stride + rects:(const viva_cpu_rect *)rects + count:(size_t)count + trimAfter:(double)trimAfter { + if (!_cpuMode || index < 0 || index >= VIVA_CPU_SURFACES || _cpuSurfaces[index] == NULL || pixels == NULL || + stride < _cpuSurfaceWidth * 4) { + return NO; + } + IOSurfaceRef surface = _cpuSurfaces[index]; + if (count > 0) { + if (IOSurfaceLock(surface, 0, NULL) != kIOReturnSuccess) { + /* The surface's memory cannot be reached: it is filled whole the next + * time it is chosen, and the window keeps showing the last frame. */ + _cpuEmptied[index] = YES; + return NO; + } + unsigned char *base = IOSurfaceGetBaseAddress(surface); + size_t row = IOSurfaceGetBytesPerRow(surface); + for (size_t at = 0; at < count; at++) { + viva_cpu_rect rect = rects[at]; + if (rect.x >= _cpuSurfaceWidth || rect.y >= _cpuSurfaceHeight) { + continue; + } + size_t width = MIN(rect.width, _cpuSurfaceWidth - rect.x); + size_t height = MIN(rect.height, _cpuSurfaceHeight - rect.y); + for (size_t line = rect.y; line < rect.y + height; line++) { + memcpy(base + line * row + rect.x * 4, pixels + line * stride + rect.x * 4, width * 4); + } + } + IOSurfaceUnlock(surface, 0, NULL); + } + [CATransaction begin]; + [CATransaction setDisableActions:YES]; + if (index == _cpuFront) { + // The same object set again is not shown again. + _cpuLayer.contents = nil; + } + _cpuLayer.contents = (id)surface; + [CATransaction commit]; + int previous = _cpuFront; + _cpuFront = index; + _cpuShown[index] = ++_cpuSerial; + if (_cpuOccluded) { + [self makeCPUSurfacesPurgeableIncludingShown:YES]; + } else { + /* The next frame is written to the surface shown before this one. A + * third exists only because that one was still with the window server + * during a burst of frames (a live resize); once the server is done with + * it, it waits purgeable rather than resident, while a blinking caret + * keeps presenting and the idle timer below never runs out. */ + for (int other = 0; other < VIVA_CPU_SURFACES; other++) { + if (other != index && other != previous && _cpuSurfaces[other] != NULL && !_cpuVolatile[other] && + !IOSurfaceIsInUse(_cpuSurfaces[other])) { + IOSurfaceSetPurgeable(_cpuSurfaces[other], kIOSurfacePurgeableVolatile, NULL); + _cpuVolatile[other] = YES; + } + } + } + _cpuLastPresent = CACurrentMediaTime(); + _cpuTrimAfter = trimAfter; + if (!_cpuTrimArmed && trimAfter > 0) { + _cpuTrimArmed = YES; + [self performSelector:@selector(cpuTrimTimerFired) withObject:nil afterDelay:trimAfter inModes:@[NSRunLoopCommonModes]]; + } + return YES; +} + +// makeCPUSurfacesPurgeable lets the system take the memory of the surfaces off +// screen, and of the one shown with shown, when it needs it: a purgeable +// surface stops counting as the process's memory and may be emptied. +- (void)makeCPUSurfacesPurgeableIncludingShown:(BOOL)shown { + for (int index = 0; index < VIVA_CPU_SURFACES; index++) { + if (_cpuSurfaces[index] == NULL || _cpuVolatile[index] || (index == _cpuFront && !shown)) { + continue; + } + IOSurfaceSetPurgeable(_cpuSurfaces[index], kIOSurfacePurgeableVolatile, NULL); + _cpuVolatile[index] = YES; + } +} + +// cpuTrimTimerFired runs once after a burst of frames. It waits out the rest +// of the idle delay when frames came since it was armed, and otherwise makes +// the surfaces off screen purgeable and does nothing more until the next frame. +- (void)cpuTrimTimerFired { + _cpuTrimArmed = NO; + CFTimeInterval remaining = _cpuTrimAfter - (CACurrentMediaTime() - _cpuLastPresent); + if (remaining > 0) { + _cpuTrimArmed = YES; + [self performSelector:@selector(cpuTrimTimerFired) withObject:nil afterDelay:remaining inModes:@[NSRunLoopCommonModes]]; + return; + } + [self makeCPUSurfacesPurgeableIncludingShown:_cpuOccluded]; +} + +// cpuOcclusionChanged makes the surface shown purgeable too while nobody can +// see the window, and takes it back when the window shows again. If the system +// emptied it meanwhile, the Go side shows the canvas again. +- (void)cpuOcclusionChanged:(NSNotification *)notification { + if (!_cpuMode || notification.object != self.window) { + return; + } + BOOL occluded = (self.window.occlusionState & NSWindowOcclusionStateVisible) == 0; + if (occluded == _cpuOccluded) { + return; + } + _cpuOccluded = occluded; + if (occluded) { + [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(cpuTrimTimerFired) object:nil]; + _cpuTrimArmed = NO; + [self makeCPUSurfacesPurgeableIncludingShown:YES]; + return; + } + if (_cpuFront < 0 || _cpuSurfaces[_cpuFront] == NULL || !_cpuVolatile[_cpuFront]) { + return; + } + uint32_t old = kIOSurfacePurgeableNonVolatile; + IOSurfaceSetPurgeable(_cpuSurfaces[_cpuFront], kIOSurfacePurgeableNonVolatile, &old); + _cpuVolatile[_cpuFront] = NO; + if (old == kIOSurfacePurgeableEmpty) { + _cpuEmptied[_cpuFront] = YES; + if (_callbackHandle != 0) { + vivaCPUSurfaceLost(_callbackHandle, self); + } + } +} + +- (BOOL)cpuGeometryWidth:(double *)width height:(double *)height scale:(double *)scale { + if (!_cpuMode) { + return NO; + } + NSScreen *screen = self.window.screen ?: NSScreen.mainScreen; + NSSize size = self.bounds.size; + if (width != NULL) { + *width = size.width; + } + if (height != NULL) { + *height = size.height; + } + if (scale != NULL) { + *scale = screen != nil ? MAX(screen.backingScaleFactor, 1.0) : 1.0; + } + return YES; +} + +- (int)textInputBitmapAtScale:(CGFloat)scale + pixels:(unsigned char **)pixels + width:(size_t *)width + height:(size_t *)height { + if (!_textInputEnabled) { + return 1; + } + return viva_text_input_bitmap( + scale, [self displayedText], _textFontSize, _textFontWeight, _textColor, + _textFrame.size, _selectedRange, _hasMarkedText, _markedRange, _caretVisible, + _textTerminal, _textHideNativeOverlays, _textMonoFace, _textCellWidth, _textBaseline, + _textAlignment, pixels, width, height); +} + +- (BOOL)textInputFrameX:(double *)x y:(double *)y width:(double *)width height:(double *)height layer:(int *)layer { + if (!_textInputEnabled) { + return NO; + } + if (x != NULL) { + *x = _textFrame.origin.x; + } + if (y != NULL) { + *y = _textFrame.origin.y; + } + if (width != NULL) { + *width = _textFrame.size.width; + } + if (height != NULL) { + *height = _textFrame.size.height; + } + if (layer != NULL) { + *layer = _textLayer; + } + return YES; +} + - (void)render { + if (_cpuMode) { + // The CPU renderer's canvas lives on the Go side; a native editor update + // asks it to draw the editor's picture again. + if (_callbackHandle != 0) { + vivaTextOverlayChanged(_callbackHandle, self); + } + return; + } [self renderWaitingForSchedule:NO]; } - (void)renderWaitingForSchedule:(BOOL)wait { + if (_cpuMode) { + [self render]; + return; + } @autoreleasepool { if (_metalLayer.drawableSize.width < 1 || _metalLayer.drawableSize.height < 1) { return; } + if (!wait && _frameInFlight) { + // The frame handed over before this one is still on its way to the + // screen, so both of the layer's drawables are in flight. Asking for + // another would block this thread inside -nextDrawable until the + // window server presents one, which takes up to a second: longer + // than the animation that asks for the frame in the first place. + // Draw after that frame is presented instead + // (-trackPresentedDrawable:). + if (viva_elapsed_milliseconds(_frameInFlightSince, mach_continuous_time()) < VIVA_FRAME_IN_FLIGHT_LIMIT_MS) { + _redrawAfterPresent = YES; + return; + } + // A frame that has not been presented for seconds was dropped: the + // graphics device failed, or the window server threw it away. Draw + // again rather than hold every later frame back; the wait the guard + // exists to avoid then costs one frame, once. + _frameInFlight = NO; + } BOOL probe = viva_input_probe_enabled(); uint64_t waitStart = probe ? mach_continuous_time() : 0; @@ -2481,6 +3045,18 @@ - (void)renderWaitingForSchedule:(BOOL)wait { }]; } + if (!wait) { + // The frame is about to be on its way to the screen: the next one + // waits for this one to be presented instead of taking the layer's + // last drawable. The handler is registered before the command + // buffer is committed; a frame presented before its handler was + // registered would never clear the mark and the window would stop + // drawing. + _frameInFlight = YES; + _frameInFlightSince = mach_continuous_time(); + [self trackPresentedDrawable:drawable]; + } + id commandBuffer = [_renderer renderToDrawable:drawable viewport:self.bounds.size inputTexture:_textTexture @@ -2511,6 +3087,28 @@ - (void)renderWaitingForSchedule:(BOOL)wait { } } +/* trackPresentedDrawable clears the in-flight mark once the frame that took the + * drawable is on the screen, and draws the frame that was held back while it was + * not. */ +- (void)trackPresentedDrawable:(id)drawable { + [drawable addPresentedHandler:^(id presented) { + (void)presented; + dispatch_async(dispatch_get_main_queue(), ^{ + if (_callbackHandle == 0) { + return; + } + _frameInFlight = NO; + if (_redrawAfterPresent) { + _redrawAfterPresent = NO; + // setNeedsDisplay is not honored without drawRect, so drawing + // here is what makes the frame that was held back reach the + // screen. + [self render]; + } + }); + }]; +} + /* recoverResources makes the window's Metal resources again after the device * stopped serving them: the driver was reset, the GPU hung, an external GPU was * unplugged or switched, or an allocation failed under pressure. What the @@ -3736,6 +4334,7 @@ - (BOOL)isPanel; - (BOOL)isHidden; - (BOOL)isMiniaturized; - (void)requestRedraw:(uintptr_t)callbackHandle; +- (void)reportPendingResize:(uintptr_t)callbackHandle; - (BOOL)isRunning; - (int)nativeStatus; @end @@ -4868,6 +5467,17 @@ - (void)requestRedraw:(uintptr_t)callbackHandle { vivaRedrawRequested(_callbackHandle, _window.contentView); } +/* reportPendingResize relays the size a window manager last left the window at, + * outside the layout pass that changed it. */ +- (void)reportPendingResize:(uintptr_t)callbackHandle { + if (callbackHandle == 0 || callbackHandle != _callbackHandle || _window == nil) { + return; + } + if ([_window.contentView isKindOfClass:[VivaMetalView class]]) { + [(VivaMetalView *)_window.contentView reportPendingResize]; + } +} + - (BOOL)isRunning { return _running; } @@ -5001,6 +5611,7 @@ int viva_application_last_status(void) { return viva_application_status; } + void *viva_application_open_window(viva_window_config config) { @autoreleasepool { if (viva_application_windows == nil) { @@ -5012,9 +5623,22 @@ int viva_application_last_status(void) { id rectanglePipeline = nil; id textPipeline = nil; id rectangleBuffer = nil; - int resourceStatus = viva_make_scene_resources( - &config, &device, &commandQueue, &rectanglePipeline, &textPipeline, &rectangleBuffer); - if (resourceStatus != 0) { + /* VIVA_SOFTWARE_RENDERING=1 asks for the CPU renderer on a machine with a + * device too, as it does on Linux: the window opens without Metal. */ + const char *rendering = getenv("VIVA_SOFTWARE_RENDERING"); + int resourceStatus = rendering != NULL && strcmp(rendering, "1") == 0 + ? 1 + : viva_make_scene_resources(&config, &device, &commandQueue, &rectanglePipeline, &textPipeline, &rectangleBuffer); + if (resourceStatus == 1) { + /* No Metal device: the window is drawn by the CPU renderer the Go + * side runs, and the view presents its canvas (see VivaMetalView's + * _cpuMode). Every other failure still ends the window. */ + device = nil; + commandQueue = nil; + rectanglePipeline = nil; + textPipeline = nil; + rectangleBuffer = nil; + } else if (resourceStatus != 0) { viva_application_status = resourceStatus; return NULL; } @@ -5104,6 +5728,15 @@ - (NSView *)webHostView { return [viva_find_window(token) webHostView]; } +void viva_view_report_size(void *view) { + if (view == NULL) { + return; + } + @autoreleasepool { + [(VivaMetalView *)view reportSize]; + } +} + static void viva_collect_closed_windows(void) { for (NSInteger index = (NSInteger)viva_application_windows.count - 1; index >= 0; index--) { VivaAppDelegate *delegate = [viva_application_windows objectAtIndex:(NSUInteger)index]; @@ -5127,7 +5760,12 @@ int viva_application_run(void) { untilDate:[NSDate distantFuture] inMode:NSDefaultRunLoopMode dequeue:YES]; - if (event.type == NSEventTypeApplicationDefined && event.subtype == VIVA_REDRAW_EVENT) { + if (event.type == NSEventTypeApplicationDefined && event.subtype == VIVA_RESIZE_EVENT) { + NSUInteger count = viva_application_windows.count; + for (NSUInteger index = 0; index < count; index++) { + [[viva_application_windows objectAtIndex:index] reportPendingResize:(uintptr_t)event.data1]; + } + } else if (event.type == NSEventTypeApplicationDefined && event.subtype == VIVA_REDRAW_EVENT) { NSUInteger count = viva_application_windows.count; for (NSUInteger index = 0; index < count; index++) { [[viva_application_windows objectAtIndex:index] requestRedraw:(uintptr_t)event.data1]; @@ -5547,6 +6185,122 @@ void viva_view_render_sync(void *view) { } } +int viva_view_cpu_acquire(void *view, size_t width, size_t height, int *fresh) { + if (view == NULL || fresh == NULL) { + return -1; + } + @autoreleasepool { + return [(VivaMetalView *)view acquireCPUSurfaceWidth:width height:height fresh:fresh]; + } +} + +int viva_view_cpu_present( + void *view, + int index, + const unsigned char *pixels, + size_t stride, + const viva_cpu_rect *rects, + size_t count, + double trim_after +) { + if (view == NULL || pixels == NULL || (rects == NULL && count > 0)) { + return 1; + } + @autoreleasepool { + return [(VivaMetalView *)view presentCPUSurface:index pixels:pixels stride:stride rects:rects count:count trimAfter:trim_after] ? 0 : 1; + } +} + +int viva_view_cpu_geometry(void *view, double *width, double *height, double *scale) { + if (view == NULL) { + return 0; + } + @autoreleasepool { + return [(VivaMetalView *)view cpuGeometryWidth:width height:height scale:scale] ? 1 : 0; + } +} + +int viva_text_input_bitmap_c( + double scale, + const unsigned char *utf8, + size_t utf8_length, + double font_size, + double font_weight, + double red, + double green, + double blue, + double alpha, + double width, + double height, + size_t selected_start, + size_t selected_length, + size_t marked_start, + size_t marked_length, + int has_marked_text, + int caret_visible, + int terminal, + int hide_native_overlays, + int mono_face, + double cell_width, + double cell_baseline, + int alignment, + unsigned char **pixels, + size_t *pixel_width, + size_t *pixel_height +) { + if (utf8 == NULL && utf8_length > 0) { + return 1; + } + @autoreleasepool { + NSString *shown = [[NSString alloc] initWithBytes:utf8 + length:utf8_length + encoding:NSUTF8StringEncoding]; + if (shown == nil) { + return 2; + } + NSColor *color = [NSColor colorWithSRGBRed:red green:green blue:blue alpha:alpha]; + int status = viva_text_input_bitmap( + scale, shown, font_size, font_weight, color, CGSizeMake(width, height), + NSMakeRange(selected_start, selected_length), has_marked_text != 0, + NSMakeRange(marked_start, marked_length), caret_visible != 0, + terminal != 0, hide_native_overlays != 0, mono_face, cell_width, cell_baseline, + alignment, pixels, pixel_width, pixel_height); + [shown release]; + return status; + } +} + +int viva_view_text_input_bitmap( + void *view, + double scale, + unsigned char **pixels, + size_t *width, + size_t *height +) { + if (view == NULL) { + return 1; + } + @autoreleasepool { + return [(VivaMetalView *)view textInputBitmapAtScale:scale pixels:pixels width:width height:height]; + } +} + +int viva_view_text_input_frame( + void *view, + double *x, + double *y, + double *width, + double *height, + int *layer +) { + if (view == NULL) { + return 0; + } + @autoreleasepool { + return [(VivaMetalView *)view textInputFrameX:x y:y width:width height:height layer:layer] ? 1 : 0; + } +} + // VivaTextMenuTarget receives the row chosen from a text menu. @interface VivaTextMenuTarget : NSObject @property(nonatomic) int chosen; diff --git a/internal/platform/darwin/offscreen.go b/internal/platform/darwin/offscreen.go index 864595eaf..4db9901c6 100644 --- a/internal/platform/darwin/offscreen.go +++ b/internal/platform/darwin/offscreen.go @@ -13,6 +13,7 @@ import ( "fmt" "unsafe" + "github.com/vivaui/viva/internal/platform" "github.com/vivaui/viva/internal/render" ) @@ -41,7 +42,7 @@ func NewOffscreen(width, height int, scale float64, clear Color) (*Offscreen, er C.double(clear.Red), C.double(clear.Green), C.double(clear.Blue), C.double(clear.Alpha), ) if handle == nil { - return nil, fmt.Errorf("darwin: no Metal device for offscreen rendering") + return nil, fmt.Errorf("darwin: no Metal device for offscreen rendering: %w", platform.ErrNoGraphics) } return &Offscreen{handle: handle, width: width, height: height, scale: scale}, nil } diff --git a/internal/platform/darwin/offscreen_cpu.go b/internal/platform/darwin/offscreen_cpu.go new file mode 100644 index 000000000..ed970366f --- /dev/null +++ b/internal/platform/darwin/offscreen_cpu.go @@ -0,0 +1,165 @@ +//go:build darwin && vivahead && !ios + +package darwin + +/* +#include +#include "native.h" +*/ +import "C" + +import ( + "fmt" + "math" + "unicode/utf16" + "unsafe" + + "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/internal/raster" + "github.com/vivaui/viva/internal/render" + "github.com/vivaui/viva/internal/scene" + "github.com/vivaui/viva/internal/softscene" + "github.com/vivaui/viva/text" +) + +// CPUOffscreen is Offscreen without a Metal device: the scene is drawn by the +// CPU rasterizer (internal/raster) and the glyphs are CoreText's, so a +// screenshot can be taken on a machine with no graphics driver, and the CPU +// pipelines can be exercised on any machine with VIVA_SOFTWARE_RENDERING=1. It +// is not safe for concurrent use. +type CPUOffscreen struct { + scene *softscene.Scene + scale float32 +} + +// NewCPUOffscreen is NewOffscreen for the CPU: a width x height scene in +// logical pixels, drawn at scale device pixels per logical pixel and cleared to +// clear before each render. +func NewCPUOffscreen(width, height int, scale float64, clear Color) (*CPUOffscreen, error) { + if width < 1 || height < 1 || math.IsNaN(scale) || scale < 1 || scale > maxOffscreenScale || + width > platform.MaxOffscreenSize || height > platform.MaxOffscreenSize { + return nil, fmt.Errorf("darwin: invalid offscreen size %dx%d at %gx", width, height, scale) + } + deviceWidth := int(math.Ceil(float64(width) * scale)) + deviceHeight := int(math.Ceil(float64(height) * scale)) + if deviceWidth > platform.MaxOffscreenSize || deviceHeight > platform.MaxOffscreenSize { + return nil, fmt.Errorf("darwin: offscreen size %dx%d at %gx is beyond %d device pixels", width, height, scale, platform.MaxOffscreenSize) + } + sc, err := softscene.New(coreTextRasterizer{}, deviceWidth, deviceHeight, float32(scale), + scene.Color{Red: float32(clear.Red), Green: float32(clear.Green), Blue: float32(clear.Blue), Alpha: float32(clear.Alpha)}, + nil, nil) + if err != nil { + return nil, err + } + return &CPUOffscreen{scene: sc, scale: float32(scale)}, nil +} + +// maxOffscreenScale matches the Metal offscreen renderer's limit. +const maxOffscreenScale = 4 + +// Set replaces the scene: rectangle and triangle instances in paint order, +// text labels, and the native text editor's picture (nil for none). +func (offscreen *CPUOffscreen) Set(rectangles []render.Rectangle, labels []TextLabel, input *TextInput) error { + if err := offscreen.scene.Set(rectangles, labels); err != nil { + return err + } + if input == nil { + offscreen.scene.SetOverlay(raster.Label{}, false) + return nil + } + if err := validateTextInput(input); err != nil { + return err + } + label, ok, err := offscreen.inputOverlay(input) + if err != nil { + return err + } + offscreen.scene.SetOverlay(label, ok) + return nil +} + +// inputOverlay asks CoreText for the editor's picture, as the window's view +// does for its own editor. +func (offscreen *CPUOffscreen) inputOverlay(input *TextInput) (raster.Label, bool, error) { + value := input.State.Value + if input.Secure { + value = repeatBullets(value) + } + var bytes *C.uchar + data := []byte(value) + if len(data) > 0 { + bytes = (*C.uchar)(unsafe.Pointer(&data[0])) + } + start, end := text.UTF16Offset(value, input.State.Selection.Start), text.UTF16Offset(value, input.State.Selection.End) + markedStart, markedEnd := text.UTF16Offset(value, input.State.Composition.Start), text.UTF16Offset(value, input.State.Composition.End) + alignment := int(input.Alignment) + if input.Placed || input.Terminal { + // A placed field draws its own caret and the terminal its own grid. + alignment = 0 + } + var pixels *C.uchar + var pixelWidth, pixelHeight C.size_t + status := C.viva_text_input_bitmap_c( + C.double(offscreen.scale), bytes, C.size_t(len(data)), + C.double(input.FontSize), C.double(input.Weight), + C.double(input.Color.Red), C.double(input.Color.Green), C.double(input.Color.Blue), C.double(input.Color.Alpha), + C.double(input.Width), C.double(input.Height), + C.size_t(start), C.size_t(end-start), C.size_t(markedStart), C.size_t(markedEnd-markedStart), + C.int(boolInt(input.State.Composing)), C.int(1), C.int(boolInt(input.Terminal)), + C.int(boolInt(input.HideNativeOverlays)), C.int(input.MonoFace), + C.double(input.CellWidth), C.double(input.Baseline), C.int(alignment), + &pixels, &pixelWidth, &pixelHeight, + ) + if status != 0 || pixels == nil { + if status == 0 || status == 2 { + return raster.Label{}, false, nil + } + return raster.Label{}, false, fmt.Errorf("darwin: offscreen editor rasterization failed with status %d", status) + } + defer C.free(unsafe.Pointer(pixels)) + if pixelWidth < 1 || pixelHeight < 1 || uint64(pixelWidth)*uint64(pixelHeight) > uint64(math.MaxInt)/4 { + return raster.Label{}, false, nil + } + size := int(pixelWidth) * int(pixelHeight) * 4 + picture := make([]byte, size) + copy(picture, unsafe.Slice((*byte)(unsafe.Pointer(pixels)), size)) + return raster.Label{ + Pix: picture, + Stride: int(pixelWidth) * 4, + Width: int(pixelWidth), + Height: int(pixelHeight), + X: platform.DevicePosition(input.X, 0, offscreen.scale), + Y: platform.DevicePosition(input.Y, 0, offscreen.scale), + Layer: input.Layer, + ShapesBefore: math.MaxUint32, + }, true, nil +} + +// repeatBullets is the masked form of a password field's text: one bullet per +// UTF-16 unit, so every range still lines up with the model. +func repeatBullets(value string) string { + units := utf16.Encode([]rune(value)) + bullets := make([]rune, len(units)) + for index := range bullets { + bullets[index] = '•' + } + return string(bullets) +} + +// Render draws the scene and returns its pixels as premultiplied BGRA, top row +// first, with their dimensions in device pixels. +func (offscreen *CPUOffscreen) Render() (pixels []byte, width, height int, err error) { + offscreen.scene.Paint() + canvas := offscreen.scene.Canvas + pixels = make([]byte, len(canvas.Pix)) + copy(pixels, canvas.Pix) + return pixels, canvas.Width, canvas.Height, nil +} + +// Close releases the pictures. +func (offscreen *CPUOffscreen) Close() { + if offscreen.scene != nil { + offscreen.scene.Close() + offscreen.scene = nil + } +} diff --git a/internal/platform/darwin/offscreen_cpu_darwin_test.go b/internal/platform/darwin/offscreen_cpu_darwin_test.go new file mode 100644 index 000000000..028ac1434 --- /dev/null +++ b/internal/platform/darwin/offscreen_cpu_darwin_test.go @@ -0,0 +1,190 @@ +//go:build darwin && vivahead && !ios + +package darwin + +import ( + "testing" + + "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/internal/render" + "github.com/vivaui/viva/internal/scene" +) + +func cpuTestScene() ([]render.Rectangle, []platform.TextLabel) { + rectangles := []render.Rectangle{{ + Bounds: scene.Rect{X: 0, Y: 0, Width: 60, Height: 30}, + Color: scene.Color{Blue: 1, Alpha: 1}, + Layer: 0, + }} + labels := []platform.TextLabel{{ + Value: "Hi", X: 4, Y: 6, Width: 40, Height: 18, FontSize: 13, + Color: platform.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1}, Layer: 1, + }} + return rectangles, labels +} + +// A machine with no Metal device renders a screenshot on the CPU: the shapes +// are the rasterizer's and the glyphs are CoreText's. +func TestCPUOffscreenRendersShapesAndText(t *testing.T) { + offscreen, err := NewCPUOffscreen(60, 30, 1, Color{Alpha: 1}) + if err != nil { + t.Fatal(err) + } + defer offscreen.Close() + rectangles, labels := cpuTestScene() + if err := offscreen.Set(rectangles, labels, nil); err != nil { + t.Fatal(err) + } + pixels, width, height, err := offscreen.Render() + if err != nil { + t.Fatal(err) + } + if width != 60 || height != 30 { + t.Fatalf("render size %dx%d, want 60x30", width, height) + } + // A corner of the page outside the label is the rectangle's blue. + corner := pixels[(2*width+50)*4:] + if corner[0] != 255 || corner[2] != 0 { + t.Fatalf("page pixel = %v, want the blue rectangle", corner[:4]) + } + // The label's line has white ink over the page: some pixel in its box is + // brighter than the page and the clear color. + ink := 0 + for y := 6; y < 24; y++ { + for x := 4; x < 44; x++ { + offset := (y*width + x) * 4 + if pixels[offset] > 40 || pixels[offset+1] > 40 || pixels[offset+2] > 200 { + ink++ + } + } + } + if ink == 0 { + t.Fatal("the label left no ink on the page") + } +} + +// The native editor's picture is part of the screenshot: with an editor shown, +// its box differs from the same scene without one. +func TestCPUOffscreenDrawsTheEditorOverlay(t *testing.T) { + render := func(input *TextInput) []byte { + t.Helper() + offscreen, err := NewCPUOffscreen(60, 30, 1, Color{Alpha: 1}) + if err != nil { + t.Fatal(err) + } + defer offscreen.Close() + rectangles, labels := cpuTestScene() + if err := offscreen.Set(rectangles, labels, input); err != nil { + t.Fatal(err) + } + pixels, _, _, err := offscreen.Render() + if err != nil { + t.Fatal(err) + } + return pixels + } + plain := render(nil) + editor := &TextInput{ + X: 4, Y: 2, Width: 40, Height: 18, FontSize: 13, + Color: Color{Red: 1, Green: 1, Blue: 1, Alpha: 1}, + State: TextState{Value: "M"}, + OnEvent: func(platform.TextEvent) (platform.TextState, error) { + return platform.TextState{Value: "M"}, nil + }, + } + withInput := render(editor) + differing := 0 + for offset := 0; offset+3 < len(withInput); offset += 4 { + if withInput[offset] != plain[offset] || withInput[offset+1] != plain[offset+1] || withInput[offset+2] != plain[offset+2] || withInput[offset+3] != plain[offset+3] { + differing++ + } + } + if differing == 0 { + t.Fatal("the editor's picture changed no pixel") + } +} + +func cpuBenchmarkScene() ([]render.Rectangle, []platform.TextLabel) { + rectangles := make([]render.Rectangle, 0, 200) + for index := 0; index < 200; index++ { + rectangles = append(rectangles, render.Rectangle{ + Bounds: scene.Rect{X: float32(index % 20 * 50), Y: float32(index / 20 * 70), Width: 40, Height: 30}, + Color: scene.Color{Red: 0.2, Green: 0.4, Blue: 0.6, Alpha: 1}, + Layer: uint16(index % 3), + }) + } + labels := make([]platform.TextLabel, 0, 20) + for index := 0; index < 20; index++ { + labels = append(labels, platform.TextLabel{ + Value: "Open host 192.168.1.20", X: 8, Y: float32(index*30 + 6), Width: 300, Height: 18, + FontSize: 13, Color: platform.Color{Alpha: 1}, Layer: 3, + }) + } + return rectangles, labels +} + +// cpuTerminalScene is a terminal-shaped page: one dark rectangle and forty +// fixed-pitch lines, the text a terminal repaint carries. +func cpuTerminalScene() ([]render.Rectangle, []platform.TextLabel) { + rectangles := []render.Rectangle{{ + Bounds: scene.Rect{Width: 1000, Height: 700}, + Color: scene.Color{Red: 0.05, Green: 0.05, Blue: 0.08, Alpha: 1}, + }} + labels := make([]platform.TextLabel, 0, 40) + line := "cogagent@host ~ % seq 1 30000 0123456789 abcdefghijklmnopqrstuvwxyz" + for index := 0; index < 40; index++ { + labels = append(labels, platform.TextLabel{ + Value: line, X: 8, Y: float32(index * 17), Width: 980, Height: 16, + FontSize: 12, Mono: true, CellWidth: 7.2, + Color: platform.Color{Red: 0.85, Green: 0.85, Blue: 0.85, Alpha: 1}, Layer: 1, + }) + } + return rectangles, labels +} + +// A steady frame of the CPU offscreen renderer: the same scene again, as a +// screenshot loop draws it. +func BenchmarkCPUOffscreenSteadyFrame(b *testing.B) { + offscreen, err := NewCPUOffscreen(1000, 700, 1, Color{Alpha: 1}) + if err != nil { + b.Fatal(err) + } + defer offscreen.Close() + rectangles, labels := cpuBenchmarkScene() + if err := offscreen.Set(rectangles, labels, nil); err != nil { + b.Fatal(err) + } + b.ReportAllocs() + b.ResetTimer() + for ben := 0; ben < b.N; ben++ { + if err := offscreen.Set(rectangles, labels, nil); err != nil { + b.Fatal(err) + } + if _, _, _, err := offscreen.Render(); err != nil { + b.Fatal(err) + } + } +} + +// A terminal-shaped frame of the CPU offscreen renderer. +func BenchmarkCPUOffscreenTerminalFrame(b *testing.B) { + offscreen, err := NewCPUOffscreen(1000, 700, 1, Color{Alpha: 1}) + if err != nil { + b.Fatal(err) + } + defer offscreen.Close() + rectangles, labels := cpuTerminalScene() + if err := offscreen.Set(rectangles, labels, nil); err != nil { + b.Fatal(err) + } + b.ReportAllocs() + b.ResetTimer() + for ben := 0; ben < b.N; ben++ { + if err := offscreen.Set(rectangles, labels, nil); err != nil { + b.Fatal(err) + } + if _, _, _, err := offscreen.Render(); err != nil { + b.Fatal(err) + } + } +} diff --git a/internal/platform/darwin/platform.go b/internal/platform/darwin/platform.go index 6894a4c35..18605d32c 100644 --- a/internal/platform/darwin/platform.go +++ b/internal/platform/darwin/platform.go @@ -4,7 +4,7 @@ package darwin /* -#cgo darwin,!ios LDFLAGS: -framework Cocoa -framework CoreGraphics -framework CoreText -framework Metal -framework QuartzCore +#cgo darwin,!ios LDFLAGS: -framework Cocoa -framework CoreGraphics -framework CoreText -framework IOSurface -framework Metal -framework QuartzCore #cgo ios LDFLAGS: -framework Foundation -framework UIKit -framework CoreGraphics -framework CoreText -framework Metal -framework QuartzCore #include #include "native.h" @@ -14,6 +14,7 @@ import "C" import ( "fmt" + "math" "runtime/cgo" "sync" "sync/atomic" @@ -196,6 +197,8 @@ type runState struct { // devices decides how many times this window may make its Metal resources // again when the renderer loses them. devices platform.DeviceRecovery + // cpu draws the window when the machine has no Metal device (see cpu.go). + cpu *cpuWindow // rebuildNextFrame says the window's instance buffers are empty because its // resources were made again, so the next frame sends the whole scene. rebuildNextFrame bool @@ -521,6 +524,34 @@ func (application *nativeApplication) OpenWindow(config Config) (platform.Window } } state.window = &nativeWindow{token: token, mode: config.WindowMode} + if view := C.viva_application_window_view(token); view != nil { + var logicalWidth, logicalHeight, viewScale C.double + if C.viva_view_cpu_geometry(view, &logicalWidth, &logicalHeight, &viewScale) == 1 { + // The window has no Metal device and is drawn by the CPU renderer. + scale := float32(viewScale) + deviceWidth := int(math.Ceil(float64(logicalWidth) * float64(viewScale))) + deviceHeight := int(math.Ceil(float64(logicalHeight) * float64(viewScale))) + cpu, err := newCPUWindow(view, config.ClearColor, config.Rectangles, config.TextLabels, scale, deviceWidth, deviceHeight) + if err == nil { + err = cpu.refreshOverlay(view, scale) + } + if err == nil { + err = cpu.present(view) + } + if err != nil { + cpu.close() + C.viva_application_close_window(token) + state.closed = true + return nil, err + } + state.cpu = cpu + } + // The application painted its first frame before this window existed, + // when the display scale was unknown. Report the size and scale the + // window really has now, with the CPU renderer ready if this window uses + // one, so the repaint lands on the display's pixel grid. + C.viva_view_report_size(view) + } return state.window, nil } @@ -610,6 +641,7 @@ func makeNativeAccessibility(nodes []AccessibilityNode) (unsafe.Pointer, []unsaf selection_start: C.int(selectionStart), selection_end: C.int(selectionEnd), text_length: C.int(textLength), + sort_direction: C.int(node.Sort), } } // The native side copies labels into NSString during the update call, so diff --git a/internal/platform/darwin/resize_report_darwin_test.go b/internal/platform/darwin/resize_report_darwin_test.go new file mode 100644 index 000000000..4a91aaaa2 --- /dev/null +++ b/internal/platform/darwin/resize_report_darwin_test.go @@ -0,0 +1,34 @@ +//go:build !ios + +package darwin + +import ( + "context" + "os/exec" + "path/filepath" + "testing" + "time" +) + +// A window manager animates a geometry change in many steps. Relaying every step +// to the application made it lay out and draw for sizes the window never stops +// at, and each draw took a drawable from the layer; a blocked drawable then held +// the main thread. The report belongs to the run loop, once, and only a live +// resize (whose frame has to land in the transaction that changes the bounds) is +// reported inside the layout pass. +func TestResizeReportsOncePerRunLoopTurn(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + executable := filepath.Join(t.TempDir(), "resize-report") + command := exec.CommandContext(ctx, "xcrun", "clang", "-fno-objc-arc", "-Werror", + "-Wno-deprecated-declarations", "testdata/resize_report.m", "-o", executable, + "-framework", "Cocoa", "-framework", "CoreText", "-framework", "Metal", "-framework", "QuartzCore", "-framework", "IOSurface") + if output, err := command.CombinedOutput(); err != nil { + t.Fatalf("compile native resize report test: %v\n%s", err, output) + } + if output, err := exec.CommandContext(ctx, executable).CombinedOutput(); err != nil { + t.Fatalf("native resize report: %v\n%s", err, output) + } else { + t.Logf("%s", output) + } +} diff --git a/internal/platform/darwin/resize_scale_darwin_test.go b/internal/platform/darwin/resize_scale_darwin_test.go new file mode 100644 index 000000000..79f6c63a3 --- /dev/null +++ b/internal/platform/darwin/resize_scale_darwin_test.go @@ -0,0 +1,34 @@ +//go:build !ios + +package darwin + +import ( + "context" + "os/exec" + "path/filepath" + "testing" + "time" +) + +// A window reports its content size and display scale to the application: once +// when it opens, before its first draw, and again whenever the size or the +// display scale changes. The application rounds cells, icons and strokes to +// whole device pixels of that scale; without it a terminal cell is a fraction of +// a device pixel wide and the background under a cell-filling glyph rounds to a +// different pixel than the glyph (#2032). +func TestWindowReportsItsDisplayScale(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + executable := filepath.Join(t.TempDir(), "resize-scale") + command := exec.CommandContext(ctx, "xcrun", "clang", "-fno-objc-arc", "-Werror", + "-Wno-deprecated-declarations", "testdata/resize_scale.m", "-o", executable, + "-framework", "Cocoa", "-framework", "CoreText", "-framework", "Metal", "-framework", "QuartzCore") + if output, err := command.CombinedOutput(); err != nil { + t.Fatalf("compile native resize scale test: %v\n%s", err, output) + } + if output, err := exec.CommandContext(ctx, executable).CombinedOutput(); err != nil { + t.Fatalf("native resize scale: %v\n%s", err, output) + } else { + t.Logf("%s", output) + } +} diff --git a/internal/platform/darwin/system_darwin.go b/internal/platform/darwin/system_darwin.go index 3655bc32e..eefc36508 100644 --- a/internal/platform/darwin/system_darwin.go +++ b/internal/platform/darwin/system_darwin.go @@ -267,40 +267,43 @@ func OpenFiles(options OpenFileOptions) ([]string, bool, error) { return nil, false, systemError("open files", nativeError) } defer C.viva_system_free_string_array(result) + return openPanelPaths(result), false, nil +} + +func openPanelPaths(result C.viva_system_string_array) []string { items := unsafe.Slice((**C.char)(unsafe.Pointer(result.items)), int(result.count)) paths := make([]string, len(items)) for index, item := range items { paths[index] = C.GoString(item) } - return paths, false, nil + return paths } -func OpenDirectory(options OpenDirectoryOptions) (string, bool, error) { +func OpenDirectories(options OpenDirectoryOptions, multiple bool) ([]string, bool, error) { title, err := systemCString("open directory title", options.Title) if err != nil { - return "", false, err + return nil, false, err } defer C.free(unsafe.Pointer(title)) directory, err := systemCString("initial directory", options.InitialDirectory) if err != nil { - return "", false, err + return nil, false, err } defer C.free(unsafe.Pointer(directory)) var result C.viva_system_string_array var nativeError *C.char - status := C.viva_system_open_files(title, directory, nil, 0, 0, 1, &result, &nativeError) + status := C.viva_system_open_files(title, directory, nil, 0, C.int(systemBoolInt(multiple)), 1, &result, &nativeError) if status == 1 { - return "", true, nil + return nil, true, nil } if status != 0 { - return "", false, systemError("open directory", nativeError) + return nil, false, systemError("open directory", nativeError) } defer C.viva_system_free_string_array(result) - if result.count != 1 { - return "", false, fmt.Errorf("darwin: open directory returned %d paths", result.count) + if !multiple && result.count != 1 { + return nil, false, fmt.Errorf("darwin: open directory returned %d paths", result.count) } - items := unsafe.Slice((**C.char)(unsafe.Pointer(result.items)), 1) - return C.GoString(items[0]), false, nil + return openPanelPaths(result), false, nil } func SaveFile(options SaveFileOptions) (string, bool, error) { diff --git a/internal/platform/darwin/testdata/accessibility_frame.m b/internal/platform/darwin/testdata/accessibility_frame.m new file mode 100644 index 000000000..235391bd9 --- /dev/null +++ b/internal/platform/darwin/testdata/accessibility_frame.m @@ -0,0 +1,135 @@ +#include "../core_text.m" +#include "../core_render.m" +#include "../watermark_darwin.m" +#include "../native.m" +#include "../main_menu_darwin.m" +#include + +// The callbacks native.m reports to Go; this test listens to none of them. +void vivaTextOverlayChanged(uintptr_t callback_handle, void *view) {} +void vivaPointerEvent(uintptr_t handle, void *view, int kind, int button, int modifiers, int clickCount, double x, double y, double screenX, double screenY) {} +void vivaViewResized(uintptr_t handle, void *view, double width, double height, double scale, int live) {} +void vivaRedrawRequested(uintptr_t handle, void *view) {} +void vivaKeyEvent(uintptr_t handle, void *view, int key, int modifiers, int repeat, const unsigned char *utf8, size_t utf8Length) {} +void vivaRawKeyEvent(uintptr_t handle, void *view, int key, int modifiers, int flags, unsigned int code, const unsigned char *utf8, size_t utf8Length, const unsigned char *typed, size_t typedLength) {} +void vivaWindowActivated(uintptr_t handle) {} +void vivaWindowDeactivated(uintptr_t handle, void *view) {} +void vivaFocusLost(uintptr_t handle, void *view) {} +int vivaTerminalCells(uint32_t character) { return 1; } +int vivaAccessibilityAction(uintptr_t handle, void *view, uint64_t node, int action, double number, const unsigned char *utf8, size_t utf8Length, int start, int end) { return 0; } +viva_text_line *vivaShapedLine(const unsigned char *utf8, size_t length, double size, double weight) { return viva_text_line_create(utf8, length, size, weight); } +viva_text_line *vivaShapedLineStyle(const unsigned char *utf8, size_t length, double size, double weight, int italic) { return viva_text_line_create_style(utf8, length, size, weight, italic); } +int vivaShortcutEvent(uintptr_t handle, void *view, int key, int modifiers, int repeat, const unsigned char *utf8, size_t utf8Length) { return 0; } +void vivaOpenURL(const char *url) {} +void vivaOpenFile(const char *path) {} +int vivaApplicationQuitRequested(void) { return 0; } +int vivaApplicationReopenRequested(void) { return 0; } +int vivaFileDropEvent(uintptr_t handle, void *view, int phase, double x, double y, const char *paths, size_t length) { return 0; } +void vivaScrollEvent(uintptr_t handle, void *view, double deltaX, double deltaY, double x, double y, int modifiers, int precise) {} +void vivaCloseRequested(uintptr_t handle, void *view) {} +void vivaWindowClosed(uintptr_t handle) {} +void vivaFrameChanged(uintptr_t handle, void *view, double x, double y, double width, double height) {} +void vivaWindowMinimized(uintptr_t handle, void *view, int minimized) {} +void vivaWindowOccluded(uintptr_t handle, void *view, int visible) {} +void vivaWindowFullscreen(uintptr_t handle, void *view, int fullscreen) {} +int vivaWindowReopenRequested(uintptr_t handle, void *view) { return 0; } +int vivaPressAt(uintptr_t handle, double x, double y) { return 0; } +void vivaTextInput(uintptr_t handle, void *view, int kind, const unsigned char *utf8, + size_t length, int64_t start, int64_t selectedLength, + int64_t replacementStart, int64_t replacementLength, int command) {} +void vivaCompositionInput(uintptr_t handle, void *view, int kind, const unsigned char *utf8, + size_t length, int64_t start, int64_t selectedLength, + int64_t replacementStart, int64_t replacementLength, int command, + int phase, int64_t rawStart, int64_t rawLength, int hasRaw) {} +void vivaTextCompositionLost(uintptr_t handle, void *view, int reason) {} +unsigned char *vivaCopyText(uintptr_t handle, void *view, size_t *length) { *length = 0; return NULL; } +int vivaFilePromiseContent(intptr_t drag, int item, const char *path) { return 1; } +void vivaFileDragFinished(intptr_t drag) {} + +// A custom-titlebar window that is never ordered front: nothing appears on screen. +static NSWindow *customTitlebarWindow(CGFloat width, CGFloat height) { + NSWindowStyleMask style = NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | + NSWindowStyleMaskMiniaturizable | NSWindowStyleMaskResizable | + NSWindowStyleMaskFullSizeContentView; + NSWindow *window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, width, height) + styleMask:style + backing:NSBackingStoreBuffered + defer:NO]; + window.titlebarAppearsTransparent = YES; + window.titleVisibility = NSWindowTitleHidden; + return window; +} + +// Accessibility frames are screen coordinates. A client places the element by +// them, and a window manager reads them right after it moved the window, so the +// frame must follow a window the application has not painted again. +static void assertScreenFrame(VivaAccessibleElement *element, NSWindow *window, + NSRect local, const char *when) { + NSRect want = [window convertRectToScreen:local]; + NSRect got = element.accessibilityFrame; + if (!NSEqualRects(got, want)) { + fprintf(stderr, + "accessibility frame is %.0f,%.0f %.0fx%.0f %s, want %.0f,%.0f %.0fx%.0f\n", + got.origin.x, got.origin.y, got.size.width, got.size.height, when, + want.origin.x, want.origin.y, want.size.width, want.size.height); + abort(); + } +} + +int main(void) { + @autoreleasepool { + [NSApplication sharedApplication]; + + NSWindow *window = customTitlebarWindow(1400, 900); + [window setFrameOrigin:NSMakePoint(240, 140)]; + NSView *view = [window contentView]; + assert(NSEqualSizes(view.bounds.size, NSMakeSize(1400, 900))); + + // A node as the paint gives it: top-left window coordinates. + viva_accessibility_node config; + memset(&config, 0, sizeof(config)); + config.id = 7; + config.role = 3; // button + config.x = 1366; + config.y = 4; + config.width = 28; + config.height = 28; + config.label = "Settings"; + config.label_length = 8; + VivaAccessibleElement *element = [[VivaAccessibleElement alloc] initWithConfig:config + windowFrame:view.bounds + focused:NO + callbackHandle:0 + view:view]; + // Bottom-left window coordinates, as AppKit reads the frame. + NSRect local = NSMakeRect(1366, 900 - 4 - 28, 28, 28); + NSRect screen = [window convertRectToScreen:local]; + if (NSEqualRects(screen, local)) { + fprintf(stderr, "the fixture must sit away from the screen's corner\n"); + abort(); + } + assertScreenFrame(element, window, local, "before the window moves"); + + // A window manager moves the window and reads the tree before the + // application has painted again. + [window setFrameOrigin:NSMakePoint(320, 210)]; + assertScreenFrame(element, window, local, "after the window moved without a repaint"); + [element release]; + + // Without a window there is no screen space; the paint's rectangle is + // the best answer rather than a crash. + VivaAccessibleElement *orphan = [[VivaAccessibleElement alloc] initWithConfig:config + windowFrame:NSMakeRect(0, 0, 1400, 900) + focused:NO + callbackHandle:0 + view:NULL]; + NSRect orphanFrame = orphan.accessibilityFrame; + if (!NSEqualRects(orphanFrame, local)) { + fprintf(stderr, "a view with no window reported %.0f,%.0f\n", orphanFrame.origin.x, orphanFrame.origin.y); + abort(); + } + [orphan release]; + printf("accessibility frames follow the window's place on screen\n"); + } + return 0; +} diff --git a/internal/platform/darwin/testdata/attention.m b/internal/platform/darwin/testdata/attention.m new file mode 100644 index 000000000..91f6dad17 --- /dev/null +++ b/internal/platform/darwin/testdata/attention.m @@ -0,0 +1,11 @@ +#import + +#include "../attention_darwin.h" + +int main(void) { + @autoreleasepool { + [NSApplication sharedApplication]; + viva_application_request_attention(); + } + return 0; +} diff --git a/internal/platform/darwin/testdata/dock_reopen.m b/internal/platform/darwin/testdata/dock_reopen.m index 5c74148b4..a177573aa 100644 --- a/internal/platform/darwin/testdata/dock_reopen.m +++ b/internal/platform/darwin/testdata/dock_reopen.m @@ -5,8 +5,9 @@ #include "../main_menu_darwin.m" #include +void vivaTextOverlayChanged(uintptr_t callback_handle, void *view) {} void vivaPointerEvent(uintptr_t handle, void *view, int kind, int button, int modifiers, int clickCount, double x, double y, double screenX, double screenY) {} -void vivaViewResized(uintptr_t handle, void *view, double width, double height) {} +void vivaViewResized(uintptr_t handle, void *view, double width, double height, double scale, int live) {} void vivaRedrawRequested(uintptr_t handle, void *view) {} void vivaKeyEvent(uintptr_t handle, void *view, int key, int modifiers, int repeat, const unsigned char *utf8, size_t utf8Length) {} void vivaRawKeyEvent(uintptr_t handle, void *view, int key, int modifiers, int flags, unsigned int code, const unsigned char *utf8, size_t utf8Length, const unsigned char *typed, size_t typedLength) {} diff --git a/internal/platform/darwin/testdata/file_drop.m b/internal/platform/darwin/testdata/file_drop.m index 9b224b1a3..7437b0b29 100644 --- a/internal/platform/darwin/testdata/file_drop.m +++ b/internal/platform/darwin/testdata/file_drop.m @@ -28,6 +28,7 @@ int vivaFileDropEvent(uintptr_t handle, void *view, int phase, double x, double } return drop_answer; } +void vivaTextOverlayChanged(uintptr_t callback_handle, void *view) {} void vivaPointerEvent(uintptr_t handle, void *view, int kind, int button, int modifiers, int clickCount, double x, double y, double screenX, double screenY) {} // The promised content callback records what it is asked for and answers as the // test says. @@ -48,7 +49,7 @@ void vivaFileDragFinished(intptr_t drag) { finished_calls++; finished_drag = drag; } -void vivaViewResized(uintptr_t handle, void *view, double width, double height) {} +void vivaViewResized(uintptr_t handle, void *view, double width, double height, double scale, int live) {} void vivaRedrawRequested(uintptr_t handle, void *view) {} void vivaKeyEvent(uintptr_t handle, void *view, int key, int modifiers, int repeat, const unsigned char *utf8, size_t utf8Length) {} void vivaRawKeyEvent(uintptr_t handle, void *view, int key, int modifiers, int flags, unsigned int code, const unsigned char *utf8, size_t utf8Length, const unsigned char *typed, size_t typedLength) {} diff --git a/internal/platform/darwin/testdata/live_resize.m b/internal/platform/darwin/testdata/live_resize.m index de5abc9db..421be37ef 100644 --- a/internal/platform/darwin/testdata/live_resize.m +++ b/internal/platform/darwin/testdata/live_resize.m @@ -7,8 +7,9 @@ #include // The callbacks native.m reports to Go; this test listens to none of them. +void vivaTextOverlayChanged(uintptr_t callback_handle, void *view) {} void vivaPointerEvent(uintptr_t handle, void *view, int kind, int button, int modifiers, int clickCount, double x, double y, double screenX, double screenY) {} -void vivaViewResized(uintptr_t handle, void *view, double width, double height) {} +void vivaViewResized(uintptr_t handle, void *view, double width, double height, double scale, int live) {} void vivaRedrawRequested(uintptr_t handle, void *view) {} void vivaKeyEvent(uintptr_t handle, void *view, int key, int modifiers, int repeat, const unsigned char *utf8, size_t utf8Length) {} void vivaRawKeyEvent(uintptr_t handle, void *view, int key, int modifiers, int flags, unsigned int code, const unsigned char *utf8, size_t utf8Length, const unsigned char *typed, size_t typedLength) {} diff --git a/internal/platform/darwin/testdata/modifier_taps.m b/internal/platform/darwin/testdata/modifier_taps.m index 7ad2a8380..3175c0e84 100644 --- a/internal/platform/darwin/testdata/modifier_taps.m +++ b/internal/platform/darwin/testdata/modifier_taps.m @@ -15,8 +15,9 @@ void vivaOpenFile(const char *path) {} int vivaApplicationQuitRequested(void) { return 0; } int vivaApplicationReopenRequested(void) { return 0; } int vivaFileDropEvent(uintptr_t handle, void *view, int phase, double x, double y, const char *paths, size_t length) { return 0; } +void vivaTextOverlayChanged(uintptr_t callback_handle, void *view) {} void vivaPointerEvent(uintptr_t handle, void *view, int kind, int button, int modifiers, int clickCount, double x, double y, double screenX, double screenY) {} -void vivaViewResized(uintptr_t handle, void *view, double width, double height) {} +void vivaViewResized(uintptr_t handle, void *view, double width, double height, double scale, int live) {} void vivaRedrawRequested(uintptr_t handle, void *view) {} void vivaKeyEvent(uintptr_t handle, void *view, int key, int modifiers, int repeat, const unsigned char *utf8, size_t utf8Length) { plain_key_calls++; } void vivaRawKeyEvent(uintptr_t handle, void *view, int key, int modifiers, int flags, unsigned int code, const unsigned char *utf8, size_t utf8Length, const unsigned char *typed, size_t typedLength) { diff --git a/internal/platform/darwin/testdata/resize_report.m b/internal/platform/darwin/testdata/resize_report.m new file mode 100644 index 000000000..85774f55c --- /dev/null +++ b/internal/platform/darwin/testdata/resize_report.m @@ -0,0 +1,121 @@ +#include "../core_text.m" +#include "../core_render.m" +#include "../watermark_darwin.m" +#include "../native.m" +#include "../main_menu_darwin.m" +#include +#include + +// The callbacks native.m reports to Go; this test listens to none of them. +void vivaTextOverlayChanged(uintptr_t callback_handle, void *view) {} +void vivaPointerEvent(uintptr_t handle, void *view, int kind, int button, int modifiers, int clickCount, double x, double y, double screenX, double screenY) {} +int resizeReports; +double resizeWidth; +double resizeHeight; +int resizeLive; +void vivaViewResized(uintptr_t handle, void *view, double width, double height, double scale, int live) { + (void)scale; + resizeReports++; + resizeWidth = width; + resizeHeight = height; + resizeLive = live; +} +void vivaRedrawRequested(uintptr_t handle, void *view) {} +void vivaKeyEvent(uintptr_t handle, void *view, int key, int modifiers, int repeat, const unsigned char *utf8, size_t utf8Length) {} +void vivaRawKeyEvent(uintptr_t handle, void *view, int key, int modifiers, int flags, unsigned int code, const unsigned char *utf8, size_t utf8Length, const unsigned char *typed, size_t typedLength) {} +void vivaWindowActivated(uintptr_t handle) {} +void vivaWindowDeactivated(uintptr_t handle, void *view) {} +void vivaFocusLost(uintptr_t handle, void *view) {} +int vivaTerminalCells(uint32_t character) { return 1; } +int vivaAccessibilityAction(uintptr_t handle, void *view, uint64_t node, int action, double number, const unsigned char *utf8, size_t utf8Length, int start, int end) { return 0; } +viva_text_line *vivaShapedLine(const unsigned char *utf8, size_t length, double size, double weight) { return viva_text_line_create(utf8, length, size, weight); } +viva_text_line *vivaShapedLineStyle(const unsigned char *utf8, size_t length, double size, double weight, int italic) { return viva_text_line_create_style(utf8, length, size, weight, italic); } +int vivaShortcutEvent(uintptr_t handle, void *view, int key, int modifiers, int repeat, const unsigned char *utf8, size_t utf8Length) { return 0; } +void vivaOpenURL(const char *url) {} +void vivaOpenFile(const char *path) {} +int vivaApplicationQuitRequested(void) { return 0; } +int vivaApplicationReopenRequested(void) { return 0; } +int vivaFileDropEvent(uintptr_t handle, void *view, int phase, double x, double y, const char *paths, size_t length) { return 0; } +void vivaCPUSurfaceLost(uintptr_t handle, void *view) {} +void vivaScrollEvent(uintptr_t handle, void *view, double deltaX, double deltaY, double x, double y, int modifiers, int precise) {} +void vivaCloseRequested(uintptr_t handle, void *view) {} +void vivaWindowClosed(uintptr_t handle) {} +void vivaFrameChanged(uintptr_t handle, void *view, double x, double y, double width, double height) {} +void vivaWindowMinimized(uintptr_t handle, void *view, int minimized) {} +void vivaWindowOccluded(uintptr_t handle, void *view, int visible) {} +void vivaWindowFullscreen(uintptr_t handle, void *view, int fullscreen) {} +int vivaWindowReopenRequested(uintptr_t handle, void *view) { return 0; } +int vivaPressAt(uintptr_t handle, double x, double y) { return 0; } +void vivaTextInput(uintptr_t handle, void *view, int kind, const unsigned char *utf8, + size_t length, int64_t start, int64_t selectedLength, + int64_t replacementStart, int64_t replacementLength, int command) {} +void vivaCompositionInput(uintptr_t handle, void *view, int kind, const unsigned char *utf8, + size_t length, int64_t start, int64_t selectedLength, + int64_t replacementStart, int64_t replacementLength, int command, + int phase, int64_t rawStart, int64_t rawLength, int hasRaw) {} +void vivaTextCompositionLost(uintptr_t handle, void *view, int reason) {} +unsigned char *vivaCopyText(uintptr_t handle, void *view, size_t *length) { *length = 0; return NULL; } + +int main(void) { + @autoreleasepool { + [NSApplication sharedApplication]; + id device = MTLCreateSystemDefaultDevice(); + assert(device != nil); + + VivaMetalView *view = [[VivaMetalView alloc] + initWithFrame:NSMakeRect(0, 0, 320, 200) + device:device + commandQueue:nil + rectanglePipeline:nil + rectangleBuffer:nil + rectangleCount:0 + rectangleClips:NULL + textPipeline:nil + textLabels:NULL + textLabelCount:0 + accessibility:NULL + accessibilityCount:0 + textInput:(viva_text_input_config){0} + dynamicTextInputEnabled:NO + pointerEventsEnabled:NO + resizeEventsEnabled:YES + keyEventsEnabled:NO + scrollEventsEnabled:NO + windowMode:0 + callbackHandle:1 + clearColor:(MTLClearColor){0, 0, 0, 1}]; + assert(view != nil); + + // A window manager animates a geometry change in many steps. Reporting + // each step means a layout pass and a draw per step; the report belongs + // to the run loop, once, for the size the window stops at. + [view setFrameSize:NSMakeSize(400, 300)]; + [view setFrameSize:NSMakeSize(520, 360)]; + [view setFrameSize:NSMakeSize(640, 480)]; + assert(resizeReports == 0); + [view reportPendingResize]; + assert(resizeReports == 1); + assert(resizeWidth == 640 && resizeHeight == 480); + assert(resizeLive == 0); + + // The same size is not reported again. + [view setFrameSize:NSMakeSize(640, 480)]; + assert(resizeReports == 1); + + // A live resize is reported inside the pass that changes the bounds, + // because its frame has to land in the same transaction. + [view beginLiveResizeRelaxation]; + [view setFrameSize:NSMakeSize(800, 600)]; + assert(resizeReports == 2 && resizeWidth == 800 && resizeHeight == 600); + assert(resizeLive == 1); + [view endLiveResizeRelaxation]; + + printf("resize report: 3 animated steps became 1 report, live reported at once\n"); + [view release]; + } + return 0; +} + +// The promised content callbacks the drag source reports to Go. +int vivaFilePromiseContent(intptr_t drag, int item, const char *path) { return 1; } +void vivaFileDragFinished(intptr_t drag) {} diff --git a/internal/platform/darwin/testdata/resize_scale.m b/internal/platform/darwin/testdata/resize_scale.m new file mode 100644 index 000000000..4b428ae41 --- /dev/null +++ b/internal/platform/darwin/testdata/resize_scale.m @@ -0,0 +1,140 @@ +#include "../core_text.m" +#include "../core_render.m" +#include "../watermark_darwin.m" +#include "../native.m" +#include "../main_menu_darwin.m" +#include +#include + +// The callbacks native.m reports to Go. This test reads only the resize one. +void vivaTextOverlayChanged(uintptr_t callback_handle, void *view) {} +void vivaPointerEvent(uintptr_t handle, void *view, int kind, int button, int modifiers, int clickCount, double x, double y, double screenX, double screenY) {} +void vivaRedrawRequested(uintptr_t handle, void *view) {} +void vivaKeyEvent(uintptr_t handle, void *view, int key, int modifiers, int repeat, const unsigned char *utf8, size_t utf8Length) {} +void vivaRawKeyEvent(uintptr_t handle, void *view, int key, int modifiers, int flags, unsigned int code, const unsigned char *utf8, size_t utf8Length, const unsigned char *typed, size_t typedLength) {} +void vivaWindowActivated(uintptr_t handle) {} +void vivaWindowDeactivated(uintptr_t handle, void *view) {} +void vivaFocusLost(uintptr_t handle, void *view) {} +int vivaTerminalCells(uint32_t character) { return 1; } +int vivaAccessibilityAction(uintptr_t handle, void *view, uint64_t node, int action, double number, const unsigned char *utf8, size_t utf8Length, int start, int end) { return 0; } +viva_text_line *vivaShapedLine(const unsigned char *utf8, size_t length, double size, double weight) { return viva_text_line_create(utf8, length, size, weight); } +viva_text_line *vivaShapedLineStyle(const unsigned char *utf8, size_t length, double size, double weight, int italic) { return viva_text_line_create_style(utf8, length, size, weight, italic); } +int vivaShortcutEvent(uintptr_t handle, void *view, int key, int modifiers, int repeat, const unsigned char *utf8, size_t utf8Length) { return 0; } +void vivaOpenURL(const char *url) {} +void vivaOpenFile(const char *path) {} +int vivaApplicationQuitRequested(void) { return 0; } +int vivaApplicationReopenRequested(void) { return 0; } +int vivaFileDropEvent(uintptr_t handle, void *view, int phase, double x, double y, const char *paths, size_t length) { return 0; } +void vivaScrollEvent(uintptr_t handle, void *view, double deltaX, double deltaY, double x, double y, int modifiers, int precise) {} +void vivaCloseRequested(uintptr_t handle, void *view) {} +void vivaWindowClosed(uintptr_t handle) {} +void vivaFrameChanged(uintptr_t handle, void *view, double x, double y, double width, double height) {} +void vivaWindowMinimized(uintptr_t handle, void *view, int minimized) {} +void vivaWindowOccluded(uintptr_t handle, void *view, int visible) {} +void vivaWindowFullscreen(uintptr_t handle, void *view, int fullscreen) {} +int vivaWindowReopenRequested(uintptr_t handle, void *view) { return 0; } +int vivaPressAt(uintptr_t handle, double x, double y) { return 0; } +void vivaTextInput(uintptr_t handle, void *view, int kind, const unsigned char *utf8, + size_t length, int64_t start, int64_t selectedLength, + int64_t replacementStart, int64_t replacementLength, int command) {} +void vivaCompositionInput(uintptr_t handle, void *view, int kind, const unsigned char *utf8, + size_t length, int64_t start, int64_t selectedLength, + int64_t replacementStart, int64_t replacementLength, int command, + int phase, int64_t rawStart, int64_t rawLength, int hasRaw) {} +void vivaTextCompositionLost(uintptr_t handle, void *view, int reason) {} +unsigned char *vivaCopyText(uintptr_t handle, void *view, size_t *length) { *length = 0; return NULL; } + +static int resize_events; +static double resize_width, resize_height, resize_scale; + +void vivaViewResized(uintptr_t handle, void *view, double width, double height, double scale, int live) { + (void)handle; + (void)view; + resize_events++; + resize_width = width; + resize_height = height; + resize_scale = scale; +} + +static VivaMetalView *metalView(NSRect frame, id device) { + return [[VivaMetalView alloc] + initWithFrame:frame + device:device + commandQueue:nil + rectanglePipeline:nil + rectangleBuffer:nil + rectangleCount:0 + rectangleClips:NULL + textPipeline:nil + textLabels:NULL + textLabelCount:0 + accessibility:NULL + accessibilityCount:0 + textInput:(viva_text_input_config){0} +dynamicTextInputEnabled:NO + pointerEventsEnabled:NO + resizeEventsEnabled:YES + keyEventsEnabled:NO + scrollEventsEnabled:NO + windowMode:VIVA_WINDOW_FRAMELESS + callbackHandle:42 + clearColor:(MTLClearColor){0, 0, 0, 1}]; +} + +int main(void) { + @autoreleasepool { + [NSApplication sharedApplication]; + id device = MTLCreateSystemDefaultDevice(); + assert(device != nil); + + NSWindow *window = [[NSWindow alloc] + initWithContentRect:NSMakeRect(200, 200, 320, 240) + styleMask:NSWindowStyleMaskTitled + backing:NSBackingStoreBuffered + defer:NO]; + assert(window != nil); + + VivaMetalView *view = metalView(NSMakeRect(0, 0, 320, 240), device); + assert(view != nil); + window.contentView = view; + assert(view.window == window); + + NSScreen *screen = window.screen ?: NSScreen.mainScreen; + assert(screen != nil); + CGFloat expected = MAX(screen.backingScaleFactor, 1.0); + + // The frame the application painted before the window existed carries no + // scale; the window reports the size and scale it really has before its + // first draw. This is the open path, run directly. + // Entering the window reports the scale once (see viewDidChangeBackingProperties). + resize_events = 0; + [view reportSize]; + assert(resize_events == 1); + assert(fabs(resize_width - 320) < 0.5 && fabs(resize_height - 240) < 0.5); + assert(fabs(resize_scale - expected) < 0.001); + + // A resize carries the display scale with the new size, so cells and + // icons are rounded for the display they land on. + [view setFrameSize:NSMakeSize(400, 300)]; + assert(resize_events == 2); + assert(fabs(resize_width - 400) < 0.5 && fabs(resize_height - 300) < 0.5); + assert(fabs(resize_scale - expected) < 0.001); + + // Moving to a display of another scale changes no size, so the backing + // properties report the same size at the scale again to repaint for it. + [view viewDidChangeBackingProperties]; + assert(resize_events == 3); + assert(fabs(resize_width - 400) < 0.5 && fabs(resize_height - 300) < 0.5); + assert(fabs(resize_scale - expected) < 0.001); + + printf("resize scale: %d events at %.1fx, last %.0fx%.0f\n", + resize_events, resize_scale, resize_width, resize_height); + [view release]; + [window release]; + } + return 0; +} + +// The promised content callbacks the drag source reports to Go. +int vivaFilePromiseContent(intptr_t drag, int item, const char *path) { return 1; } +void vivaFileDragFinished(intptr_t drag) {} diff --git a/internal/platform/darwin/testdata/text_selection.m b/internal/platform/darwin/testdata/text_selection.m index dd769ff83..dd12dfd23 100644 --- a/internal/platform/darwin/testdata/text_selection.m +++ b/internal/platform/darwin/testdata/text_selection.m @@ -10,13 +10,14 @@ static int recordedKinds[16]; static int recordedClicks[16]; static int recordedCount; +void vivaTextOverlayChanged(uintptr_t callback_handle, void *view) {} void vivaPointerEvent(uintptr_t handle, void *view, int kind, int button, int modifiers, int clickCount, double x, double y, double screenX, double screenY) { if (recordedCount < 16) { recordedKinds[recordedCount] = kind; recordedClicks[recordedCount++] = clickCount; } } -void vivaViewResized(uintptr_t handle, void *view, double width, double height) {} +void vivaViewResized(uintptr_t handle, void *view, double width, double height, double scale, int live) {} void vivaRedrawRequested(uintptr_t handle, void *view) {} // viva_test_keyboard_event builds a real key event, so characters re-applied // with modifiers are resolved by the active layout and key code. diff --git a/internal/platform/darwin/testdata/traffic_lights.m b/internal/platform/darwin/testdata/traffic_lights.m index 5789e46f0..0b2d57474 100644 --- a/internal/platform/darwin/testdata/traffic_lights.m +++ b/internal/platform/darwin/testdata/traffic_lights.m @@ -6,8 +6,9 @@ #include // The callbacks native.m reports to Go; this test listens to none of them. +void vivaTextOverlayChanged(uintptr_t callback_handle, void *view) {} void vivaPointerEvent(uintptr_t handle, void *view, int kind, int button, int modifiers, int clickCount, double x, double y, double screenX, double screenY) {} -void vivaViewResized(uintptr_t handle, void *view, double width, double height) {} +void vivaViewResized(uintptr_t handle, void *view, double width, double height, double scale, int live) {} void vivaRedrawRequested(uintptr_t handle, void *view) {} void vivaKeyEvent(uintptr_t handle, void *view, int key, int modifiers, int repeat, const unsigned char *utf8, size_t utf8Length) {} void vivaRawKeyEvent(uintptr_t handle, void *view, int key, int modifiers, int flags, unsigned int code, const unsigned char *utf8, size_t utf8Length, const unsigned char *typed, size_t typedLength) {} diff --git a/internal/platform/darwin/testdata/window_close.m b/internal/platform/darwin/testdata/window_close.m index 5ea1e3503..1c8d4b752 100644 --- a/internal/platform/darwin/testdata/window_close.m +++ b/internal/platform/darwin/testdata/window_close.m @@ -11,12 +11,13 @@ static int closedCalls; static BOOL released; +void vivaTextOverlayChanged(uintptr_t callback_handle, void *view) {} void vivaPointerEvent(uintptr_t handle, void *view, int kind, int button, int modifiers, int clickCount, double x, double y, double screenX, double screenY) { assert(!released || handle != 1); assert(kind == VIVA_POINTER_EXIT); pointerCalls++; } -void vivaViewResized(uintptr_t handle, void *view, double width, double height) {} +void vivaViewResized(uintptr_t handle, void *view, double width, double height, double scale, int live) {} void vivaRedrawRequested(uintptr_t handle, void *view) {} void vivaKeyEvent(uintptr_t handle, void *view, int key, int modifiers, int repeat, const unsigned char *utf8, size_t utf8Length) {} void vivaRawKeyEvent(uintptr_t handle, void *view, int key, int modifiers, int flags, unsigned int code, const unsigned char *utf8, size_t utf8Length, const unsigned char *typed, size_t typedLength) {} diff --git a/internal/platform/darwin/testdata/window_decoration.m b/internal/platform/darwin/testdata/window_decoration.m index a5806202e..c78ea1434 100644 --- a/internal/platform/darwin/testdata/window_decoration.m +++ b/internal/platform/darwin/testdata/window_decoration.m @@ -5,6 +5,7 @@ #include "../main_menu_darwin.m" #include +void vivaTextOverlayChanged(uintptr_t callback_handle, void *view) {} void vivaPointerEvent(uintptr_t handle, void *view, int kind, int button, int modifiers, int clickCount, double x, double y, double screenX, double screenY) {} #include "window_test_callbacks.h" diff --git a/internal/platform/darwin/testdata/window_notification.m b/internal/platform/darwin/testdata/window_notification.m index 02f6ff06e..0c34adefc 100644 --- a/internal/platform/darwin/testdata/window_notification.m +++ b/internal/platform/darwin/testdata/window_notification.m @@ -7,6 +7,7 @@ #include static unsigned downs, ups; +void vivaTextOverlayChanged(uintptr_t callback_handle, void *view) {} void vivaPointerEvent(uintptr_t handle, void *view, int kind, int button, int modifiers, int clickCount, double x, double y, double screenX, double screenY) { assert(handle == 1); if (kind == VIVA_POINTER_DOWN) downs++; diff --git a/internal/platform/darwin/testdata/window_opacity.m b/internal/platform/darwin/testdata/window_opacity.m index 9bd50bfe9..c61c8f8a2 100644 --- a/internal/platform/darwin/testdata/window_opacity.m +++ b/internal/platform/darwin/testdata/window_opacity.m @@ -5,6 +5,7 @@ #include "../main_menu_darwin.m" #include +void vivaTextOverlayChanged(uintptr_t callback_handle, void *view) {} void vivaPointerEvent(uintptr_t handle, void *view, int kind, int button, int modifiers, int clickCount, double x, double y, double screenX, double screenY) {} #include "window_test_callbacks.h" @@ -39,6 +40,10 @@ static void check(int mode, double alpha) { mode, alpha, view.isOpaque, view.layer.isOpaque, view.opaqueAncestor == view, expected); abort(); } + if (view.mouseDownCanMoveWindow) { + fprintf(stderr, "mode=%d alpha=%.2f: a press in the view would move the window\n", mode, alpha); + abort(); + } [view removeFromSuperview]; [view release]; [background release]; diff --git a/internal/platform/darwin/testdata/window_size.m b/internal/platform/darwin/testdata/window_size.m index bbb866887..f2de83412 100644 --- a/internal/platform/darwin/testdata/window_size.m +++ b/internal/platform/darwin/testdata/window_size.m @@ -7,6 +7,7 @@ #include // The callbacks native.m reports to Go; this test listens to none of them. +void vivaTextOverlayChanged(uintptr_t callback_handle, void *view) {} void vivaPointerEvent(uintptr_t handle, void *view, int kind, int button, int modifiers, int clickCount, double x, double y, double screenX, double screenY) {} #include "window_test_callbacks.h" diff --git a/internal/platform/darwin/testdata/window_test_callbacks.h b/internal/platform/darwin/testdata/window_test_callbacks.h index 26805a1de..6928e9000 100644 --- a/internal/platform/darwin/testdata/window_test_callbacks.h +++ b/internal/platform/darwin/testdata/window_test_callbacks.h @@ -1,5 +1,5 @@ // Window fixtures define the pointer callback they need and ignore the other Go callbacks. -void vivaViewResized(uintptr_t handle, void *view, double width, double height) {} +void vivaViewResized(uintptr_t handle, void *view, double width, double height, double scale, int live) {} void vivaRedrawRequested(uintptr_t handle, void *view) {} void vivaKeyEvent(uintptr_t handle, void *view, int key, int modifiers, int repeat, const unsigned char *utf8, size_t utf8Length) {} void vivaRawKeyEvent(uintptr_t handle, void *view, int key, int modifiers, int flags, unsigned int code, const unsigned char *utf8, size_t utf8Length, const unsigned char *typed, size_t typedLength) {} diff --git a/internal/platform/idle_trim.go b/internal/platform/idle_trim.go new file mode 100644 index 000000000..3aeec342e --- /dev/null +++ b/internal/platform/idle_trim.go @@ -0,0 +1,12 @@ +package platform + +import "time" + +// IdleTrimDelay is how long a window goes without presenting before its +// renderer gives back the memory only drawing needs: the driver's caches on +// Windows, the presentation buffers the CPU renderer keeps off screen on macOS, +// and its packing buffer on Linux. Each platform waits for it with a one-shot +// timer or deadline that a burst of painting arms once; an idle window does +// nothing further. It is longer than a caret blink, so a blinking caret, which +// presents twice a second, keeps its buffers. +const IdleTrimDelay = 2 * time.Second diff --git a/internal/platform/linux/atspi_bridge.go b/internal/platform/linux/atspi_bridge.go index d08d9cae6..26a5c8e62 100644 --- a/internal/platform/linux/atspi_bridge.go +++ b/internal/platform/linux/atspi_bridge.go @@ -427,6 +427,12 @@ func (bridge *atspiBridge) announceChanges(window *atspiWindow, path string, old state("expanded", next.Expanded) state("collapsed", !next.Expanded) } + if changed&platform.ChangedMultiSelectable != 0 { + state("multiselectable", next.MultiSelectable) + } + if changed&platform.ChangedSort != 0 { + bridge.emit(path, atspiEventObject, "AttributesChanged", "", 0, 0, nil) + } if changed&platform.ChangedName != 0 { bridge.emit(path, atspiEventObject, "PropertyChange", "accessible-name", 0, 0, next.Label) } diff --git a/internal/platform/linux/atspi_model.go b/internal/platform/linux/atspi_model.go index 2ac3e56c0..c4e4128af 100644 --- a/internal/platform/linux/atspi_model.go +++ b/internal/platform/linux/atspi_model.go @@ -170,6 +170,8 @@ func atspiRole(node platform.AccessibilityNode) uint32 { return atspiRoleSeparator case platform.A11yRoleProgress: return atspiRoleProgressBar + case platform.A11yRoleColumnHeader: + return atspiRoleColumnHeader } return atspiRolePanel } @@ -179,6 +181,8 @@ func atspiRoleName(role uint32) string { switch role { case atspiRoleCheckBox: return "check box" + case atspiRoleColumnHeader: + return "column header" case atspiRoleComboBox: return "combo box" case atspiRoleFrame: @@ -259,6 +263,7 @@ func atspiStates(node platform.AccessibilityNode) [2]uint32 { set(node.Mixed, atspiStateIndeterminate) set(patterns.Has(platform.PatternSelectionItem), atspiStateSelectable) set(node.Selected, atspiStateSelected) + set(node.MultiSelectable && patterns.Has(platform.PatternSelection), atspiStateMultiselectable) if patterns.Has(platform.PatternExpandCollapse) { set(true, atspiStateExpandable) set(node.Expanded, atspiStateExpanded) @@ -360,9 +365,24 @@ func atspiAttributes(node platform.AccessibilityNode) [][2]string { if node.Role == platform.A11yRoleHeading { attributes = append(attributes, [2]string{"xml-roles", "heading"}) } + // A column header's sort is the object attribute aria-sort maps to. + if node.Role == platform.A11yRoleColumnHeader { + attributes = append(attributes, [2]string{"sort", atspiSortWord(node.Sort)}) + } return attributes } +// atspiSortWord is a sort direction as the sort attribute writes it. +func atspiSortWord(sort gfx.SortDirection) string { + switch sort { + case gfx.SortAscending: + return "ascending" + case gfx.SortDescending: + return "descending" + } + return "none" +} + // atspiTextUnit maps a granularity to our text unit. A sentence is not // something the text layer knows, so it is the line. func atspiTextUnit(granularity uint32) platform.AccessibilityTextUnit { diff --git a/internal/platform/linux/attention_gtk_linux.go b/internal/platform/linux/attention_gtk_linux.go new file mode 100644 index 000000000..3ffdb4618 --- /dev/null +++ b/internal/platform/linux/attention_gtk_linux.go @@ -0,0 +1,20 @@ +//go:build linux && vivagtk + +package linux + +import "fmt" + +// RequestAttention asks the compositor to highlight the window's taskbar entry +// until it gets the keyboard. GTK owns the toplevel, so the request runs on its +// thread. +func (w *gtkWindow) RequestAttention() error { + if w == nil || w.app == nil { + return fmt.Errorf("linux: window is closed") + } + w.app.enqueue(func() { + if !w.closed { + w.g.windowSetUrgency(w.toplevel, 1) + } + }) + return nil +} diff --git a/internal/platform/linux/attention_linux.go b/internal/platform/linux/attention_linux.go new file mode 100644 index 000000000..90fb03963 --- /dev/null +++ b/internal/platform/linux/attention_linux.go @@ -0,0 +1,23 @@ +//go:build linux && !android + +package linux + +import "fmt" + +// RequestAttention marks the window as demanding attention in _NET_WM_STATE. +// The window manager draws the taskbar highlight and clears it when the user +// gives the window the keyboard. +func (window *nativeWindow) RequestAttention() error { + if window == nil || window.closed.Load() { + return fmt.Errorf("linux: window is closed") + } + win := window.state.win + win.mu.Lock() + defer win.mu.Unlock() + if win.connection == 0 || win.frame.stateAtom == 0 || win.frame.demandsAttention == 0 { + return fmt.Errorf("linux: window attention is unavailable") + } + win.attentionRequested.Store(true) + win.sendToRoot(win.frame.stateAtom, [5]uint32{netWMStateAdd, win.frame.demandsAttention, 0, sourceApp}) + return nil +} diff --git a/internal/platform/linux/attention_linux_test.go b/internal/platform/linux/attention_linux_test.go new file mode 100644 index 000000000..2b1ccdc13 --- /dev/null +++ b/internal/platform/linux/attention_linux_test.go @@ -0,0 +1,48 @@ +//go:build linux && !android + +package linux + +import ( + "encoding/binary" + "testing" + "unsafe" +) + +func TestRequestAttentionAddsTheDemandsAttentionState(t *testing.T) { + var words [5]uint32 + var destination, mask uint32 + win := &window{ + api: &xcbAPI{ + sendEvent: func(_ uintptr, _ uint8, target, eventMask uint32, data *byte) xcbVoidCookie { + destination, mask = target, eventMask + message := (*xcbClientEvent)(unsafe.Pointer(data)) + for index := range words { + words[index] = binary.LittleEndian.Uint32(message.Data[index*4:]) + } + return xcbVoidCookie{} + }, + flush: func(uintptr) int32 { return 0 }, + }, + connection: 1, + screen: &xcbScreen{Root: 7}, + frame: frameState{ + stateAtom: 10, + demandsAttention: 20, + }, + } + window := &nativeWindow{state: &linuxWindowState{win: win}} + if err := window.RequestAttention(); err != nil { + t.Fatal(err) + } + // EWMH 5.7: data.l[0] is the action, l[1] the property, l[3] the source + // indication. The root window and the substructure mask are the protocol's. + if destination != 7 || mask != xcbEventSubstructureRedirect|xcbEventSubstructureNotify { + t.Fatalf("message went to root=%d mask=%#x", destination, mask) + } + if words != [5]uint32{netWMStateAdd, 20, 0, sourceApp, 0} { + t.Fatalf("attention message = %v, want _NET_WM_STATE_DEMANDS_ATTENTION added", words) + } + if !win.attentionRequested.Load() { + t.Fatal("the window did not remember that it asked for attention") + } +} diff --git a/internal/platform/linux/cpu_lcd_linux_test.go b/internal/platform/linux/cpu_lcd_linux_test.go index 350ca7193..bdb885ef1 100644 --- a/internal/platform/linux/cpu_lcd_linux_test.go +++ b/internal/platform/linux/cpu_lcd_linux_test.go @@ -51,11 +51,11 @@ func TestCPUOffscreenLCDTextIsBlendedPerChannel(t *testing.T) { // each run owns with its color, as the Vulkan path does with spans. func TestCPUGridLCDLabelKeepsItsRunColors(t *testing.T) { useSystemFonts(t, fontSettings{Antialias: cairoAntialiasSubpixel, HintStyle: cairoHintSlight, SubpixelOrder: cairoSubpixelRGB}) - services, err := newTextServices() + offscreen, err := NewCPUOffscreen(32, 20, 1, platform.Color{Alpha: 1}) if err != nil { t.Fatal(err) } - defer services.close() + t.Cleanup(offscreen.Close) label := platform.TextLabel{ Value: "AB", Width: 32, Height: 20, FontSize: 14, Mono: true, CellWidth: 8, Color: platform.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1}, @@ -64,25 +64,28 @@ func TestCPUGridLCDLabelKeepsItsRunColors(t *testing.T) { {Column: 1, Bytes: 1, Cells: 1, Color: gfx.RGB(0, 0, 255)}, }, } - image, ok, err := rasterizeLabel(services, label, 1, 0, labelImage{}, true) - if err != nil || !ok { - t.Fatalf("rasterize: ok=%v err=%v", ok, err) - } - if !image.lcd { - t.Fatal("grid text was not rasterized as LCD coverage") - } - if len(image.spans) != 2 { - t.Fatalf("%d spans, want one per run", len(image.spans)) + if err := offscreen.Set(nil, []platform.TextLabel{label}); err != nil { + t.Fatal(err) } - first, second := image.spans[0], image.spans[1] - if first.Color.Red != 1 || first.Color.Green != 0 || first.Color.Blue != 0 { - t.Fatalf("first span color %+v, want red", first.Color) + pixels, err := offscreen.Image() + if err != nil { + t.Fatal(err) } - if second.Color.Red != 0 || second.Color.Green != 0 || second.Color.Blue != 1 { - t.Fatalf("second span color %+v, want blue", second.Color) + red, blue := 0, 0 + for y := 0; y < pixels.Rect.Dy(); y++ { + for x := 0; x < pixels.Rect.Dx(); x++ { + offset := y*pixels.Stride + x*4 + r, g, b := pixels.Pix[offset], pixels.Pix[offset+1], pixels.Pix[offset+2] + if r > g+16 && r > b+16 { + red++ + } + if b > r+16 && b > g+16 { + blue++ + } + } } - if first.From >= first.To || second.From >= second.To || first.To > second.From { - t.Fatalf("span columns %d..%d and %d..%d are not the runs' own", first.From, first.To, second.From, second.To) + if red == 0 || blue == 0 { + t.Fatalf("colored ink red=%d blue=%d, want both runs' colors", red, blue) } } diff --git a/internal/platform/linux/cpu_offscreen_linux.go b/internal/platform/linux/cpu_offscreen_linux.go index 1a055d820..7be1aadce 100644 --- a/internal/platform/linux/cpu_offscreen_linux.go +++ b/internal/platform/linux/cpu_offscreen_linux.go @@ -11,6 +11,7 @@ import ( "github.com/vivaui/viva/internal/raster" "github.com/vivaui/viva/internal/render" "github.com/vivaui/viva/internal/scene" + "github.com/vivaui/viva/internal/softscene" ) // CPUOffscreen is Offscreen without a GPU: the scene is drawn by the CPU rasterizer @@ -59,7 +60,7 @@ func (offscreen *CPUOffscreen) Set(rectangles []render.Rectangle, labels []platf offscreen.rects = append(offscreen.rects[:0], rectangles...) offscreen.labels = offscreen.labels[:0] for index := range labels { - prepared, ok, err := prepareLabel(offscreen.services, labels[index], offscreen.scale, offscreen.canvas.Width, offscreen.canvas.Height, offscreen.clear.Alpha >= 1) + prepared, ok, err := softscene.PrepareLabel(linuxTextRasterizer{offscreen.services}, labels[index], offscreen.scale, offscreen.canvas.Width, offscreen.canvas.Height, offscreen.clear.Alpha >= 1) if err != nil { return fmt.Errorf("linux: label %d: %w", index, err) } @@ -96,123 +97,3 @@ func (offscreen *CPUOffscreen) Close() { } offscreen.canvas, offscreen.rects, offscreen.labels = nil, nil, nil } - -// prepareLabel turns one text label (or image) into the picture the rasterizer composites, placed -// on the device pixel grid the way the Vulkan backend places it: the texture's top left is a whole -// device pixel (platform.DevicePosition), a clip takes every device pixel it touches. ok is false -// when the label draws nothing. -func prepareLabel(services *textServices, l platform.TextLabel, scale float32, canvasWidth, canvasHeight int, allowLCD bool) (label raster.Label, ok bool, err error) { - image, ok, err := rasterizeLabel(services, l, scale, canvasWidth, labelImage{}, allowLCD) - if err != nil || !ok { - return raster.Label{}, false, err - } - label, ok = placeLabel(l, scale, image, canvasWidth, canvasHeight) - return label, ok, nil -} - -// labelImage is a label's picture at one scale, premultiplied BGRA with no padding between rows, -// unless lcd: then it is per-channel coverage with the luminance in alpha, and spans are the column -// ranges of a fixed-pitch line that are text of one color. -type labelImage struct { - pixels []byte - width, height int - // skip is the device column of a text label the picture starts at: a line wider than a - // texture holds, wide, is drawn from the window of it the canvas shows (textWindow). It - // is 0 for every other label. - skip int - wide bool - lcd bool - spans []raster.Span -} - -// textWindow is the part of a text label drawn into its picture at scale on a canvas -// canvasWidth device pixels wide: the device columns from skip to skip+width of the label, -// height high. A label one texture holds is drawn whole. A wider one, wide, is drawn from -// the columns of it the canvas and its clip show, keeping have, the picture it has, while -// that still holds them (platform.WideTextLabelWindow); the Vulkan backend draws the same -// window. ok is false when nothing is drawn: none of a wide line can be seen, or no -// texture holds the label. -func textWindow(l platform.TextLabel, scale float32, canvasWidth int, have labelImage) (skip, width, height int, wide, ok bool) { - full := int(math.Ceil(float64(l.Width * scale))) - height = int(math.Ceil(float64(l.Height * scale))) - haveSkip, haveWidth := 0, 0 - if have.wide { - haveSkip, haveWidth = have.skip, have.width - } - skip, width, wide, ok = platform.WideTextLabelWindow(l, scale, full, height, canvasWidth, haveSkip, haveWidth) - return skip, width, height, wide, ok && platform.LabelTextureFits(width, height) -} - -// rasterizeLabel draws a label's text, or resamples its image to the device pixels it covers. ok is -// false when it draws nothing. The picture does not depend on where the label is, except that an -// image smaller than its bitmap does, through the fraction of a pixel it starts at, and a line -// wider than a texture holds is drawn from the window of it a canvas canvasWidth device pixels -// wide shows, kept from have, the picture the label has (textWindow). With allowLCD, and the -// desktop asking for subpixel antialiasing, text comes back as per-channel coverage for the -// rasterizer to tint, the same way the Vulkan LCD shader reads it. -func rasterizeLabel(services *textServices, l platform.TextLabel, scale float32, canvasWidth int, have labelImage, allowLCD bool) (image labelImage, ok bool, err error) { - if l.Width <= 0 || l.Height <= 0 || (l.Value == "" && len(l.Bitmap) == 0) { - return labelImage{}, false, nil - } - if len(l.Bitmap) > 0 { - width, height := l.BitmapWidth, l.BitmapHeight - shownWidth, shownHeight := platform.DeviceExtent(l.X, l.Width, scale), platform.DeviceExtent(l.Y, l.Height, scale) - switch { - case shownWidth <= 0 || shownHeight <= 0: - return labelImage{}, false, nil - case shownWidth <= width && shownHeight <= height && (shownWidth < width || shownHeight < height): - return labelImage{pixels: platform.ResampleBGRA(l.Bitmap, l.BitmapStride, width, height, shownWidth, shownHeight), width: shownWidth, height: shownHeight}, true, nil - } - return labelImage{pixels: platform.TightBitmap(l.Bitmap, width, height, l.BitmapStride), width: width, height: height}, true, nil - } - skip, width, height, wide, shown := textWindow(l, scale, canvasWidth, have) - if !shown { - return labelImage{}, false, nil - } - pixels, lcd, err := services.rasterizeWindow(l, scale, skip, width, height, allowLCD) - if err != nil { - return labelImage{}, false, err - } - image = labelImage{pixels: pixels, width: width, height: height, skip: skip, wide: wide, lcd: lcd} - if lcd && len(services.spans) > 0 { - image.spans = make([]raster.Span, len(services.spans)) - for index, span := range services.spans { - image.spans[index] = raster.Span{ - From: span.Left, To: span.Right, - Color: scene.Color{Red: span.Color[0], Green: span.Color[1], Blue: span.Color[2], Alpha: span.Color[3]}, - } - } - } - return image, true, nil -} - -// placeLabel puts a label's picture on the canvas: its top left on a whole device pixel and its -// clip, if a canvas clip cuts it, on the device pixels the clip touches. ok is false when the clip -// leaves nothing. -func placeLabel(l platform.TextLabel, scale float32, image labelImage, canvasWidth, canvasHeight int) (label raster.Label, ok bool) { - x, y := platform.DevicePosition(l.X, l.OriginX, scale)+image.skip, platform.DevicePosition(l.Y, l.OriginY, scale) - if len(l.Bitmap) > 0 { - x, y = platform.DevicePosition(l.X, 0, scale), platform.DevicePosition(l.Y, 0, scale) - } - label = raster.Label{Pix: image.pixels, Stride: image.width * 4, Width: image.width, Height: image.height, X: x, Y: y, Layer: l.Layer, - Image: len(l.Bitmap) > 0, Radius: l.ImageRadius, Fade: l.ImageFade, - ShapesBefore: l.ShapesBefore, LCD: image.lcd, Spans: image.spans, - Color: scene.Color{Red: float32(l.Color.Red), Green: float32(l.Color.Green), Blue: float32(l.Color.Blue), Alpha: float32(l.Color.Alpha)}} - if len(l.Bitmap) > 0 { - label.Width, label.Height = platform.DeviceExtent(l.X, l.Width, scale), platform.DeviceExtent(l.Y, l.Height, scale) - if label.Width != image.width || label.Height != image.height { - label.SourceWidth, label.SourceHeight = image.width, image.height - } - } - if l.Clipped { - left := max(int(math.Floor(float64(l.Clip.X*scale))), 0) - top := max(int(math.Floor(float64(l.Clip.Y*scale))), 0) - right := min(int(math.Ceil(float64((l.Clip.X+l.Clip.Width)*scale))), canvasWidth) - bottom := min(int(math.Ceil(float64((l.Clip.Y+l.Clip.Height)*scale))), canvasHeight) - if right <= left || bottom <= top { - return raster.Label{}, false - } - label.Clipped, label.Clip = true, render.Scissor{Left: left, Top: top, Right: right, Bottom: bottom} - } - return label, true -} diff --git a/internal/platform/linux/cpu_window_linux.go b/internal/platform/linux/cpu_window_linux.go index 85f93c27d..458311567 100644 --- a/internal/platform/linux/cpu_window_linux.go +++ b/internal/platform/linux/cpu_window_linux.go @@ -5,6 +5,7 @@ package linux import ( "fmt" "math" + "time" "github.com/vivaui/viva/internal/platform/windowframe" @@ -51,8 +52,12 @@ type cpuWindowRenderer struct { // full says the next present composes the whole window again. full bool // scratch is where a damaged rectangle narrower than the canvas is packed - // row by row, because PutImage takes a rectangle without a stride. - scratch []byte + // row by row, because PutImage takes a rectangle without a stride. It is + // given back once the window has been idle for platform.IdleTrimDelay: + // lastPacked is when it was last used, and trimDue says it is still held. + scratch []byte + lastPacked time.Time + trimDue bool // checked is set after the first request was checked with the server, so a // wrong depth or drawable fails once with the server's reason instead of // quietly drawing nothing. @@ -78,7 +83,7 @@ func newCPUWindowRenderer(win *window, scale float32, clear platform.Color, rect } gc := win.api.generateID(win.connection) if err := win.checkRequest("create window drawing context", win.api.createGC(win.connection, gc, win.id, 0, nil)); err != nil { - scene.close() + scene.Close() services.close() return nil, err } @@ -95,19 +100,19 @@ func newCPUWindowRenderer(win *window, scale float32, clear platform.Color, rect // apply takes a frame into the retained scene. Painting waits for present, as // the GPU renderer's command recording does. func (renderer *cpuWindowRenderer) apply(frame platform.Frame) (bool, error) { - return renderer.scene.apply(frame) + return renderer.scene.Apply(frame) } // stage is apply: staging exists to defer GPU command recording, and the CPU // records nothing until present. func (renderer *cpuWindowRenderer) stage(frame platform.Frame) (bool, error) { - return renderer.scene.apply(frame) + return renderer.scene.Apply(frame) } func (renderer *cpuWindowRenderer) present() error { - damage := renderer.scene.paint() + damage := renderer.scene.Paint() if renderer.margin == 0 { - if damage.Right <= damage.Left || damage.Bottom <= damage.Top { + if len(damage) == 0 { return nil } renderer.presents++ @@ -117,30 +122,49 @@ func (renderer *cpuWindowRenderer) present() error { } else { renderer.partials++ } - return renderer.push(renderer.scene.canvas, damage) + for _, box := range damage { + if err := renderer.push(renderer.scene.Canvas, box); err != nil { + return err + } + } + renderer.win.api.flush(renderer.win.connection) + return nil } if renderer.full { + if renderer.out.Pix == nil { + renderer.out.Resize(int(renderer.width), int(renderer.height)) + } renderer.composeAll() renderer.full = false renderer.presents++ renderer.rebuilds++ - return renderer.push(renderer.out, renderer.out.Bounds()) + if err := renderer.push(renderer.out, renderer.out.Bounds()); err != nil { + return err + } + renderer.win.api.flush(renderer.win.connection) + return nil } - if damage.Right <= damage.Left || damage.Bottom <= damage.Top { + if len(damage) == 0 { return nil } - renderer.composeDamage(damage) renderer.presents++ renderer.partials++ offset := int(renderer.margin) - return renderer.push(renderer.out, render.Scissor{ - Left: damage.Left + offset, Top: damage.Top + offset, - Right: damage.Right + offset, Bottom: damage.Bottom + offset, - }) + for _, box := range damage { + renderer.composeDamage(box) + if err := renderer.push(renderer.out, render.Scissor{ + Left: box.Left + offset, Top: box.Top + offset, + Right: box.Right + offset, Bottom: box.Bottom + offset, + }); err != nil { + return err + } + } + renderer.win.api.flush(renderer.win.connection) + return nil } func (renderer *cpuWindowRenderer) presentFull() error { - renderer.scene.damageAll() + renderer.scene.DamageAll() renderer.full = true return renderer.present() } @@ -152,7 +176,7 @@ func (renderer *cpuWindowRenderer) composeAll() { return } renderer.frameDrawer.Draw(renderer.out, - raster.Params{Scale: renderer.scale, Damage: renderer.out.Bounds()}, + raster.Params{Scale: renderer.scale}, []render.Rectangle{renderer.shadowRectangle()}, nil) renderer.cacheCorners() renderer.copyContent() @@ -164,7 +188,7 @@ func (renderer *cpuWindowRenderer) composeAll() { // composeDamage copies a damaged content rectangle into the composed window // picture and puts the shadow back where the rectangle meets a rounded corner. func (renderer *cpuWindowRenderer) composeDamage(damage render.Scissor) { - src := renderer.scene.canvas + src := renderer.scene.Canvas left, top := max(damage.Left, 0), max(damage.Top, 0) right, bottom := min(damage.Right, src.Width), min(damage.Bottom, src.Height) if right <= left || bottom <= top { @@ -186,7 +210,7 @@ func (renderer *cpuWindowRenderer) composeDamage(damage render.Scissor) { } func (renderer *cpuWindowRenderer) copyContent() { - src, out := renderer.scene.canvas, renderer.out + src, out := renderer.scene.Canvas, renderer.out offset := int(renderer.margin) for row := 0; row < src.Height; row++ { from := row * src.Stride @@ -245,7 +269,7 @@ func (renderer *cpuWindowRenderer) maskCorner(index int, area render.Scissor) { if width <= 0 { return } - src, out := renderer.scene.canvas, renderer.out + src, out := renderer.scene.Canvas, renderer.out offset := int(renderer.margin) rect := scene.Rect{X: float32(offset) / renderer.scale, Y: float32(offset) / renderer.scale, Width: float32(src.Width) / renderer.scale, Height: float32(src.Height) / renderer.scale} for y := area.Top; y < area.Bottom; y++ { @@ -262,9 +286,10 @@ func (renderer *cpuWindowRenderer) maskCorner(index int, area render.Scissor) { } } -// push copies one damaged region of canvas to the window. A region as wide as -// the canvas is sent straight from its rows; a narrower one is packed into the -// scratch buffer first. Both go in bounded strips. +// push copies one damaged rectangle of canvas to the window. A rectangle as +// wide as the canvas is sent straight from its rows; a narrower one is packed +// into the scratch buffer first. Both go in bounded strips. The caller flushes +// the connection once after the frame's last rectangle. func (renderer *cpuWindowRenderer) push(canvas *raster.Canvas, damage render.Scissor) error { left, top := max(damage.Left, 0), max(damage.Top, 0) right, bottom := min(damage.Right, canvas.Width), min(damage.Bottom, canvas.Height) @@ -284,6 +309,7 @@ func (renderer *cpuWindowRenderer) push(canvas *raster.Canvas, damage render.Sci renderer.scratch = make([]byte, need) } pixels = renderer.scratch[:need] + renderer.lastPacked, renderer.trimDue = time.Now(), true for row := range rows { from := (top+row)*canvas.Stride + left*4 copy(pixels[row*width*4:(row+1)*width*4], canvas.Pix[from:from+width*4]) @@ -303,10 +329,37 @@ func (renderer *cpuWindowRenderer) push(canvas *raster.Canvas, damage render.Sci } } } - renderer.win.api.flush(renderer.win.connection) return nil } +// trimDeadline is when the idle window gives back its packing buffer, if it +// holds one. The event loop sleeps no longer than this, once. +func (renderer *cpuWindowRenderer) trimDeadline() (time.Time, bool) { + return renderer.lastPacked.Add(platform.IdleTrimDelay), renderer.trimDue +} + +// trimIdle gives back the packing buffer, which only a present uses: the next +// narrow rectangle makes it again. +func (renderer *cpuWindowRenderer) trimIdle() { + renderer.scratch, renderer.trimDue = nil, false +} + +// releaseUnmapped gives back every picture the next full present makes again, +// while the window is unmapped: the scene's canvas, the composed window and its +// corner shadows, and the packing buffer. Mapping the window again exposes it, +// and the full present that answers paints and composes everything; a present +// before then is a full one too. The label pictures stay, since drawing the +// text again costs more than keeping it. +func (renderer *cpuWindowRenderer) releaseUnmapped() { + renderer.scene.Release() + if renderer.out != nil { + renderer.out.Release() + } + renderer.cornerShadow = [4][]byte{} + renderer.trimIdle() + renderer.full = true +} + func (renderer *cpuWindowRenderer) resize(width, height uint32) error { if width == 0 || height == 0 { return nil @@ -316,8 +369,8 @@ func (renderer *cpuWindowRenderer) resize(width, height uint32) error { } renderer.width, renderer.height = width, height contentWidth, contentHeight := windowframe.ContentSize(width, renderer.margin), windowframe.ContentSize(height, renderer.margin) - if int(contentWidth) != renderer.scene.canvas.Width || int(contentHeight) != renderer.scene.canvas.Height { - if err := renderer.scene.resize(int(contentWidth), int(contentHeight)); err != nil { + if int(contentWidth) != renderer.scene.Canvas.Width || int(contentHeight) != renderer.scene.Canvas.Height { + if err := renderer.scene.Resize(int(contentWidth), int(contentHeight)); err != nil { return err } } @@ -333,7 +386,7 @@ func (renderer *cpuWindowRenderer) resize(width, height uint32) error { } func (renderer *cpuWindowRenderer) setScale(scale float32) error { - if err := renderer.scene.setScale(scale); err != nil { + if err := renderer.scene.SetScale(scale); err != nil { return err } renderer.scale = max(scale, 1) @@ -349,8 +402,8 @@ func (renderer *cpuWindowRenderer) setFrameMargin(margin uint32) error { } renderer.margin = margin contentWidth, contentHeight := windowframe.ContentSize(renderer.width, margin), windowframe.ContentSize(renderer.height, margin) - if int(contentWidth) != renderer.scene.canvas.Width || int(contentHeight) != renderer.scene.canvas.Height { - if err := renderer.scene.resize(int(contentWidth), int(contentHeight)); err != nil { + if int(contentWidth) != renderer.scene.Canvas.Width || int(contentHeight) != renderer.scene.Canvas.Height { + if err := renderer.scene.Resize(int(contentWidth), int(contentHeight)); err != nil { return err } } @@ -368,7 +421,7 @@ func (renderer *cpuWindowRenderer) surfaceSize(width, height uint32) (uint32, ui return width, height } -func (renderer *cpuWindowRenderer) refreshText() error { return renderer.scene.refreshText() } +func (renderer *cpuWindowRenderer) refreshText() error { return renderer.scene.RefreshText() } func (renderer *cpuWindowRenderer) forgetSurfaceCapabilities() {} @@ -383,10 +436,10 @@ func (renderer *cpuWindowRenderer) deviceSize() (uint32, uint32) { } func (renderer *cpuWindowRenderer) firstRectangle() (render.Rectangle, bool) { - if len(renderer.scene.rects) == 0 { + if len(renderer.scene.Rects) == 0 { return render.Rectangle{}, false } - return renderer.scene.rects[0], true + return renderer.scene.Rects[0], true } func (renderer *cpuWindowRenderer) stats() rendererStats { @@ -395,7 +448,7 @@ func (renderer *cpuWindowRenderer) stats() rendererStats { func (renderer *cpuWindowRenderer) close() { if renderer.scene != nil { - renderer.scene.close() + renderer.scene.Close() renderer.scene = nil } if renderer.services != nil { diff --git a/internal/platform/linux/cpu_window_linux_test.go b/internal/platform/linux/cpu_window_linux_test.go index 07ed00e42..9356f7090 100644 --- a/internal/platform/linux/cpu_window_linux_test.go +++ b/internal/platform/linux/cpu_window_linux_test.go @@ -5,6 +5,7 @@ package linux import ( "bytes" "testing" + "time" "unsafe" "github.com/vivaui/viva/internal/platform/windowframe" @@ -46,7 +47,7 @@ func fakePutImageAPI(calls *[]putCall, capture bool) *xcbAPI { func testCPUWindow(canvas *raster.Canvas, calls *[]putCall, capture bool) *cpuWindowRenderer { return &cpuWindowRenderer{ - scene: &softScene{canvas: canvas, scale: 1, clear: scene.Color{Alpha: 1}}, + scene: &softScene{Canvas: canvas, Scale: 1, Clear: scene.Color{Alpha: 1}}, win: &window{api: fakePutImageAPI(calls, capture), connection: 1, id: 2}, gc: 3, depth: 24, @@ -124,12 +125,12 @@ func TestCPUWindowPresentPaintsAndClearsDamage(t *testing.T) { canvas := raster.NewCanvas(8, 6) var calls []putCall renderer := testCPUWindow(canvas, &calls, true) - renderer.scene.rects = []render.Rectangle{{ + renderer.scene.Rects = []render.Rectangle{{ Kind: scene.KindRectangle, Bounds: scene.Rect{Width: 8, Height: 6}, Color: scene.Color{Red: 1, Alpha: 1}, }} - renderer.scene.damageAll() + renderer.scene.DamageAll() if err := renderer.present(); err != nil { t.Fatal(err) @@ -144,7 +145,7 @@ func TestCPUWindowPresentPaintsAndClearsDamage(t *testing.T) { if pixel := calls[0].data[:4]; pixel[0] != 0 || pixel[1] != 0 || pixel[2] != 255 { t.Fatalf("first pixel %v, want red", pixel) } - if renderer.scene.pending() { + if renderer.scene.Pending() { t.Fatal("damage remains after present") } if err := renderer.present(); err != nil { @@ -164,12 +165,12 @@ func TestCPUWindowPresentFullSendsEverything(t *testing.T) { canvas := raster.NewCanvas(8, 6) var calls []putCall renderer := testCPUWindow(canvas, &calls, true) - renderer.scene.rects = []render.Rectangle{{ + renderer.scene.Rects = []render.Rectangle{{ Kind: scene.KindRectangle, Bounds: scene.Rect{Width: 8, Height: 6}, Color: scene.Color{Green: 1, Alpha: 1}, }} - renderer.scene.damageAll() + renderer.scene.DamageAll() if err := renderer.present(); err != nil { t.Fatal(err) } @@ -216,12 +217,12 @@ func BenchmarkCPUWindowPresent(b *testing.B) { canvas := raster.NewCanvas(1280, 800) var calls []putCall renderer := testCPUWindow(canvas, &calls, false) - renderer.scene.rects = []render.Rectangle{ + renderer.scene.Rects = []render.Rectangle{ {Kind: scene.KindRectangle, Bounds: scene.Rect{Width: 1280, Height: 800}, Color: scene.Color{Red: 0.97, Green: 0.97, Blue: 0.98, Alpha: 1}}, {Kind: scene.KindRectangle, Bounds: scene.Rect{Width: 220, Height: 800}, Color: scene.Color{Red: 0.93, Green: 0.94, Blue: 0.96, Alpha: 1}}, } for i := range 24 { - renderer.scene.rects = append(renderer.scene.rects, render.Rectangle{ + renderer.scene.Rects = append(renderer.scene.Rects, render.Rectangle{ Kind: scene.KindRectangle, Bounds: scene.Rect{X: 12, Y: float32(40 + i*28), Width: 196, Height: 24}, Color: scene.Color{Red: 0.1, Green: 0.25, Blue: 0.9, Alpha: 0.12}, Radius: 6, }) @@ -230,7 +231,7 @@ func BenchmarkCPUWindowPresent(b *testing.B) { b.ReportAllocs() b.SetBytes(1280 * 800 * 4) for range b.N { - renderer.scene.damageAll() + renderer.scene.DamageAll() if err := renderer.present(); err != nil { b.Fatal(err) } @@ -241,7 +242,7 @@ func BenchmarkCPUWindowPresent(b *testing.B) { b.ReportAllocs() b.SetBytes(int64((damage.Right - damage.Left) * (damage.Bottom - damage.Top) * 4)) for range b.N { - renderer.scene.damage = damage + renderer.scene.Damage.Set(damage) if err := renderer.present(); err != nil { b.Fatal(err) } @@ -257,7 +258,7 @@ func framedCPUWindow(t *testing.T) (*cpuWindowRenderer, *[]putCall) { var calls []putCall content := raster.NewCanvas(int(windowframe.ContentSize(width, margin)), int(windowframe.ContentSize(height, margin))) renderer := &cpuWindowRenderer{ - scene: &softScene{canvas: content, scale: 1, clear: scene.Color{Alpha: 1}, rects: []render.Rectangle{{ + scene: &softScene{Canvas: content, Scale: 1, Clear: scene.Color{Alpha: 1}, Rects: []render.Rectangle{{ Kind: scene.KindRectangle, Bounds: scene.Rect{Width: float32(content.Width), Height: float32(content.Height)}, Color: scene.Color{Red: 0.2, Green: 0.4, Blue: 0.8, Alpha: 1}, @@ -266,7 +267,7 @@ func framedCPUWindow(t *testing.T) (*cpuWindowRenderer, *[]putCall) { gc: 3, depth: 32, margin: margin, width: width, height: height, scale: 1, full: true, } renderer.out = raster.NewCanvas(width, height) - renderer.scene.damageAll() + renderer.scene.DamageAll() return renderer, &calls } @@ -312,7 +313,7 @@ func TestCPUWindowComposesPartialDamage(t *testing.T) { if err := renderer.present(); err != nil { t.Fatal(err) } - renderer.scene.damage = render.Scissor{Left: 10, Top: 5, Right: 18, Bottom: 11} + renderer.scene.Damage.Set(render.Scissor{Left: 10, Top: 5, Right: 18, Bottom: 11}) if err := renderer.present(); err != nil { t.Fatal(err) } @@ -333,7 +334,7 @@ func TestCPUWindowComposesDamageInARoundedCorner(t *testing.T) { t.Fatal(err) } content := outPixel(renderer.out, 50, 40) - renderer.scene.damage = render.Scissor{Left: 0, Top: 0, Right: 11, Bottom: 11} + renderer.scene.Damage.Set(render.Scissor{Left: 0, Top: 0, Right: 11, Bottom: 11}) if err := renderer.present(); err != nil { t.Fatal(err) } @@ -375,7 +376,7 @@ func BenchmarkCPUWindowFramePresent(b *testing.B) { var calls []putCall content := raster.NewCanvas(int(windowframe.ContentSize(width, margin)), int(windowframe.ContentSize(height, margin))) renderer := &cpuWindowRenderer{ - scene: &softScene{canvas: content, scale: 1, clear: scene.Color{Alpha: 1}, rects: []render.Rectangle{{ + scene: &softScene{Canvas: content, Scale: 1, Clear: scene.Color{Alpha: 1}, Rects: []render.Rectangle{{ Kind: scene.KindRectangle, Bounds: scene.Rect{Width: float32(content.Width), Height: float32(content.Height)}, Color: scene.Color{Red: 0.2, Green: 0.4, Blue: 0.8, Alpha: 1}, @@ -384,13 +385,13 @@ func BenchmarkCPUWindowFramePresent(b *testing.B) { gc: 3, depth: 32, margin: margin, width: width, height: height, scale: 1, full: true, } renderer.out = raster.NewCanvas(width, height) - renderer.scene.damageAll() + renderer.scene.DamageAll() renderer.present() b.Run("full", func(b *testing.B) { b.ReportAllocs() b.SetBytes(width * height * 4) for range b.N { - renderer.scene.damageAll() + renderer.scene.DamageAll() renderer.full = true if err := renderer.present(); err != nil { b.Fatal(err) @@ -403,10 +404,91 @@ func BenchmarkCPUWindowFramePresent(b *testing.B) { b.SetBytes(int64((damage.Right - damage.Left) * (damage.Bottom - damage.Top) * 4)) for range b.N { renderer.full = false - renderer.scene.damage = damage + renderer.scene.Damage.Set(damage) if err := renderer.present(); err != nil { b.Fatal(err) } } }) } + +// Two damaged rectangles far apart are painted and sent as two requests of +// their own pixels, not as the box around both. +func TestCPUWindowSendsDistantDamageSeparately(t *testing.T) { + canvas := raster.NewCanvas(64, 48) + var calls []putCall + renderer := testCPUWindow(canvas, &calls, true) + renderer.scene.Rects = []render.Rectangle{{Kind: scene.KindRectangle, Bounds: scene.Rect{Width: 64, Height: 48}, Color: scene.Color{Red: 1, Alpha: 1}}} + renderer.scene.DamageAll() + if err := renderer.present(); err != nil { + t.Fatal(err) + } + caret := render.Scissor{Left: 4, Top: 30, Right: 6, Bottom: 40} + clock := render.Scissor{Left: 50, Top: 2, Right: 62, Bottom: 8} + renderer.scene.Damage.Add(caret) + renderer.scene.Damage.Add(clock) + if err := renderer.present(); err != nil { + t.Fatal(err) + } + sent := calls[1:] + if len(sent) != 2 { + t.Fatalf("%d requests for two distant changes, want 2: %+v", len(sent), sent) + } + area := 0 + for _, call := range sent { + area += int(call.width) * int(call.height) + } + if want := 2*10 + 12*6; area != want { + t.Fatalf("sent %d pixels for a caret and a clock, want %d", area, want) + } +} + +// The packing buffer a narrow rectangle needed is given back once the window +// has been idle, and nothing more is due after that. +func TestCPUWindowTrimsThePackingBufferWhenIdle(t *testing.T) { + canvas := patternedCanvas(8, 6) + var calls []putCall + renderer := testCPUWindow(canvas, &calls, true) + if _, due := renderer.trimDeadline(); due { + t.Fatal("a renderer that packed nothing has a trim due") + } + before := time.Now() + if err := renderer.push(canvas, render.Scissor{Left: 2, Top: 1, Right: 6, Bottom: 4}); err != nil { + t.Fatal(err) + } + deadline, due := renderer.trimDeadline() + if !due || deadline.Before(before.Add(platform.IdleTrimDelay)) { + t.Fatalf("trim deadline %v (due %v), want %v after the push", deadline, due, platform.IdleTrimDelay) + } + renderer.trimIdle() + if renderer.scratch != nil { + t.Fatal("the packing buffer was kept after the idle trim") + } + if _, due := renderer.trimDeadline(); due { + t.Fatal("a trim is still due after the trim") + } +} + +// An unmapped window gives back its canvases, and the next present paints and +// sends the whole window as it was. +func TestCPUWindowRepaintsAllAfterReleasingWhileUnmapped(t *testing.T) { + renderer, calls := framedCPUWindow(t) + if err := renderer.present(); err != nil { + t.Fatal(err) + } + want := append([]byte(nil), renderer.out.Pix...) + renderer.releaseUnmapped() + if renderer.scene.Canvas.Pix != nil || renderer.out.Pix != nil { + t.Fatal("an unmapped window kept its canvases") + } + if err := renderer.present(); err != nil { + t.Fatal(err) + } + last := (*calls)[len(*calls)-1] + if last.width != 100 || last.height != 80 { + t.Fatalf("the present after the release sent %dx%d, want the whole 100x80 window", last.width, last.height) + } + if !bytes.Equal(renderer.out.Pix, want) { + t.Fatal("the window drawn again differs from the window before the release") + } +} diff --git a/internal/platform/linux/gtk_input_linux.go b/internal/platform/linux/gtk_input_linux.go index d6e0b8926..c4accb5dd 100644 --- a/internal/platform/linux/gtk_input_linux.go +++ b/internal/platform/linux/gtk_input_linux.go @@ -427,6 +427,7 @@ func (w *gtkWindow) setKeyboard(focused bool) { w.ime.setFocused(focused) } if focused { + w.g.windowSetUrgency(w.toplevel, 0) if w.config.OnActivate != nil { w.config.OnActivate() } diff --git a/internal/platform/linux/gtk_library_linux.go b/internal/platform/linux/gtk_library_linux.go index 38ca55ad1..108c918ff 100644 --- a/internal/platform/linux/gtk_library_linux.go +++ b/internal/platform/linux/gtk_library_linux.go @@ -66,6 +66,7 @@ type gtkLibrary struct { windowFullscreen func(window uintptr) windowUnfullscreen func(window uintptr) windowPresent func(window uintptr) + windowSetUrgency func(window uintptr, urgent int32) windowGetPosition func(window uintptr, x, y *int32) windowGetSize func(window uintptr, width, height *int32) windowBeginMove func(window uintptr, button, rootX, rootY int32, timestamp uint32) @@ -378,6 +379,7 @@ func (g *gtkLibrary) bindAll() { b(&g.windowFullscreen, "gtk_window_fullscreen") b(&g.windowUnfullscreen, "gtk_window_unfullscreen") b(&g.windowPresent, "gtk_window_present") + b(&g.windowSetUrgency, "gtk_window_set_urgency_hint") b(&g.windowGetPosition, "gtk_window_get_position") b(&g.windowGetSize, "gtk_window_get_size") b(&g.windowBeginMove, "gtk_window_begin_move_drag") diff --git a/internal/platform/linux/gtk_pieces_linux.go b/internal/platform/linux/gtk_pieces_linux.go index ad64c37d8..1c52e87c7 100644 --- a/internal/platform/linux/gtk_pieces_linux.go +++ b/internal/platform/linux/gtk_pieces_linux.go @@ -55,7 +55,7 @@ func (w *gtkWindow) layoutPieces() { unit, ratio := float64(w.unit), float64(w.ratio) boxes, covers := w.pieceBoxes[:0], w.coverBoxes[:0] for i, view := range w.snapped { - for _, o := range w.scene.overlays(i) { + for _, o := range w.scene.Overlays(i) { boxes = addBox(boxes, box{ int32(math.Floor(float64(o.Left) / unit)), int32(math.Floor(float64(o.Top) / unit)), int32(math.Ceil(float64(o.Right) / unit)), int32(math.Ceil(float64(o.Bottom) / unit)), diff --git a/internal/platform/linux/gtk_wayland_linux.go b/internal/platform/linux/gtk_wayland_linux.go index 820c446b3..090b2a5bf 100644 --- a/internal/platform/linux/gtk_wayland_linux.go +++ b/internal/platform/linux/gtk_wayland_linux.go @@ -12,6 +12,7 @@ import ( "github.com/ebitengine/purego" "github.com/vivaui/viva/internal/input" "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/internal/raster" "github.com/vivaui/viva/internal/render" ) @@ -420,7 +421,7 @@ func (s *waylandSurface) attach() error { } s.viewportWidth, s.viewportHeight, s.regionWidth, s.regionHeight = 0, 0, 0, 0 s.positioned(s.offsetX, s.offsetY) - s.w.scene.damageAll() + s.w.scene.DamageAll() s.resized(w) // A new subsurface takes effect with the next commit of its parent: make GTK draw once more. w.g.widgetQueueDraw(w.toplevel) @@ -509,10 +510,10 @@ func (s *waylandSurface) updateRegions(w *gtkWindow, width, height int32) { // draws over the page is: the pointer belongs to the page there and to Viva over it. holes := s.holes[:0] scale := float64(w.scale) - for i, view := range w.scene.views { + for i, view := range w.scene.Views { b := view.Bounds holes = append(holes, int32(math.Floor(float64(b.X))), int32(math.Floor(float64(b.Y))), int32(math.Ceil(float64(b.X+b.Width))), int32(math.Ceil(float64(b.Y+b.Height)))) - for _, o := range w.scene.overlays(i) { + for _, o := range w.scene.Overlays(i) { holes = append(holes, -1, int32(math.Floor(float64(o.Left)/scale)), int32(math.Floor(float64(o.Top)/scale)), int32(math.Ceil(float64(o.Right)/scale)), int32(math.Ceil(float64(o.Bottom)/scale))) } for _, c := range view.Covers { @@ -575,7 +576,7 @@ type wlBuffer struct { stride int busy, dead bool // pending is what changed in the canvas since the buffer was last filled. - pending render.Scissor + pending raster.Region } const wlShmArgb8888 = 0 @@ -598,7 +599,8 @@ func (s *waylandSurface) newBuffer(width, height int) *wlBuffer { return nil } pool := c.create(s.s.shm, 0, c.core["wl_shm_pool"], c.version(s.s.shm), 0, wlArg(fd), wlArg(uint32(size))) - b := &wlBuffer{s: s, mem: mem, width: width, height: height, stride: stride, pending: render.Scissor{Right: width, Bottom: height}} + b := &wlBuffer{s: s, mem: mem, width: width, height: height, stride: stride} + b.pending.Set(render.Scissor{Right: width, Bottom: height}) b.buffer = c.create(pool, 0, c.core["wl_buffer"], c.version(pool), 0, 0, wlArg(uint32(width)), wlArg(uint32(height)), wlArg(uint32(stride)), wlShmArgb8888) c.destroy(pool, 1) b.id = wlRegister(b) @@ -664,13 +666,12 @@ func (s *waylandSurface) present(w *gtkWindow) { if s.child == 0 || w.scene == nil { return } - canvas := w.scene.canvas - damage := w.scene.paint() + canvas := w.scene.Canvas + damage := w.scene.Paint() c := s.s.c - hasDamage := damage.Right > damage.Left && damage.Bottom > damage.Top for _, b := range s.buffers { - if hasDamage { - b.pending = unionScissor(b.pending, damage) + for _, box := range damage { + b.pending.Add(box) } } b := s.freeBuffer(canvas.Width, canvas.Height) @@ -679,15 +680,19 @@ func (s *waylandSurface) present(w *gtkWindow) { s.deferred = true return } - area := intersectScissor(b.pending, canvas.Bounds()) - if area.Right <= area.Left || area.Bottom <= area.Top { + // The buffer is given the frames it missed since it was last filled, as well + // as this one's damage, and the compositor is told those rectangles. + area := b.pending + area.Limit(canvas.Bounds()) + if area.Empty() { return // the buffer already holds the canvas as it is } - for y := area.Top; y < area.Bottom; y++ { - copy(b.mem[y*b.stride+area.Left*4:y*b.stride+area.Right*4], canvas.Pix[y*canvas.Stride+area.Left*4:y*canvas.Stride+area.Right*4]) + for _, box := range area.Rects() { + for y := box.Top; y < box.Bottom; y++ { + copy(b.mem[y*b.stride+box.Left*4:y*b.stride+box.Right*4], canvas.Pix[y*canvas.Stride+box.Left*4:y*canvas.Stride+box.Right*4]) + } } - b.pending = render.Scissor{} - damage = area + b.pending.Reset() if c.version(s.child) < 4 && (s.viewportWidth <= 0 || s.viewportHeight <= 0 || canvas.Width <= 0 || canvas.Height <= 0) { // updateRegions sets the viewport and repeats the frame later. Until then, skip the frame: the // buffer copied above is up to date, and the other buffers keep the damage still to be shown. @@ -695,35 +700,23 @@ func (s *waylandSurface) present(w *gtkWindow) { } b.busy = true c.request(s.child, 1, wlArg(b.buffer), 0, 0) // attach - if c.version(s.child) >= 4 { - c.request(s.child, 9, wlArg(uint32(damage.Left)), wlArg(uint32(damage.Top)), wlArg(uint32(damage.Right-damage.Left)), wlArg(uint32(damage.Bottom-damage.Top))) // damage_buffer - } else { - // GDK can create a v3 surface. Damage is then in logical surface coordinates, - // after the viewport has mapped the canvas to the window's size. - left := int32(math.Floor(float64(damage.Left) * float64(s.viewportWidth) / float64(canvas.Width))) - top := int32(math.Floor(float64(damage.Top) * float64(s.viewportHeight) / float64(canvas.Height))) - right := int32(math.Ceil(float64(damage.Right) * float64(s.viewportWidth) / float64(canvas.Width))) - bottom := int32(math.Ceil(float64(damage.Bottom) * float64(s.viewportHeight) / float64(canvas.Height))) - c.request(s.child, 2, wlArg(uint32(left)), wlArg(uint32(top)), wlArg(uint32(right-left)), wlArg(uint32(bottom-top))) // damage + for _, damage := range area.Rects() { + if c.version(s.child) >= 4 { + c.request(s.child, 9, wlArg(uint32(damage.Left)), wlArg(uint32(damage.Top)), wlArg(uint32(damage.Right-damage.Left)), wlArg(uint32(damage.Bottom-damage.Top))) // damage_buffer + } else { + // GDK can create a v3 surface. Damage is then in logical surface coordinates, + // after the viewport has mapped the canvas to the window's size. + left := int32(math.Floor(float64(damage.Left) * float64(s.viewportWidth) / float64(canvas.Width))) + top := int32(math.Floor(float64(damage.Top) * float64(s.viewportHeight) / float64(canvas.Height))) + right := int32(math.Ceil(float64(damage.Right) * float64(s.viewportWidth) / float64(canvas.Width))) + bottom := int32(math.Ceil(float64(damage.Bottom) * float64(s.viewportHeight) / float64(canvas.Height))) + c.request(s.child, 2, wlArg(uint32(left)), wlArg(uint32(top)), wlArg(uint32(right-left)), wlArg(uint32(bottom-top))) // damage + } } c.request(s.child, 6) // commit c.flush(s.s.display) } -func unionScissor(a, b render.Scissor) render.Scissor { - if a.Right <= a.Left || a.Bottom <= a.Top { - return b - } - if b.Right <= b.Left || b.Bottom <= b.Top { - return a - } - return render.Scissor{Left: min(a.Left, b.Left), Top: min(a.Top, b.Top), Right: max(a.Right, b.Right), Bottom: max(a.Bottom, b.Bottom)} -} - -func intersectScissor(a, b render.Scissor) render.Scissor { - return render.Scissor{Left: max(a.Left, b.Left), Top: max(a.Top, b.Top), Right: min(a.Right, b.Right), Bottom: min(a.Bottom, b.Bottom)} -} - // wp_cursor_shape_device_v1.shape for the cursors the application asks for, in app.Cursor order. var cursorShapes = [...]uint32{1 /* default */, 9 /* text */, 4 /* pointer */, 8 /* crosshair */, 6 /* wait */, 26 /* ew-resize */, 27 /* ns-resize */, 29 /* nwse-resize */, 28 /* nesw-resize */, 15 /* not-allowed */, 5 /* grabbing */} diff --git a/internal/platform/linux/gtk_wayland_regions_native_linux_test.go b/internal/platform/linux/gtk_wayland_regions_native_linux_test.go index cf573439d..5388d1967 100644 --- a/internal/platform/linux/gtk_wayland_regions_native_linux_test.go +++ b/internal/platform/linux/gtk_wayland_regions_native_linux_test.go @@ -71,15 +71,15 @@ func gtkRegionSnapshot(ctx context.Context, app *gtkApplication, probe *gtkRegio resizeCalls: probe.resizeCalls, resizeEdge: probe.resizeEdge, scale: w.scale, - canvasWidth: w.scene.canvas.Width, + canvasWidth: w.scene.Canvas.Width, viewportWidth: int(w.wl.viewportWidth), - views: len(w.scene.views), + views: len(w.scene.Views), } device := w.g.gdkSeatPointer(w.g.gdkDisplaySeat(w.g.gdkDisplayDefault())) state.gdkPointer = w.g.gdkDeviceWindowAt(device, &state.gdkX, &state.gdkY) state.gtkArea = w.g.widgetGetWindow(w.area) if state.views > 0 { - state.overlays = len(w.scene.overlays(0)) + state.overlays = len(w.scene.Overlays(0)) } if probe.getFocus != nil { state.gtkFocus = probe.getFocus(w.toplevel) diff --git a/internal/platform/linux/gtk_web_linux.go b/internal/platform/linux/gtk_web_linux.go index 152b2327f..4e041b27c 100644 --- a/internal/platform/linux/gtk_web_linux.go +++ b/internal/platform/linux/gtk_web_linux.go @@ -1231,7 +1231,7 @@ func (w *gtkWindow) layoutViews() { }}) w.places = append(w.places, viewPlace{int32(left), int32(top), int32(right - left), int32(bottom - top)}) } - w.scene.setViews(w.snapped) + w.scene.SetViews(w.snapped) for _, v := range w.views { at, found := viewPlace{}, false for i := range w.snapped { diff --git a/internal/platform/linux/gtk_window_linux.go b/internal/platform/linux/gtk_window_linux.go index da0714331..49c230c53 100644 --- a/internal/platform/linux/gtk_window_linux.go +++ b/internal/platform/linux/gtk_window_linux.go @@ -514,7 +514,7 @@ func (w *gtkWindow) cleanup() { } w.releaseSurface() if w.scene != nil { - w.scene.close() + w.scene.Close() w.scene = nil } if w.text != nil { @@ -630,11 +630,11 @@ func (w *gtkWindow) resize() { deviceHeight = max(int(math.Round(float64(w.height*w.ratio)))*int(w.unit), 1) } w.releaseSurface() - if err := w.scene.setScale(w.scale); err != nil { + if err := w.scene.SetScale(w.scale); err != nil { w.app.fail(err) return } - if err := w.scene.resize(deviceWidth, deviceHeight); err != nil { + if err := w.scene.Resize(deviceWidth, deviceHeight); err != nil { w.app.fail(err) return } @@ -698,12 +698,12 @@ func (w *gtkWindow) present(frame platform.Frame, err error) { // apply puts a frame the text layer has merged into the scene, and on to the screen. func (w *gtkWindow) apply(frame platform.Frame) { - changed, err := w.scene.apply(frame) + changed, err := w.scene.Apply(frame) if err != nil { w.app.fail(err) return } - if len(w.scene.views) > 0 { + if len(w.scene.Views) > 0 { // What Viva draws over a page decides where the pointer is the page's. w.updateOverlayRegions() } @@ -714,19 +714,20 @@ func (w *gtkWindow) apply(frame platform.Frame) { // queuePaint asks for the scene's pending damage to reach the screen. func (w *gtkWindow) queuePaint() { - if w.closed || !w.scene.pending() { + if w.closed || !w.scene.Pending() { return } if w.wl != nil { w.wl.present(w) return } - d := w.scene.damage unit := int(w.unit) - left, top := d.Left/unit, d.Top/unit - w.g.widgetQueueDrawArea(w.area, int32(left), int32(top), int32((d.Right+unit-1)/unit-left), int32((d.Bottom+unit-1)/unit-top)) - if len(w.pieces) > 0 { - w.invalidatePieces(int32(left), int32(top), int32((d.Right+unit-1)/unit), int32((d.Bottom+unit-1)/unit)) + for _, d := range w.scene.Damage.Rects() { + left, top := d.Left/unit, d.Top/unit + w.g.widgetQueueDrawArea(w.area, int32(left), int32(top), int32((d.Right+unit-1)/unit-left), int32((d.Bottom+unit-1)/unit-top)) + if len(w.pieces) > 0 { + w.invalidatePieces(int32(left), int32(top), int32((d.Right+unit-1)/unit), int32((d.Bottom+unit-1)/unit)) + } } } @@ -736,7 +737,7 @@ func (w *gtkWindow) draw(widget, cr uintptr) { if w.wl != nil || w.closed { return } - w.scene.paint() + w.scene.Paint() surface := w.canvasSurface() if surface == 0 { return @@ -763,7 +764,7 @@ func (w *gtkWindow) canvasSurface() uintptr { if w.cairoSurface != 0 { return w.cairoSurface } - canvas := w.scene.canvas + canvas := w.scene.Canvas surface := w.g.cairoSurfaceForData(&canvas.Pix[0], cairoFormatARGB32, int32(canvas.Width), int32(canvas.Height), int32(canvas.Stride)) if surface == 0 { return 0 @@ -833,7 +834,7 @@ func (w *gtkWindow) refreshText() { if w.closed || w.scene == nil { return } - if err := w.scene.refreshText(); err != nil { + if err := w.scene.RefreshText(); err != nil { w.app.fail(err) return } diff --git a/internal/platform/linux/interface_font_linux_test.go b/internal/platform/linux/interface_font_linux_test.go index 6d2d2660f..24601f0fe 100644 --- a/internal/platform/linux/interface_font_linux_test.go +++ b/internal/platform/linux/interface_font_linux_test.go @@ -47,16 +47,16 @@ func TestASoftSceneDrawsALabelAgainWhenTheInterfaceFamilyChanges(t *testing.T) { if err != nil { t.Fatal(err) } - live.paint() - before := bytes.Clone(live.canvas.Pix) + live.Paint() + before := bytes.Clone(live.Canvas.Pix) engine.SetFontFamily(family) - changed, err := live.apply(platform.Frame{TextLabels: []platform.TextLabel{interfaceFontLabel(engine.FontGeneration())}}) + changed, err := live.Apply(platform.Frame{TextLabels: []platform.TextLabel{interfaceFontLabel(engine.FontGeneration())}}) if err != nil || !changed { t.Fatalf("a frame with the same text and a new font generation: changed %v, err %v", changed, err) } - live.paint() - if bytes.Equal(before, live.canvas.Pix) { + live.Paint() + if bytes.Equal(before, live.Canvas.Pix) { t.Fatalf("the canvas is the same in %q as in the desktop's font: the label kept its old picture", family) } } diff --git a/internal/platform/linux/portal_directory_linux_test.go b/internal/platform/linux/portal_directory_linux_test.go index 60f6a6476..fc3616f57 100644 --- a/internal/platform/linux/portal_directory_linux_test.go +++ b/internal/platform/linux/portal_directory_linux_test.go @@ -9,17 +9,22 @@ import ( func TestDirectoryPortalRequestCarriesInitialDirectory(t *testing.T) { for _, directory := range []string{"/tmp/My projects", "/tmp/项目/"} { t.Run(directory, func(t *testing.T) { - request := directoryPortalRequest(OpenDirectoryOptions{Title: "Choose folder", InitialDirectory: directory}, "x11:2a") + request := directoryPortalRequest(OpenDirectoryOptions{Title: "Choose folder", InitialDirectory: directory}, true, "x11:2a") decoder := dbus.NewDecoder(encodeFileRequest(request, "tok")) if parent, title := decoder.String(), decoder.String(); parent != "x11:2a" || title != "Choose folder" { t.Fatalf("parent %q title %q", parent, title) } - seenFolder, seenDirectory := false, false + seenFolder, seenDirectory, seenMultiple := false, false, false end := decoder.ArrayLength(8) for decoder.Pos() < end && decoder.Err() == nil { decoder.Align(8) key, signature := decoder.String(), decoder.Signature() switch key { + case "multiple": + if signature != "b" || !decoder.Bool() { + t.Fatal("multiple option is wrong") + } + seenMultiple = true case "directory": if signature != "b" || !decoder.Bool() { t.Fatal("directory option is wrong") @@ -42,8 +47,8 @@ func TestDirectoryPortalRequestCarriesInitialDirectory(t *testing.T) { decoder.Skip(signature) } } - if decoder.Err() != nil || !decoder.Done() || !seenFolder || !seenDirectory { - t.Fatalf("request: error %v, done %v, folder %v, directory %v", decoder.Err(), decoder.Done(), seenFolder, seenDirectory) + if decoder.Err() != nil || !decoder.Done() || !seenFolder || !seenDirectory || !seenMultiple { + t.Fatalf("request: error %v, done %v, folder %v, directory %v, multiple %v", decoder.Err(), decoder.Done(), seenFolder, seenDirectory, seenMultiple) } }) } diff --git a/internal/platform/linux/soft_scene_linux.go b/internal/platform/linux/soft_scene_linux.go index 4fb46138b..92627783b 100644 --- a/internal/platform/linux/soft_scene_linux.go +++ b/internal/platform/linux/soft_scene_linux.go @@ -3,366 +3,37 @@ package linux import ( - "fmt" - "math" - - "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/internal/platform" - "github.com/vivaui/viva/internal/raster" "github.com/vivaui/viva/internal/render" "github.com/vivaui/viva/internal/scene" + "github.com/vivaui/viva/internal/softscene" ) -// softScene is the retained scene of a window drawn by the CPU (ADR 0064): the rectangle -// instances and text labels the application sent, the picture of each label, and the part of the -// canvas that changed since it was last painted. A presenter (the GTK shell's drawing area, a -// Wayland surface) takes the canvas and the damaged region from it; nothing here depends on a -// display server. -// -// A frame names the instances that changed, so the damage is the pixels those covered before and -// cover now (raster.Box), and a label that is the same as the one in its slot keeps its picture -// and costs nothing. Typing in a text field repaints the field. -type softScene struct { - services *textServices - canvas *raster.Canvas - drawer raster.Rasterizer - scale float32 - clear scene.Color - - rects []render.Rectangle - labels []softLabel - // views are the places native views fill; holes are the same in device pixels. - views []platform.NativeView - holes []raster.Hole - drawn []raster.Label // the labels painted this time, in slot order; scratch - damage render.Scissor -} - -// softLabel is one slot of the label list. -type softLabel struct { - label platform.TextLabel - runs []gfx.TextRun // backs label.Runs, which is only valid for the call that carried it - // image is the label's picture at imageScale, if it has been drawn. - image labelImage - imageScale float32 - hasImage bool - // placed is the picture on the canvas, visible says it draws anything. - placed raster.Label - visible bool -} +// softScene is the retained scene of a window drawn by the CPU (ADR 0064), with +// the text drawn by the platform's Pango: shared with the other platforms whose +// windows are drawn by the CPU rasterizer. +type softScene = softscene.Scene -// newSoftScene makes a scene for a canvas of the given device size. rectangles and labels are the -// window's first content. +// newSoftScene makes a scene for a canvas of the given device size. rectangles +// and labels are the window's first content. func newSoftScene(services *textServices, width, height int, scale float32, clear platform.Color, rectangles []render.Rectangle, labels []platform.TextLabel) (*softScene, error) { - if width < 1 || height < 1 { - return nil, fmt.Errorf("linux: invalid canvas size %dx%d", width, height) - } - s := &softScene{ - services: services, - canvas: raster.NewCanvas(width, height), - scale: max(scale, 1), - clear: scene.Color{Red: float32(clear.Red), Green: float32(clear.Green), Blue: float32(clear.Blue), Alpha: float32(clear.Alpha)}, - } - s.rects = append(s.rects, rectangles...) - if err := s.setLabels(labels); err != nil { - return nil, err - } - s.damageAll() - return s, nil -} - -func (s *softScene) damageAll() { s.damage = s.canvas.Bounds() } - -// addDamage adds a box of device pixels to what must be painted. -func (s *softScene) addDamage(box render.Scissor) { - bounds := s.canvas.Bounds() - box = render.Scissor{Left: max(box.Left, bounds.Left), Top: max(box.Top, bounds.Top), Right: min(box.Right, bounds.Right), Bottom: min(box.Bottom, bounds.Bottom)} - if box.Right <= box.Left || box.Bottom <= box.Top { - return - } - if s.damage.Right <= s.damage.Left || s.damage.Bottom <= s.damage.Top { - s.damage = box - return - } - s.damage = render.Scissor{Left: min(s.damage.Left, box.Left), Top: min(s.damage.Top, box.Top), Right: max(s.damage.Right, box.Right), Bottom: max(s.damage.Bottom, box.Bottom)} -} - -// apply takes a frame into the scene and reports whether anything on the canvas changed. -func (s *softScene) apply(frame platform.Frame) (bool, error) { - if frame.Update.Empty() && frame.TextLabels == nil && frame.NativeViews == nil { - return false, nil - } - if !frame.Update.Empty() { - if err := s.applyRectangles(frame); err != nil { - return false, err - } - } - if frame.NativeViews != nil { - s.setViews(frame.NativeViews) - } - if frame.TextLabels != nil { - if err := platform.ValidateTextLabels(frame.TextLabels); err != nil { - return false, err - } - if err := s.setLabels(frame.TextLabels); err != nil { - return false, err - } - } - return s.pending(), nil -} - -func (s *softScene) pending() bool { - return s.damage.Right > s.damage.Left && s.damage.Bottom > s.damage.Top -} - -func (s *softScene) applyRectangles(frame platform.Frame) error { - if err := render.ValidateRectangles(frame.Rectangles); err != nil { - return err - } - update := frame.Update - if update.First < 0 || update.Count < 0 || update.First > len(frame.Rectangles) || update.Count > len(frame.Rectangles)-update.First { - return fmt.Errorf("linux: invalid rectangle update") - } - if update.Rebuild { - s.rects = append(s.rects[:0], frame.Rectangles...) - s.damageAll() - return nil - } - if len(frame.Rectangles) < len(s.rects) { - if !update.Shrink || update.First > len(frame.Rectangles) || update.First+update.Count != len(frame.Rectangles) { - return fmt.Errorf("linux: rectangle count shrank outside a suffix update") - } - for index := len(frame.Rectangles); index < len(s.rects); index++ { - s.addDamage(raster.Box(&s.rects[index], s.scale)) - } - s.rects = s.rects[:len(frame.Rectangles)] - } - if len(frame.Rectangles) > len(s.rects) { - if update.First > len(s.rects) || update.First+update.Count != len(frame.Rectangles) { - return fmt.Errorf("linux: rectangle count grew outside a suffix update") - } - } - for i := update.First; i < update.First+update.Count; i++ { - if i < len(s.rects) { - s.addDamage(raster.Box(&s.rects[i], s.scale)) - } - s.addDamage(raster.Box(&frame.Rectangles[i], s.scale)) - } - if len(frame.Rectangles) > len(s.rects) { - s.rects = append(s.rects, frame.Rectangles[len(s.rects):]...) - } - copy(s.rects[update.First:update.First+update.Count], frame.Rectangles[update.First:update.First+update.Count]) - return nil -} - -// setLabels replaces the label list. A slot whose label is the same as before keeps its picture. -func (s *softScene) setLabels(labels []platform.TextLabel) error { - for i := len(labels); i < len(s.labels); i++ { - if s.labels[i].visible { - s.addDamage(labelBox(&s.labels[i].placed)) - } - } - if len(labels) > cap(s.labels) { - s.labels = append(s.labels[:cap(s.labels)], make([]softLabel, len(labels)-cap(s.labels))...) - } - s.labels = s.labels[:len(labels)] - for i := range labels { - if err := s.setLabel(&s.labels[i], labels[i]); err != nil { - return fmt.Errorf("linux: label %d: %w", i, err) - } - } - return nil -} - -func (s *softScene) setLabel(slot *softLabel, next platform.TextLabel) error { - previous := slot.placed - wasVisible := slot.visible - redraw := !slot.hasImage || slot.imageScale != s.scale || labelContentChanged(slot.label, next) || (len(next.Bitmap) > 0 && bitmapShownChanged(slot.label, next, s.scale)) - var have labelImage - if !redraw && slot.image.wide { - // A line wider than a texture holds is drawn again when its picture, a window of - // it, no longer holds the part of it the canvas shows. - have = slot.image - skip, width, _, _, ok := textWindow(next, s.scale, s.canvas.Width, have) - redraw = !ok || skip != have.skip || width != have.width - } - slot.runs = append(slot.runs[:0], next.Runs...) - slot.label = next - slot.label.Runs = slot.runs - if redraw { - image, ok, err := rasterizeLabel(s.services, slot.label, s.scale, s.canvas.Width, have, s.clear.Alpha >= 1) - if err != nil { - return err - } - slot.image, slot.imageScale, slot.hasImage = image, s.scale, ok - if !ok { - slot.image = labelImage{} - } - } - slot.visible = false - if slot.hasImage && slot.image.width > 0 { - slot.placed, slot.visible = placeLabel(slot.label, s.scale, slot.image, s.canvas.Width, s.canvas.Height) - } - switch { - case !wasVisible && !slot.visible: - case redraw || wasVisible != slot.visible || slot.placed.X != previous.X || slot.placed.Y != previous.Y || - slot.placed.Layer != previous.Layer || slot.placed.Clipped != previous.Clipped || slot.placed.Clip != previous.Clip: - if wasVisible { - s.addDamage(labelBox(&previous)) - } - if slot.visible { - s.addDamage(labelBox(&slot.placed)) - } - } - return nil -} - -// labelBox is the device pixels a placed label may paint. -func labelBox(l *raster.Label) render.Scissor { - box := render.Scissor{Left: l.X, Top: l.Y, Right: l.X + l.Width, Bottom: l.Y + l.Height} - if l.Clipped { - box = render.Scissor{Left: max(box.Left, l.Clip.Left), Top: max(box.Top, l.Clip.Top), Right: min(box.Right, l.Clip.Right), Bottom: min(box.Bottom, l.Clip.Bottom)} - } - return box -} - -// labelContentChanged reports whether the two labels need different pictures. Where a label is -// and how it is clipped are not in it: scrolling text costs no layout. -func labelContentChanged(previous, next platform.TextLabel) bool { - return previous.Value != next.Value || previous.Width != next.Width || previous.Height != next.Height || previous.FontSize != next.FontSize || previous.Italic != next.Italic || - previous.Weight != next.Weight || previous.Color != next.Color || previous.FontGeneration != next.FontGeneration || previous.Mono != next.Mono || previous.MonoFace != next.MonoFace || previous.CellWidth != next.CellWidth || - previous.Baseline != next.Baseline || - !platform.SameTextRuns(previous.Runs, next.Runs) || previous.BitmapID != next.BitmapID || previous.BitmapVersion != next.BitmapVersion || - previous.BitmapWidth != next.BitmapWidth || previous.BitmapHeight != next.BitmapHeight || previous.BitmapStride != next.BitmapStride || - !platform.SameBitmapBytes(previous.Bitmap, next.Bitmap) -} - -// bitmapShownChanged reports whether an image covers a different number of device pixels than it -// did, which happens when it moves across a pixel boundary and is smaller than its bitmap. -func bitmapShownChanged(previous, next platform.TextLabel, scale float32) bool { - return platform.DeviceExtent(previous.X, previous.Width, scale) != platform.DeviceExtent(next.X, next.Width, scale) || - platform.DeviceExtent(previous.Y, previous.Height, scale) != platform.DeviceExtent(next.Y, next.Height, scale) -} - -// resize gives the scene a canvas of another device size. Everything is painted again. -func (s *softScene) resize(width, height int) error { - if width < 1 || height < 1 { - return fmt.Errorf("linux: invalid canvas size %dx%d", width, height) - } - if width == s.canvas.Width && height == s.canvas.Height { - return nil - } - s.canvas.Resize(width, height) - return s.replace() -} - -// setScale draws everything at another scale. -func (s *softScene) setScale(scale float32) error { - scale = max(scale, 1) - if scale == s.scale { - return nil - } - s.scale = scale - return s.replace() -} - -// setViews replaces the places of the native views. The pixels under a view and under its old place -// are painted again. -func (s *softScene) setViews(views []platform.NativeView) { - for _, hole := range s.holes { - s.addDamage(hole.Box) - } - s.views = append(s.views[:0], views...) - s.placeHoles() -} - -// placeHoles works out the holes in device pixels, on the grid the views are placed on. -func (s *softScene) placeHoles() { - s.holes = s.holes[:0] - for _, view := range s.views { - b := view.Bounds - box := render.Scissor{ - Left: int(math.Round(float64(b.X * s.scale))), Top: int(math.Round(float64(b.Y * s.scale))), - Right: int(math.Round(float64((b.X + b.Width) * s.scale))), Bottom: int(math.Round(float64((b.Y + b.Height) * s.scale))), - } - s.holes = append(s.holes, raster.Hole{Box: box, Layer: view.Layer}) - s.addDamage(box) - } -} - -// overlays returns the parts of the view that something on a higher layer covers, in device pixels: -// where the pointer belongs to Viva although a page is under it. -func (s *softScene) overlays(index int) []render.Scissor { - if index < 0 || index >= len(s.holes) { - return nil - } - hole := s.holes[index] - var covered []render.Scissor - for i := range s.rects { - r := &s.rects[i] - if r.Layer <= hole.Layer || r.Kind == scene.KindShadow || r.Color.Alpha <= 0 { - continue - } - box := render.Scissor{Left: max(hole.Box.Left, 0), Top: hole.Box.Top, Right: hole.Box.Right, Bottom: hole.Box.Bottom} - if shown := raster.Box(r, s.scale); shown.Right > shown.Left && shown.Bottom > shown.Top { - box = render.Scissor{Left: max(box.Left, shown.Left), Top: max(box.Top, shown.Top), Right: min(box.Right, shown.Right), Bottom: min(box.Bottom, shown.Bottom)} - if box.Right > box.Left && box.Bottom > box.Top { - covered = append(covered, box) - } - } - } - for i := range s.labels { - l := &s.labels[i] - if l.visible && l.placed.Layer > hole.Layer { - box := labelBox(&l.placed) - box = render.Scissor{Left: max(box.Left, hole.Box.Left), Top: max(box.Top, hole.Box.Top), Right: min(box.Right, hole.Box.Right), Bottom: min(box.Bottom, hole.Box.Bottom)} - if box.Right > box.Left && box.Bottom > box.Top { - covered = append(covered, box) - } - } - } - return covered + return softscene.New(linuxTextRasterizer{services}, width, height, scale, + scene.Color{Red: float32(clear.Red), Green: float32(clear.Green), Blue: float32(clear.Blue), Alpha: float32(clear.Alpha)}, + rectangles, labels) } -// refreshText draws every label again, after the fonts changed. -func (s *softScene) refreshText() error { - for i := range s.labels { - s.labels[i].hasImage = false - } - return s.replace() -} +// linuxTextRasterizer gives the shared scene the glyphs Pango draws. +type linuxTextRasterizer struct{ services *textServices } -// replace places every label again and paints all of the canvas. -func (s *softScene) replace() error { - for i := range s.labels { - if err := s.setLabel(&s.labels[i], s.labels[i].label); err != nil { - return fmt.Errorf("linux: label %d: %w", i, err) - } - } - s.placeHoles() - s.damageAll() - return nil +func (r linuxTextRasterizer) Rasterize(label platform.TextLabel, scale float32, skip, width, height int, allowLCD bool) ([]byte, bool, error) { + return r.services.rasterizeWindow(label, scale, skip, width, height, allowLCD) } -// paint draws what changed into the canvas and returns the region it drew, empty when nothing had -// changed. -func (s *softScene) paint() render.Scissor { - if !s.pending() { - return render.Scissor{} - } - damage := s.damage - s.drawn = s.drawn[:0] - for i := range s.labels { - if s.labels[i].visible { - s.drawn = append(s.drawn, s.labels[i].placed) - } +func (r linuxTextRasterizer) Spans() []softscene.Span { + spans := r.services.spans + out := make([]softscene.Span, len(spans)) + for index, span := range spans { + out[index] = softscene.Span{Left: span.Left, Right: span.Right, Color: span.Color} } - s.drawer.Draw(s.canvas, raster.Params{Scale: s.scale, Clear: s.clear, Holes: s.holes, Damage: damage}, s.rects, s.drawn) - s.damage = render.Scissor{} - return damage -} - -// close releases the pictures. -func (s *softScene) close() { - s.canvas, s.rects, s.labels, s.drawn = nil, nil, nil, nil + return out } diff --git a/internal/platform/linux/soft_scene_linux_test.go b/internal/platform/linux/soft_scene_linux_test.go index 098156018..a04b4d5ba 100644 --- a/internal/platform/linux/soft_scene_linux_test.go +++ b/internal/platform/linux/soft_scene_linux_test.go @@ -36,7 +36,7 @@ func TestSoftSceneFramesPaintWhatAFullPaintWould(t *testing.T) { if err != nil { t.Fatal(err) } - live.paint() + live.Paint() wantRects, wantLabels := append([]render.Rectangle(nil), rects...), append([]platform.TextLabel(nil), labels...) step := func(name string, frame platform.Frame) { t.Helper() @@ -46,16 +46,16 @@ func TestSoftSceneFramesPaintWhatAFullPaintWould(t *testing.T) { if frame.TextLabels != nil { wantLabels = append(wantLabels[:0], frame.TextLabels...) } - if _, err := live.apply(frame); err != nil { + if _, err := live.Apply(frame); err != nil { t.Fatalf("%s: %v", name, err) } - live.paint() - whole, err := newSoftScene(services, live.canvas.Width, live.canvas.Height, scale, clear, wantRects, wantLabels) + live.Paint() + whole, err := newSoftScene(services, live.Canvas.Width, live.Canvas.Height, scale, clear, wantRects, wantLabels) if err != nil { t.Fatal(err) } - whole.paint() - if !bytes.Equal(live.canvas.Pix, whole.canvas.Pix) { + whole.Paint() + if !bytes.Equal(live.Canvas.Pix, whole.Canvas.Pix) { t.Fatalf("scale %g, after %s: canvas differs from a full paint", scale, name) } } @@ -87,18 +87,22 @@ func TestSoftSceneTypingPaintsOnlyTheLine(t *testing.T) { if err != nil { t.Fatal(err) } - if got := live.paint(); got != live.canvas.Bounds() { + if got := live.Paint(); len(got) != 1 || got[0] != live.Canvas.Bounds() { t.Fatalf("first paint covers %+v, want the whole canvas", got) } - if got := live.paint(); got.Right > got.Left { + if got := live.Paint(); len(got) != 0 { t.Fatalf("a scene with nothing new painted %+v", got) } labels[0].Value = "Hello!" - changed, err := live.apply(platform.Frame{TextLabels: labels}) + changed, err := live.Apply(platform.Frame{TextLabels: labels}) if err != nil || !changed { t.Fatalf("apply = %v, %v", changed, err) } - got := live.paint() + painted := live.Paint() + if len(painted) != 1 { + t.Fatalf("typing repainted %+v, want one rectangle", painted) + } + got := painted[0] if got.Top > 6 || got.Bottom < 26 || got.Bottom > 40 || got.Left > 8 { t.Fatalf("typing repainted %+v, want about the first label's 8,6 70x20", got) } @@ -115,26 +119,26 @@ func TestSoftSceneMagnifiedBitmapPanRepaintsTheVisibleRegion(t *testing.T) { if err != nil { t.Fatal(err) } - scene.paint() - probe := 6*scene.canvas.Stride + 8*4 - if got := scene.canvas.Pix[probe : probe+4]; !bytes.Equal(got, []byte{0, 128, 127, 255}) && !bytes.Equal(got, []byte{0, 128, 128, 255}) { + scene.Paint() + probe := 6*scene.Canvas.Stride + 8*4 + if got := scene.Canvas.Pix[probe : probe+4]; !bytes.Equal(got, []byte{0, 128, 127, 255}) && !bytes.Equal(got, []byte{0, 128, 128, 255}) { t.Fatalf("initial zoom sample = %v, want the center of the two source pixels", got) } label.X = -750000 label.Clip.X = 7 - if changed, err := scene.apply(platform.Frame{TextLabels: []platform.TextLabel{label}}); err != nil || !changed { + if changed, err := scene.Apply(platform.Frame{TextLabels: []platform.TextLabel{label}}); err != nil || !changed { t.Fatalf("pan: changed=%t, error=%v", changed, err) } - scene.paint() + scene.Paint() full, err := newSoftScene(nil, 20, 10, 1, clear, nil, []platform.TextLabel{label}) if err != nil { t.Fatal(err) } - full.paint() - if !bytes.Equal(scene.canvas.Pix, full.canvas.Pix) { + full.Paint() + if !bytes.Equal(scene.Canvas.Pix, full.Canvas.Pix) { t.Fatal("the partial repaint differs from a full paint after pan and clip changes") } - if got := scene.canvas.Pix[probe : probe+4]; !bytes.Equal(got, []byte{0, 255, 0, 255}) { + if got := scene.Canvas.Pix[probe : probe+4]; !bytes.Equal(got, []byte{0, 255, 0, 255}) { t.Fatalf("panned zoom sample = %v, want the green source edge", got) } } @@ -150,15 +154,15 @@ func TestSoftSceneShrinksWithASuffixUpdate(t *testing.T) { if err != nil { t.Fatal(err) } - if err := soft.applyRectangles(platform.Frame{ + if _, err := soft.Apply(platform.Frame{ Update: render.Update{First: 1, Count: 1, Shrink: true}, Rectangles: rects[:2], }); err != nil { t.Fatal(err) } - if len(soft.rects) != 2 { - t.Fatalf("shrunk rectangles = %d", len(soft.rects)) + if len(soft.Rects) != 2 { + t.Fatalf("shrunk rectangles = %d", len(soft.Rects)) } - if err := soft.applyRectangles(platform.Frame{ + if _, err := soft.Apply(platform.Frame{ Update: render.Update{First: 1, Count: 1}, Rectangles: rects[:1], }); err == nil { t.Fatal("shrink without Shrink accepted") diff --git a/internal/platform/linux/system_linux.go b/internal/platform/linux/system_linux.go index c8588a5a9..277b86a76 100644 --- a/internal/platform/linux/system_linux.go +++ b/internal/platform/linux/system_linux.go @@ -779,35 +779,42 @@ func OpenFiles(options OpenFileOptions) ([]string, bool, error) { return paths, false, nil } -func directoryPortalRequest(options OpenDirectoryOptions, parent string) portalFileRequest { +func directoryPortalRequest(options OpenDirectoryOptions, multiple bool, parent string) portalFileRequest { return portalFileRequest{ - method: "OpenFile", parent: parent, title: options.Title, directory: true, + method: "OpenFile", parent: parent, title: options.Title, directory: true, multiple: multiple, currentFolder: options.InitialDirectory, } } -func OpenDirectory(options OpenDirectoryOptions) (string, bool, error) { - paths, canceled, err := portalChoose(directoryPortalRequest(options, portalParent())) +func OpenDirectories(options OpenDirectoryOptions, multiple bool) ([]string, bool, error) { + paths, canceled, err := portalChoose(directoryPortalRequest(options, multiple, portalParent())) if !errors.Is(err, errServiceMissing) { - return firstPath(paths), canceled, singlePathError(paths, canceled, err, "open directory") + if err == nil && !canceled && (len(paths) == 0 || !multiple && len(paths) != 1) { + return nil, false, fmt.Errorf("linux: open directory dialog returned %d paths", len(paths)) + } + return paths, canceled, err } backend, executable, err := fileDialogBackend() if err != nil { - return "", false, err + return nil, false, err } - arguments, err := openDirectoryDialogArguments(backend, options) + arguments, err := openDirectoryDialogArguments(backend, options, multiple) if err != nil { - return "", false, err + return nil, false, err } output, canceled, err := runDialog("open directory", executable, arguments) if err != nil || canceled { - return "", canceled, err + return nil, canceled, err } - paths = splitDialogOutput(string(output), "\n") - if len(paths) != 1 { - return "", false, fmt.Errorf("linux: open directory dialog returned %d paths", len(paths)) + selection := strings.TrimSuffix(string(output), "\n") + if selection == "" { + return nil, false, fmt.Errorf("linux: open directory dialog returned no paths") } - return paths[0], false, nil + if backend == "zenity" && multiple { + return strings.Split(selection, dialogSeparator), false, nil + } + // KDialog's --getexistingdirectory always returns one directory. + return []string{selection}, false, nil } func SaveFile(options SaveFileOptions) (string, bool, error) { @@ -1002,10 +1009,13 @@ func openDialogArguments(backend string, options OpenFileOptions) ([]string, str } } -func openDirectoryDialogArguments(backend string, options OpenDirectoryOptions) ([]string, error) { +func openDirectoryDialogArguments(backend string, options OpenDirectoryOptions, multiple bool) ([]string, error) { switch backend { case "zenity": arguments := []string{"--file-selection", "--directory"} + if multiple { + arguments = append(arguments, "--multiple", "--separator="+dialogSeparator) + } if options.Title != "" { arguments = append(arguments, "--title="+options.Title) } diff --git a/internal/platform/linux/system_linux_test.go b/internal/platform/linux/system_linux_test.go index e0a33c66b..8ba9603ad 100644 --- a/internal/platform/linux/system_linux_test.go +++ b/internal/platform/linux/system_linux_test.go @@ -240,14 +240,14 @@ func TestFileDialogArguments(t *testing.T) { if !reflect.DeepEqual(save, []string{"--file-selection", "--save", "--confirm-overwrite", "--title=Save", "--filename=notes.txt", "--file-filter=Text | *.txt *.md"}) { t.Fatalf("save arguments = %#v", save) } - zenityDirectory, err := openDirectoryDialogArguments("zenity", OpenDirectoryOptions{Title: "Choose folder"}) + zenityDirectory, err := openDirectoryDialogArguments("zenity", OpenDirectoryOptions{Title: "Choose folder"}, false) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(zenityDirectory, []string{"--file-selection", "--directory", "--title=Choose folder"}) { t.Fatalf("zenity directory arguments = %#v", zenityDirectory) } - kdialogDirectory, err := openDirectoryDialogArguments("kdialog", OpenDirectoryOptions{Title: "Choose folder"}) + kdialogDirectory, err := openDirectoryDialogArguments("kdialog", OpenDirectoryOptions{Title: "Choose folder"}, true) if err != nil { t.Fatal(err) } @@ -256,6 +256,32 @@ func TestFileDialogArguments(t *testing.T) { } } +func TestOpenDirectoriesReturnsAllZenitySelections(t *testing.T) { + bin := t.TempDir() + t.Setenv("DBUS_SESSION_BUS_ADDRESS", "unix:path="+filepath.Join(bin, "no-bus")) + t.Setenv("PATH", bin) + // Emulate the helper's command-line contract. Without --multiple Zenity + // only lets the user select the first directory. + script := `#!/bin/sh +case " $* " in + *" --multiple "*) ;; + *) printf '%s\n' '/tmp/第一组'; exit 0 ;; +esac +for arg do + case "$arg" in --separator=*) sep=${arg#--separator=} ;; esac +done +printf '%s%s%s\n' '/tmp/第一组' "$sep" '/tmp/with +newline' +` + if err := os.WriteFile(filepath.Join(bin, "zenity"), []byte(script), 0o755); err != nil { + t.Fatal(err) + } + paths, canceled, err := OpenDirectories(OpenDirectoryOptions{}, true) + if want := []string{"/tmp/第一组", "/tmp/with\nnewline"}; err != nil || canceled || !reflect.DeepEqual(paths, want) { + t.Fatalf("selected %q, canceled %t, err %v; want %q", paths, canceled, err, want) + } +} + func TestFileDialogCancellation(t *testing.T) { path := filepath.Join(t.TempDir(), "dialog") if err := os.WriteFile(path, []byte("#!/bin/sh\nexit 1\n"), 0o755); err != nil { @@ -610,7 +636,7 @@ func TestOpenDirectoryInitialDirectory(t *testing.T) { for _, directory := range []string{"/tmp/My projects", "/tmp/My projects/"} { for _, backend := range []string{"zenity", "kdialog"} { t.Run(backend+directory, func(t *testing.T) { - got, err := openDirectoryDialogArguments(backend, OpenDirectoryOptions{Title: "Choose folder", InitialDirectory: directory}) + got, err := openDirectoryDialogArguments(backend, OpenDirectoryOptions{Title: "Choose folder", InitialDirectory: directory}, false) if err != nil { t.Fatal(err) } diff --git a/internal/platform/linux/vulkan_window_linux.go b/internal/platform/linux/vulkan_window_linux.go index e09495af1..026c93806 100644 --- a/internal/platform/linux/vulkan_window_linux.go +++ b/internal/platform/linux/vulkan_window_linux.go @@ -3,6 +3,7 @@ package linux import ( + "time" "unsafe" "github.com/vivaui/viva/internal/platform" @@ -108,5 +109,11 @@ func (window *vulkanWindow) stats() rendererStats { } func (window *vulkanWindow) close() { window.renderer.Close() } +// The Vulkan renderer's buffers are the swapchain's, which the driver keeps; +// it has nothing of its own to give back when idle or unmapped. +func (window *vulkanWindow) trimDeadline() (time.Time, bool) { return time.Time{}, false } +func (window *vulkanWindow) trimIdle() {} +func (window *vulkanWindow) releaseUnmapped() {} + // software reports whether the device is a CPU rasterizer (lavapipe). func (window *vulkanWindow) software() bool { return window.renderer.Software() } diff --git a/internal/platform/linux/wide_label_linux_test.go b/internal/platform/linux/wide_label_linux_test.go index 61b720a5b..fb0b45a52 100644 --- a/internal/platform/linux/wide_label_linux_test.go +++ b/internal/platform/linux/wide_label_linux_test.go @@ -148,37 +148,29 @@ func TestSoftSceneDrawsAWideLineFromWhatTheCanvasShows(t *testing.T) { if err != nil { t.Fatal(err) } - live.paint() + live.Paint() for _, step := range []struct { name string x float32 - skip int // the first column of the line's picture, or -1 for none }{ - {"scrolled inside its picture", -100, 0}, - {"scrolled past its picture", -8000, 11400}, - {"scrolled a little", -8100, 11400}, - {"scrolled off the canvas", -40000, -1}, - {"scrolled back", -8000, 11400}, + {"scrolled inside its picture", -100}, + {"scrolled past its picture", -8000}, + {"scrolled a little", -8100}, + {"scrolled off the canvas", -40000}, + {"scrolled back", -8000}, } { next := label next.X = step.x - if _, err := live.apply(platform.Frame{TextLabels: []platform.TextLabel{next}}); err != nil { + if _, err := live.Apply(platform.Frame{TextLabels: []platform.TextLabel{next}}); err != nil { t.Fatalf("%s: %v", step.name, err) } - live.paint() - slot := &live.labels[0] - switch { - case step.skip < 0 && (slot.hasImage || slot.visible): - t.Errorf("%s: the line has a picture", step.name) - case step.skip >= 0 && (!slot.hasImage || !slot.visible || slot.image.skip != step.skip || slot.image.width != 1800): - t.Errorf("%s: picture from column %d, %d wide (drawn %v); want %d, 1800", step.name, slot.image.skip, slot.image.width, slot.hasImage, step.skip) - } - whole, err := newSoftScene(services, live.canvas.Width, live.canvas.Height, scale, clear, nil, []platform.TextLabel{next}) + live.Paint() + whole, err := newSoftScene(services, live.Canvas.Width, live.Canvas.Height, scale, clear, nil, []platform.TextLabel{next}) if err != nil { t.Fatal(err) } - whole.paint() - if !bytes.Equal(live.canvas.Pix, whole.canvas.Pix) { + whole.Paint() + if !bytes.Equal(live.Canvas.Pix, whole.Canvas.Pix) { t.Fatalf("%s: canvas differs from a full paint", step.name) } } diff --git a/internal/platform/linux/window_controls_linux.go b/internal/platform/linux/window_controls_linux.go index 73b00d3a3..02ca78165 100644 --- a/internal/platform/linux/window_controls_linux.go +++ b/internal/platform/linux/window_controls_linux.go @@ -56,6 +56,9 @@ type frameState struct { maximizedHorizontal uint32 fullscreen uint32 above uint32 + // demandsAttention is _NET_WM_STATE_DEMANDS_ATTENTION, the taskbar highlight + // the window asks for while it is in the background. + demandsAttention uint32 // fullscreenMonitors is _NET_WM_FULLSCREEN_MONITORS (fullscreen_linux.go). fullscreenMonitors uint32 maximized bool @@ -88,6 +91,7 @@ func (win *window) openFrame() error { {"_NET_WM_STATE_MAXIMIZED_HORZ", &win.frame.maximizedHorizontal}, {"_NET_WM_STATE_FULLSCREEN", &win.frame.fullscreen}, {"_NET_WM_STATE_ABOVE", &win.frame.above}, + {"_NET_WM_STATE_DEMANDS_ATTENTION", &win.frame.demandsAttention}, {"_NET_WM_FULLSCREEN_MONITORS", &win.frame.fullscreenMonitors}, {"WM_CHANGE_STATE", &win.frame.changeStateAtom}, } { diff --git a/internal/platform/linux/window_linux.go b/internal/platform/linux/window_linux.go index eb9a7c62e..7651405f6 100644 --- a/internal/platform/linux/window_linux.go +++ b/internal/platform/linux/window_linux.go @@ -116,6 +116,9 @@ type window struct { minimizeHandler platform.MinimizeHandler // maximizeHandler is the application's callback, run on the loop. maximizeHandler platform.MaximizeHandler + // attentionRequested says the window asked the window manager for the + // demands-attention state and has not taken the keyboard since. + attentionRequested atomic.Bool // lastFrame is the content rectangle last reported to OnFrameChange. lastFrame gfx.Rect configureX int16 @@ -313,6 +316,7 @@ func RunApplication(start platform.ApplicationStart) error { application.fail(fmt.Errorf("linux: poll X11 connections failed (errno %d)", *application.windows[0].win.api.errnoLocation())) break } + application.trimIdleRenderers() if application.inputMethod != nil { // A key the input method never answered gives up here, not before. application.inputMethod.Expire() @@ -545,9 +549,34 @@ func (application *linuxApplication) pollTimeout() int32 { timeout = retryTimeout } } + for _, state := range application.windows { + if state.renderer == nil { + continue + } + if deadline, waiting := state.renderer.trimDeadline(); waiting { + trimTimeout := int32(max(time.Until(deadline).Milliseconds()+1, 0)) + if timeout < 0 || trimTimeout < timeout { + timeout = trimTimeout + } + } + } return timeout } +// trimIdleRenderers lets the renderers of windows that have been idle since +// their trim deadline give back what only drawing needs. +func (application *linuxApplication) trimIdleRenderers() { + now := time.Now() + for _, state := range application.windows { + if state.renderer == nil { + continue + } + if deadline, waiting := state.renderer.trimDeadline(); waiting && !now.Before(deadline) { + state.renderer.trimIdle() + } + } +} + // bufferedEvent peeks only at events already read from the socket. Preserve // their order with any input held by motion/configure coalescing. func (state *linuxWindowState) bufferedEvent() bool { @@ -995,6 +1024,9 @@ func (state *linuxWindowState) handleEvent(event unsafe.Pointer) (bool, error) { case xcbMapNotify, xcbUnmapNotify: if (*xcbMapEvent)(event).Window == win.id && kind == xcbUnmapNotify { state.exposed = false + // Nothing shows the window's pixels until it is mapped and exposed again, + // and the present that answers the exposure draws them all. + renderer.releaseUnmapped() } if kind == xcbMapNotify && (*xcbMapEvent)(event).Window == win.id && state.hidden { // The window manager mapped the window after Hide raced its first @@ -1237,6 +1269,16 @@ func (state *linuxWindowState) handleEvent(event unsafe.Pointer) (bool, error) { // The same details, outside a grab, are the window becoming active. if realFocus && keyboardFocus { win.clipboardFocusedAt.Store(monotonicNow()) + if win.attentionRequested.Swap(false) { + // The window manager usually clears the hint on focus; asking it + // again keeps the taskbar entry from staying highlighted when a + // manager only clears it on its own focus path. + win.mu.Lock() + if win.connection != 0 { + win.sendToRoot(win.frame.stateAtom, [5]uint32{netWMStateRemove, win.frame.demandsAttention, 0, sourceApp}) + } + win.mu.Unlock() + } if config.OnActivate != nil { config.OnActivate() if err := state.refreshReadOnlyTextInput(); err != nil { diff --git a/internal/platform/linux/window_preview_linux_test.go b/internal/platform/linux/window_preview_linux_test.go index 95decb15a..feac1bce6 100644 --- a/internal/platform/linux/window_preview_linux_test.go +++ b/internal/platform/linux/window_preview_linux_test.go @@ -134,7 +134,7 @@ func TestPreviewNativeX11Contract(t *testing.T) { t.Fatal(err) } cpu := renderer.(*cpuWindowRenderer) - if cpu.scene.canvas.Pix[3] != 0 { + if cpu.scene.Canvas.Pix[3] != 0 { t.Fatal("transparent preview corner is opaque") } control := &nativeWindow{state: &linuxWindowState{win: win}} diff --git a/internal/platform/linux/window_renderer_fake_linux_test.go b/internal/platform/linux/window_renderer_fake_linux_test.go index 9e1ea2fbc..c27bea6da 100644 --- a/internal/platform/linux/window_renderer_fake_linux_test.go +++ b/internal/platform/linux/window_renderer_fake_linux_test.go @@ -3,6 +3,8 @@ package linux import ( + "time" + "github.com/vivaui/viva/internal/platform" "github.com/vivaui/viva/internal/render" ) @@ -67,8 +69,11 @@ func (renderer *fakeWindowRenderer) refreshText() error { return nil } func (renderer *fakeWindowRenderer) forgetSurfaceCapabilities() { renderer.record("forget") } -func (renderer *fakeWindowRenderer) alpha() bool { return false } -func (renderer *fakeWindowRenderer) frameMargin() uint32 { return 0 } +func (renderer *fakeWindowRenderer) trimDeadline() (time.Time, bool) { return time.Time{}, false } +func (renderer *fakeWindowRenderer) trimIdle() {} +func (renderer *fakeWindowRenderer) releaseUnmapped() {} +func (renderer *fakeWindowRenderer) alpha() bool { return false } +func (renderer *fakeWindowRenderer) frameMargin() uint32 { return 0 } func (renderer *fakeWindowRenderer) deviceSize() (uint32, uint32) { return renderer.deviceWidth, renderer.deviceHeight } diff --git a/internal/platform/linux/window_renderer_linux.go b/internal/platform/linux/window_renderer_linux.go index 16bf34dbf..11cff1049 100644 --- a/internal/platform/linux/window_renderer_linux.go +++ b/internal/platform/linux/window_renderer_linux.go @@ -6,6 +6,7 @@ import ( "errors" "os" "sync/atomic" + "time" "github.com/vivaui/viva/internal/diag" "github.com/vivaui/viva/internal/platform" @@ -37,6 +38,14 @@ type windowRenderer interface { deviceSize() (uint32, uint32) firstRectangle() (render.Rectangle, bool) stats() rendererStats + // trimDeadline is when an idle window gives back memory only drawing needs, + // if it holds any; trimIdle gives it back. The event loop bounds its sleep by + // the deadline once, so an idle window does nothing after the trim. + trimDeadline() (time.Time, bool) + trimIdle() + // releaseUnmapped gives back what the next full present makes again, while + // the window is unmapped and nothing shows its pixels. + releaseUnmapped() close() } diff --git a/internal/platform/web/accessibility.go b/internal/platform/web/accessibility.go index 19255da7e..2935cb27c 100644 --- a/internal/platform/web/accessibility.go +++ b/internal/platform/web/accessibility.go @@ -35,6 +35,10 @@ type accessibilityDescription struct { PosInSet, SetSize int32 Live string Range gfx.ValueRange + // MultiSelectable is aria-multiselectable of a list, and Sort the aria-sort + // of a column header, empty when it sorts nothing. + MultiSelectable bool + Sort string } func describeAccessibility(destination []accessibilityDescription, hits []gfx.Hit, activeScope gfx.ID) []accessibilityDescription { @@ -90,6 +94,9 @@ func describeAccessibility(destination []accessibilityDescription, hits []gfx.Hi SetSize: hit.SetSize, Live: accessibilityLive(hit.Live), Range: hit.Range, + + MultiSelectable: hit.MultiSelectable, + Sort: accessibilitySort(hit.Sort), }) } return destination @@ -117,6 +124,18 @@ func accessibilityLive(live gfx.LiveRegion) string { return "" } +// accessibilitySort is a column header's aria-sort, empty for one the rows are +// not sorted by, which leaves the attribute off as ARIA asks. +func accessibilitySort(sort gfx.SortDirection) string { + switch sort { + case gfx.SortAscending: + return "ascending" + case gfx.SortDescending: + return "descending" + } + return "" +} + func accessibilityElement(role gfx.Role, multiline, hasRange bool) string { if role == gfx.RoleCombobox { return "input" @@ -189,6 +208,8 @@ func accessibilityRole(role gfx.Role) string { return "separator" case gfx.RoleProgressBar: return "progressbar" + case gfx.RoleColumnHeader: + return "columnheader" default: return "button" } diff --git a/internal/platform/web/accessibility_js.go b/internal/platform/web/accessibility_js.go index c0f217fcb..728d92d25 100644 --- a/internal/platform/web/accessibility_js.go +++ b/internal/platform/web/accessibility_js.go @@ -202,6 +202,13 @@ func applyAccessibilityDescription(node *accessibilityDOMNode, description acces if initial || before.SetSize != description.SetSize { setNumberAttribute(node.element, "aria-setsize", float64(description.SetSize), description.SetSize > 0) } + if initial || before.Sort != description.Sort { + setOptionalAttribute(node.element, "aria-sort", description.Sort) + } + if initial || before.Role != description.Role || before.MultiSelectable != description.MultiSelectable { + supported := description.Role == "listbox" || description.Role == "grid" + setBooleanState(node.element, "aria-multiselectable", description.MultiSelectable, supported && description.MultiSelectable) + } if initial || before.Live != description.Live { setOptionalAttribute(node.element, "aria-live", description.Live) } @@ -285,7 +292,9 @@ func applySelectionStates(element js.Value, description accessibilityDescription setBooleanState(element, "aria-pressed", false, false) setBooleanState(element, "aria-selected", false, false) setBooleanState(element, "aria-current", false, false) - case "tab": + case "tab", "option", "gridcell": + // An item chosen among its siblings says so with aria-selected, which + // a list that chooses several reads for each of its options. setBooleanState(element, "aria-selected", description.Selected, true) setBooleanState(element, "aria-pressed", false, false) setBooleanState(element, "aria-checked", false, false) diff --git a/internal/platform/web/painter.go b/internal/platform/web/painter.go index 2d87ca915..8cb4c9457 100644 --- a/internal/platform/web/painter.go +++ b/internal/platform/web/painter.go @@ -301,9 +301,10 @@ func (p *painter) fileDrop(phase gfx.FileDropPhase, x, y float32, files []platfo // accessibleHit finds the control a request names. Labels share their // control's ID and are not controls, and a region declared by Container has no -// target. +// target, and a control behind an open modal is hidden from assistive +// technology. func (p *painter) accessibleHit(id gfx.ID) (gfx.Hit, bool) { - return interaction.Control(p.canvas.Hits(), id) + return interaction.Control(p.canvas.Hits(), p.focus.Router().ActiveScope(), id) } // accessibilityFocus gives a control the keyboard, as a Tab onto it would. diff --git a/internal/platform/windows/accessibility_pattern_windows.go b/internal/platform/windows/accessibility_pattern_windows.go index 11d5e236e..9c2cbcbdb 100644 --- a/internal/platform/windows/accessibility_pattern_windows.go +++ b/internal/platform/windows/accessibility_pattern_windows.go @@ -482,7 +482,15 @@ func uiaGetSelection(this, result uintptr) uintptr { return 0 } -func uiaGetCanSelectMultiple(this, result uintptr) uintptr { return writeBool(result, false) } +// uiaGetCanSelectMultiple says whether the list lets the user choose several of +// its items at once. +func uiaGetCanSelectMultiple(this, result uintptr) uintptr { + _, node, status := patternNode(this) + if status != 0 { + return status + } + return writeBool(result, node.MultiSelectable) +} func uiaGetIsSelectionRequired(this, result uintptr) uintptr { return writeBool(result, false) } diff --git a/internal/platform/windows/accessibility_text_windows.go b/internal/platform/windows/accessibility_text_windows.go index 8d6c7465f..7db6b0772 100644 --- a/internal/platform/windows/accessibility_text_windows.go +++ b/internal/platform/windows/accessibility_text_windows.go @@ -1,9 +1,11 @@ package windows import ( + "slices" "sync/atomic" "unsafe" + "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/internal/platform" ) @@ -29,6 +31,9 @@ type uiaTextRange struct { Table *uintptr // first, as in uiaInterface: this points at the table Owner *uiaProvider Start, End int + // An excerpt supplied by a custom control only describes this selection; + // an equally long selection made later may be on another line entirely. + Selection *gfx.TextSelection References atomic.Uint32 } @@ -50,8 +55,8 @@ func initializeTextRangeTable(unknown []uintptr) { copy(uiaTextRangeTable[3:], methods[:]) } -func newTextRange(owner *uiaProvider, start, end int) *uiaTextRange { - made := &uiaTextRange{Table: &uiaTextRangeTable[0], Owner: owner, Start: start, End: end} +func newTextRange(owner *uiaProvider, start, end int, selection *gfx.TextSelection) *uiaTextRange { + made := &uiaTextRange{Table: &uiaTextRangeTable[0], Owner: owner, Start: start, End: end, Selection: selection} made.References.Store(1) uiaRanges.Store(uintptr(unsafe.Pointer(made)), made) return made @@ -72,9 +77,14 @@ func rangeAt(address uintptr) *uiaTextRange { return value.(*uiaTextRange) } +func (made *uiaTextRange) snapshot() (platform.AccessibilityNode, bool) { + node, ok := made.Owner.snapshot() + return node, ok && node.TextSelection == made.Selection +} + // state is the text the range reads and where it lies in it, clamped. func (made *uiaTextRange) state() (node platform.AccessibilityNode, text []rune, start, end int, ok bool) { - node, ok = made.Owner.snapshot() + node, ok = made.snapshot() if !ok { return node, nil, 0, 0, false } @@ -179,7 +189,7 @@ func uiaTextGetSelection(this, result uintptr) uintptr { return status } start, end := caret(node, text) - array, ok := unknownArrayData([]uintptr{newTextRange(provider, start, end).address()}) + array, ok := unknownArrayData([]uintptr{newTextRange(provider, start, end, node.TextSelection).address()}) if !ok { return windowsResult(resultOutOfMemory) } @@ -192,11 +202,18 @@ func uiaTextGetVisibleRanges(this, result uintptr) uintptr { return windowsResult(resultPointer) } *(*uintptr)(pointer(result)) = 0 - provider, _, text, status := textNode(this) + provider, node, text, status := textNode(this) if status != 0 { return status } - array, ok := unknownArrayData([]uintptr{newTextRange(provider, 0, len(text)).address()}) + var ranges []uintptr + if node.TextSelection == nil || slices.ContainsFunc(node.TextSelection.Bounds, func(row gfx.Rect) bool { + _, visible := clipSelectionRow(row, node) + return visible + }) { + ranges = []uintptr{newTextRange(provider, 0, len(text), node.TextSelection).address()} + } + array, ok := unknownArrayData(ranges) if !ok { return windowsResult(resultOutOfMemory) } @@ -221,7 +238,7 @@ func uiaTextRangeFromPoint(this, point, result uintptr) uintptr { return status } _, end := caret(node, text) - return writeRange(result, newTextRange(provider, end, end)) + return writeRange(result, newTextRange(provider, end, end, node.TextSelection)) } func uiaTextGetDocumentRange(this, result uintptr) uintptr { @@ -229,11 +246,11 @@ func uiaTextGetDocumentRange(this, result uintptr) uintptr { return windowsResult(resultPointer) } *(*uintptr)(pointer(result)) = 0 - provider, _, text, status := textNode(this) + provider, node, text, status := textNode(this) if status != 0 { return status } - return writeRange(result, newTextRange(provider, 0, len(text))) + return writeRange(result, newTextRange(provider, 0, len(text), node.TextSelection)) } func uiaTextGetSupportedSelection(this, result uintptr) uintptr { @@ -249,7 +266,7 @@ func uiaRangeClone(this, result uintptr) uintptr { if made == nil { return windowsResult(resultInvalidArgument) } - return writeRange(result, newTextRange(made.Owner, made.Start, made.End)) + return writeRange(result, newTextRange(made.Owner, made.Start, made.End, made.Selection)) } func uiaRangeCompare(this, other, result uintptr) uintptr { @@ -340,7 +357,7 @@ func uiaRangeFindText(this, pattern, backward, ignoreCase, result uintptr) uintp if !ok { return 0 } - return writeRange(result, newTextRange(made.Owner, start+found, start+foundEnd)) + return writeRange(result, newTextRange(made.Owner, start+found, start+foundEnd, made.Selection)) } // uiaRangeGetAttributeValue says only that the field is read-only or not; @@ -355,7 +372,7 @@ func uiaRangeGetAttributeValue(this, attribute, result uintptr) uintptr { if made == nil { return windowsResult(resultInvalidArgument) } - node, ok := made.Owner.snapshot() + node, ok := made.snapshot() if !ok { return windowsResult(resultElementNotAvailable) } @@ -373,9 +390,8 @@ func uiaRangeGetAttributeValue(this, attribute, result uintptr) uintptr { return 0 } -// uiaRangeGetBoundingRectangles gives the field's own rectangle: where a glyph -// falls inside it is the text layout's to say, and the field is the best bound -// a reader following the range can be given. +// A custom selection supplies its visible rows. A subrange of it may only +// cover part of a row, whose character positions the adapter does not know. func uiaRangeGetBoundingRectangles(this, result uintptr) uintptr { if result == 0 { return windowsResult(resultPointer) @@ -385,12 +401,19 @@ func uiaRangeGetBoundingRectangles(this, result uintptr) uintptr { if made == nil { return windowsResult(resultInvalidArgument) } - node, ok := made.Owner.snapshot() + node, ok := made.snapshot() if !ok { return windowsResult(resultElementNotAvailable) } - bounds := made.Owner.Tree.providerBounds(made.Owner, node) - array, ok := doubleArrayData([]float64{bounds.X, bounds.Y, bounds.Width, bounds.Height}) + var coordinates []float64 + if node.TextSelection == nil { + bounds := made.Owner.Tree.providerBounds(made.Owner, node) + coordinates = []float64{bounds.X, bounds.Y, bounds.Width, bounds.Height} + } else if node.Selection.Valid && made.Start < made.End && + made.Start == int(min(node.Selection.Start, node.Selection.End)) && made.End == int(max(node.Selection.Start, node.Selection.End)) { + coordinates = made.Owner.Tree.selectionRectangles(node) + } + array, ok := doubleArrayData(coordinates) if !ok { return windowsResult(resultOutOfMemory) } @@ -498,6 +521,9 @@ func uiaRangeSelect(this uintptr) uintptr { if !ok { return windowsResult(resultElementNotAvailable) } + if node.TextSelection != nil { + return windowsResult(resultNotSupported) + } return made.Owner.act(node, platform.AccessibilityRequest{Action: platform.AccessibilitySetSelection, Start: int32(start), End: int32(end)}) } diff --git a/internal/platform/windows/accessibility_windows.go b/internal/platform/windows/accessibility_windows.go index c7aa6ba28..a89b1b5e1 100644 --- a/internal/platform/windows/accessibility_windows.go +++ b/internal/platform/windows/accessibility_windows.go @@ -52,6 +52,9 @@ const ( uiaFullDescriptionProperty = 30159 uiaIsDataValidForFormProperty = 30186 uiaHeadingLevelProperty = 30173 + uiaItemStatusProperty = 30026 + uiaCanSelectMultipleProperty = 30060 + uiaAriaPropertiesProperty = 30102 // UIA_HeadingLevel1Id is 80051; "none" is one below it. uiaHeadingLevelNone = 80050 @@ -81,6 +84,7 @@ const ( uiaDataItemControlType = 50029 uiaWindowControlType = 50032 uiaSeparatorControlType = 50038 + uiaHeaderItemControlType = 50035 variantEmpty = 0 variantI4 = 3 @@ -525,6 +529,9 @@ var propertyOrder = [...]struct { {uiaPositionInSetProperty, platform.ChangedPosition}, {uiaSizeOfSetProperty, platform.ChangedPosition}, {uiaLiveSettingProperty, platform.ChangedLive}, + {uiaItemStatusProperty, platform.ChangedSort}, + {uiaAriaPropertiesProperty, platform.ChangedSort}, + {uiaCanSelectMultipleProperty, platform.ChangedMultiSelectable}, } func appendPropertyChanges(changes []uiaPropertyChange, provider *uiaProvider, oldNode, newNode platform.AccessibilityNode) []uiaPropertyChange { @@ -1101,15 +1108,50 @@ func (tree *uiaTree) providerBounds(provider *uiaProvider, node platform.Accessi } func (tree *uiaTree) boundsLocked(node platform.AccessibilityNode) uiaRectangle { + return tree.screenRectLocked(tree.clientOrigin(), gfx.Rect{X: node.X, Y: node.Y, Width: node.Width, Height: node.Height}) +} + +func (tree *uiaTree) clientOrigin() point { origin := point{} clientToScreen.Call(tree.window, uintptr(unsafe.Pointer(&origin))) + return origin +} + +func (tree *uiaTree) screenRectLocked(origin point, rect gfx.Rect) uiaRectangle { scale := float64(tree.scale) return uiaRectangle{ - X: float64(origin.X) + float64(node.X)*scale, - Y: float64(origin.Y) + float64(node.Y)*scale, - Width: math.Max(0, float64(node.Width)*scale), - Height: math.Max(0, float64(node.Height)*scale), + X: float64(origin.X) + float64(rect.X)*scale, + Y: float64(origin.Y) + float64(rect.Y)*scale, + Width: math.Max(0, float64(rect.Width)*scale), + Height: math.Max(0, float64(rect.Height)*scale), + } +} + +func (tree *uiaTree) selectionRectangles(node platform.AccessibilityNode) []float64 { + tree.mu.RLock() + defer tree.mu.RUnlock() + rows := node.TextSelection.Bounds + if tree.closed || len(rows) == 0 { + return nil + } + origin := tree.clientOrigin() + values := make([]float64, 0, 4*len(rows)) + for _, row := range rows { + clipped, visible := clipSelectionRow(row, node) + if !visible { + continue + } + rect := tree.screenRectLocked(origin, clipped) + values = append(values, rect.X, rect.Y, rect.Width, rect.Height) } + return values +} + +// The terminal knows its viewport; an enclosing panel can clip it further. +func clipSelectionRow(row gfx.Rect, node platform.AccessibilityNode) (gfx.Rect, bool) { + left, top := max(row.X, node.X), max(row.Y, node.Y) + right, bottom := min(row.X+row.Width, node.X+node.Width), min(row.Y+row.Height, node.Y+node.Height) + return gfx.Rect{X: left, Y: top, Width: right - left, Height: bottom - top}, right > left && bottom > top } // controlType is the UI Automation control type for a node role (see @@ -1157,6 +1199,8 @@ func controlType(role uint8) int32 { return uiaDataItemControlType case platform.A11yRoleSeparator: return uiaSeparatorControlType + case platform.A11yRoleColumnHeader: + return uiaHeaderItemControlType default: return uiaGroupControlType } @@ -1261,11 +1305,40 @@ func propertyVariant(property int32, node platform.AccessibilityNode) (variant, return variant{}, false } return integerVariant(node.SetSize), true + // UI Automation has no sort property: a column header reports its sort as + // the aria-sort of AriaProperties, and as the ItemStatus a screen reader + // reads after the header's name. + case uiaItemStatusProperty: + if node.Role != platform.A11yRoleColumnHeader || node.Sort == gfx.SortNone { + return variant{}, false + } + return stringVariant(sortWord(node.Sort)) + case uiaAriaPropertiesProperty: + if node.Role != platform.A11yRoleColumnHeader { + return variant{}, false + } + return stringVariant("sort=" + sortWord(node.Sort)) + case uiaCanSelectMultipleProperty: + if !node.Patterns().Has(platform.PatternSelection) { + return variant{}, false + } + return booleanVariant(node.MultiSelectable), true default: return variant{}, false } } +// sortWord is a sort direction as aria-sort writes it. +func sortWord(sort gfx.SortDirection) string { + switch sort { + case gfx.SortAscending: + return "ascending" + case gfx.SortDescending: + return "descending" + } + return "none" +} + func integerVariant(value int32) variant { return variant{Type: variantI4, Value: uint64(uint32(value))} } diff --git a/internal/platform/windows/accessibility_windows_test.go b/internal/platform/windows/accessibility_windows_test.go index 73744959f..8f87cd08c 100644 --- a/internal/platform/windows/accessibility_windows_test.go +++ b/internal/platform/windows/accessibility_windows_test.go @@ -2,6 +2,7 @@ package windows import ( "math" + "slices" "syscall" "testing" "unsafe" @@ -322,6 +323,133 @@ func TestUIATextRangesMoveByUnitAndSelect(t *testing.T) { } } +func TestUIASelectedTextRectanglesFollowTheVisibleRows(t *testing.T) { + selection := &gfx.TextSelection{Text: "甲\n𐐷", Bounds: []gfx.Rect{ + {X: 4, Y: 40, Width: 32, Height: 12}, + {X: 12, Y: 52, Width: 24, Height: 12}, + {X: 12, Y: 430, Width: 24, Height: 12}, // clipped by the parent control + }} + node := platform.AccessibilityNode{ + ID: gfx.Item(1), Role: platform.A11yRoleTextField, Focused: true, ReadOnly: true, + X: 10, Y: 20, Width: 600, Height: 400, Value: selection.Text, + Selection: platform.AccessibilitySelection{Start: 3, End: 0, Valid: true}, TextSelection: selection, + } + tree := engagedTree(t, true, []platform.AccessibilityNode{node}) + tree.setScale(1.5) + provider := tree.children[0] + field := tree.providerBounds(provider, node) + checkVisibleRanges := func(want int) { + t.Helper() + var array uintptr + if status := uiaTextGetVisibleRanges(provider.patternPointer(patternText), uintptr(unsafe.Pointer(&array))); status != 0 { + t.Fatalf("GetVisibleRanges = %#x", status) + } + defer clearVariant(&variant{Type: variantArray | variantUnknown, Value: uint64(array)}) + if got := uiaTestArrayLength(t, array); got != want { + t.Errorf("GetVisibleRanges returned %d ranges, want %d", got, want) + } + } + selectedRange := func() uintptr { + t.Helper() + var array, data uintptr + if status := uiaTextGetSelection(provider.patternPointer(patternText), uintptr(unsafe.Pointer(&array))); status != 0 { + t.Fatalf("GetSelection = %#x", status) + } + t.Cleanup(func() { clearVariant(&variant{Type: variantArray | variantUnknown, Value: uint64(array)}) }) + if status, _, _ := safeArrayAccessData.Call(array, uintptr(unsafe.Pointer(&data))); status != 0 { + t.Fatalf("accessing selected range = %#x", status) + } + selected := *(*uintptr)(pointer(data)) + safeArrayUnaccessData.Call(array) + return selected + } + first := selectedRange() + checkVisibleRanges(1) + var text uintptr + if status := uiaRangeGetText(first, ^uintptr(0), uintptr(unsafe.Pointer(&text))); status != 0 || utf16Pointer(text) != selection.Text { + t.Fatalf("GetText = %#x %q, want %q", status, utf16Pointer(text), selection.Text) + } + clearVariant(&variant{Type: variantBSTR, Value: uint64(text)}) + if status := uiaRangeSelect(first); uint32(status) != resultNotSupported { + t.Fatalf("Select on a read-only terminal excerpt = %#x", status) + } + if got, want := uiaTestRangeRectangles(t, first), []float64{ + field.X, field.Y + 30, 39, 18, field.X + 3, field.Y + 48, 36, 18, + }; !slices.Equal(got, want) { + t.Fatalf("selected rectangles = %v, want %v", got, want) + } + // A character range has no character-level geometry supplied by the terminal. + var moved int32 + if status := uiaRangeMoveEndpointByUnit(first, textRangeEndpointEnd, 0, ^uintptr(1), uintptr(unsafe.Pointer(&moved))); status != 0 || moved != -2 { + t.Fatalf("shortening the selected range = %#x, moved %d", status, moved) + } + if bounds := uiaTestRangeRectangles(t, first); len(bounds) != 0 { + t.Fatalf("partial range advertised whole rows: %v", bounds) + } + first = selectedRange() + node.TextSelection = &gfx.TextSelection{Text: "丙\n丁", Bounds: []gfx.Rect{{X: 20, Y: 100, Width: 8, Height: 12}}} + node.Value = node.TextSelection.Text + if err := tree.update([]platform.AccessibilityNode{node}); err != nil { + t.Fatal(err) + } + if got, want := uiaTestRangeRectangles(t, selectedRange()), []float64{field.X + 15, field.Y + 120, 12, 18}; !slices.Equal(got, want) { + t.Fatalf("new selection = %v, want %v", got, want) + } + var array uintptr + if status := uiaRangeGetBoundingRectangles(first, uintptr(unsafe.Pointer(&array))); uint32(status) != resultElementNotAvailable { + t.Fatalf("superseded selection returned %#x, want UIA_E_ELEMENTNOTAVAILABLE", status) + } + node.TextSelection = &gfx.TextSelection{Text: node.Value} // selected text scrolled offscreen + if err := tree.update([]platform.AccessibilityNode{node}); err != nil { + t.Fatal(err) + } + if bounds := uiaTestRangeRectangles(t, selectedRange()); len(bounds) != 0 { + t.Fatalf("offscreen selection bounds = %v", bounds) + } + checkVisibleRanges(0) + node.TextSelection = &gfx.TextSelection{Text: node.Value, Bounds: []gfx.Rect{{X: 20, Y: 430, Width: 8, Height: 12}}} + if err := tree.update([]platform.AccessibilityNode{node}); err != nil { + t.Fatal(err) + } + checkVisibleRanges(0) + node.TextSelection = nil + if err := tree.update([]platform.AccessibilityNode{node}); err != nil { + t.Fatal(err) + } + if got, want := uiaTestRangeRectangles(t, selectedRange()), []float64{field.X, field.Y, field.Width, field.Height}; !slices.Equal(got, want) { + t.Fatalf("ordinary text field = %v, want %v", got, want) + } + checkVisibleRanges(1) +} + +func uiaTestArrayLength(t *testing.T, array uintptr) int { + t.Helper() + var last int32 + if status, _, _ := automation.NewProc("SafeArrayGetUBound").Call(array, 1, uintptr(unsafe.Pointer(&last))); status != 0 { + t.Fatalf("GetUBound = %#x", status) + } + return int(last) + 1 +} + +func uiaTestRangeRectangles(t *testing.T, span uintptr) []float64 { + t.Helper() + var array uintptr + if status := uiaRangeGetBoundingRectangles(span, uintptr(unsafe.Pointer(&array))); status != 0 { + t.Fatalf("GetBoundingRectangles = %#x", status) + } + defer clearVariant(&variant{Type: variantArray | variantR8, Value: uint64(array)}) + length := uiaTestArrayLength(t, array) + if length == 0 { + return nil + } + var data uintptr + if status, _, _ := safeArrayAccessData.Call(array, uintptr(unsafe.Pointer(&data))); status != 0 { + t.Fatalf("accessing rectangle coordinates = %#x", status) + } + defer safeArrayUnaccessData.Call(array) + return slices.Clone(unsafe.Slice((*float64)(pointer(data)), length)) +} + func TestUIAPatternTablesHaveEveryFunction(t *testing.T) { if !initializeUIACallbacks() { t.Skip("UI Automation is unsupported on this architecture") diff --git a/internal/platform/windows/api_windows.go b/internal/platform/windows/api_windows.go index 46031556c..4fde1e2b8 100644 --- a/internal/platform/windows/api_windows.go +++ b/internal/platform/windows/api_windows.go @@ -54,7 +54,7 @@ func vtable(object uintptr, index int) uintptr { return *(*uintptr)(unsafe.Add(pointer(*(*uintptr)(pointer(object))), index*int(unsafe.Sizeof(uintptr(0))))) } -// comCall0 to comCall7 call method index of a COM object with that many +// comCall0 to comCall8 call method index of a COM object with that many // arguments after the object itself. They have a fixed arity because a variadic // wrapper allocates its argument slice on every call; uintptrescapes keeps what // an argument points at alive through the call, which a pointer converted at the @@ -108,6 +108,12 @@ func comCall7(object uintptr, index int, a0 uintptr, a1 uintptr, a2 uintptr, a3 return result } +//go:uintptrescapes +func comCall8(object uintptr, index int, a0, a1, a2, a3, a4, a5, a6, a7 uintptr) uintptr { + result, _, _ := syscall.SyscallN(vtable(object, index), object, a0, a1, a2, a3, a4, a5, a6, a7) + return result +} + func release(object *uintptr) { if *object != 0 { comCall0(*object, 2) diff --git a/internal/platform/windows/attention_windows.go b/internal/platform/windows/attention_windows.go new file mode 100644 index 000000000..22b33cd2a --- /dev/null +++ b/internal/platform/windows/attention_windows.go @@ -0,0 +1,48 @@ +package windows + +import ( + "fmt" + "unsafe" +) + +// FLASHWINFO.dwFlags: flash the caption and the taskbar button, and keep +// flashing until the window comes to the foreground. +const ( + flashWindowAll = 0x00000003 + flashWindowTimerNoFG = 0x0000000C +) + +var flashWindowEx = user.NewProc("FlashWindowEx") + +// flashWindowInfo is Win32's FLASHWINFO. The two fields after the handle are +// unused while FLASHW_TIMERNOFG keeps the flash running. +type flashWindowInfo struct { + Size uint32 + Window uintptr + Flags uint32 + Count uint32 + Timeout uint32 +} + +func (window *nativeWindow) RequestAttention() error { + if window == nil || window.closed.Load() { + return fmt.Errorf("windows: window is closed") + } + handle := window.state.window + if handle == 0 { + return fmt.Errorf("windows: window is unavailable") + } + if ok, _, _ := isWindow.Call(handle); ok == 0 { + return fmt.Errorf("windows: window is unavailable") + } + info := flashWindowInfo{ + Size: uint32(unsafe.Sizeof(flashWindowInfo{})), + Window: handle, + Flags: flashWindowAll | flashWindowTimerNoFG, + } + // The return value says whether the window was active before the call, not + // whether it succeeded; a background window is the normal case and returns + // zero. The flash is stopped by the system when the window is destroyed. + flashWindowEx.Call(uintptr(unsafe.Pointer(&info))) + return nil +} diff --git a/internal/platform/windows/attention_windows_test.go b/internal/platform/windows/attention_windows_test.go new file mode 100644 index 000000000..3b5e44e28 --- /dev/null +++ b/internal/platform/windows/attention_windows_test.go @@ -0,0 +1,35 @@ +package windows + +import ( + "runtime" + "testing" + + "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/internal/render" +) + +// RequestAttention runs against a real HWND: the flash request is the shell's +// to draw, but the call itself must reach a live window without an error. +func TestRequestAttentionReachesARealWindow(t *testing.T) { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + err := RunApplication(func(application platform.Application) error { + opened, err := application.OpenWindow(platform.Config{ + Title: "Viva attention test", Width: 320, Height: 200, + OnResize: func(platform.Size) (platform.Frame, error) { + return platform.Frame{Update: render.Update{Rebuild: true}}, nil + }, + }) + if err != nil { + return err + } + defer opened.Close() + if err := opened.(*nativeWindow).RequestAttention(); err != nil { + t.Fatal(err) + } + return nil + }) + if err != nil { + t.Fatal(err) + } +} diff --git a/internal/platform/windows/device_windows.go b/internal/platform/windows/device_windows.go index 8d6e095bd..89c826520 100644 --- a/internal/platform/windows/device_windows.go +++ b/internal/platform/windows/device_windows.go @@ -104,9 +104,7 @@ func (renderer *renderer) recover(software bool) error { if err := renderer.growInstanceBuffer(len(renderer.instances)); err != nil { return err } - region := box{Right: uint32(len(renderer.instances) * rectangleInstanceBytes), Bottom: 1, Back: 1} - comCall6(renderer.context, 48, renderer.buffer, 0, uintptr(unsafe.Pointer(®ion)), uintptr(unsafe.Pointer(&renderer.instances[0])), 0, 0) - return nil + return renderer.uploadInstances(0, len(renderer.instances)) } // recoverDevice answers a failure that came from a lost device. It refuses when diff --git a/internal/platform/windows/device_windows_test.go b/internal/platform/windows/device_windows_test.go index dfab480ac..7bba7590a 100644 --- a/internal/platform/windows/device_windows_test.go +++ b/internal/platform/windows/device_windows_test.go @@ -27,7 +27,13 @@ func staticWindow(t *testing.T) uintptr { // as a recovery from a lost one does, and checks that what it holds in memory is // uploaded again: the rectangles to a new buffer, the labels as they are drawn. func TestRendererMakesItsDeviceAgain(t *testing.T) { - var drawn renderer + t.Run("default", func(t *testing.T) { checkDeviceRecovery(t, false) }) + t.Run("low-memory", func(t *testing.T) { checkDeviceRecovery(t, true) }) +} + +func checkDeviceRecovery(t *testing.T, lowMemory bool) { + t.Helper() + drawn := renderer{lowMemoryUploads: lowMemory} if err := drawn.initialize(staticWindow(t), platform.Color{Alpha: 1}); err != nil { t.Skipf("no graphics device: %v", err) } @@ -54,6 +60,9 @@ func TestRendererMakesItsDeviceAgain(t *testing.T) { if drawn.capacity != len(rectangles) || drawn.buffer == 0 || drawn.view == 0 { t.Fatalf("the rectangles were not uploaded again: capacity %d", drawn.capacity) } + if got := drawn.upload != 0; got != lowMemory { + t.Fatalf("recover(software %v) recreated a dedicated upload buffer = %v, want %v", software, got, lowMemory) + } if drawn.labels[0].view != 0 || drawn.labels[0].label.Value != "Viva" { t.Fatal("a label kept a texture of the old device, or lost its text") } diff --git a/internal/platform/windows/materials_windows.go b/internal/platform/windows/materials_windows.go index d12423027..1b44166c0 100644 --- a/internal/platform/windows/materials_windows.go +++ b/internal/platform/windows/materials_windows.go @@ -77,7 +77,7 @@ func (renderer *renderer) initializeComposition(software bool) bool { } err := renderer.createCompositionDevice(software) if err == nil { - err = renderer.createResources() + err = renderer.createResourcesWithFallback() if err == nil { renderer.describeDevice() return true diff --git a/internal/platform/windows/offscreen_update_windows_test.go b/internal/platform/windows/offscreen_update_windows_test.go index 7c4d3de3a..6872562ff 100644 --- a/internal/platform/windows/offscreen_update_windows_test.go +++ b/internal/platform/windows/offscreen_update_windows_test.go @@ -16,6 +16,7 @@ import ( // middle and recolor shapes together. func TestOffscreenIncrementalUpdatesDrawWhatARebuildDraws(t *testing.T) { incremental := newOffscreen(t, 160, 120, 1) + lowMemory := newUploadTestScreen(t, 160, 120, true) random := rand.New(rand.NewSource(3)) graph := scene.New() var store render.Store @@ -67,16 +68,20 @@ func TestOffscreenIncrementalUpdatesDrawWhatARebuildDraws(t *testing.T) { if !update.Rebuild && !update.Shrink && update.First+update.Count > len(incremental.renderer.instances) { grows++ } - if err := incremental.renderer.apply(platform.Frame{Update: update, Rectangles: rectangles}); err != nil { - t.Fatalf("batch %d: update %+v: %v", batch, update, err) - } - got, err := incremental.Image() - if err != nil { - t.Fatal(err) - } - want := renderScene(t, newOffscreen(t, 160, 120, 1), append([]render.Rectangle(nil), rectangles...), nil) - if !bytes.Equal(got.Pix, want.Pix) { - t.Fatalf("batch %d: update %+v drew other pixels than a rebuild of %d instances", batch, update, len(rectangles)) + reference := newOffscreen(t, 160, 120, 1) + want := renderScene(t, reference, append([]render.Rectangle(nil), rectangles...), nil) + reference.Close() // Each batch needs a fresh reference device only until its pixels are read. + for _, screen := range []*Offscreen{incremental, lowMemory} { + if err := screen.renderer.apply(platform.Frame{Update: update, Rectangles: rectangles}); err != nil { + t.Fatalf("batch %d: update %+v: %v", batch, update, err) + } + got, err := screen.Image() + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(got.Pix, want.Pix) { + t.Fatalf("batch %d (low-memory uploads %t): update %+v drew other pixels than a rebuild of %d instances", batch, screen.renderer.lowMemoryUploads, update, len(rectangles)) + } } } if shrinks == 0 || grows == 0 { diff --git a/internal/platform/windows/offscreen_windows.go b/internal/platform/windows/offscreen_windows.go index f78a2a0ae..4587028ee 100644 --- a/internal/platform/windows/offscreen_windows.go +++ b/internal/platform/windows/offscreen_windows.go @@ -27,11 +27,19 @@ type Offscreen struct { // NewOffscreen creates a renderer for a width x height logical-pixel scene at // the given backing scale, cleared to clear before each render. func NewOffscreen(width, height int, scale float64, clear platform.Color) (*Offscreen, error) { + return NewOffscreenWithConfig(platform.Config{Width: width, Height: height, ClearColor: clear}, scale) +} + +// NewOffscreenWithConfig draws with the window's dimensions, clear color +// and D3D11 upload policy. +func NewOffscreenWithConfig(config platform.Config, scale float64) (*Offscreen, error) { + width, height := config.Width, config.Height if width < 1 || height < 1 || scale < 1 { return nil, fmt.Errorf("windows: invalid offscreen size %dx%d at %gx", width, height, scale) } offscreen := &Offscreen{width: width, height: height, scale: scale} - offscreen.renderer.color = clear + offscreen.renderer.color = config.ClearColor + offscreen.renderer.lowMemoryUploads = config.D3D11LowMemoryUploads levels := [...]uint32{0xb000} var status uintptr for _, driver := range [...]uintptr{1, 5} { @@ -45,7 +53,7 @@ func NewOffscreen(width, height int, scale float64, clear platform.Color) (*Offs if err := hresult(status); err != nil { return nil, fmt.Errorf("create D3D11 device, hardware and software (WARP) both failed: %w: %w", platform.ErrNoGraphics, err) } - if err := offscreen.renderer.createResources(); err != nil { + if err := offscreen.renderer.createResourcesWithFallback(); err != nil { offscreen.Close() return nil, err } diff --git a/internal/platform/windows/renderer_windows.go b/internal/platform/windows/renderer_windows.go index 4000775fc..f52c1fcc3 100644 --- a/internal/platform/windows/renderer_windows.go +++ b/internal/platform/windows/renderer_windows.go @@ -1,6 +1,7 @@ package windows import ( + "errors" "fmt" "math" "os" @@ -137,6 +138,9 @@ type renderer struct { rectangleVertex, rectangleFragment, textVertex, textFragment uintptr buffer, view, constants, blend, textBlend, raster, sampler uintptr direct *directRasterizer + upload uintptr + uploadCapacity int + lowMemoryUploads bool instances []rectangleInstance rectangleClips []render.Rectangle // only Layer, Clipped and Clip are kept rectangleBatches []render.Batch @@ -277,7 +281,7 @@ func (renderer *renderer) createDeviceAndResources(software bool) error { release(&renderer.swap) continue } - err := renderer.createResources() + err := renderer.createResourcesWithFallback() if err == nil { renderer.describeDevice() } @@ -335,7 +339,12 @@ func (renderer *renderer) createResources() error { } } buffer := bufferDesc{Bytes: uint32(unsafe.Sizeof(frameConstants{})), Bind: 4} + buffer.Usage, buffer.CPU = renderer.mutableResourceUsage() if err := hresult(comCall3(renderer.device, 3, uintptr(unsafe.Pointer(&buffer)), 0, uintptr(unsafe.Pointer(&renderer.constants)))); err != nil { + err = fmt.Errorf("create frame constants: %w", err) + if renderer.lowMemoryUploads { + return lowMemoryUploadError(err) + } return err } blending := blendDesc{} @@ -368,6 +377,25 @@ func (renderer *renderer) createResources() error { return nil } +// createResourcesWithFallback retries pipeline creation with default uploads +// when a device accepts the requested shaders but rejects a dynamic resource. +// The device-loss path remains responsible for recreating a removed device. +func (renderer *renderer) createResourcesWithFallback() error { + err := renderer.createResources() + if err == nil || !errors.Is(err, errLowMemoryUpload) || renderer.deviceLost() { + return err + } + renderer.lowMemoryUploads = false + renderer.releasePipelineResources() + return renderer.createResources() +} + +func (renderer *renderer) releasePipelineResources() { + for _, object := range [...]*uintptr{&renderer.device1, &renderer.constants, &renderer.blend, &renderer.textBlend, &renderer.raster, &renderer.sampler, &renderer.rectangleVertex, &renderer.rectangleFragment, &renderer.textVertex, &renderer.textFragment} { + release(object) + } +} + // storeRectangles copies the changed instances and their layer and clip, then // regroups the batches. It returns the range of instances to upload. func (renderer *renderer) storeRectangles(frame platform.Frame) (first, count int, err error) { @@ -434,6 +462,17 @@ func (renderer *renderer) storeRectangles(frame platform.Frame) (first, count in } func (renderer *renderer) apply(frame platform.Frame) error { + err := renderer.applyOnce(frame) + if err == nil || !errors.Is(err, errLowMemoryUpload) || renderer.deviceLost() { + return err + } + if err := renderer.disableLowMemoryUploads(); err != nil { + return err + } + return renderer.applyOnce(frame) +} + +func (renderer *renderer) applyOnce(frame platform.Frame) error { compositingChanged := false update := frame.Update if !update.Empty() { @@ -449,8 +488,9 @@ func (renderer *renderer) apply(frame platform.Frame) error { first, count = 0, len(renderer.instances) } if count > 0 { - region := box{Left: uint32(first * rectangleInstanceBytes), Right: uint32((first + count) * rectangleInstanceBytes), Bottom: 1, Back: 1} - comCall6(renderer.context, 48, renderer.buffer, 0, uintptr(unsafe.Pointer(®ion)), uintptr(unsafe.Pointer(&renderer.instances[first])), 0, 0) + if err := renderer.uploadInstances(first, count); err != nil { + return err + } } } if frame.TextLabels != nil { @@ -636,6 +676,17 @@ func swapChainResize(bufferWidth, bufferHeight, width, height int, hasTarget, he // compositing batch onto it. The window's present and the offscreen render // share it, so a screenshot is made of the pixels the window would show. func (renderer *renderer) draw(width, height int, scale float32) error { + err := renderer.drawOnce(width, height, scale) + if err == nil || !errors.Is(err, errLowMemoryUpload) || renderer.deviceLost() { + return err + } + if err := renderer.disableLowMemoryUploads(); err != nil { + return err + } + return renderer.drawOnce(width, height, scale) +} + +func (renderer *renderer) drawOnce(width, height int, scale float32) error { renderer.frameNumber++ defer func() { renderer.releaseShared() @@ -669,7 +720,9 @@ func (renderer *renderer) draw(width, height int, scale float32) error { comCall1(renderer.context, 24, 4) frame := &scratch.frame *frame = frameConstants{Width: float32(width) / scale, Height: float32(height) / scale, PixelSize: 1 / scale} - comCall6(renderer.context, 48, renderer.constants, 0, 0, uintptr(unsafe.Pointer(frame)), 0, 0) + if err := renderer.writeFrame(frame); err != nil { + return err + } comCall3(renderer.context, 7, 0, 1, uintptr(unsafe.Pointer(&renderer.constants))) // the vertex shaders comCall3(renderer.context, 16, 0, 1, uintptr(unsafe.Pointer(&renderer.constants))) // the text pixel shader boundKind := compositingBatchKind(0) @@ -694,7 +747,9 @@ func (renderer *renderer) draw(width, height int, scale float32) error { current = scissor } frame.InstanceOffset = uint32(batch.First) - comCall6(renderer.context, 48, renderer.constants, 0, 0, uintptr(unsafe.Pointer(frame)), 0, 0) + if err := renderer.writeFrame(frame); err != nil { + return err + } comCall4(renderer.context, 21, 6, uintptr(batch.Count), 0, uintptr(batch.First)) case compositeText: if boundKind != compositeText { @@ -708,7 +763,9 @@ func (renderer *renderer) draw(width, height int, scale float32) error { index := renderer.labelOrder[labelOffset] label := &renderer.labels[index] if label.label.TextureID != 0 { - renderer.drawSharedTexture(label, scale, width, height, frame, ¤t) + if err := renderer.drawSharedTexture(label, scale, width, height, frame, ¤t); err != nil { + return err + } continue } if label.label.Width <= 0 || label.label.Height <= 0 || label.label.Value == "" && len(label.label.Bitmap) == 0 { @@ -744,7 +801,9 @@ func (renderer *renderer) draw(width, height int, scale float32) error { } comCall3(renderer.context, 8, 1, 1, uintptr(unsafe.Pointer(&label.view))) if len(label.spans) == 0 { - comCall6(renderer.context, 48, renderer.constants, 0, 0, uintptr(unsafe.Pointer(frame)), 0, 0) + if err := renderer.writeFrame(frame); err != nil { + return err + } if scissor != current { renderer.setScissor(scissor) current = scissor @@ -763,7 +822,9 @@ func (renderer *renderer) draw(width, height int, scale float32) error { continue } frame.TextColor = [4]float32{span.color.R, span.color.G, span.color.B, span.color.A} - comCall6(renderer.context, 48, renderer.constants, 0, 0, uintptr(unsafe.Pointer(frame)), 0, 0) + if err := renderer.writeFrame(frame); err != nil { + return err + } if cut != current { renderer.setScissor(cut) current = cut @@ -781,6 +842,8 @@ func (renderer *renderer) draw(width, height int, scale float32) error { // drawScratch holds what draw hands Direct3D by address; see draw. type drawScratch struct { + mapped resourceData + copyBox box clear [4]float32 viewport viewport scissor scissorRect @@ -837,6 +900,8 @@ func (renderer *renderer) releaseDevice() { renderer.capacity, renderer.width, renderer.height = 0, 0, 0 renderer.bufferWidth, renderer.bufferHeight = 0, 0 renderer.releaseComposition() + release(&renderer.upload) + renderer.uploadCapacity = 0 for _, object := range [...]*uintptr{&renderer.target, &renderer.swap, &renderer.view, &renderer.buffer, &renderer.constants, &renderer.blend, &renderer.textBlend, &renderer.raster, &renderer.sampler, &renderer.rectangleVertex, &renderer.rectangleFragment, &renderer.textVertex, &renderer.textFragment, &renderer.context, &renderer.device} { release(object) } diff --git a/internal/platform/windows/shared_windows.go b/internal/platform/windows/shared_windows.go index c7d0f77e7..bbf8ffa86 100644 --- a/internal/platform/windows/shared_windows.go +++ b/internal/platform/windows/shared_windows.go @@ -178,7 +178,7 @@ func (renderer *renderer) openShared(label platform.TextLabel) (*sharedTexture, // quad shader, narrowed to its scissor. If the latest slot's keyed mutex times // out, it falls back to the last valid slot drawn by this label to avoid a // blank-frame flicker. -func (renderer *renderer) drawSharedTexture(label *labelTexture, scale float32, width, height int, frame *frameConstants, current *scissorRect) { +func (renderer *renderer) drawSharedTexture(label *labelTexture, scale float32, width, height int, frame *frameConstants, current *scissorRect) error { l := label.label if label.picture != nil || label.view != 0 || label.texture != 0 { // A slot that showed text or a bitmap before keeps nothing of it. @@ -189,25 +189,28 @@ func (renderer *renderer) drawSharedTexture(label *labelTexture, scale float32, entry = renderer.acquireShared(renderer.shared[label.lastSharedID]) } if entry == nil { - return + return nil } label.lastSharedID = entry.id scissor, visible := labelScissor(l, scale, width, height) if !visible { - return + return nil } x, y := platform.DevicePosition(l.X, 0, scale), platform.DevicePosition(l.Y, 0, scale) w, h := platform.DeviceExtent(l.X, l.Width, scale), platform.DeviceExtent(l.Y, l.Height, scale) frame.Bounds = [4]float32{float32(x) / scale, float32(y) / scale, float32(w) / scale, float32(h) / scale} frame.TextShape = [4]float32{l.Width, l.Height, l.ImageRadius, l.ImageFade} frame.TextMode = 0 - comCall6(renderer.context, 48, renderer.constants, 0, 0, uintptr(unsafe.Pointer(frame)), 0, 0) + if err := renderer.writeFrame(frame); err != nil { + return err + } if scissor != *current { renderer.setScissor(scissor) *current = scissor } comCall3(renderer.context, 8, 1, 1, uintptr(unsafe.Pointer(&entry.view))) comCall2(renderer.context, 13, 6, 0) + return nil } // releaseShared releases the keyed mutexes the frame read, its draws issued: diff --git a/internal/platform/windows/system_directory_windows_test.go b/internal/platform/windows/system_directory_windows_test.go index 85564d471..449862126 100644 --- a/internal/platform/windows/system_directory_windows_test.go +++ b/internal/platform/windows/system_directory_windows_test.go @@ -47,3 +47,29 @@ func TestFileDialogInitialDirectory(t *testing.T) { t.Fatal(err) } } + +func TestDirectoryDialogSelectionMode(t *testing.T) { + for _, multiple := range []bool{false, true} { + err := withSTA(func() error { + dialog, err := createFileDialog(&openDialogClass, &openDialogInterface) + if err != nil { + return err + } + defer release(&dialog) + if err := configureDirectoryDialog(dialog, OpenDirectoryOptions{}, multiple); err != nil { + return err + } + var flags uint32 + if err := hresult(comCall1(dialog, 10, uintptr(unsafe.Pointer(&flags)))); err != nil { + return err + } + if flags&pickFolders == 0 || (flags&allowMultiSelect != 0) != multiple { + return fmt.Errorf("directory dialog options %#x for multiple=%t", flags, multiple) + } + return nil + }) + if err != nil { + t.Fatal(err) + } + } +} diff --git a/internal/platform/windows/system_windows.go b/internal/platform/windows/system_windows.go index 707fec3f5..eddb7c6e5 100644 --- a/internal/platform/windows/system_windows.go +++ b/internal/platform/windows/system_windows.go @@ -552,8 +552,8 @@ func OpenFiles(options OpenFileOptions) ([]string, bool, error) { return paths, canceled, err } -func OpenDirectory(options OpenDirectoryOptions) (string, bool, error) { - var path string +func OpenDirectories(options OpenDirectoryOptions, multiple bool) ([]string, bool, error) { + var paths []string canceled := false err := withSTA(func() error { dialog, err := createFileDialog(&openDialogClass, &openDialogInterface) @@ -561,11 +561,7 @@ func OpenDirectory(options OpenDirectoryOptions) (string, bool, error) { return err } defer release(&dialog) - flags := uint32(forceFileSystem | pathMustExist | noChangeDirectory | pickFolders) - if err := configureFileDialog(dialog, options.Title, nil, flags); err != nil { - return err - } - if err := setFileDialogDirectory(dialog, options.InitialDirectory); err != nil { + if err := configureDirectoryDialog(dialog, options, multiple); err != nil { return err } status := uint32(comCall1(dialog, 3, dialogOwner())) @@ -576,15 +572,21 @@ func OpenDirectory(options OpenDirectoryOptions) (string, bool, error) { if err := hresult(uintptr(status)); err != nil { return fmt.Errorf("windows: show open directory dialog: %w", err) } - var item uintptr - if err := hresult(comCall1(dialog, 20, uintptr(unsafe.Pointer(&item)))); err != nil { - return fmt.Errorf("windows: get open directory result: %w", err) - } - defer release(&item) - path, err = shellItemPath(item) + paths, err = dialogResults(dialog) return err }) - return path, canceled, err + return paths, canceled, err +} + +func configureDirectoryDialog(dialog uintptr, options OpenDirectoryOptions, multiple bool) error { + flags := uint32(forceFileSystem | pathMustExist | noChangeDirectory | pickFolders) + if multiple { + flags |= allowMultiSelect + } + if err := configureFileDialog(dialog, options.Title, nil, flags); err != nil { + return err + } + return setFileDialogDirectory(dialog, options.InitialDirectory) } func setFileDialogDirectory(dialog uintptr, directory string) error { diff --git a/internal/platform/windows/text_windows.go b/internal/platform/windows/text_windows.go index 462224ff5..6588b491a 100644 --- a/internal/platform/windows/text_windows.go +++ b/internal/platform/windows/text_windows.go @@ -438,19 +438,31 @@ func (renderer *renderer) uploadLabel(label *labelTexture, pixels []byte, scale } if label.texture != 0 && label.view != 0 && label.width == width && label.height == height { // The same size as the texture it replaces: write the new pixels into it. - comCall6(renderer.context, 48, label.texture, 0, 0, uintptr(unsafe.Pointer(&pixels[0])), uintptr(width*4), 0) + if err := renderer.writeLabel(label.texture, pixels, width, height); err != nil { + return err + } label.scale, label.skip, label.stale = scale, skip, false renderer.labelRebuilds++ return nil } - description := textureDesc{Width: uint32(width), Height: uint32(height), Mips: 1, Array: 1, Format: 87, Samples: 1, Usage: 0, Bind: 8} // DEFAULT, not IMMUTABLE: a changed label's pixels are written into it + description := textureDesc{Width: uint32(width), Height: uint32(height), Mips: 1, Array: 1, Format: 87, Samples: 1, Bind: 8} + description.Usage, description.CPU = renderer.mutableResourceUsage() data := resourceData{Data: unsafe.Pointer(&pixels[0]), Pitch: uint32(width * 4)} release(&label.view) release(&label.texture) if err := hresult(comCall3(renderer.device, 5, uintptr(unsafe.Pointer(&description)), uintptr(unsafe.Pointer(&data)), uintptr(unsafe.Pointer(&label.texture)))); err != nil { + err = fmt.Errorf("create mutable label texture: %w", err) + if renderer.lowMemoryUploads { + return lowMemoryUploadError(err) + } return err } if err := hresult(comCall3(renderer.device, 7, label.texture, 0, uintptr(unsafe.Pointer(&label.view)))); err != nil { + release(&label.texture) + err = fmt.Errorf("create mutable label texture view: %w", err) + if renderer.lowMemoryUploads { + return lowMemoryUploadError(err) + } return err } label.scale = scale diff --git a/internal/platform/windows/trim_windows.go b/internal/platform/windows/trim_windows.go index 79e591314..fd445ac9e 100644 --- a/internal/platform/windows/trim_windows.go +++ b/internal/platform/windows/trim_windows.go @@ -3,6 +3,8 @@ package windows import ( "time" "unsafe" + + "github.com/vivaui/viva/internal/platform" ) // A graphics driver keeps what a frame needed (staging copies of uploads, @@ -17,8 +19,8 @@ import ( const ( trimTimerID = 2 // trimIdle is how long a window must go without presenting before its driver - // memory is trimmed. - trimIdle = 2 * time.Second + // memory is trimmed: the delay every platform's renderer waits. + trimIdle = platform.IdleTrimDelay ) // dxgiDevice3IID is IID_IDXGIDevice3. diff --git a/internal/platform/windows/upload_windows.go b/internal/platform/windows/upload_windows.go new file mode 100644 index 000000000..21a0ea184 --- /dev/null +++ b/internal/platform/windows/upload_windows.go @@ -0,0 +1,128 @@ +package windows + +import ( + "errors" + "fmt" + "unsafe" +) + +const ( + dynamicUsage = 2 // D3D11_USAGE_DYNAMIC + cpuWriteAccess = 0x10000 + writeDiscard = 4 // D3D11_MAP_WRITE_DISCARD +) + +var errLowMemoryUpload = errors.New("low-memory D3D11 upload failed") + +func lowMemoryUploadError(err error) error { + return fmt.Errorf("%w: %w", errLowMemoryUpload, err) +} + +// The constants and mutable label textures must allow CPU writes only when +// their updates use Map(WRITE_DISCARD). +func (renderer *renderer) mutableResourceUsage() (usage, cpu uint32) { + if renderer.lowMemoryUploads { + return dynamicUsage, cpuWriteAccess + } + return 0, 0 // D3D11_USAGE_DEFAULT for UpdateSubresource +} + +// disableLowMemoryUploads switches an existing device to UpdateSubresource for +// all resources whose descriptors depend on the upload policy. Releasing the +// optional upload storage first gives the replacement resources the most room +// to be created when the original failure was caused by memory pressure. +func (renderer *renderer) disableLowMemoryUploads() error { + if !renderer.lowMemoryUploads { + return nil + } + release(&renderer.upload) + renderer.uploadCapacity = 0 + for index := range renderer.labels { + if renderer.labels[index].picture == nil { + renderer.labels[index].dropTexture() + } + } + description := bufferDesc{Bytes: uint32(unsafe.Sizeof(frameConstants{})), Bind: 4} + var constants uintptr + if err := hresult(comCall3(renderer.device, 3, uintptr(unsafe.Pointer(&description)), 0, uintptr(unsafe.Pointer(&constants)))); err != nil { + return fmt.Errorf("create default frame constants: %w", err) + } + renderer.lowMemoryUploads = false + release(&renderer.constants) + renderer.constants = constants + return nil +} + +// uploadInstances updates only the changed range of the structured GPU buffer. +// The optional copy source avoids a large driver-side allocation observed on +// Intel Iris Xe on the first UpdateSubresource, even for a small range. +func (renderer *renderer) uploadInstances(first, count int) error { + n := count * rectangleInstanceBytes + region := &renderer.drawScratch.copyBox + if !renderer.lowMemoryUploads { + left := uint32(first * rectangleInstanceBytes) + *region = box{Left: left, Right: left + uint32(n), Bottom: 1, Back: 1} + comCall6(renderer.context, 48, renderer.buffer, 0, uintptr(unsafe.Pointer(region)), uintptr(unsafe.Pointer(&renderer.instances[first])), 0, 0) + return nil + } + // growInstanceBuffer has already checked the device's byte limit. + if n > renderer.uploadCapacity { + description := bufferDesc{Bytes: uint32(n), Usage: dynamicUsage, Bind: 1, CPU: cpuWriteAccess} + var upload uintptr + if err := hresult(comCall3(renderer.device, 3, uintptr(unsafe.Pointer(&description)), 0, uintptr(unsafe.Pointer(&upload)))); err != nil { + return lowMemoryUploadError(fmt.Errorf("create scene upload buffer: %w", err)) + } + release(&renderer.upload) + renderer.upload, renderer.uploadCapacity = upload, n + } + mapped := &renderer.drawScratch.mapped + if err := hresult(comCall5(renderer.context, 14, renderer.upload, 0, writeDiscard, 0, uintptr(unsafe.Pointer(mapped)))); err != nil { + return lowMemoryUploadError(fmt.Errorf("map scene upload buffer: %w", err)) + } + copy(unsafe.Slice((*rectangleInstance)(mapped.Data), count), renderer.instances[first:first+count]) + comCall2(renderer.context, 15, renderer.upload, 0) + // CopySubresourceRegion addresses buffers in bytes. The source begins at + // zero after every discard, even for a patch in the middle of the scene. + *region = box{Right: uint32(n), Bottom: 1, Back: 1} + comCall8(renderer.context, 46, renderer.buffer, 0, uintptr(first*rectangleInstanceBytes), 0, 0, renderer.upload, 0, uintptr(unsafe.Pointer(region))) + return nil +} + +// writeFrame replaces all shader constants for the next draw. +func (renderer *renderer) writeFrame(frame *frameConstants) error { + if !renderer.lowMemoryUploads { + comCall6(renderer.context, 48, renderer.constants, 0, 0, uintptr(unsafe.Pointer(frame)), 0, 0) + return nil + } + mapped := &renderer.drawScratch.mapped + if err := hresult(comCall5(renderer.context, 14, renderer.constants, 0, writeDiscard, 0, uintptr(unsafe.Pointer(mapped)))); err != nil { + return lowMemoryUploadError(fmt.Errorf("map frame constants: %w", err)) + } + *(*frameConstants)(mapped.Data) = *frame + comCall2(renderer.context, 15, renderer.constants, 0) + return nil +} + +// writeLabel updates a same-size mutable text or bitmap texture. D3D may pad +// each mapped row, whereas the rasterizer supplies tightly packed BGRA. +func (renderer *renderer) writeLabel(texture uintptr, pixels []byte, width, height int) error { + if !renderer.lowMemoryUploads { + comCall6(renderer.context, 48, texture, 0, 0, uintptr(unsafe.Pointer(&pixels[0])), uintptr(width*4), 0) + return nil + } + mapped := &renderer.drawScratch.mapped + if err := hresult(comCall5(renderer.context, 14, texture, 0, writeDiscard, 0, uintptr(unsafe.Pointer(mapped)))); err != nil { + return lowMemoryUploadError(fmt.Errorf("map label texture: %w", err)) + } + widthBytes, pitch := width*4, int(mapped.Pitch) + if pitch == widthBytes { + copy(unsafe.Slice((*byte)(mapped.Data), widthBytes*height), pixels) + } else { + for y := 0; y < height; y++ { + row := unsafe.Slice((*byte)(unsafe.Add(mapped.Data, y*pitch)), widthBytes) + copy(row, pixels[y*widthBytes:(y+1)*widthBytes]) + } + } + comCall2(renderer.context, 15, texture, 0) + return nil +} diff --git a/internal/platform/windows/upload_windows_test.go b/internal/platform/windows/upload_windows_test.go new file mode 100644 index 000000000..750849735 --- /dev/null +++ b/internal/platform/windows/upload_windows_test.go @@ -0,0 +1,210 @@ +package windows + +import ( + "bytes" + "errors" + "image/color" + "runtime" + "testing" + "unsafe" + + "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/internal/render" + "github.com/vivaui/viva/internal/scene" +) + +func TestWindowUploadModeIsIndependent(t *testing.T) { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + err := RunApplication(func(application platform.Application) error { + renderers := make(map[bool]*renderer) + for _, lowMemory := range []bool{true, false} { + window, err := application.OpenWindow(platform.Config{ + Title: "Upload test", Width: 64, Height: 64, WindowMode: platform.WindowNotification, + ClearColor: black, D3D11LowMemoryUploads: lowMemory, + }) + if err != nil { + return err + } + defer window.Close() + renderers[lowMemory] = &window.(*nativeWindow).state.renderer + } + // Upload the first rectangle after both windows have selected a mode. + frame := platform.Frame{Update: initialUpdate(1), Rectangles: []render.Rectangle{ + {Bounds: scene.Rect{Width: 16, Height: 16}, Color: scene.Color{Red: 1, Alpha: 1}}, + }} + for lowMemory, drawn := range renderers { + if err := drawn.apply(frame); err != nil { + return err + } + if got := drawn.upload != 0; got != lowMemory { + t.Errorf("window with D3D11LowMemoryUploads=%t has dedicated upload buffer = %t", lowMemory, got) + } + } + return nil + }) + if err != nil { + t.Fatal(err) + } +} + +func TestUploadsPreserveOtherInstancesAndBitmapRows(t *testing.T) { + for _, option := range []struct { + name string + lowMemory bool + usage, cpu uint32 + }{ + {"default", false, 0, 0}, + {"low-memory", true, dynamicUsage, cpuWriteAccess}, + } { + t.Run(option.name, func(t *testing.T) { + screen := newUploadTestScreen(t, 48, 24, option.lowMemory) + checkPartialSceneUpload(t, screen) + + // GetDesc on the real D3D resources distinguishes the upload paths + // even when both render the same pixels. + var constants bufferDesc + var bitmap textureDesc + if screen.renderer.constants == 0 || screen.renderer.labels[0].texture == 0 { + t.Fatal("missing constants or mutable bitmap texture") + } + comCall1(screen.renderer.constants, 10, uintptr(unsafe.Pointer(&constants))) + comCall1(screen.renderer.labels[0].texture, 10, uintptr(unsafe.Pointer(&bitmap))) + if constants.Usage != option.usage || constants.CPU != option.cpu || + bitmap.Usage != option.usage || bitmap.CPU != option.cpu { + t.Errorf("usage/CPU access: constants %d/%#x, bitmap %d/%#x, want %d/%#x", + constants.Usage, constants.CPU, bitmap.Usage, bitmap.CPU, option.usage, option.cpu) + } + if got, want := screen.renderer.upload != 0, option.lowMemory; got != want { + t.Errorf("dedicated rectangle upload buffer: got %t, want %t", got, want) + } + }) + } +} + +func TestLowMemoryUploadsFallBackToDefaultResources(t *testing.T) { + screen := newUploadTestScreen(t, 48, 24, true) + const width, height = 7, 6 + pixels := make([]byte, width*height*4) + for index := range pixels { + pixels[index] = 255 + } + labels := []platform.TextLabel{{ + X: 4, Y: 12, Width: width, Height: height, + BitmapWidth: width, BitmapHeight: height, BitmapStride: width * 4, + Bitmap: pixels, BitmapID: 1, + }} + before := renderScene(t, screen, []render.Rectangle{{ + Bounds: scene.Rect{X: 2, Y: 2, Width: 16, Height: 8}, + Color: scene.Color{Red: 1, Alpha: 1}, + }}, labels) + + if !screen.renderer.lowMemoryUploads || screen.renderer.upload == 0 { + t.Fatal("the test scene did not use low-memory uploads") + } + if screen.renderer.labels[0].texture == 0 { + t.Fatal("the test scene did not create a mutable label texture") + } + + if err := screen.renderer.disableLowMemoryUploads(); err != nil { + t.Fatal(err) + } + if screen.renderer.lowMemoryUploads { + t.Fatal("low-memory uploads remained enabled after fallback") + } + if screen.renderer.upload != 0 || screen.renderer.uploadCapacity != 0 { + t.Fatalf("dedicated upload buffer survived fallback: %d bytes", screen.renderer.uploadCapacity) + } + var constants bufferDesc + if err := hresult(comCall1(screen.renderer.constants, 10, uintptr(unsafe.Pointer(&constants)))); err != nil { + t.Fatal(err) + } + if constants.Usage != 0 || constants.CPU != 0 { + t.Fatalf("fallback constants usage/CPU = %d/%#x, want 0/0", constants.Usage, constants.CPU) + } + if screen.renderer.labels[0].texture != 0 { + t.Fatal("mutable label texture was not released for recreation") + } + + after, err := screen.Image() + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(before.Pix, after.Pix) { + t.Fatal("fallback changed rendered pixels") + } + var bitmap textureDesc + if err := hresult(comCall1(screen.renderer.labels[0].texture, 10, uintptr(unsafe.Pointer(&bitmap)))); err != nil { + t.Fatal(err) + } + if bitmap.Usage != 0 || bitmap.CPU != 0 { + t.Fatalf("fallback bitmap usage/CPU = %d/%#x, want 0/0", bitmap.Usage, bitmap.CPU) + } +} + +func newUploadTestScreen(t *testing.T, width, height int, lowMemory bool) *Offscreen { + t.Helper() + screen, err := NewOffscreenWithConfig(platform.Config{ + Width: width, Height: height, ClearColor: black, D3D11LowMemoryUploads: lowMemory, + }, 1) + if errors.Is(err, platform.ErrNoGraphics) { + t.Skip(err) + } + if err != nil { + t.Fatal(err) + } + t.Cleanup(screen.Close) + return screen +} + +func checkPartialSceneUpload(t *testing.T, screen *Offscreen) { + t.Helper() + var rects []render.Rectangle + for index, shade := range []scene.Color{{Red: 1, Alpha: 1}, {Green: 1, Alpha: 1}, {Blue: 1, Alpha: 1}} { + rects = append(rects, render.Rectangle{Bounds: scene.Rect{X: float32(index * 12), Width: 10, Height: 8}, Color: shade}) + } + // An odd width exercises the mapped row pitch when the driver pads it. + const width, height = 7, 6 + bitmap := func(flip bool) []byte { + pixels := make([]byte, width*height*4) + for y := 0; y < height; y++ { + for x := 0; x < width; x++ { + i := 4 * (y*width + x) + pixels[i+3] = 255 + if (y < height/2) != flip { + pixels[i+2] = 255 + } else { + pixels[i] = 255 + } + } + } + return pixels + } + labels := []platform.TextLabel{{X: 4, Y: 12, Width: width, Height: height, BitmapWidth: width, BitmapHeight: height, BitmapStride: width * 4, Bitmap: bitmap(false), BitmapID: 1}} + first := renderScene(t, screen, rects, labels) + red, blue := color.RGBA{R: 255, A: 255}, color.RGBA{B: 255, A: 255} + if first.RGBAAt(7, 13) != red || first.RGBAAt(7, 16) != blue { + t.Fatal("incorrect initial bitmap rows") + } + rects[1].Color = scene.Color{Red: 1, Green: 1, Alpha: 1} + labels[0].Bitmap, labels[0].BitmapID = bitmap(true), 2 + err := screen.renderer.apply(platform.Frame{Update: render.Update{First: 1, Count: 1}, Rectangles: rects, TextLabels: labels}) + if err != nil { + t.Fatal(err) + } + next, err := screen.Image() + if err != nil { + t.Fatal(err) + } + for _, sample := range []struct { + x, y int + want color.RGBA + }{ + {4, 4, red}, {16, 4, color.RGBA{R: 255, G: 255, A: 255}}, {28, 4, blue}, + {7, 13, blue}, {7, 16, red}, + } { + if got := next.RGBAAt(sample.x, sample.y); got != sample.want { + t.Errorf("pixel (%d,%d) = %v, want %v", sample.x, sample.y, got, sample.want) + } + } +} diff --git a/internal/platform/windows/window_windows.go b/internal/platform/windows/window_windows.go index a1fd41746..f0f4e996a 100644 --- a/internal/platform/windows/window_windows.go +++ b/internal/platform/windows/window_windows.go @@ -424,6 +424,7 @@ func (application *windowsApplication) OpenWindow(config platform.Config) (platf } } state.configureBackdropRenderer() + state.renderer.lowMemoryUploads = config.D3D11LowMemoryUploads if err := state.renderer.initialize(state.window, config.ClearColor); err != nil { destroyWindow.Call(state.window) return nil, err diff --git a/internal/raster/bench_test.go b/internal/raster/bench_test.go index f85a66f59..507c49702 100644 --- a/internal/raster/bench_test.go +++ b/internal/raster/bench_test.go @@ -36,7 +36,7 @@ func benchmarkDraw(b *testing.B, scale float32, damaged bool) { params := Params{Scale: scale, Clear: scene.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1}} if damaged { // The line a text field redraws as the user types. - params.Damage = render.Scissor{Left: int(260 * scale), Top: int(300 * scale), Right: int(460 * scale), Bottom: int(332 * scale)} + params.Damage = []render.Scissor{{Left: int(260 * scale), Top: int(300 * scale), Right: int(460 * scale), Bottom: int(332 * scale)}} } var r Rasterizer r.Draw(canvas, params, rects, nil) // warm the scratch lists @@ -52,6 +52,39 @@ func BenchmarkDrawWindow(b *testing.B) { benchmarkDraw(b, 1, false) } func BenchmarkDrawWindow150Percent(b *testing.B) { benchmarkDraw(b, 1.5, false) } func BenchmarkDrawTypingLine(b *testing.B) { benchmarkDraw(b, 1, true) } +// BenchmarkDrawTwoDistantChanges draws a frame in which a caret in the content and a clock in the +// top corner changed: as a region of two rectangles, and as the one box around both that a single +// damage rectangle would repaint. +func BenchmarkDrawTwoDistantChanges(b *testing.B) { + const width, height = 1280, 800 + caret := render.Scissor{Left: 300, Top: 500, Right: 302, Bottom: 518} + clock := render.Scissor{Left: 1180, Top: 4, Right: 1270, Bottom: 22} + var region Region + region.Add(caret) + region.Add(clock) + for _, run := range []struct { + name string + damage []render.Scissor + }{ + {"region", region.Rects()}, + {"bounds", []render.Scissor{region.Bounds()}}, + } { + b.Run(run.name, func(b *testing.B) { + canvas := NewCanvas(width, height) + rects := uiScene(width, height) + params := Params{Scale: 1, Clear: scene.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1}} + var r Rasterizer + r.Draw(canvas, params, rects, nil) + params.Damage = run.damage + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + r.Draw(canvas, params, rects, nil) + } + }) + } +} + func TestSteadyFramesAllocateNothing(t *testing.T) { canvas := NewCanvas(640, 400) rects := uiScene(640, 400) diff --git a/internal/raster/canvas.go b/internal/raster/canvas.go index 0768919f4..0902a88b3 100644 --- a/internal/raster/canvas.go +++ b/internal/raster/canvas.go @@ -44,6 +44,11 @@ func (c *Canvas) Resize(width, height int) { c.Stride, c.Width, c.Height = width*4, width, height } +// Release gives back the pixel storage and keeps the size: Pix is nil until Resize makes it +// again. It is for a canvas nothing shows for a while, whose pixels are all drawn again before it +// is next presented. +func (c *Canvas) Release() { c.Pix = nil } + // Bounds is the whole canvas as a scissor. func (c *Canvas) Bounds() render.Scissor { return render.Scissor{Right: c.Width, Bottom: c.Height} diff --git a/internal/raster/damage_test.go b/internal/raster/damage_test.go index b37b59033..3211a950e 100644 --- a/internal/raster/damage_test.go +++ b/internal/raster/damage_test.go @@ -33,8 +33,8 @@ func randomInstance(random *rand.Rand, width, height float32) render.Rectangle { return instance } -// Redrawing only the Box of what changed gives the pixels a full redraw gives: this is what lets a -// presenter keep a damage region instead of repainting the window. +// Redrawing only the Boxes of what changed, gathered in a Region, gives the pixels a full redraw +// gives: this is what lets a presenter keep a damage region instead of repainting the window. func TestRedrawingTheBoxOfAChangeEqualsRedrawingAll(t *testing.T) { const width, height = 96, 72 for _, scale := range []float32{1, 1.25, 1.5, 2} { @@ -46,11 +46,11 @@ func TestRedrawingTheBoxOfAChangeEqualsRedrawingAll(t *testing.T) { scene1[i] = randomInstance(random, width, height) } scene2 := append([]render.Rectangle(nil), scene1...) - var damage render.Scissor + var damage Region for _, index := range random.Perm(count)[:1+random.Intn(3)] { scene2[index] = randomInstance(random, width, height) for _, instance := range []*render.Rectangle{&scene1[index], &scene2[index]} { - damage = union(damage, Box(instance, scale)) + damage.Add(Box(instance, scale)) } } size := func() (int, int) { return int(width * scale), int(height * scale) } @@ -59,26 +59,17 @@ func TestRedrawingTheBoxOfAChangeEqualsRedrawingAll(t *testing.T) { var drawer Rasterizer params := Params{Scale: scale, Clear: white} drawer.Draw(partial, params, scene1, nil) - params.Damage = intersect(partial.Bounds(), damage) + damage.Limit(partial.Bounds()) + params.Damage = damage.Rects() drawer.Draw(partial, params, scene2, nil) drawer.Draw(full, Params{Scale: scale, Clear: white}, scene2, nil) if !bytes.Equal(partial.Pix, full.Pix) { - t.Fatalf("scale %g round %d: redrawing %+v differs from redrawing all", scale, round, damage) + t.Fatalf("scale %g round %d: redrawing %+v differs from redrawing all", scale, round, damage.Rects()) } } } } -func union(a, b render.Scissor) render.Scissor { - if empty(a) { - return b - } - if empty(b) { - return a - } - return render.Scissor{Left: min(a.Left, b.Left), Top: min(a.Top, b.Top), Right: max(a.Right, b.Right), Bottom: max(a.Bottom, b.Bottom)} -} - // Nothing an instance paints lies outside its Box, whatever the shape. func TestAnInstancePaintsOnlyInsideItsBox(t *testing.T) { const width, height = 80, 60 diff --git a/internal/raster/lcd_test.go b/internal/raster/lcd_test.go index 930cccbf5..edae0be9f 100644 --- a/internal/raster/lcd_test.go +++ b/internal/raster/lcd_test.go @@ -123,7 +123,7 @@ func TestLCDLabelDrawAllocatesNothing(t *testing.T) { }, } var drawer Rasterizer - params := Params{Scale: 1, Clear: scene.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1}, Damage: render.Scissor{Right: 64, Bottom: 20}} + params := Params{Scale: 1, Clear: scene.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1}, Damage: []render.Scissor{{Right: 64, Bottom: 20}}} drawer.Draw(c, params, nil, []Label{label}) if allocs := testing.AllocsPerRun(50, func() { drawer.Draw(c, params, nil, []Label{label}) diff --git a/internal/raster/raster.go b/internal/raster/raster.go index 797e546ba..aa36116bd 100644 --- a/internal/raster/raster.go +++ b/internal/raster/raster.go @@ -69,9 +69,9 @@ type Params struct { Clear scene.Color // Holes are the parts that end up transparent (see Hole). Holes []Hole - // Damage is the part of the canvas to redraw, in device pixels. The zero value redraws all of it. - // Pixels outside it are not read or written. - Damage render.Scissor + // Damage is the parts of the canvas to redraw, in device pixels: the rectangles of a Region, + // which do not overlap. Empty redraws all of it. Pixels outside them are not read or written. + Damage []render.Scissor } // Rasterizer draws frames. It holds scratch lists so that a steady stream of frames allocates @@ -84,7 +84,8 @@ type Rasterizer struct { // Draw paints the damaged part of c: clear, then for each layer in ascending order the layer's // rectangle instances in paint order and after them its labels in list order. This is the order -// the GPU backends use, so a popover layer covers the page layer whatever the list order. +// the GPU backends use, so a popover layer covers the page layer whatever the list order. The +// scene is sorted once and then drawn into each damaged rectangle in turn. func (r *Rasterizer) Draw(c *Canvas, p Params, rects []render.Rectangle, labels []Label) { if c == nil || c.Width <= 0 || c.Height <= 0 { return @@ -93,25 +94,30 @@ func (r *Rasterizer) Draw(c *Canvas, p Params, rects []render.Rectangle, labels if !(scale > 0) { scale = 1 } - damage := c.Bounds() - if p.Damage != (render.Scissor{}) { - damage = intersect(damage, p.Damage) - } - if empty(damage) { - return - } - c.clearRegion(damage, p.Clear) - r.batches = render.GroupBatches(r.batches, rects) r.order = r.order[:0] for i := range labels { r.order = append(r.order, i) } slices.SortStableFunc(r.order, func(a, b int) int { return int(labels[a].Layer) - int(labels[b].Layer) }) - - bi, li, hi := 0, 0, 0 r.holes = append(r.holes[:0], p.Holes...) slices.SortStableFunc(r.holes, func(a, b Hole) int { return int(a.Layer) - int(b.Layer) }) + if len(p.Damage) == 0 { + r.drawArea(c, c.Bounds(), p.Clear, scale, rects, labels) + return + } + for _, area := range p.Damage { + r.drawArea(c, intersect(c.Bounds(), area), p.Clear, scale, rects, labels) + } +} + +// drawArea clears one damaged rectangle and draws the sorted scene into it. +func (r *Rasterizer) drawArea(c *Canvas, damage render.Scissor, clear scene.Color, scale float32, rects []render.Rectangle, labels []Label) { + if empty(damage) { + return + } + c.clearRegion(damage, clear) + bi, li, hi := 0, 0, 0 holes := r.holes for bi < len(r.batches) || li < len(r.order) || hi < len(holes) { layer := uint16(math.MaxUint16) diff --git a/internal/raster/raster_test.go b/internal/raster/raster_test.go index 26b3468ce..0483b8146 100644 --- a/internal/raster/raster_test.go +++ b/internal/raster/raster_test.go @@ -87,7 +87,7 @@ func TestOnlyTheDamagedPartIsTouched(t *testing.T) { var r Rasterizer r.Draw(c, Params{Scale: 1, Clear: white}, []render.Rectangle{rect(0, 0, 8, 8, blue)}, nil) before := append([]byte(nil), c.Pix...) - r.Draw(c, Params{Scale: 1, Clear: white, Damage: render.Scissor{Left: 2, Top: 2, Right: 4, Bottom: 4}}, + r.Draw(c, Params{Scale: 1, Clear: white, Damage: []render.Scissor{{Left: 2, Top: 2, Right: 4, Bottom: 4}}}, []render.Rectangle{rect(0, 0, 8, 8, red)}, nil) for y := 0; y < 8; y++ { for x := 0; x < 8; x++ { diff --git a/internal/raster/region.go b/internal/raster/region.go new file mode 100644 index 000000000..d319c0131 --- /dev/null +++ b/internal/raster/region.go @@ -0,0 +1,139 @@ +package raster + +import "github.com/vivaui/viva/internal/render" + +// RegionRects is the most rectangles a Region keeps. Each rectangle costs a pass +// over the scene when it is drawn and a request when it is presented, so the +// set stays small; a fifth change joins the rectangle it grows least. +const RegionRects = 4 + +// regionWholePercent is how much of the canvas, in percent, a region may cover +// before it is drawn whole: beyond it the pixels left out save less than the +// passes and the presents of several rectangles cost. +const regionWholePercent = 60 + +// Region is a set of at most RegionRects disjoint rectangles of device pixels: +// the parts of a canvas that changed. Two small changes far apart, a caret and +// a clock, stay two small rectangles instead of the box around both. Adding a +// rectangle never loses pixels; the region may cover more than was added when +// it merges. The zero value is empty, and a Region allocates nothing. +type Region struct { + rects [RegionRects]render.Scissor + count int +} + +// Empty reports whether the region covers no pixel. +func (r *Region) Empty() bool { return r.count == 0 } + +// Rects are the region's rectangles, disjoint and not empty. The slice is the +// region's own: it is valid until the region next changes. +func (r *Region) Rects() []render.Scissor { return r.rects[:r.count] } + +// Reset empties the region. +func (r *Region) Reset() { r.count = 0 } + +// Set makes the region the one rectangle box. +func (r *Region) Set(box render.Scissor) { + r.count = 0 + r.Add(box) +} + +// Area is the number of pixels the region covers. +func (r *Region) Area() int { + total := 0 + for _, box := range r.rects[:r.count] { + total += area(box) + } + return total +} + +// Bounds is the smallest rectangle around the region, empty for an empty one. +func (r *Region) Bounds() render.Scissor { + if r.count == 0 { + return render.Scissor{} + } + bounds := r.rects[0] + for _, box := range r.rects[1:r.count] { + bounds = unionBox(bounds, box) + } + return bounds +} + +// Add adds the pixels of box. A rectangle it overlaps, or meets along a whole +// side, joins it, so the rectangles stay disjoint and no pixel is drawn twice; +// when the region is full, box joins the rectangle whose bounding box grows the +// least. +func (r *Region) Add(box render.Scissor) { + if empty(box) { + return + } + for { + joined := false + for index := 0; index < r.count; index++ { + other := r.rects[index] + if !empty(intersect(other, box)) || area(unionBox(other, box)) == area(other)+area(box) { + box = unionBox(other, box) + r.remove(index) + joined = true + break + } + } + if !joined { + break + } + } + if r.count < RegionRects { + r.rects[r.count] = box + r.count++ + return + } + best, growth := 0, -1 + for index, other := range r.rects[:r.count] { + if grown := area(unionBox(other, box)) - area(other) - area(box); growth < 0 || grown < growth { + best, growth = index, grown + } + } + box = unionBox(r.rects[best], box) + r.remove(best) + r.Add(box) +} + +// AddRegion adds the pixels of another region. +func (r *Region) AddRegion(other *Region) { + for _, box := range other.rects[:other.count] { + r.Add(box) + } +} + +// Limit keeps the region inside bounds, and makes it all of bounds when it +// covers so much of them that drawing the rectangles one by one would cost more +// than drawing everything once. +func (r *Region) Limit(bounds render.Scissor) { + kept := 0 + for _, box := range r.rects[:r.count] { + if box = intersect(box, bounds); !empty(box) { + r.rects[kept] = box + kept++ + } + } + r.count = kept + if kept > 0 && !empty(bounds) && r.Area()*100 >= area(bounds)*regionWholePercent { + r.rects[0], r.count = bounds, 1 + } +} + +func (r *Region) remove(index int) { + copy(r.rects[index:r.count], r.rects[index+1:r.count]) + r.count-- +} + +func area(box render.Scissor) int { + if empty(box) { + return 0 + } + return (box.Right - box.Left) * (box.Bottom - box.Top) +} + +func unionBox(a, b render.Scissor) render.Scissor { + return render.Scissor{Left: min(a.Left, b.Left), Top: min(a.Top, b.Top), Right: max(a.Right, b.Right), Bottom: max(a.Bottom, b.Bottom)} +} diff --git a/internal/raster/region_test.go b/internal/raster/region_test.go new file mode 100644 index 000000000..b0b9d2fe6 --- /dev/null +++ b/internal/raster/region_test.go @@ -0,0 +1,85 @@ +package raster + +import ( + "math/rand" + "testing" + + "github.com/vivaui/viva/internal/render" +) + +func covers(r *Region, x, y int) int { + count := 0 + for _, box := range r.Rects() { + if x >= box.Left && x < box.Right && y >= box.Top && y < box.Bottom { + count++ + } + } + return count +} + +// Two small changes far apart, a caret and a clock, repaint only their own pixels. +func TestRegionKeepsDistantChangesApart(t *testing.T) { + caret := render.Scissor{Left: 300, Top: 500, Right: 302, Bottom: 518} + clock := render.Scissor{Left: 1180, Top: 4, Right: 1270, Bottom: 22} + var region Region + region.Add(caret) + region.Add(clock) + region.Limit(render.Scissor{Right: 1280, Bottom: 800}) + if got, want := region.Area(), area(caret)+area(clock); got != want { + t.Fatalf("region of a caret and a clock covers %d pixels (%+v), want %d", got, region.Rects(), want) + } +} + +// Whatever is added, every added pixel is covered exactly once and the region +// never holds more than RegionRects rectangles: a change beyond them merges +// instead of being dropped. +func TestRegionCoversEveryAddedPixelOnce(t *testing.T) { + const width, height = 64, 48 + random := rand.New(rand.NewSource(3)) + for round := 0; round < 300; round++ { + var region Region + var added []render.Scissor + for range 1 + random.Intn(12) { + left, top := random.Intn(width), random.Intn(height) + box := render.Scissor{Left: left, Top: top, Right: left + 1 + random.Intn(12), Bottom: top + 1 + random.Intn(12)} + added = append(added, box) + region.Add(box) + } + if len(region.Rects()) > RegionRects { + t.Fatalf("round %d: %d rectangles, want at most %d", round, len(region.Rects()), RegionRects) + } + for y := 0; y < height+12; y++ { + for x := 0; x < width+12; x++ { + n := covers(®ion, x, y) + if n > 1 { + t.Fatalf("round %d: pixel %d,%d is in %d rectangles of %+v", round, x, y, n, region.Rects()) + } + for _, box := range added { + if x >= box.Left && x < box.Right && y >= box.Top && y < box.Bottom && n == 0 { + t.Fatalf("round %d: pixel %d,%d of %+v is not in %+v", round, x, y, box, region.Rects()) + } + } + } + } + } +} + +// Damage that covers most of the canvas is drawn whole, as one rectangle; a +// small part stays as it is, clipped to the canvas. +func TestRegionLimitFallsBackToTheWholeCanvas(t *testing.T) { + bounds := render.Scissor{Right: 100, Bottom: 100} + var large Region + large.Add(render.Scissor{Right: 100, Bottom: 40}) + large.Add(render.Scissor{Top: 70, Right: 100, Bottom: 100}) + large.Limit(bounds) + if rects := large.Rects(); len(rects) != 1 || rects[0] != bounds { + t.Fatalf("70%% of the canvas became %+v, want the whole canvas", rects) + } + var small Region + small.Add(render.Scissor{Left: -10, Top: -10, Right: 10, Bottom: 10}) + small.Add(render.Scissor{Left: 90, Top: 90, Right: 120, Bottom: 120}) + small.Limit(bounds) + if got := small.Area(); got != 200 { + t.Fatalf("two corners clipped to the canvas cover %d pixels (%+v), want 200", got, small.Rects()) + } +} diff --git a/internal/reloadwire/codec.go b/internal/reloadwire/codec.go index 99c1563d3..01ee08d58 100644 --- a/internal/reloadwire/codec.go +++ b/internal/reloadwire/codec.go @@ -9,7 +9,7 @@ import ( ) const ( - ProtocolVersion = 32 + ProtocolVersion = 33 MaxFrameBytes = 32 << 20 MaxStateBytes = 8 << 20 maxItems = 200_000 @@ -60,6 +60,8 @@ type WindowConfig struct { HasClose bool HasSnapshot bool HasRestore bool + + D3D11LowMemoryUploads bool } type Hello struct { @@ -298,6 +300,7 @@ func encodeWindowConfig(result *encoder, value WindowConfig) { result.bool(value.HasClose) result.bool(value.HasSnapshot) result.bool(value.HasRestore) + result.bool(value.D3D11LowMemoryUploads) } func decodeWindowConfig(value *decoder) WindowConfig { @@ -308,6 +311,7 @@ func decodeWindowConfig(value *decoder) WindowConfig { ClearRed: value.f64(), ClearGreen: value.f64(), ClearBlue: value.f64(), ClearAlpha: value.f64(), HasClick: value.bool(), HasPointer: value.bool(), HasKey: value.bool(), HasShortcut: value.bool(), HasScroll: value.bool(), HasModifierTap: value.bool(), HasClose: value.bool(), HasSnapshot: value.bool(), HasRestore: value.bool(), + D3D11LowMemoryUploads: value.bool(), } } diff --git a/internal/reloadwire/input_test.go b/internal/reloadwire/input_test.go index fbafab7f0..9b4c51b26 100644 --- a/internal/reloadwire/input_test.go +++ b/internal/reloadwire/input_test.go @@ -181,7 +181,7 @@ func decodeResultError(data []byte) error { _, err := decodeEventResult(data); func TestWindowConfigCodecPreservesInputCapabilities(t *testing.T) { want := Hello{Token: "capabilities", Config: WindowConfig{ Title: "input", Width: 640, Height: 480, WindowMode: 2, TitlebarHeight: 36, TrafficLightScale: 0.9, - MinWidth: 480, MinHeight: 320, + MinWidth: 480, MinHeight: 320, D3D11LowMemoryUploads: true, HasClick: true, HasPointer: true, HasKey: true, HasShortcut: true, HasScroll: true, HasModifierTap: true, HasClose: true, HasSnapshot: true, HasRestore: true, }} diff --git a/internal/semantic/role.go b/internal/semantic/role.go index 9284a8c55..284e22aac 100644 --- a/internal/semantic/role.go +++ b/internal/semantic/role.go @@ -29,4 +29,7 @@ const ( RoleStatus RoleSeparator RoleProgress + // RoleColumnHeader is a table column's header that sorts the rows when + // pressed. + RoleColumnHeader ) diff --git a/internal/softscene/damage_test.go b/internal/softscene/damage_test.go new file mode 100644 index 000000000..986963cde --- /dev/null +++ b/internal/softscene/damage_test.go @@ -0,0 +1,97 @@ +package softscene + +import ( + "bytes" + "testing" + + "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/internal/raster" + "github.com/vivaui/viva/internal/render" + "github.com/vivaui/viva/internal/scene" +) + +func damageTestScene(t *testing.T, rects []render.Rectangle) *Scene { + t.Helper() + s, err := New(noText{}, 400, 300, 1, scene.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1}, rects, nil) + if err != nil { + t.Fatal(err) + } + s.Paint() + return s +} + +func paintedArea(rects []render.Scissor) int { + total := 0 + for _, box := range rects { + total += (box.Right - box.Left) * (box.Bottom - box.Top) + } + return total +} + +// A caret in the content and a clock in a corner that change in one frame +// repaint their own pixels, not the box around both, and the canvas ends as a +// full paint of the new scene would leave it. +func TestDistantChangesRepaintOnlyTheirAreas(t *testing.T) { + background := render.Rectangle{Bounds: scene.Rect{Width: 400, Height: 300}, Color: scene.Color{Red: 0.9, Green: 0.9, Blue: 0.9, Alpha: 1}} + caret := render.Rectangle{Bounds: scene.Rect{X: 40, Y: 250, Width: 2, Height: 16}, Color: scene.Color{Alpha: 1}} + clock := render.Rectangle{Bounds: scene.Rect{X: 330, Y: 6, Width: 60, Height: 14}, Color: scene.Color{Blue: 1, Alpha: 1}} + s := damageTestScene(t, []render.Rectangle{background, caret, clock}) + + next := []render.Rectangle{background, caret, clock} + next[1].Bounds.X = 48 + next[2].Color = scene.Color{Red: 1, Alpha: 1} + if _, err := s.Apply(platform.Frame{Update: render.Update{First: 1, Count: 2}, Rectangles: next}); err != nil { + t.Fatal(err) + } + painted := s.Paint() + want := 0 + for _, instance := range []*render.Rectangle{&caret, &next[1], &next[2]} { + want += paintedArea([]render.Scissor{raster.Box(instance, 1)}) + } + if got := paintedArea(painted); len(painted) < 2 || got > want { + t.Fatalf("a caret and a clock repainted %+v (%d pixels), want at most their boxes' %d pixels", painted, got, want) + } + whole := damageTestScene(t, next) + if !bytes.Equal(s.Canvas.Pix, whole.Canvas.Pix) { + t.Fatal("the partial repaint differs from a full paint of the new scene") + } +} + +// A change that covers most of the window repaints the window whole, as one +// rectangle. +func TestLargeDamageRepaintsTheWholeCanvas(t *testing.T) { + background := render.Rectangle{Bounds: scene.Rect{Width: 400, Height: 300}, Color: scene.Color{Red: 0.9, Green: 0.9, Blue: 0.9, Alpha: 1}} + panel := render.Rectangle{Bounds: scene.Rect{Width: 380, Height: 280}, Color: scene.Color{Green: 1, Alpha: 1}} + s := damageTestScene(t, []render.Rectangle{background, panel}) + next := []render.Rectangle{background, panel} + next[1].Color = scene.Color{Red: 1, Alpha: 1} + if _, err := s.Apply(platform.Frame{Update: render.Update{First: 1, Count: 1}, Rectangles: next}); err != nil { + t.Fatal(err) + } + if painted := s.Paint(); len(painted) != 1 || painted[0] != s.Canvas.Bounds() { + t.Fatalf("a change over most of the window repainted %+v, want the whole canvas", painted) + } +} + +// A window whose caret and clock change every frame allocates nothing to track +// and paint the damage. +func TestSteadyDistantChangesAllocateNothing(t *testing.T) { + background := render.Rectangle{Bounds: scene.Rect{Width: 400, Height: 300}, Color: scene.Color{Red: 0.9, Green: 0.9, Blue: 0.9, Alpha: 1}} + caret := render.Rectangle{Bounds: scene.Rect{X: 40, Y: 250, Width: 2, Height: 16}, Color: scene.Color{Alpha: 1}} + clock := render.Rectangle{Bounds: scene.Rect{X: 330, Y: 6, Width: 60, Height: 14}, Color: scene.Color{Blue: 1, Alpha: 1}} + s := damageTestScene(t, []render.Rectangle{background, caret, clock}) + next := []render.Rectangle{background, caret, clock} + frame := platform.Frame{Update: render.Update{First: 1, Count: 2}, Rectangles: next} + step := 0 + if allocs := testing.AllocsPerRun(50, func() { + step++ + next[1].Bounds.X = float32(40 + step%8) + next[2].Color.Red = float32(step % 2) + if _, err := s.Apply(frame); err != nil { + t.Fatal(err) + } + s.Paint() + }); allocs != 0 { + t.Fatalf("%g allocations per frame, want 0", allocs) + } +} diff --git a/internal/softscene/labelimage.go b/internal/softscene/labelimage.go new file mode 100644 index 000000000..393f754b5 --- /dev/null +++ b/internal/softscene/labelimage.go @@ -0,0 +1,136 @@ +package softscene + +import ( + "math" + + "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/internal/raster" + "github.com/vivaui/viva/internal/render" + "github.com/vivaui/viva/internal/scene" +) + +// labelImage is a label's picture at one scale, premultiplied BGRA with no +// padding between rows, unless lcd: then it is per-channel coverage with the +// luminance in alpha, and spans are the column ranges of a fixed-pitch line that +// are text of one color. +type labelImage struct { + pixels []byte + width, height int + // skip is the device column of a text label the picture starts at: a line + // wider than a texture holds, wide, is drawn from the window of it the canvas + // shows (textWindow). It is 0 for every other label. + skip int + wide bool + lcd bool + spans []raster.Span +} + +// textWindow is the part of a text label drawn into its picture at scale on a +// canvas canvasWidth device pixels wide: the device columns from skip to +// skip+width of the label, height high. A label one texture holds is drawn +// whole. A wider one, wide, is drawn from the columns of it the canvas and its +// clip show, keeping have, the picture it has, while that still holds them +// (platform.WideTextLabelWindow). ok is false when nothing is drawn: none of a +// wide line can be seen, or no texture holds the label. +func textWindow(l platform.TextLabel, scale float32, canvasWidth int, have labelImage) (skip, width, height int, wide, ok bool) { + full := int(math.Ceil(float64(l.Width * scale))) + height = int(math.Ceil(float64(l.Height * scale))) + haveSkip, haveWidth := 0, 0 + if have.wide { + haveSkip, haveWidth = have.skip, have.width + } + skip, width, wide, ok = platform.WideTextLabelWindow(l, scale, full, height, canvasWidth, haveSkip, haveWidth) + return skip, width, height, wide, ok && platform.LabelTextureFits(width, height) +} + +// rasterizeLabel draws a label's text, or resamples its image to the device +// pixels it covers. ok is false when it draws nothing. The picture does not +// depend on where the label is, except that an image smaller than its bitmap +// does, through the fraction of a pixel it starts at, and a line wider than a +// texture holds is drawn from the window of it a canvas canvasWidth device +// pixels wide shows, kept from have, the picture the label has (textWindow). +// With allowLCD, and the desktop asking for subpixel antialiasing, text comes +// back as per-channel coverage for the rasterizer to tint. +func rasterizeLabel(text Rasterizer, l platform.TextLabel, scale float32, canvasWidth int, have labelImage, allowLCD bool) (image labelImage, ok bool, err error) { + if l.Width <= 0 || l.Height <= 0 || (l.Value == "" && len(l.Bitmap) == 0) { + return labelImage{}, false, nil + } + if len(l.Bitmap) > 0 { + width, height := l.BitmapWidth, l.BitmapHeight + shownWidth, shownHeight := platform.DeviceExtent(l.X, l.Width, scale), platform.DeviceExtent(l.Y, l.Height, scale) + switch { + case shownWidth <= 0 || shownHeight <= 0: + return labelImage{}, false, nil + case shownWidth <= width && shownHeight <= height && (shownWidth < width || shownHeight < height): + return labelImage{pixels: platform.ResampleBGRA(l.Bitmap, l.BitmapStride, width, height, shownWidth, shownHeight), width: shownWidth, height: shownHeight}, true, nil + } + return labelImage{pixels: platform.TightBitmap(l.Bitmap, width, height, l.BitmapStride), width: width, height: height}, true, nil + } + skip, width, height, wide, shown := textWindow(l, scale, canvasWidth, have) + if !shown { + return labelImage{}, false, nil + } + pixels, lcd, err := text.Rasterize(l, scale, skip, width, height, allowLCD) + if err != nil { + return labelImage{}, false, err + } + image = labelImage{pixels: pixels, width: width, height: height, skip: skip, wide: wide, lcd: lcd} + if lcd { + spans := text.Spans() + if len(spans) > 0 { + image.spans = make([]raster.Span, len(spans)) + for index, span := range spans { + image.spans[index] = raster.Span{ + From: span.Left, To: span.Right, + Color: scene.Color{Red: span.Color[0], Green: span.Color[1], Blue: span.Color[2], Alpha: span.Color[3]}, + } + } + } + } + return image, true, nil +} + +// PrepareLabel turns one text label (or image) into the picture the rasterizer +// composites, placed on the device pixel grid the way the GPU backends place it: +// the picture's top left is a whole device pixel (platform.DevicePosition), a +// clip takes every device pixel it touches. ok is false when the label draws +// nothing. +func PrepareLabel(text Rasterizer, l platform.TextLabel, scale float32, canvasWidth, canvasHeight int, allowLCD bool) (label raster.Label, ok bool, err error) { + image, ok, err := rasterizeLabel(text, l, scale, canvasWidth, labelImage{}, allowLCD) + if err != nil || !ok { + return raster.Label{}, false, err + } + label, ok = placeLabel(l, scale, image, canvasWidth, canvasHeight) + return label, ok, nil +} + +// placeLabel puts a label's picture on the canvas: its top left on a whole +// device pixel and its clip, if a canvas clip cuts it, on the device pixels the +// clip touches. ok is false when the clip leaves nothing. +func placeLabel(l platform.TextLabel, scale float32, image labelImage, canvasWidth, canvasHeight int) (label raster.Label, ok bool) { + x, y := platform.DevicePosition(l.X, l.OriginX, scale)+image.skip, platform.DevicePosition(l.Y, l.OriginY, scale) + if len(l.Bitmap) > 0 { + x, y = platform.DevicePosition(l.X, 0, scale), platform.DevicePosition(l.Y, 0, scale) + } + label = raster.Label{Pix: image.pixels, Stride: image.width * 4, Width: image.width, Height: image.height, X: x, Y: y, Layer: l.Layer, + Image: len(l.Bitmap) > 0, Radius: l.ImageRadius, Fade: l.ImageFade, + ShapesBefore: l.ShapesBefore, LCD: image.lcd, Spans: image.spans, + Color: scene.Color{Red: float32(l.Color.Red), Green: float32(l.Color.Green), Blue: float32(l.Color.Blue), Alpha: float32(l.Color.Alpha)}} + if len(l.Bitmap) > 0 { + label.Width, label.Height = platform.DeviceExtent(l.X, l.Width, scale), platform.DeviceExtent(l.Y, l.Height, scale) + if label.Width != image.width || label.Height != image.height { + label.SourceWidth, label.SourceHeight = image.width, image.height + } + } + if l.Clipped { + left := max(int(math.Floor(float64(l.Clip.X*scale))), 0) + top := max(int(math.Floor(float64(l.Clip.Y*scale))), 0) + right := min(int(math.Ceil(float64((l.Clip.X+l.Clip.Width)*scale))), canvasWidth) + bottom := min(int(math.Ceil(float64((l.Clip.Y+l.Clip.Height)*scale))), canvasHeight) + if right <= left || bottom <= top { + return raster.Label{}, false + } + label.Clipped, label.Clip = true, render.Scissor{Left: left, Top: top, Right: right, Bottom: bottom} + } + return label, true +} diff --git a/internal/softscene/overlay_test.go b/internal/softscene/overlay_test.go new file mode 100644 index 000000000..1cad9c3bc --- /dev/null +++ b/internal/softscene/overlay_test.go @@ -0,0 +1,71 @@ +package softscene + +import ( + "testing" + + "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/internal/raster" + "github.com/vivaui/viva/internal/render" + "github.com/vivaui/viva/internal/scene" +) + +// noText is a Rasterizer for scenes whose labels are pictures: it never draws +// a glyph. +type noText struct{} + +func (noText) Rasterize(label platform.TextLabel, scale float32, skip, width, height int, allowLCD bool) ([]byte, bool, error) { + return nil, false, nil +} + +func (noText) Spans() []Span { return nil } + +func overlayPixel(t *testing.T, s *Scene, x, y int) []byte { + t.Helper() + offset := y*s.Canvas.Stride + x*4 + return s.Canvas.Pix[offset : offset+4] +} + +// The platform's native editor is composited after the frame's content in its +// layer and before anything on a higher layer: a popover over the editor covers +// it, and the editor covers the page under it. +func TestOverlayDrawsAfterItsLayerAndUnderHigherLayers(t *testing.T) { + clear := scene.Color{Alpha: 1} + page := render.Rectangle{ + Bounds: scene.Rect{X: 0, Y: 0, Width: 20, Height: 20}, + Color: scene.Color{Blue: 1, Alpha: 1}, + Layer: 0, + } + popover := render.Rectangle{ + Bounds: scene.Rect{X: 10, Y: 0, Width: 10, Height: 20}, + Color: scene.Color{Green: 1, Alpha: 1}, + Layer: 1, + } + s, err := New(noText{}, 20, 20, 1, clear, []render.Rectangle{page, popover}, nil) + if err != nil { + t.Fatal(err) + } + s.Paint() + + red := make([]byte, 10*10*4) + for i := 0; i < len(red); i += 4 { + red[i+2], red[i+3] = 255, 255 // premultiplied BGRA: red + } + s.SetOverlay(raster.Label{ + Pix: red, Stride: 10 * 4, Width: 10, Height: 10, + X: 5, Y: 5, Layer: 0, ShapesBefore: ^uint32(0), + }, true) + s.Paint() + + if got := overlayPixel(t, s, 8, 8); got[2] != 255 || got[0] != 0 { + t.Fatalf("page pixel under the editor = %v, want the editor's red", got) + } + if got := overlayPixel(t, s, 12, 8); got[1] != 255 || got[2] != 0 { + t.Fatalf("pixel under the popover = %v, want the popover's green, not the editor", got) + } + + s.SetOverlay(raster.Label{}, false) + s.Paint() + if got := overlayPixel(t, s, 8, 8); got[0] != 255 || got[2] != 0 { + t.Fatalf("pixel after the editor left = %v, want the page's blue", got) + } +} diff --git a/internal/softscene/scene.go b/internal/softscene/scene.go new file mode 100644 index 000000000..5d1240698 --- /dev/null +++ b/internal/softscene/scene.go @@ -0,0 +1,455 @@ +// Package softscene is the retained scene of a window drawn by the CPU +// rasterizer: the rectangle instances and text labels the application sent, the +// picture of each label, and the part of the canvas that changed since it was +// last painted. A presenter (an X11 or Wayland surface, a macOS view) takes the +// canvas and the damaged region from it; nothing here depends on a display +// server or a graphics device. +// +// A frame names the instances that changed, so the damage is the pixels those +// covered before and cover now (raster.Box), and a label that is the same as the +// one in its slot keeps its picture and costs nothing. Typing in a text field +// repaints the field. +// +// The text of a label is drawn by the platform's own engine, behind Rasterizer; +// on a Linux desktop that is Pango, on macOS CoreText. +package softscene + +import ( + "fmt" + "math" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/internal/raster" + "github.com/vivaui/viva/internal/render" + "github.com/vivaui/viva/internal/scene" +) + +// Span is the columns of an LCD grid label's picture, left to right in device +// pixels, that are text of one color, as the rasterizer's text engine reports +// them. +type Span struct { + Left, Right int + Color [4]float32 +} + +// Rasterizer draws the glyphs of a text label into the coverage bitmap of its +// picture. The scene owns placement and blending; what draws the glyphs is the +// platform's text engine. +type Rasterizer interface { + // Rasterize draws the device columns from skip to skip+width of the label, + // height rows tall, at scale. With allowLCD the result may be the coverage of + // each color channel (lcd reports it), to be blended with the label's color by + // the rasterizer. + Rasterize(label platform.TextLabel, scale float32, skip, width, height int, allowLCD bool) (pixels []byte, lcd bool, err error) + // Spans are the colors of the last LCD grid label rasterized, valid until the + // next call of Rasterize; empty for a label that is all in label.Color. + Spans() []Span +} + +// Scene is the retained scene of one window drawn by the CPU. +type Scene struct { + text Rasterizer + Canvas *raster.Canvas + drawer raster.Rasterizer + Scale float32 + // Clear is the color the canvas is cleared to before it is painted. + Clear scene.Color + + Rects []render.Rectangle + labels []softLabel + // Views are the places native views fill; holes are the same in device pixels. + Views []platform.NativeView + // overlay is a picture drawn after the frame's own content in its layer: a + // platform's native text editor, which the frontend of the platform makes. + overlay raster.Label + hasOverlay bool + holes []raster.Hole + drawn []raster.Label // the labels painted this time, in slot order; scratch + // Damage is the part of the canvas that changed since it was last painted: a + // few rectangles, so that two small changes far apart repaint only themselves. + Damage raster.Region + // painted is what the last Paint drew, which it returns. + painted raster.Region +} + +// softLabel is one slot of the label list. +type softLabel struct { + label platform.TextLabel + runs []gfx.TextRun // backs label.Runs, which is only valid for the call that carried it + // image is the label's picture at imageScale, if it has been drawn. + image labelImage + imageScale float32 + hasImage bool + // placed is the picture on the canvas, visible says it draws anything. + placed raster.Label + visible bool +} + +// New makes a scene for a canvas of the given device size. rectangles and labels +// are the window's first content. +func New(text Rasterizer, width, height int, scale float32, clear scene.Color, rectangles []render.Rectangle, labels []platform.TextLabel) (*Scene, error) { + if width < 1 || height < 1 { + return nil, fmt.Errorf("softscene: invalid canvas size %dx%d", width, height) + } + s := &Scene{ + text: text, + Canvas: raster.NewCanvas(width, height), + Scale: max(scale, 1), + Clear: clear, + } + s.Rects = append(s.Rects, rectangles...) + if err := s.setLabels(labels); err != nil { + return nil, err + } + s.DamageAll() + return s, nil +} + +// DamageAll marks the whole canvas as changed. +func (s *Scene) DamageAll() { s.Damage.Set(s.Canvas.Bounds()) } + +// addDamage adds a box of device pixels to what must be painted. +func (s *Scene) addDamage(box render.Scissor) { + bounds := s.Canvas.Bounds() + box = render.Scissor{Left: max(box.Left, bounds.Left), Top: max(box.Top, bounds.Top), Right: min(box.Right, bounds.Right), Bottom: min(box.Bottom, bounds.Bottom)} + s.Damage.Add(box) +} + +// Apply takes a frame into the scene and reports whether anything on the canvas +// changed. +func (s *Scene) Apply(frame platform.Frame) (bool, error) { + if frame.Update.Empty() && frame.TextLabels == nil && frame.NativeViews == nil { + return false, nil + } + if !frame.Update.Empty() { + if err := s.applyRectangles(frame); err != nil { + return false, err + } + } + if frame.NativeViews != nil { + s.SetViews(frame.NativeViews) + } + if frame.TextLabels != nil { + if err := platform.ValidateTextLabels(frame.TextLabels); err != nil { + return false, err + } + if err := s.setLabels(frame.TextLabels); err != nil { + return false, err + } + } + return s.Pending(), nil +} + +// Set replaces the whole scene: the rectangles in paint order and the labels. +// It is what a renderer that draws whole frames, like an offscreen one, uses. +func (s *Scene) Set(rectangles []render.Rectangle, labels []platform.TextLabel) error { + if err := render.ValidateRectangles(rectangles); err != nil { + return err + } + s.Rects = append(s.Rects[:0], rectangles...) + if err := s.setLabels(labels); err != nil { + return fmt.Errorf("softscene: %w", err) + } + s.DamageAll() + return nil +} + +// Pending reports whether anything waits to be painted. +func (s *Scene) Pending() bool { + return !s.Damage.Empty() +} + +func (s *Scene) applyRectangles(frame platform.Frame) error { + if err := render.ValidateRectangles(frame.Rectangles); err != nil { + return err + } + update := frame.Update + if update.First < 0 || update.Count < 0 || update.First > len(frame.Rectangles) || update.Count > len(frame.Rectangles)-update.First { + return fmt.Errorf("softscene: invalid rectangle update") + } + if update.Rebuild { + s.Rects = append(s.Rects[:0], frame.Rectangles...) + s.DamageAll() + return nil + } + if len(frame.Rectangles) < len(s.Rects) { + if !update.Shrink || update.First > len(frame.Rectangles) || update.First+update.Count != len(frame.Rectangles) { + return fmt.Errorf("softscene: rectangle count shrank outside a suffix update") + } + for index := len(frame.Rectangles); index < len(s.Rects); index++ { + s.addDamage(raster.Box(&s.Rects[index], s.Scale)) + } + s.Rects = s.Rects[:len(frame.Rectangles)] + } + if len(frame.Rectangles) > len(s.Rects) { + if update.First > len(s.Rects) || update.First+update.Count != len(frame.Rectangles) { + return fmt.Errorf("softscene: rectangle count grew outside a suffix update") + } + } + for i := update.First; i < update.First+update.Count; i++ { + if i < len(s.Rects) { + s.addDamage(raster.Box(&s.Rects[i], s.Scale)) + } + s.addDamage(raster.Box(&frame.Rectangles[i], s.Scale)) + } + if len(frame.Rectangles) > len(s.Rects) { + s.Rects = append(s.Rects, frame.Rectangles[len(s.Rects):]...) + } + copy(s.Rects[update.First:update.First+update.Count], frame.Rectangles[update.First:update.First+update.Count]) + return nil +} + +// setLabels replaces the label list. A slot whose label is the same as before +// keeps its picture. +func (s *Scene) setLabels(labels []platform.TextLabel) error { + for i := len(labels); i < len(s.labels); i++ { + if s.labels[i].visible { + s.addDamage(labelBox(&s.labels[i].placed)) + } + } + if len(labels) > cap(s.labels) { + s.labels = append(s.labels[:cap(s.labels)], make([]softLabel, len(labels)-cap(s.labels))...) + } + s.labels = s.labels[:len(labels)] + for i := range labels { + if err := s.setLabel(&s.labels[i], labels[i]); err != nil { + return fmt.Errorf("softscene: label %d: %w", i, err) + } + } + return nil +} + +func (s *Scene) setLabel(slot *softLabel, next platform.TextLabel) error { + previous := slot.placed + wasVisible := slot.visible + redraw := !slot.hasImage || slot.imageScale != s.Scale || labelContentChanged(slot.label, next) || (len(next.Bitmap) > 0 && bitmapShownChanged(slot.label, next, s.Scale)) + var have labelImage + if !redraw && slot.image.wide { + // A line wider than a texture holds is drawn again when its picture, a window of + // it, no longer holds the part of it the canvas shows. + have = slot.image + skip, width, _, _, ok := textWindow(next, s.Scale, s.Canvas.Width, have) + redraw = !ok || skip != have.skip || width != have.width + } + slot.runs = append(slot.runs[:0], next.Runs...) + slot.label = next + slot.label.Runs = slot.runs + if redraw { + image, ok, err := rasterizeLabel(s.text, slot.label, s.Scale, s.Canvas.Width, have, s.Clear.Alpha >= 1) + if err != nil { + return err + } + slot.image, slot.imageScale, slot.hasImage = image, s.Scale, ok + if !ok { + slot.image = labelImage{} + } + } + slot.visible = false + if slot.hasImage && slot.image.width > 0 { + slot.placed, slot.visible = placeLabel(slot.label, s.Scale, slot.image, s.Canvas.Width, s.Canvas.Height) + } + switch { + case !wasVisible && !slot.visible: + case redraw || wasVisible != slot.visible || slot.placed.X != previous.X || slot.placed.Y != previous.Y || + slot.placed.Layer != previous.Layer || slot.placed.Clipped != previous.Clipped || slot.placed.Clip != previous.Clip: + if wasVisible { + s.addDamage(labelBox(&previous)) + } + if slot.visible { + s.addDamage(labelBox(&slot.placed)) + } + } + return nil +} + +// labelBox is the device pixels a placed label may paint. +func labelBox(l *raster.Label) render.Scissor { + box := render.Scissor{Left: l.X, Top: l.Y, Right: l.X + l.Width, Bottom: l.Y + l.Height} + if l.Clipped { + box = render.Scissor{Left: max(box.Left, l.Clip.Left), Top: max(box.Top, l.Clip.Top), Right: min(box.Right, l.Clip.Right), Bottom: min(box.Bottom, l.Clip.Bottom)} + } + return box +} + +// LabelBox is labelBox for callers that compose the canvas themselves. +func LabelBox(l *raster.Label) render.Scissor { return labelBox(l) } + +// labelContentChanged reports whether the two labels need different pictures. +// Where a label is and how it is clipped are not in it: scrolling text costs no +// layout. +func labelContentChanged(previous, next platform.TextLabel) bool { + return previous.Value != next.Value || previous.Width != next.Width || previous.Height != next.Height || previous.FontSize != next.FontSize || previous.Italic != next.Italic || + previous.Weight != next.Weight || previous.Color != next.Color || previous.FontGeneration != next.FontGeneration || previous.Mono != next.Mono || previous.MonoFace != next.MonoFace || previous.CellWidth != next.CellWidth || + previous.Baseline != next.Baseline || + !platform.SameTextRuns(previous.Runs, next.Runs) || previous.BitmapID != next.BitmapID || previous.BitmapVersion != next.BitmapVersion || + previous.BitmapWidth != next.BitmapWidth || previous.BitmapHeight != next.BitmapHeight || previous.BitmapStride != next.BitmapStride || + !platform.SameBitmapBytes(previous.Bitmap, next.Bitmap) +} + +// bitmapShownChanged reports whether an image covers a different number of +// device pixels than it did, which happens when it moves across a pixel +// boundary and is smaller than its bitmap. +func bitmapShownChanged(previous, next platform.TextLabel, scale float32) bool { + return platform.DeviceExtent(previous.X, previous.Width, scale) != platform.DeviceExtent(next.X, next.Width, scale) || + platform.DeviceExtent(previous.Y, previous.Height, scale) != platform.DeviceExtent(next.Y, next.Height, scale) +} + +// Resize gives the scene a canvas of another device size. Everything is painted +// again. +func (s *Scene) Resize(width, height int) error { + if width < 1 || height < 1 { + return fmt.Errorf("softscene: invalid canvas size %dx%d", width, height) + } + if width == s.Canvas.Width && height == s.Canvas.Height { + return nil + } + s.Canvas.Resize(width, height) + return s.replace() +} + +// SetScale draws everything at another scale. +func (s *Scene) SetScale(scale float32) error { + scale = max(scale, 1) + if scale == s.Scale { + return nil + } + s.Scale = scale + return s.replace() +} + +// SetViews replaces the places of the native views. The pixels under a view and +// under its old place are painted again. +func (s *Scene) SetViews(views []platform.NativeView) { + for _, hole := range s.holes { + s.addDamage(hole.Box) + } + s.Views = append(s.Views[:0], views...) + s.placeHoles() +} + +// placeHoles works out the holes in device pixels, on the grid the views are +// placed on. +func (s *Scene) placeHoles() { + s.holes = s.holes[:0] + for _, view := range s.Views { + b := view.Bounds + box := render.Scissor{ + Left: int(math.Round(float64(b.X * s.Scale))), Top: int(math.Round(float64(b.Y * s.Scale))), + Right: int(math.Round(float64((b.X + b.Width) * s.Scale))), Bottom: int(math.Round(float64((b.Y + b.Height) * s.Scale))), + } + s.holes = append(s.holes, raster.Hole{Box: box, Layer: view.Layer}) + s.addDamage(box) + } +} + +// Overlays returns the parts of the view that something on a higher layer +// covers, in device pixels: where the pointer belongs to Viva although a page is +// under it. +func (s *Scene) Overlays(index int) []render.Scissor { + if index < 0 || index >= len(s.holes) { + return nil + } + hole := s.holes[index] + var covered []render.Scissor + for i := range s.Rects { + r := &s.Rects[i] + if r.Layer <= hole.Layer || r.Kind == scene.KindShadow || r.Color.Alpha <= 0 { + continue + } + box := render.Scissor{Left: max(hole.Box.Left, 0), Top: hole.Box.Top, Right: hole.Box.Right, Bottom: hole.Box.Bottom} + if shown := raster.Box(r, s.Scale); shown.Right > shown.Left && shown.Bottom > shown.Top { + box = render.Scissor{Left: max(box.Left, shown.Left), Top: max(box.Top, shown.Top), Right: min(box.Right, shown.Right), Bottom: min(box.Bottom, shown.Bottom)} + if box.Right > box.Left && box.Bottom > box.Top { + covered = append(covered, box) + } + } + } + for i := range s.labels { + l := &s.labels[i] + if l.visible && l.placed.Layer > hole.Layer { + box := labelBox(&l.placed) + box = render.Scissor{Left: max(box.Left, hole.Box.Left), Top: max(box.Top, hole.Box.Top), Right: min(box.Right, hole.Box.Right), Bottom: min(box.Bottom, hole.Box.Bottom)} + if box.Right > box.Left && box.Bottom > box.Top { + covered = append(covered, box) + } + } + } + return covered +} + +// RefreshText draws every label again, after the fonts changed. +func (s *Scene) RefreshText() error { + for i := range s.labels { + s.labels[i].hasImage = false + } + return s.replace() +} + +// replace places every label again and paints all of the canvas. +func (s *Scene) replace() error { + for i := range s.labels { + if err := s.setLabel(&s.labels[i], s.labels[i].label); err != nil { + return fmt.Errorf("softscene: label %d: %w", i, err) + } + } + s.placeHoles() + s.DamageAll() + return nil +} + +// SetOverlay sets a picture composited after the frame's content in its layer -- +// the platform's native editor, which the platform makes -- or removes it when +// ok is false. Its old and new place are painted again. +func (s *Scene) SetOverlay(label raster.Label, ok bool) { + if s.hasOverlay { + s.addDamage(labelBox(&s.overlay)) + } + s.overlay, s.hasOverlay = label, ok + if ok { + s.addDamage(labelBox(&label)) + } +} + +// Paint draws what changed into the canvas and returns the rectangles it drew, +// disjoint, none when nothing had changed. A change that covers most of the +// canvas is drawn as the whole canvas. The rectangles are the scene's own and +// are valid until the next Paint. +func (s *Scene) Paint() []render.Scissor { + if s.Canvas.Pix == nil && s.Canvas.Width > 0 && s.Canvas.Height > 0 { + // Release gave the pixels back: make them again, all of them to be painted. + s.Canvas.Resize(s.Canvas.Width, s.Canvas.Height) + s.DamageAll() + } + s.Damage.Limit(s.Canvas.Bounds()) + if !s.Pending() { + return nil + } + s.painted = s.Damage + s.Damage.Reset() + s.drawn = s.drawn[:0] + for i := range s.labels { + if s.labels[i].visible { + s.drawn = append(s.drawn, s.labels[i].placed) + } + } + if s.hasOverlay { + s.drawn = append(s.drawn, s.overlay) + } + damage := s.painted.Rects() + s.drawer.Draw(s.Canvas, raster.Params{Scale: s.Scale, Clear: s.Clear, Holes: s.holes, Damage: damage}, s.Rects, s.drawn) + return damage +} + +// Release gives back the canvas's pixels while nothing shows them, as when the +// window is unmapped; the labels keep their pictures. The next Paint makes the +// canvas again and paints all of it. +func (s *Scene) Release() { + s.Canvas.Release() + s.DamageAll() +} + +// Close releases the pictures. +func (s *Scene) Close() { + s.Canvas, s.Rects, s.labels, s.drawn = nil, nil, nil, nil +} diff --git a/keymap/chord.go b/keymap/chord.go index 06af43cb3..41d332b84 100644 --- a/keymap/chord.go +++ b/keymap/chord.go @@ -6,14 +6,20 @@ import ( "github.com/vivaui/viva/gfx" ) -// Chord is a modifier set and one key: a printable character in Char, or a -// named key in Key. A valid chord sets exactly one of the two. Letters are -// stored in lower case, so Shift+P is Modifiers Shift with Char 'p'. The zero -// Chord is no chord at all. +// Chord is a modifier set and one key: a printable character in Char, a named +// key in Key, or a mouse button in Button. A valid chord sets exactly one of the +// three. Letters are stored in lower case, so Shift+P is Modifiers Shift with +// Char 'p'. The zero Chord is no chord at all. +// +// The buttons a chord may use are the middle button and the two side buttons +// (gfx.PointerButtonMiddle, PointerButtonBack, PointerButtonForward): the +// primary and secondary buttons select, drag and open menus, so a chord never +// takes them. type Chord struct { Modifiers gfx.Modifiers Char byte Key gfx.Key + Button gfx.PointerButton } const modifierMask = gfx.ModifierShift | gfx.ModifierControl | gfx.ModifierAlt | gfx.ModifierMeta @@ -55,6 +61,28 @@ var namedKeys = [...]struct { {gfx.KeyF12, "F12", "F12", "f12"}, } +// mouseButtons are the mouse buttons a chord may use, written the same three +// ways as namedKeys. +var mouseButtons = [...]struct { + button gfx.PointerButton + label string + keycap string + saved string +}{ + {gfx.PointerButtonMiddle, "Middle Click", "Middle Click", "mouse_middle"}, + {gfx.PointerButtonBack, "Mouse Back", "Mouse Back", "mouse_back"}, + {gfx.PointerButtonForward, "Mouse Forward", "Mouse Forward", "mouse_forward"}, +} + +func mouseButton(button gfx.PointerButton) (int, bool) { + for index := range mouseButtons { + if mouseButtons[index].button == button { + return index, true + } + } + return 0, false +} + func namedKey(key gfx.Key) (int, bool) { for index := range namedKeys { if namedKeys[index].key == key { @@ -65,12 +93,16 @@ func namedKey(key gfx.Key) (int, bool) { } // Valid reports whether the chord can be bound: only the four modifiers, and -// either a named key or a printable ASCII character that is not an upper-case -// letter. +// one of a named key, a printable ASCII character that is not an upper-case +// letter, or the middle or a side mouse button. func (chord Chord) Valid() bool { if chord.Modifiers&^modifierMask != 0 { return false } + if chord.Button != gfx.PointerButtonNone { + _, bound := mouseButton(chord.Button) + return bound && chord.Key == gfx.KeyUnknown && chord.Char == 0 + } if chord.Key != gfx.KeyUnknown { _, named := namedKey(chord.Key) return named && chord.Char == 0 @@ -103,6 +135,21 @@ func FromEvent(event gfx.KeyEvent) (chord Chord, ok bool) { return chord, chord.Valid() } +// FromPointer is the chord a press of a mouse button makes: the button with the +// modifiers held. ok is false for a button a chord cannot use: the primary and +// secondary buttons, or none. A shortcut acts on the press, so a caller that +// records chords offers PointerDown events. +func FromPointer(event gfx.PointerEvent) (chord Chord, ok bool) { + chord = Chord{Modifiers: event.Modifiers & modifierMask, Button: event.Button} + if !chord.Valid() { + return Chord{}, false + } + return chord, true +} + +// IsMouse reports whether the chord is a mouse button rather than a key. +func (chord Chord) IsMouse() bool { return chord.Button != gfx.PointerButtonNone } + // Label is the chord as a sentence, modifiers first: "Cmd+Shift+P", // "Ctrl+Tab", "Alt+Space". The names are the same on every platform; a menu // that wants the platform's symbols uses Keycaps. An invalid chord has no label. @@ -123,6 +170,10 @@ func (chord Chord) Label() string { if chord.Modifiers&gfx.ModifierShift != 0 { label.WriteString("Shift+") } + if index, ok := mouseButton(chord.Button); ok { + label.WriteString(mouseButtons[index].label) + return label.String() + } if index, ok := namedKey(chord.Key); ok { label.WriteString(namedKeys[index].label) return label.String() @@ -164,6 +215,9 @@ func (chord Chord) Keycaps(dst []string) []string { if chord.Modifiers&gfx.ModifierMeta != 0 { dst = append(dst, modifierKeycap(gfx.ModifierMeta)) } + if index, ok := mouseButton(chord.Button); ok { + return append(dst, mouseButtons[index].keycap) + } if index, ok := namedKey(chord.Key); ok { return append(dst, namedKeys[index].keycap) } @@ -174,12 +228,16 @@ func (chord Chord) Keycaps(dst []string) []string { } // Name is the chord's key as a settings file writes it, without the modifiers: -// the character, or the name of a named key ("page_up", "f5"). An invalid chord -// has no name. Parse reads it back. +// the character, the name of a named key ("page_up", "f5"), or of a mouse +// button ("mouse_middle", "mouse_back", "mouse_forward"). An invalid chord has +// no name. Parse reads it back. func (chord Chord) Name() string { if !chord.Valid() { return "" } + if index, ok := mouseButton(chord.Button); ok { + return mouseButtons[index].saved + } if index, ok := namedKey(chord.Key); ok { return namedKeys[index].saved } @@ -188,9 +246,15 @@ func (chord Chord) Name() string { // Parse is the inverse of Name: the chord with the given modifiers and the key // the name stands for. An upper-case letter is read as its lower-case form. ok -// is false for a name that is neither a named key nor one character, and for a -// result that is not a valid chord. +// is false for a name that is neither a named key, a mouse button nor one +// character, and for a result that is not a valid chord. func Parse(modifiers gfx.Modifiers, name string) (Chord, bool) { + for index := range mouseButtons { + if mouseButtons[index].saved == name { + chord := Chord{Modifiers: modifiers, Button: mouseButtons[index].button} + return chord, chord.Valid() + } + } for index := range namedKeys { if namedKeys[index].saved == name { chord := Chord{Modifiers: modifiers, Key: namedKeys[index].key} diff --git a/keymap/chord_test.go b/keymap/chord_test.go index 3c4326a6d..ad58ee55b 100644 --- a/keymap/chord_test.go +++ b/keymap/chord_test.go @@ -112,3 +112,64 @@ func TestPrimaryIsOneOfTheModifiers(t *testing.T) { t.Fatalf("Primary = %v", Primary) } } + +func TestFromPointerNamesTheMiddleAndSideButtons(t *testing.T) { + for _, test := range []struct { + name string + event gfx.PointerEvent + want Chord + ok bool + }{ + {"middle", gfx.PointerEvent{Kind: gfx.PointerDown, Button: gfx.PointerButtonMiddle}, Chord{Button: gfx.PointerButtonMiddle}, true}, + {"back with a modifier", gfx.PointerEvent{Kind: gfx.PointerDown, Button: gfx.PointerButtonBack, Modifiers: gfx.ModifierControl}, Chord{Modifiers: gfx.ModifierControl, Button: gfx.PointerButtonBack}, true}, + {"forward", gfx.PointerEvent{Kind: gfx.PointerDown, Button: gfx.PointerButtonForward, Modifiers: Primary | gfx.ModifierShift}, Chord{Modifiers: Primary | gfx.ModifierShift, Button: gfx.PointerButtonForward}, true}, + {"modifiers beyond the four are dropped", gfx.PointerEvent{Button: gfx.PointerButtonMiddle, Modifiers: 1<<6 | gfx.ModifierAlt}, Chord{Modifiers: gfx.ModifierAlt, Button: gfx.PointerButtonMiddle}, true}, + {"primary selects", gfx.PointerEvent{Kind: gfx.PointerDown, Button: gfx.PointerButtonPrimary}, Chord{}, false}, + {"secondary opens a menu", gfx.PointerEvent{Kind: gfx.PointerDown, Button: gfx.PointerButtonSecondary, Modifiers: Primary}, Chord{}, false}, + {"no button", gfx.PointerEvent{Kind: gfx.PointerMove}, Chord{}, false}, + } { + got, ok := FromPointer(test.event) + if ok != test.ok || got != test.want { + t.Errorf("%s: FromPointer = %+v, %v; want %+v, %v", test.name, got, ok, test.want, test.ok) + } + if got.IsMouse() != test.ok { + t.Errorf("%s: IsMouse = %v", test.name, got.IsMouse()) + } + } +} + +func TestMouseChordsWriteThemselvesAndRoundTrip(t *testing.T) { + for _, test := range []struct { + chord Chord + label, keycap, saved string + }{ + {Chord{Button: gfx.PointerButtonMiddle}, "Middle Click", "Middle Click", "mouse_middle"}, + {Chord{Modifiers: gfx.ModifierControl, Button: gfx.PointerButtonBack}, "Ctrl+Mouse Back", "Mouse Back", "mouse_back"}, + {Chord{Modifiers: gfx.ModifierAlt | gfx.ModifierShift, Button: gfx.PointerButtonForward}, "Alt+Shift+Mouse Forward", "Mouse Forward", "mouse_forward"}, + } { + if got := test.chord.Label(); got != test.label { + t.Errorf("%+v: Label = %q, want %q", test.chord, got, test.label) + } + if got := test.chord.Name(); got != test.saved { + t.Errorf("%+v: Name = %q, want %q", test.chord, got, test.saved) + } + if caps := test.chord.Keycaps(nil); len(caps) == 0 || caps[len(caps)-1] != test.keycap { + t.Errorf("%+v: Keycaps = %q", test.chord, caps) + } + parsed, ok := Parse(test.chord.Modifiers, test.chord.Name()) + if !ok || parsed != test.chord { + t.Errorf("Parse(%q) = %+v, %v; want %+v", test.chord.Name(), parsed, ok, test.chord) + } + } + for _, chord := range []Chord{ + {Button: gfx.PointerButtonPrimary}, + {Button: gfx.PointerButtonSecondary}, + {Button: gfx.PointerButtonMiddle, Char: 'a'}, + {Button: gfx.PointerButtonBack, Key: gfx.KeyTab}, + {Button: gfx.PointerButtonForward + 1}, + } { + if chord.Valid() || chord.Name() != "" || chord.Label() != "" { + t.Errorf("%+v is a valid chord", chord) + } + } +} diff --git a/keymap/doc.go b/keymap/doc.go index 7e5a25bd2..55655e2d1 100644 --- a/keymap/doc.go +++ b/keymap/doc.go @@ -1,9 +1,10 @@ -// Package keymap names keyboard shortcuts and keeps a user-editable table of +// Package keymap names keyboard and mouse-button shortcuts and keeps a user-editable table of // them. // -// A Chord is a set of modifiers and one key: a printable ASCII character, or -// one of the named keys that type nothing (Tab, the arrows, the function keys). -// Chord.FromEvent turns the gfx.KeyEvent a window delivers into one, and a chord +// A Chord is a set of modifiers and one key: a printable ASCII character, one +// of the named keys that type nothing (Tab, the arrows, the function keys), or +// the middle or a side mouse button. FromEvent turns the gfx.KeyEvent a window +// delivers into one and FromPointer a press of a mouse button, and a chord // writes itself three ways: Label for a sentence ("Cmd+Shift+P"), Keycaps for // the symbols a menu paints (⌘ ⇧ P on macOS, Ctrl Shift P elsewhere) and Name // for a settings file ("page_up"), which Parse reads back. diff --git a/ui/drawer_paint.go b/ui/drawer_paint.go index cc1ae77aa..ad346c096 100644 --- a/ui/drawer_paint.go +++ b/ui/drawer_paint.go @@ -22,7 +22,7 @@ func drawerDeclComponent(spec *DrawerDecl, Surface *gfx.Canvas, Palette Theme, b drawer := components.BeginDrawer(Surface, Palette, bounds, components.DrawerOptions{ Layer: layer, Scope: spec.GetScope(), DismissID: spec.GetDismiss(), CloseID: spec.GetClose(), Side: drawerSideComponent(spec.Side), ContentExtent: spec.Size, InitialFocusID: spec.InitialFocus, - HandleID: spec.GetHandle(), Offset: spec.GetOffset(), + HandleID: spec.GetHandle(), Offset: spec.GetOffset(), HeaderInset: titlebarHeight(Surface), }) if spec.Swipe { drawer = drawer.WithHandle() @@ -54,10 +54,19 @@ func drawerComponent(spec *DrawerDeclaration, surface *gfx.Canvas, palette Theme drawer := components.BeginDrawer(surface, palette, bounds, components.DrawerOptions{ Layer: layer, Scope: spec.GetScope(), DismissID: spec.GetDismiss(), CloseID: spec.GetClose(), Side: drawerSideComponent(spec.Side), ContentExtent: spec.Size, InitialFocusID: spec.InitialFocus, - HandleID: spec.GetHandle(), Offset: spec.GetOffset(), + HandleID: spec.GetHandle(), Offset: spec.GetOffset(), HeaderInset: titlebarHeight(surface), }) if spec.Swipe { drawer = drawer.WithHandle() } return drawer } + +// titlebarHeight is the strip a drawer's header keeps clear of: the window +// buttons' strip of a custom-titlebar window, zero without one. +func titlebarHeight(canvas *gfx.Canvas) float32 { + if canvas == nil { + return 0 + } + return canvas.TitlebarHeight() +} diff --git a/ui/drawer_test.go b/ui/drawer_test.go index ca6767c1e..9641b0919 100644 --- a/ui/drawer_test.go +++ b/ui/drawer_test.go @@ -4,6 +4,7 @@ import ( "testing" "time" + "github.com/vivaui/viva/app" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" ) @@ -220,3 +221,30 @@ func TestDrawerInsetLeavesTheWindowEdgeOutside(t *testing.T) { t.Fatal("a press beside the panel did not close it") } } + +// In a custom-titlebar window a drawer still covers the whole window, the +// titlebar strip included, but its title and close button start below the strip +// the window buttons cover, and a press on the strip beside the panel is a +// press on the backdrop. The strip's height is whatever the window configured; +// the insets at its ends are platform ones and are not what keeps a title clear. +func TestDrawerHeaderKeepsClearOfTheTitlebar(t *testing.T) { + m := &drawerModel{title: "Host", side: ui.DrawerLeft} + const strip = float32(36) + d := openPageWith(t, ui.PageConfig{View: m.page}, app.Config{ + WindowMode: app.WindowCustomTitlebar, TitlebarHeight: strip, Width: 480, Height: 480, + }) + d.click("Open") + if err := d.driver.Advance(time.Second); err != nil { + t.Fatal(err) + } + close, name := d.hit("Close drawer").Bounds, d.hit("Name").Bounds + if close.Y < strip || name.Y < strip || close.Y > strip+24 { + t.Fatalf("close %v and body %v do not start just under the %vpx titlebar strip", close, name, strip) + } + if err := d.driver.Click(400, strip/2); err != nil { + t.Fatal(err) + } + if m.open { + t.Fatal("the scrim does not cover the titlebar strip: a press there left the drawer open") + } +} diff --git a/ui/list_anchor_test.go b/ui/list_anchor_test.go new file mode 100644 index 000000000..4e2ca75d8 --- /dev/null +++ b/ui/list_anchor_test.go @@ -0,0 +1,87 @@ +package ui_test + +import ( + "strconv" + "testing" + + "github.com/vivaui/viva/ui" +) + +// talkRows is a conversation: two short lines, then a long reply, over and over, so +// the rows a List has not measured are far from the average of those it has. +type talkRows struct { + list ui.ListState + n int +} + +func (m *talkRows) height(i int) float32 { + if i%3 == 2 { + return 300 + } + return 30 +} + +func (m *talkRows) page(c ui.C) { + ui.Column(c).Fill().Children(func() { + ui.List(c, &m.list, m.n, func(row ui.ListRow) { + row.Element.Height(m.height(row.Index)).Children(func() { + ui.Text(row.C, "row "+strconv.Itoa(row.Index)) + }) + }).Label("Talk").Grow(1) + }) +} + +// rowTop is where the row named label starts on screen. +func (d *pageDriver) rowTop(label string) (float32, bool) { + for _, hit := range d.driver.Snapshot().Hits { + if hit.Label == label && !hit.IsLabel && !hit.Backdrop { + return hit.Bounds.Y, true + } + } + return 0, false +} + +// Read upward from the end, a List brings in rows it has never measured. Their heights, +// and the average it estimates the rows above them by, change where the list computes +// every row above to start; the rows on screen must still move by what the wheel moved +// them, as on a page, not jump by the difference (which here is more than the viewport). +func TestListKeepsTheRowsOnScreenAsRowsAboveAreMeasured(t *testing.T) { + m := &talkRows{n: 600} + m.list.Label = func(i int) string { return "row " + strconv.Itoa(i) } + d := openPage(t, m.page) + d.repaint() + m.list.ScrollToEnd() + for range 12 { + d.repaint() + } + area := d.ListArea("Talk") + // The wheel moves content by exactly wheelStep. A row may land up to tolerance + // off that, from snapping to whole pixels; a jump is several times the step. + const wheelStep = 24 + const tolerance = wheelStep / 8 + // Sample a short row in the middle half of the viewport, so neither its bounds + // before the wheel nor after it are clipped by the viewport's edges. + low, high := area.Y+area.Height/4, area.Y+area.Height*3/4 + for step := range 300 { + label := "" + var before float32 + first, last := m.list.Visible() + for i := first; i <= last && label == ""; i++ { + if y, ok := d.rowTop("row " + strconv.Itoa(i)); ok && i%3 != 2 && y > low && y < high { + label, before = "row "+strconv.Itoa(i), y + } + } + if label == "" { + d.wheel(area, 0, -wheelStep, 0) + continue + } + d.wheel(area, 0, -wheelStep, 0) + after, ok := d.rowTop(label) + if !ok { + t.Fatalf("step %d: a wheel of %d took %s at %v off the screen", step, wheelStep, label, before) + } + if moved := after - before; moved < wheelStep-tolerance || moved > wheelStep+tolerance { + t.Fatalf("step %d: a wheel of %d moved %s by %v", step, wheelStep, label, moved) + } + } +} diff --git a/ui/list_selection_test.go b/ui/list_selection_test.go index babc1fc5e..9a4c834e7 100644 --- a/ui/list_selection_test.go +++ b/ui/list_selection_test.go @@ -374,3 +374,18 @@ func TestListIsOneTabStop(t *testing.T) { t.Fatalf("Tab out of the list reached %q: the other rows are stops too", d.Focused()) } } + +// Shift with an arrow in a list that chooses one row moves the choice, as a plain +// arrow does: there is no range to extend. +func TestListOfOneChoiceShiftArrowMoves(t *testing.T) { + m := newSelecting("alpha", "beta", "gamma") + m.list.Selection = nil + d := openPage(t, m.page) + d.click("alpha") + if err := d.driver.Key(gfx.KeyDown, gfx.ModifierShift); err != nil { + t.Fatal(err) + } + if m.list.Selected() != 1 || d.Focused() != "beta" || m.list.Chosen(0) { + t.Fatalf("Shift+Down: selected %d, focus %q, alpha still chosen %v", m.list.Selected(), d.Focused(), m.list.Chosen(0)) + } +} diff --git a/ui/shortcut_test.go b/ui/shortcut_test.go index 08a46be95..c84038bed 100644 --- a/ui/shortcut_test.go +++ b/ui/shortcut_test.go @@ -193,3 +193,123 @@ func TestListShortcutActsWhileARowHasFocus(t *testing.T) { t.Fatalf("the List's Delete acted %d times with a row focused", deletes) } } + +// mouseModel is a window that goes back on the mouse's back button anywhere, +// closes a tab on a middle click on it, and has a strip whose middle click acts on +// any tab inside it. +type mouseModel struct { + backs, ctrlForwards, tabCloses, stripCloses, pageMiddles, clicks int + chipCloses, chipButtons int + menu bool +} + +func (m *mouseModel) page(c ui.C) { + if ui.Shortcut(c, 0, "mouse_back") { + m.backs++ + } + if ui.Shortcut(c, ui.Ctrl, "mouse_forward") { + m.ctrlForwards++ + } + if ui.Shortcut(c, 0, "mouse_middle") { + m.pageMiddles++ + } + ui.Column(c).Pad(16).Gap(8).Children(func() { + tab := ui.Button(c, "Tab") + if tab.Clicked() { + m.clicks++ + } + if tab.Shortcut(0, "mouse_middle") { + m.tabCloses++ + } + strip := ui.Row(c).Gap(4).Children(func() { + ui.Button(c, "Inside") + }) + if strip.Shortcut(0, "mouse_middle") { + m.stripCloses++ + } + // A tab drawn as a container: its own hit, a title without one, and a + // close button inside it. + k := c.Key("chip") + chip := ui.Row(k).Gap(4).Pad(4).Hit(ui.ID(k), "Chip").Children(func() { + ui.Text(c, "Chip title") + if ui.Button(k, "Close chip").Clicked() { + m.chipButtons++ + } + }) + if chip.Shortcut(0, "mouse_middle") { + m.chipCloses++ + } + ui.Button(c, "Elsewhere") + more := ui.Button(c, "More") + if more.Clicked() { + m.menu = !m.menu + } + ui.Popover(c, more, &m.menu, ui.PopoverSpec{Align: ui.Start}, func() { ui.Button(c, "Rename") }) + }) +} + +func (d *pageDriver) press(Label string, button gfx.PointerButton) { + d.t.Helper() + x, y := center(d.hit(Label).Bounds) + if err := d.driver.Press(x, y, button); err != nil { + d.t.Fatal(err) + } + if err := d.driver.Release(x, y, button); err != nil { + d.t.Fatal(err) + } +} + +// A mouse button's Shortcut acts on a press wherever it lands, the innermost +// element's own winning over a page-wide one, and never clicks what it lands on. +func TestShortcutActsOnMouseButtonsWhereThePressLands(t *testing.T) { + m := &mouseModel{} + d := openPage(t, m.page) + + d.press("Elsewhere", gfx.PointerButtonBack) + if m.backs != 1 { + t.Fatalf("back button: backs %d", m.backs) + } + d.press("Tab", gfx.PointerButtonForward) + if m.ctrlForwards != 0 { + t.Fatal("forward without Control acted on the Control+forward Shortcut") + } + d.withModifier(gfx.KeyControlLeft, func() { d.press("Tab", gfx.PointerButtonForward) }) + if m.ctrlForwards != 1 { + t.Fatalf("Control+forward: %d", m.ctrlForwards) + } + + d.press("Tab", gfx.PointerButtonMiddle) + if m.tabCloses != 1 || m.pageMiddles != 0 || m.clicks != 0 { + t.Fatalf("middle click on the tab: tab %d, page %d, clicks %d", m.tabCloses, m.pageMiddles, m.clicks) + } + d.press("Inside", gfx.PointerButtonMiddle) + if m.stripCloses != 1 || m.pageMiddles != 0 { + t.Fatalf("middle click in the strip: strip %d, page %d", m.stripCloses, m.pageMiddles) + } + d.press("Chip", gfx.PointerButtonMiddle) + if m.chipCloses != 1 || m.pageMiddles != 0 { + t.Fatalf("middle click on a container with a hit of its own: chip %d, page %d", m.chipCloses, m.pageMiddles) + } + d.press("Close chip", gfx.PointerButtonMiddle) + if m.chipCloses != 2 || m.chipButtons != 0 || m.pageMiddles != 0 { + t.Fatalf("middle click on a button in the container: chip %d, button %d, page %d", m.chipCloses, m.chipButtons, m.pageMiddles) + } + d.press("Elsewhere", gfx.PointerButtonMiddle) + if m.pageMiddles != 1 || m.tabCloses != 1 || m.stripCloses != 1 { + t.Fatalf("middle click elsewhere: page %d, tab %d, strip %d", m.pageMiddles, m.tabCloses, m.stripCloses) + } + + d.click("Tab") + if m.clicks != 1 || m.tabCloses != 1 { + t.Fatalf("primary click: clicks %d, closes %d", m.clicks, m.tabCloses) + } + + d.click("More") + if !m.menu { + t.Fatal("the popover did not open") + } + d.press("Rename", gfx.PointerButtonBack) + if m.backs != 1 { + t.Fatal("a page-wide mouse Shortcut acted while an overlay was open") + } +} diff --git a/ui/table_checked_test.go b/ui/table_checked_test.go index 28d63b83b..214321fd8 100644 --- a/ui/table_checked_test.go +++ b/ui/table_checked_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/keymap" "github.com/vivaui/viva/ui" ) @@ -25,19 +26,21 @@ func (d *pageDriver) clickHit(hit gfx.Hit) { } } -// A table given Checked has a checkbox for each row and one in the header: the -// row's ticks are the keys of the Selection, the header ticks or clears them all, -// and it is mixed while only some are ticked. -func TestTableCheckedTicksRowsAndHeader(t *testing.T) { +// A table with a Selection and Checkboxes has a checkbox for each row and one in +// the header: a row's tick is its place in the Selection, a tick makes the row the +// selected one as a Primary click would, the header chooses or clears them all and +// is mixed while only some are chosen, and Changed reports each. +func TestTableCheckboxesShowTheSelection(t *testing.T) { var state ui.TableState - var checked ui.Selection + var chosen ui.Selection + state.Selection = &chosen changes := 0 d := openPage(t, func(c ui.C) { ui.Table(c, &state, ui.TableSpec{ - Source: wholeRows{}, Checked: &checked, + Source: wholeRows{}, Checkboxes: true, Columns: titledColumns(nil, []string{"Host", "Port"}, nil), }).Width(400).Height(200) - if state.CheckedChanged() { + if state.Changed() { changes++ } }) @@ -46,26 +49,63 @@ func TestTableCheckedTicksRowsAndHeader(t *testing.T) { t.Fatalf("row checkboxes = %d, want one for each of the 3 rows", len(boxes)) } d.clickHit(boxes[1]) - if !checked.Has(1) || checked.Len() != 1 || changes != 1 { - t.Fatalf("after a tick on row 1: checked %v (len %d), changes %d", checked.Has(1), checked.Len(), changes) + if !chosen.Has(1) || chosen.Len() != 1 || changes != 1 { + t.Fatalf("after a tick on row 1: chosen %v (len %d), changes %d", chosen.Has(1), chosen.Len(), changes) + } + if state.Selected() != 1 { + t.Fatalf("a tick on row 1 left row %d selected; a tick chooses as a Primary click does", state.Selected()) } - if state.Selected() != -1 { - t.Fatalf("a tick selected row %d; ticks and the selected row are separate", state.Selected()) + d.clickHit(d.rowChecks()[2]) + if !chosen.Has(1) || !chosen.Has(2) || chosen.Len() != 2 { + t.Fatalf("a second tick replaced the first: %d chosen", chosen.Len()) + } + if boxes := d.rowChecks(); !boxes[1].Checked || !boxes[2].Checked || boxes[0].Checked { + t.Fatalf("the checkboxes do not show the Selection: %v %v %v", boxes[0].Checked, boxes[1].Checked, boxes[2].Checked) } header := d.hit("Select all rows") if header.Checked || !header.Mixed { - t.Fatalf("header with one of three ticked: checked %v, mixed %v; want mixed", header.Checked, header.Mixed) + t.Fatalf("header with two of three chosen: checked %v, mixed %v; want mixed", header.Checked, header.Mixed) } d.clickHit(header) - if checked.Len() != 3 { - t.Fatalf("%d rows ticked after the header was pressed with some ticked, want all 3", checked.Len()) + if chosen.Len() != 3 { + t.Fatalf("%d rows chosen after the header was pressed with some chosen, want all 3", chosen.Len()) } if h := d.hit("Select all rows"); !h.Checked || h.Mixed { - t.Fatalf("header with every row ticked: checked %v, mixed %v", h.Checked, h.Mixed) + t.Fatalf("header with every row chosen: checked %v, mixed %v", h.Checked, h.Mixed) } d.clickHit(d.hit("Select all rows")) - if checked.Len() != 0 { - t.Fatalf("%d rows ticked after the header was pressed with all ticked, want none", checked.Len()) + if chosen.Len() != 0 { + t.Fatalf("%d rows chosen after the header was pressed with all chosen, want none", chosen.Len()) + } + if changes != 4 { + t.Fatalf("Changed reported %d times for four ticks", changes) + } +} + +// Space ticks the row the keys are on in a table with checkboxes, where it would +// otherwise activate the row and choose it alone. +func TestTableCheckboxesSpaceTicksTheRow(t *testing.T) { + var state ui.TableState + var chosen ui.Selection + state.Selection = &chosen + d := openPage(t, func(c ui.C) { + ui.Table(c, &state, ui.TableSpec{ + Source: wholeRows{}, Checkboxes: true, + Columns: titledColumns(nil, []string{"Host", "Port"}, nil), + }).Width(400).Height(200) + }) + d.click("alpha") + // Primary with an arrow moves the keys without choosing. + if err := d.driver.Key(gfx.KeyDown, keymap.Primary); err != nil { + t.Fatal(err) + } + d.key(gfx.KeySpace) + if !chosen.Has(0) || !chosen.Has(1) || chosen.Len() != 2 { + t.Fatalf("Space on beta after alpha was chosen: alpha %v, beta %v, %d chosen", chosen.Has(0), chosen.Has(1), chosen.Len()) + } + d.key(gfx.KeySpace) + if chosen.Has(1) || chosen.Len() != 1 { + t.Fatalf("Space again kept beta chosen: %d chosen", chosen.Len()) } } @@ -75,9 +115,10 @@ func TestTableCheckedTicksRowsAndHeader(t *testing.T) { func TestTableCheckedKeepsTheApplicationsColumnIndexes(t *testing.T) { var state ui.TableState var checked ui.Selection + state.Selection = &checked d := openPage(t, func(c ui.C) { ui.Table(c, &state, ui.TableSpec{ - Source: wholeRows{}, Checked: &checked, + Source: wholeRows{}, Checkboxes: true, Columns: titledColumns(nil, []string{"Host", "Port"}, nil), }).Width(400).Height(200) }) @@ -102,10 +143,11 @@ func TestTableCheckedKeepsTheApplicationsColumnIndexes(t *testing.T) { func TestTableCheckedSortsByTheApplicationsColumn(t *testing.T) { var state ui.TableState var checked ui.Selection + state.Selection = &checked clicked := -1 d := openPage(t, func(c ui.C) { table := ui.Table(c, &state, ui.TableSpec{ - Source: wholeRows{}, Checked: &checked, + Source: wholeRows{}, Checkboxes: true, Columns: titledColumns(nil, []string{"Host", "Port"}, []bool{true, true}), }).Width(400).Height(200) if column, ok := table.HeaderClicked(); ok { @@ -118,15 +160,16 @@ func TestTableCheckedSortsByTheApplicationsColumn(t *testing.T) { } } -// Checked rows repaint without allocating. +// Chosen rows with checkboxes repaint without allocating. func TestTableCheckedRepaintsWithoutAllocating(t *testing.T) { var state ui.TableState var checked ui.Selection checked.Add(1) + state.Selection = &checked rows := ui.TableRows{{"alpha", ""}, {"beta", ":22"}, {"gamma", ""}} // cells made once: wholeRows builds them in each call columns := titledColumns(nil, []string{"Host", "Port"}, nil) d := openPage(t, func(c ui.C) { - ui.Table(c, &state, ui.TableSpec{Source: &rows, Checked: &checked, Columns: columns}).Width(400).Height(200) + ui.Table(c, &state, ui.TableSpec{Source: &rows, Checkboxes: true, Columns: columns}).Width(400).Height(200) }) d.repaint() d.repaint() @@ -140,10 +183,11 @@ func TestTableCheckedRepaintsWithoutAllocating(t *testing.T) { func TestTableCheckedWithFrozenColumnsTicksOnce(t *testing.T) { var state ui.TableState var checked ui.Selection + state.Selection = &checked rows := ui.TableRows{{"alpha", "a", "b"}, {"beta", "c", "d"}, {"gamma", "e", "f"}} columns := titledColumns([]ui.TableColumn{{Width: 120}, {Width: 160}, {Width: 160}}, []string{"Host", "Port", "User"}, nil) d := openPage(t, func(c ui.C) { - ui.Table(c, &state, ui.TableSpec{Source: &rows, Checked: &checked, Columns: columns, FrozenColumns: 1}).Width(300).Height(200) + ui.Table(c, &state, ui.TableSpec{Source: &rows, Checkboxes: true, Columns: columns, FrozenColumns: 1}).Width(300).Height(200) }) boxes := d.rowChecks() if len(boxes) == 0 { diff --git a/ui/table_filter_test.go b/ui/table_filter_test.go index 68443a15e..37a029a36 100644 --- a/ui/table_filter_test.go +++ b/ui/table_filter_test.go @@ -18,7 +18,7 @@ func TestFilterButtonReportsItsColumn(t *testing.T) { columns[1].Filterable = true spec := ui.TableSpec{Source: wholeRows{}, Columns: columns} if checkedTable { - spec.Checked = &checked + state.Selection, spec.Checkboxes = &checked, true } d := openPage(t, func(c ui.C) { table := ui.Table(c, &state, spec).Width(400).Height(200) diff --git a/ui/table_paint.go b/ui/table_paint.go index 559a6f9f3..5c4fb6554 100644 --- a/ui/table_paint.go +++ b/ui/table_paint.go @@ -42,7 +42,7 @@ func paintTableRows(f *Frame, t *TableDecl, rows Rect, First, Last int, top, con if t.GetState().Scroll.GetDragging() { id = gfx.ID{} } - table.RowState(id, cells, components.TableRowState{Selected: row == t.GetState().Selected()}) + table.RowState(id, cells, components.TableRowState{Selected: t.GetState().Chosen(row)}) if lead > 0 && !id.IsZero() { paintRowCheckbox(f, t, row, Rect{X: rows.X, Y: top + float32(row)*rowHeight, Width: t.GetSpec().Columns[0].Width, Height: rowHeight}) } @@ -163,7 +163,9 @@ func paintTableHeaderRow(f *Frame, t *TableDecl, r Rect, headerHeight, rowHeight } canvas.LabelCenter(arrow, Rect{X: x, Y: cell.Y, Width: 12, Height: cell.Height}, gfx.TextStyle{Size: fontSize, Weight: gfx.WeightMedium, Color: f.Palette.MutedForeground}) } - canvas.HitWithLabel(t.GetSpec().Header.At(column-lead), cell, title) + canvas.HitWithOptions(t.GetSpec().Header.At(column-lead), cell, title, gfx.HitOptions{ + Role: gfx.RoleColumnHeader, Sort: t.GetState().GetSortDirection(column - lead), + }) } for column, cell := range cells { if column >= lead && column < len(t.GetSpec().Columns) && t.GetSpec().Columns[column].Filterable { @@ -204,7 +206,8 @@ func paintFilterButton(f *Frame, t *TableDecl, column int, cell Rect) { const checkSize = 16 // paintRowCheckbox paints the checkbox of a row in the cell of the column of -// checkboxes; a click on it was applied where the table was declared. +// checkboxes, ticked while the row is chosen; a click on it was applied where the +// table was declared. func paintRowCheckbox(f *Frame, t *TableDecl, row int, cell Rect) { canvas := f.Surface id := base.CheckID(canvas, t.GetSpec().Rows, row) @@ -213,7 +216,7 @@ func paintRowCheckbox(f *Frame, t *TableDecl, row int, cell Rect) { label = "Select row" } box := Rect{X: cell.X + (cell.Width-checkSize)/2, Y: cell.Y + (cell.Height-checkSize)/2, Width: checkSize, Height: checkSize} - components.BeginCheckbox(canvas, f.Palette, id, box, t.GetSpec().Checked.Has(row)).Label(label).Paint() + components.BeginCheckbox(canvas, f.Palette, id, box, t.GetState().Chosen(row)).Label(label).Paint() } // paintHeaderCheckbox paints the checkbox of the header: ticked when every row is, diff --git a/ui/table_selection_test.go b/ui/table_selection_test.go new file mode 100644 index 000000000..8cbca61c4 --- /dev/null +++ b/ui/table_selection_test.go @@ -0,0 +1,277 @@ +package ui_test + +import ( + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/keymap" + "github.com/vivaui/viva/ui" +) + +// choosingTable is a table of four hosts the tests click, move through and press +// keys in, choosing several rows when multi is set. +type choosingTable struct { + state ui.TableState + chosen ui.Selection + rows ui.TableRows + columns []ui.TableColumn + changed int + sorted int // header clicks +} + +func newChoosingTable(multi bool) *choosingTable { + m := &choosingTable{ + rows: ui.TableRows{{"alpha", "22"}, {"beta", "23"}, {"gamma", "24"}, {"delta", "25"}}, + columns: titledColumns(nil, []string{"Host", "Port"}, []bool{true, false}), + } + if multi { + m.state.Selection = &m.chosen + } + return m +} + +func (m *choosingTable) page(c ui.C) { + table := ui.Table(c, &m.state, ui.TableSpec{Source: &m.rows, Columns: m.columns}).Label("Hosts").Width(400).Height(240) + if column, ok := table.HeaderClicked(); ok { + m.state.SortBy(column) + m.sorted++ + } + if m.state.Changed() { + m.changed++ + } +} + +func (m *choosingTable) has(rows ...int) bool { + if m.chosen.Len() != len(rows) { + return false + } + for _, row := range rows { + if !m.chosen.Has(row) { + return false + } + } + return true +} + +// keyWith presses key with modifiers held. +func (d *pageDriver) keyWith(key gfx.Key, modifiers gfx.Modifiers) { + d.t.Helper() + if err := d.driver.Key(key, modifiers); err != nil { + d.t.Fatal(err) + } +} + +// Without a Selection a table chooses one row however it is clicked or moved: +// Shift and Primary change nothing about that, and Primary+A chooses nothing. +func TestTableSingleChoiceIgnoresRangeModifiers(t *testing.T) { + m := newChoosingTable(false) + d := openPage(t, m.page) + d.click("alpha") + d.withModifier(gfx.KeyShiftLeft, func() { d.click("gamma") }) + if m.state.Selected() != 2 || m.state.Chosen(0) || m.state.Chosen(1) || !m.state.Chosen(2) { + t.Fatalf("Shift-click in a table of one choice: selected %d, alpha %v, beta %v", m.state.Selected(), m.state.Chosen(0), m.state.Chosen(1)) + } + d.keyWith(gfx.KeyDown, gfx.ModifierShift) + if m.state.Selected() != 3 || m.state.Chosen(2) || d.Focused() != "delta" { + t.Fatalf("Shift+Down in a table of one choice: selected %d, gamma still chosen %v, focus %q", m.state.Selected(), m.state.Chosen(2), d.Focused()) + } + if _, err := d.driver.ShortcutChord(keymap.Primary, 'a'); err != nil { + t.Fatal(err) + } + if m.state.Selected() != 3 || m.state.Chosen(0) { + t.Fatalf("Primary+A in a table of one choice chose rows: selected %d", m.state.Selected()) + } +} + +// Shift-click chooses the rows from the anchor, the row last clicked without +// Shift, to the clicked one; Primary-click adds a row or takes it out and moves the +// anchor there; Changed reports each. +func TestTableModifierClicks(t *testing.T) { + m := newChoosingTable(true) + d := openPage(t, m.page) + d.click("alpha") + if !m.has(0) || m.state.Selected() != 0 || m.changed != 1 { + t.Fatalf("click: chosen %d, selected %d, changed %d", m.chosen.Len(), m.state.Selected(), m.changed) + } + d.withModifier(gfx.KeyShiftLeft, func() { d.click("gamma") }) + if !m.has(0, 1, 2) || m.state.Selected() != 2 { + t.Fatalf("Shift-click from alpha to gamma: %d chosen, selected %d", m.chosen.Len(), m.state.Selected()) + } + // A Shift range is from the anchor whichever way it goes, and the new one + // stands for the last. + d.withModifier(gfx.KeyShiftLeft, func() { d.click("beta") }) + if !m.has(0, 1) || m.state.Selected() != 1 { + t.Fatalf("Shift-click back to beta: %d chosen, selected %d", m.chosen.Len(), m.state.Selected()) + } + d.withModifier(primaryKey(), func() { d.click("delta") }) + if !m.has(0, 1, 3) || m.state.Selected() != 3 { + t.Fatalf("Primary-click on delta: %d chosen, selected %d", m.chosen.Len(), m.state.Selected()) + } + d.withModifier(primaryKey(), func() { d.click("alpha") }) + if !m.has(1, 3) { + t.Fatalf("Primary-click on a chosen row kept it: %d chosen", m.chosen.Len()) + } + // The anchor is where the last Primary-click was. + d.withModifier(gfx.KeyShiftLeft, func() { d.click("beta") }) + if !m.chosen.Has(0) || !m.chosen.Has(1) || m.chosen.Has(2) { + t.Fatalf("Shift-click after a Primary-click on alpha did not range from alpha: %d chosen", m.chosen.Len()) + } + d.click("gamma") + if !m.has(2) || m.state.Selected() != 2 { + t.Fatalf("a plain click did not choose gamma alone: %d chosen", m.chosen.Len()) + } + if m.changed != 7 { + t.Fatalf("Changed reported %d times for seven clicks that changed the choice", m.changed) + } +} + +// Shift with the arrows extends the choice from the anchor, Primary with them moves +// the keys without choosing, and Primary+A chooses every row. +func TestTableKeysExtendAndSelectAll(t *testing.T) { + m := newChoosingTable(true) + d := openPage(t, m.page) + d.click("beta") + d.keyWith(gfx.KeyDown, gfx.ModifierShift) + d.keyWith(gfx.KeyDown, gfx.ModifierShift) + if !m.has(1, 2, 3) || m.state.Selected() != 3 || d.Focused() != "delta" { + t.Fatalf("Shift+Down twice from beta: %d chosen, selected %d, focus %q", m.chosen.Len(), m.state.Selected(), d.Focused()) + } + d.keyWith(gfx.KeyUp, gfx.ModifierShift) + if !m.has(1, 2) || m.state.Selected() != 2 { + t.Fatalf("Shift+Up shrinks the range toward the anchor: %d chosen, selected %d", m.chosen.Len(), m.state.Selected()) + } + d.keyWith(gfx.KeyUp, keymap.Primary) + d.keyWith(gfx.KeyUp, keymap.Primary) + if !m.has(1, 2) || m.state.Selected() != 0 || d.Focused() != "alpha" { + t.Fatalf("Primary+Up moved the choice: %d chosen, selected %d, focus %q", m.chosen.Len(), m.state.Selected(), d.Focused()) + } + d.key(gfx.KeyDown) + if !m.has(1) || m.state.Selected() != 1 { + t.Fatalf("a plain Down did not choose beta alone: %d chosen, selected %d", m.chosen.Len(), m.state.Selected()) + } + changed := m.changed + if _, err := d.driver.ShortcutChord(keymap.Primary, 'a'); err != nil { + t.Fatal(err) + } + if !m.has(0, 1, 2, 3) || m.changed != changed+1 { + t.Fatalf("Primary+A: %d chosen, changed %d (was %d)", m.chosen.Len(), m.changed, changed) + } +} + +// Space does not activate a row of a table that chooses several, which would +// choose it alone; Control+Space adds it or takes it out off macOS. +func TestTableSpaceKeepsTheChoice(t *testing.T) { + m := newChoosingTable(true) + d := openPage(t, m.page) + d.click("alpha") + d.withModifier(primaryKey(), func() { d.click("gamma") }) + d.key(gfx.KeySpace) + if !m.has(0, 2) || m.state.Selected() != 2 { + t.Fatalf("Space changed the choice: %d chosen, selected %d", m.chosen.Len(), m.state.Selected()) + } + if primaryKey() == gfx.KeyMetaLeft { + return // Control+Space is the input source switch on macOS + } + d.keyWith(gfx.KeySpace, gfx.ModifierControl) + if !m.has(0) { + t.Fatalf("Control+Space did not take gamma out: %d chosen", m.chosen.Len()) + } +} + +// The rows are one stop of Tab: only the row the keys are on is reached by Tab, +// the others by the arrows. +func TestTableRowsAreOneTabStop(t *testing.T) { + m := newChoosingTable(true) + d := openPage(t, m.page) + stops := func() (n int, label string) { + for _, hit := range d.driver.Snapshot().Hits { + if hit.Role == gfx.RoleOption && hit.Focusable && !hit.SkipTab { + n++ + label = hit.Label + } + } + return + } + if n, label := stops(); n != 1 || label != "alpha" { + t.Fatalf("before a choice: %d rows reached by Tab (%q), want the first row only", n, label) + } + d.click("gamma") + if n, label := stops(); n != 1 || label != "gamma" { + t.Fatalf("after a click on gamma: %d rows reached by Tab (%q), want gamma only", n, label) + } +} + +// Assistive technology sees the rows as options of a list named by the element's +// Label, multi-selectable when the table has a Selection, each saying whether it is +// chosen; a sortable header says how it sorts, through ascending, descending and +// unsorted as it is clicked. +func TestTableAccessibility(t *testing.T) { + find := func(nodes []app.AccessNode, role gfx.Role, label string) (app.AccessNode, bool) { + for _, node := range nodes { + if node.Role == role && node.Label == label { + return node, true + } + } + return app.AccessNode{}, false + } + for _, multi := range []bool{false, true} { + m := newChoosingTable(multi) + d := openPage(t, m.page) + d.click("alpha") + if multi { + d.withModifier(primaryKey(), func() { d.click("gamma") }) + } + nodes := d.driver.Accessibility() + list, ok := find(nodes, gfx.RoleListBox, "Hosts") + if !ok { + t.Fatalf("multi %v: no list named Hosts in %d nodes", multi, len(nodes)) + } + if list.MultiSelectable != multi { + t.Fatalf("multi %v: the list is multi-selectable %v", multi, list.MultiSelectable) + } + for row, name := range []string{"alpha", "beta", "gamma", "delta"} { + option, ok := find(nodes, gfx.RoleOption, name) + if !ok { + t.Fatalf("multi %v: no option for %s", multi, name) + } + if option.Selected != m.state.Chosen(row) { + t.Fatalf("multi %v: %s reports selected %v, chosen %v", multi, name, option.Selected, m.state.Chosen(row)) + } + } + for clicks, want := range []gfx.SortDirection{gfx.SortNone, gfx.SortAscending, gfx.SortDescending, gfx.SortNone} { + if clicks > 0 { + d.click("Host") + } + header, ok := find(d.driver.Accessibility(), gfx.RoleColumnHeader, "Host") + if !ok { + t.Fatalf("multi %v: the sortable Host header is not a column header", multi) + } + if header.Sort != want { + t.Fatalf("multi %v: after %d clicks the header reports %v, want %v", multi, clicks, header.Sort, want) + } + } + if _, ok := find(d.driver.Accessibility(), gfx.RoleColumnHeader, "Port"); ok { + t.Fatalf("multi %v: the Port column, not sortable, is a column header to press", multi) + } + } +} + +// A sortable header is reached by Tab, and Enter or Space on it sorts by it, as a +// click does. +func TestTableHeaderSortsFromTheKeyboard(t *testing.T) { + m := newChoosingTable(false) + d := openPage(t, m.page) + d.key(gfx.KeyTab) + if d.Focused() != "Host" { + t.Fatalf("Tab went to %q; the sortable header comes first", d.Focused()) + } + d.key(gfx.KeyEnter) + if column, descending, ok := m.state.Sort(); !ok || column != 0 || descending { + t.Fatalf("Enter on the Host header: sort %d %v %v, want ascending by Host", column, descending, ok) + } + d.key(gfx.KeySpace) + if _, descending, ok := m.state.Sort(); !ok || !descending { + t.Fatalf("Space on the Host header: descending %v, ok %v", descending, ok) + } +} diff --git a/website/content/guides/en/declarative-layout.md b/website/content/guides/en/declarative-layout.md index c397f7065..464989988 100644 --- a/website/content/guides/en/declarative-layout.md +++ b/website/content/guides/en/declarative-layout.md @@ -318,21 +318,24 @@ import ( ) type model struct { - table ui.TableState - rows ui.TableRows + table ui.TableState + servers ui.TableRows // in the order they were added + rows ui.TableRows // in the order the table shows them } func newModel() *model { - return &model{rows: ui.TableRows{ + m := &model{servers: ui.TableRows{ {"web-01", "Running", "eu-west"}, {"web-02", "Running", "us-east"}, {"db-primary", "Degraded", "eu-west"}, {"cache", "Stopped", "us-east"}, }} + m.sortRows() + return m } -// page declares the table. A header click sorts the rows; a row click and the -// arrow keys select a row, and the table keeps the selection and the scroll +// page declares the table. A header click sorts the rows by that column, up, then +// down, then back in their own order; a row click and the arrow keys select a row, and the table keeps the selection and the scroll // position itself. func (m *model) page(c ui.C) { ui.Column(c).Fill().Pad(24).Gap(12).Children(func() { @@ -356,9 +359,11 @@ func (m *model) page(c ui.C) { }) } -// sortRows orders the rows by the column the table reports as sorted. The table -// paints the arrow; the application owns the data and its order. +// sortRows orders the rows by the column the table reports as sorted, or in their +// own order when none is. The table paints the arrow; the application owns the +// data and its order. func (m *model) sortRows() { + m.rows = append(m.rows[:0], m.servers...) column, descending, ok := m.table.Sort() if !ok { return diff --git a/website/content/guides/en/system-integration.md b/website/content/guides/en/system-integration.md index f503769d8..67d5d5f61 100644 --- a/website/content/guides/en/system-integration.md +++ b/website/content/guides/en/system-integration.md @@ -10,7 +10,7 @@ The `app` package exposes a small, synchronous set of system integrations. An op | Capability | Functions | | --- | --- | | Clipboard text | `app.ClipboardText`, `app.SetClipboardText`, `app.SetSensitiveClipboardText` | -| File dialogs | `app.OpenFiles`, `app.OpenDirectory`, `app.SaveFile` | +| File dialogs | `app.OpenFiles`, `app.OpenDirectory`, `app.OpenDirectories`, `app.SaveFile` | | Open a URL | `app.OpenURL` | | Open a local document in its default application (never a program) | `app.OpenPath` | | Open a local file, such as an HTML page, in the default browser whatever opens its type | `app.OpenPathInBrowser` | @@ -24,6 +24,7 @@ The `app` package exposes a small, synchronous set of system integrations. An op | Status-area icons and panels | `Application.AddStatusItem`, `app.WindowPanel` | | Fixed-pitch fonts | `app.MonospaceFamilies` | | Dock badge | `Application.SetDockBadge` | +| Window attention | `Window.RequestAttention` | | The icon the file manager shows for a file or folder | `app.FileIcon` | ## What each platform uses @@ -330,4 +331,5 @@ func main() { - To follow the system's light or dark look, read `app.SystemAppearance` while painting and call `app.WatchSystemAppearance` once with a function that requests a redraw. It is called on the event-loop thread, only when the look really changed. Linux listens to the desktop portal's signal while something watches, falls back to the XSETTINGS manager, `GTK_THEME` and the GTK and KDE configuration files, and answers `AppearanceUnknown` when none gives a preference; a headless `Driver` answers `AppearanceUnknown` until `SetSystemAppearance` says otherwise. - If the user can pick light or dark regardless of the system, call `app.SetNativeAppearance` with that pick so macOS's own window buttons, menus, file dialogs and native text editing match the window; `AppearanceUnknown` hands them back to the system, and `SystemAppearance` keeps reporting the system's look meanwhile. - The Dock badge is macOS's own: a label in the red badge at the corner of the application's Dock tile, which the system draws and sizes. Windows and Linux have no Dock tile and do nothing with it; an empty label removes the badge. +- `Window.RequestAttention` is for something that waits on the user, such as a confirmation in a background window. It asks the desktop for its own highlight — a Dock bounce, a taskbar flash, an urgency hint — and does nothing while the window is active. The system decides how long the highlight lasts; a closed or unsupported window reports an error. - Linux clipboard reads have a three-second deadline and add no idle worker or polling loop. diff --git a/website/content/guides/zh/declarative-layout.md b/website/content/guides/zh/declarative-layout.md index cbfffb66e..ea5bc332d 100644 --- a/website/content/guides/zh/declarative-layout.md +++ b/website/content/guides/zh/declarative-layout.md @@ -319,21 +319,24 @@ import ( ) type model struct { - table ui.TableState - rows ui.TableRows + table ui.TableState + servers ui.TableRows // in the order they were added + rows ui.TableRows // in the order the table shows them } func newModel() *model { - return &model{rows: ui.TableRows{ + m := &model{servers: ui.TableRows{ {"web-01", "Running", "eu-west"}, {"web-02", "Running", "us-east"}, {"db-primary", "Degraded", "eu-west"}, {"cache", "Stopped", "us-east"}, }} + m.sortRows() + return m } -// page declares the table. A header click sorts the rows; a row click and the -// arrow keys select a row, and the table keeps the selection and the scroll +// page declares the table. A header click sorts the rows by that column, up, then +// down, then back in their own order; a row click and the arrow keys select a row, and the table keeps the selection and the scroll // position itself. func (m *model) page(c ui.C) { ui.Column(c).Fill().Pad(24).Gap(12).Children(func() { @@ -357,9 +360,11 @@ func (m *model) page(c ui.C) { }) } -// sortRows orders the rows by the column the table reports as sorted. The table -// paints the arrow; the application owns the data and its order. +// sortRows orders the rows by the column the table reports as sorted, or in their +// own order when none is. The table paints the arrow; the application owns the +// data and its order. func (m *model) sortRows() { + m.rows = append(m.rows[:0], m.servers...) column, descending, ok := m.table.Sort() if !ok { return diff --git a/website/content/guides/zh/system-integration.md b/website/content/guides/zh/system-integration.md index bb798b654..63f18b5b7 100644 --- a/website/content/guides/zh/system-integration.md +++ b/website/content/guides/zh/system-integration.md @@ -10,7 +10,7 @@ group: guides | 能力 | 函数 | | --- | --- | | 剪贴板文本 | `app.ClipboardText`、`app.SetClipboardText`、`app.SetSensitiveClipboardText` | -| 文件对话框 | `app.OpenFiles`、`app.OpenDirectory`、`app.SaveFile` | +| 文件对话框 | `app.OpenFiles`、`app.OpenDirectory`、`app.OpenDirectories`、`app.SaveFile` | | 打开 URL | `app.OpenURL` | | 用默认应用打开本地文档(绝不运行程序) | `app.OpenPath` | | 用默认浏览器打开本地文件(如 HTML 页面),不论该类型关联到哪个应用 | `app.OpenPathInBrowser` | @@ -24,6 +24,7 @@ group: guides | 状态栏图标与面板 | `Application.AddStatusItem`、`app.WindowPanel` | | 等宽字体 | `app.MonospaceFamilies` | | Dock 角标 | `Application.SetDockBadge` | +| 窗口提醒 | `Window.RequestAttention` | | 文件管理器为文件或文件夹显示的图标 | `app.FileIcon` | ## 各平台用什么实现 @@ -320,4 +321,5 @@ func main() { - 要跟随系统的浅色或深色外观,就在绘制时读取 `app.SystemAppearance`,并只调用一次 `app.WatchSystemAppearance`,传入一个请求重绘的函数。它在事件循环线程上调用,且只在外观真的变了时调用。Linux 不监听桌面门户,而是在窗口获得焦点时重新读取一次,桌面没有给出偏好时返回 `AppearanceUnknown`;无窗口的 `Driver` 在调用 `SetSystemAppearance` 之前也返回 `AppearanceUnknown`。 - 如果用户可以不管系统而固定选择浅色或深色,就用这个选择调用 `app.SetNativeAppearance`,这样 macOS 自己绘制的窗口按钮、菜单、文件对话框和原生文本编辑会和窗口一致;传入 `AppearanceUnknown` 就还给系统,期间 `SystemAppearance` 仍然报告系统自己的外观。 - Dock 角标用 macOS 自己的机制:系统在应用 Dock 图标右上角画一个红色徽标并写入这段文字,尺寸也由系统决定。Windows 和 Linux 没有 Dock 图标,什么也不做;空文字表示去掉角标。 +- `Window.RequestAttention` 用于等待用户处理的事情,例如后台窗口里的确认请求。它让桌面用系统自己的方式提醒——Dock 图标跳动、任务栏按钮闪烁或紧急提示——窗口已经在前台时什么也不做。高亮持续多久由系统决定;已关闭或不支持的窗口返回错误。 - Linux 剪贴板读取有三秒期限,不增加空闲线程或轮询循环。