From ec5ca62da09cd63dcf9e372456b30680df7bcaaa Mon Sep 17 00:00:00 2001
From: ezreal <71426102+Ezreal-byte@users.noreply.github.com>
Date: Sat, 21 Nov 2026 15:59:17 +0800
Subject: [PATCH 01/47] fix(linux): fall back to a hand for the grabbing cursor
---
internal/platform/linux/system_linux.go | 4 ++-
internal/platform/linux/system_linux_test.go | 33 +++++++++++++-------
2 files changed, 24 insertions(+), 13 deletions(-)
diff --git a/internal/platform/linux/system_linux.go b/internal/platform/linux/system_linux.go
index 1185474e3..d10f031c2 100644
--- a/internal/platform/linux/system_linux.go
+++ b/internal/platform/linux/system_linux.go
@@ -485,7 +485,9 @@ func SetCursorShape(shape uint8) error {
if hooks := shellHooks.Load(); hooks != nil {
return hooks.setCursorShape(shape)
}
- glyphs := [...]uint16{68, 152, 60, 34, 150, 108, 116, 134, 136, 88}
+ // Keep the font fallback aligned with all visible gfx cursor shapes,
+ // including Grabbing (10), used while panning images and dragging cards.
+ glyphs := [...]uint16{68, 152, 60, 34, 150, 108, 116, 134, 136, 88, 58}
if int(shape) >= len(glyphs) && shape != cursorHidden {
return fmt.Errorf("linux: invalid cursor %d", shape)
}
diff --git a/internal/platform/linux/system_linux_test.go b/internal/platform/linux/system_linux_test.go
index 784ca10a1..5662311b2 100644
--- a/internal/platform/linux/system_linux_test.go
+++ b/internal/platform/linux/system_linux_test.go
@@ -210,7 +210,7 @@ func TestClipboardEncodingHelpers(t *testing.T) {
}
}
-func TestSetCursorShapeAppliesAndReleasesCursor(t *testing.T) {
+func TestSetCursorShapeAppliesAndReleasesEveryFallbackGlyph(t *testing.T) {
var nextID uint32 = 40
var fontName string
var sourceGlyph, maskGlyph uint16
@@ -256,17 +256,26 @@ func TestSetCursorShapeAppliesAndReleasesCursor(t *testing.T) {
activeWindow.Store(win)
t.Cleanup(func() { activeWindow.Store(nil) })
- if err := SetCursorShape(2); err != nil {
- t.Fatal(err)
- }
- if fontName != "cursor" || sourceGlyph != 60 || maskGlyph != 61 {
- t.Fatalf("cursor font = %q, glyphs = %d/%d", fontName, sourceGlyph, maskGlyph)
- }
- if requests != 3 || cursorValue != 42 || win.cursor != 42 {
- t.Fatalf("requests = %d, applied = %d, retained = %d", requests, cursorValue, win.cursor)
- }
- if !reflect.DeepEqual(freed, []uint32{9}) {
- t.Fatalf("freed cursors = %v", freed)
+ glyphs := []uint16{68, 152, 60, 34, 150, 108, 116, 134, 136, 88, 58}
+ if len(glyphs) != int(cursorHidden) {
+ t.Fatalf("%d fallback glyphs for %d visible shapes: a new shape needs a glyph", len(glyphs), cursorHidden)
+ }
+ for shape, glyph := range glyphs {
+ nextID, fontName, sourceGlyph, maskGlyph = 40, "", 0, 0
+ cursorValue, freed, requests = 0, nil, 0
+ win.cursor = 9
+ if err := SetCursorShape(uint8(shape)); err != nil {
+ t.Fatalf("cursor %d: %v", shape, err)
+ }
+ if fontName != "cursor" || sourceGlyph != glyph || maskGlyph != glyph+1 {
+ t.Fatalf("cursor %d: font = %q, glyphs = %d/%d", shape, fontName, sourceGlyph, maskGlyph)
+ }
+ if requests != 3 || cursorValue != 42 || win.cursor != 42 {
+ t.Fatalf("cursor %d: requests = %d, applied = %d, retained = %d", shape, requests, cursorValue, win.cursor)
+ }
+ if !reflect.DeepEqual(freed, []uint32{9}) {
+ t.Fatalf("cursor %d: freed cursors = %v", shape, freed)
+ }
}
}
From 3929552ebc6808a708b098a581d7fbeb83f68c53 Mon Sep 17 00:00:00 2001
From: MYCF711 <1451895195@qq.com>
Date: Sat, 21 Nov 2026 15:59:27 +0800
Subject: [PATCH 02/47] feat(app): report a web view's title, history and
loading
---
app/web.go | 66 +++++-
app/web_test.go | 90 +++++++
docs/web-views.md | 24 +-
examples/guides/webview/main.go | 11 +-
internal/platform/darwin/web_darwin.go | 76 +++++-
internal/platform/darwin/web_darwin.h | 7 +
internal/platform/darwin/web_darwin.m | 49 +++-
internal/platform/linux/gtk_app_linux.go | 10 +-
internal/platform/linux/gtk_web_linux.go | 100 +++++++-
internal/platform/web_host.go | 19 ++
internal/platform/web_load_error.go | 220 ++++++++++++++++++
internal/platform/web_load_error_test.go | 131 +++++++++++
internal/platform/windows/web_windows.go | 106 +++++++--
internal/platform/windows/webview2_windows.go | 46 ++--
.../content/guides/en/system-integration.md | 11 +-
.../content/guides/zh/system-integration.md | 11 +-
16 files changed, 915 insertions(+), 62 deletions(-)
create mode 100644 internal/platform/web_load_error.go
create mode 100644 internal/platform/web_load_error_test.go
diff --git a/app/web.go b/app/web.go
index f428b4356..f8431c00e 100644
--- a/app/web.go
+++ b/app/web.go
@@ -183,10 +183,57 @@ const (
WebLoadFinished
)
+// WebLoadError is why a navigation did not load the page, in the terms every engine can be held to:
+// the engines name the same failures differently, so a failed load reads the same way on every
+// platform. WebLoadNoError is a navigation that loaded.
+type WebLoadError = platform.WebLoadError
+
+const (
+ // WebLoadNoError is a navigation that loaded.
+ WebLoadNoError = platform.WebLoadNoError
+ // WebLoadUnknownError is a navigation the engine reports as failed without saying why, or with
+ // a reason Viva does not classify; WebLoad.Description carries whatever the engine said.
+ WebLoadUnknownError = platform.WebLoadUnknownError
+ // WebLoadCancelled is a navigation that was stopped: by the engine, or by a policy that
+ // interrupted the load it was part of.
+ WebLoadCancelled = platform.WebLoadCancelled
+ // WebLoadTimeout is a server that did not answer in time.
+ WebLoadTimeout = platform.WebLoadTimeout
+ // WebLoadHostNotFound is a name that did not resolve.
+ WebLoadHostNotFound = platform.WebLoadHostNotFound
+ // WebLoadServerUnreachable is a host that could not be reached: no route, or a connection that
+ // was refused.
+ WebLoadServerUnreachable = platform.WebLoadServerUnreachable
+ // WebLoadConnectionLost is a connection that broke while the page was arriving, or a machine
+ // with no network at all.
+ WebLoadConnectionLost = platform.WebLoadConnectionLost
+ // WebLoadBadServerResponse is an answer the engine could not read as HTTP, or one that broke its
+ // own framing.
+ WebLoadBadServerResponse = platform.WebLoadBadServerResponse
+ // WebLoadBadCertificate is a TLS certificate the engine refused, or a client certificate the
+ // server refused.
+ WebLoadBadCertificate = platform.WebLoadBadCertificate
+ // WebLoadRedirectFailed is a redirect the engine could not follow.
+ WebLoadRedirectFailed = platform.WebLoadRedirectFailed
+ // WebLoadAuthenticationRequired is a server or proxy that stopped the navigation for credentials
+ // the engine did not have.
+ WebLoadAuthenticationRequired = platform.WebLoadAuthenticationRequired
+)
+
// WebLoad is one step of a page's navigation.
type WebLoad struct {
Phase WebLoadPhase
URL string
+ // Title is the title of the document the engine holds at this step: empty before a page has
+ // one, and still the title of the document being left at WebLoadStarted.
+ Title string
+ // Code is why the navigation failed, when Phase is WebLoadFinished and the page did not load;
+ // WebLoadNoError when it did, and at every earlier step.
+ // Description is the engine's own message for it, when the engine gives one: WebView2 names a
+ // status and no text, so it is empty on Windows. An application that shows a failed load reads
+ // Description when it is not empty and Code otherwise, which names the failure as well.
+ Code WebLoadError
+ Description string
}
// WebView is one open page.
@@ -251,7 +298,10 @@ func (host *WebHost) Open(config WebViewConfig) (*WebView, error) {
}
if config.OnLoad != nil {
platformConfig.OnLoad = func(load platform.WebLoad) {
- config.OnLoad(WebLoad{Phase: WebLoadPhase(load.Phase), URL: load.URL})
+ config.OnLoad(WebLoad{
+ Phase: WebLoadPhase(load.Phase), URL: load.URL, Title: load.Title,
+ Code: WebLoadError(load.Code), Description: load.Description,
+ })
host.requestPaint()
}
}
@@ -290,6 +340,20 @@ func (view *WebView) Reload() { view.native.Reload() }
func (view *WebView) Back() { view.native.Back() }
func (view *WebView) Forward() { view.native.Forward() }
+// Title is the title of the page's current document: empty before the engine has one, and after the
+// page closes. It is what the engine reports when it is asked, which can change after WebLoad
+// reports WebLoadFinished, so a toolbar reads it on the paint it draws for.
+func (view *WebView) Title() string { return view.native.Title() }
+
+// CanGoBack and CanGoForward report whether the page's history has an entry each way, which is what
+// a Back or a Forward button is disabled by.
+func (view *WebView) CanGoBack() bool { return view.native.CanGoBack() }
+func (view *WebView) CanGoForward() bool { return view.native.CanGoForward() }
+
+// IsLoading reports whether the page is loading a navigation: true from the step the engine starts
+// one until it finishes or fails, which is when WebLoad reports WebLoadStarted and WebLoadFinished.
+func (view *WebView) IsLoading() bool { return view.native.IsLoading() }
+
// Eval runs a script in the page. The result is not read back: have the script post a message.
func (view *WebView) Eval(script string) { view.native.Eval(script) }
diff --git a/app/web_test.go b/app/web_test.go
index 57990df9a..063f0b565 100644
--- a/app/web_test.go
+++ b/app/web_test.go
@@ -234,3 +234,93 @@ func TestEphemeralReachesThePlatformAndIsOffByDefault(t *testing.T) {
t.Fatalf("the platform got %+v, want the flag as the application set it", opened)
}
}
+
+// testWebView is a page as the platform hands one over: the state the test sets is what the
+// application reads back, and nothing reaches a window.
+type testWebView struct {
+ title string
+ canGoBack bool
+ canGoForward bool
+ loading bool
+ loaded []string
+}
+
+func (view *testWebView) Load(url string) {
+ view.loaded = append(view.loaded, url)
+}
+
+func (view *testWebView) LoadHTML(html, baseURL string) {
+ view.loaded = append(view.loaded, baseURL)
+}
+
+func (view *testWebView) Reload() {}
+func (view *testWebView) Back() {}
+func (view *testWebView) Forward() {}
+func (view *testWebView) Eval(script string) {}
+func (view *testWebView) PostMessage(text string) {}
+func (view *testWebView) Focus() {}
+func (view *testWebView) Title() string { return view.title }
+func (view *testWebView) CanGoBack() bool { return view.canGoBack }
+func (view *testWebView) CanGoForward() bool { return view.canGoForward }
+func (view *testWebView) IsLoading() bool { return view.loading }
+func (view *testWebView) Close() {}
+
+func TestAPageReportsItsOwnState(t *testing.T) {
+ page := &testWebView{title: "Settings", canGoBack: true, loading: true}
+ host := &WebHost{native: &platform.WebHost{Open: func(platform.WebViewConfig) (platform.WebView, error) {
+ return page, nil
+ }}}
+ view, err := host.Open(WebViewConfig{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if view.Title() != "Settings" || !view.CanGoBack() || view.CanGoForward() || !view.IsLoading() {
+ t.Fatalf("title=%q back=%v forward=%v loading=%v, want the page's own state",
+ view.Title(), view.CanGoBack(), view.CanGoForward(), view.IsLoading())
+ }
+ // The state is read from the page each time, so what the page reports later is what the
+ // application sees.
+ page.title, page.canGoBack, page.canGoForward, page.loading = "", false, true, false
+ if view.Title() != "" || view.CanGoBack() || !view.CanGoForward() || view.IsLoading() {
+ t.Fatalf("title=%q back=%v forward=%v loading=%v, want the page's new state",
+ view.Title(), view.CanGoBack(), view.CanGoForward(), view.IsLoading())
+ }
+ view.Load("https://example.com/next")
+ if len(page.loaded) != 1 || page.loaded[0] != "https://example.com/next" {
+ t.Fatalf("the page got %q", page.loaded)
+ }
+}
+
+func TestALoadReportCarriesTheTitleAndTheFailure(t *testing.T) {
+ var report func(platform.WebLoad)
+ host := &WebHost{native: &platform.WebHost{Open: func(config platform.WebViewConfig) (platform.WebView, error) {
+ report = config.OnLoad
+ return &testWebView{}, nil
+ }}}
+ var loads []WebLoad
+ if _, err := host.Open(WebViewConfig{OnLoad: func(load WebLoad) { loads = append(loads, load) }}); err != nil {
+ t.Fatal(err)
+ }
+ if report == nil {
+ t.Fatal("the platform got no load callback")
+ }
+ report(platform.WebLoad{Phase: platform.WebLoadFinished, URL: "https://example.com/", Title: "Example Domain"})
+ if len(loads) != 1 {
+ t.Fatalf("a load that finished reported %d times", len(loads))
+ }
+ if got := loads[0]; got.Phase != WebLoadFinished || got.URL != "https://example.com/" ||
+ got.Title != "Example Domain" || got.Code != WebLoadNoError || got.Description != "" {
+ t.Fatalf("a load that finished = %+v", got)
+ }
+ report(platform.WebLoad{
+ Phase: platform.WebLoadFinished, URL: "https://example.com/missing", Title: "Error",
+ Code: platform.WebLoadHostNotFound, Description: "A server with the specified hostname could not be found.",
+ })
+ if len(loads) != 2 {
+ t.Fatalf("a load that failed reported after %d loads", len(loads))
+ }
+ if got := loads[1]; got.Title != "Error" || got.Code != WebLoadHostNotFound ||
+ got.Description != "A server with the specified hostname could not be found." {
+ t.Fatalf("a load that failed = %+v, want the title and the engine's reason", got)
+ }
+}
diff --git a/docs/web-views.md b/docs/web-views.md
index 6bfb1ba69..3b07e42a0 100644
--- a/docs/web-views.md
+++ b/docs/web-views.md
@@ -46,6 +46,16 @@ scheme, a message in each direction and a menu that stands over the page.
engine's failed load. macOS (`NSHTTPURLResponse`) and Windows (`CreateWebResourceResponse`) answer with
the full response. The feature was tested on macOS in a real WKWebView page; Linux (WebKitGTK) and Windows
(WebView2) were type-checked only, because no engine of either was available.
+- The page answers for its own state: `Title` is the engine's title for the document it has now,
+ `CanGoBack` and `CanGoForward` say whether its history has an entry each way, and `IsLoading` says
+ whether a navigation is in flight. They are read from the engine when they are asked, not cached, so
+ a toolbar that draws Back, Forward and a title follows the page by reading them on the paint it draws
+ for.
+- `OnLoad` reports each step of a navigation (`WebLoadStarted`, `WebLoadCommitted`, `WebLoadFinished`)
+ with the address as you wrote it and the title the engine has at that step. The step that ends a load
+ that failed carries `Code`, a `WebLoadError` that names the same failures on every engine, and
+ `Description`, the engine's own words for it. A navigation your `Navigate` refused is not reported:
+ that is the answer you gave, and the engine's interruption of it would be the same thing twice.
- The page and the application talk through `window.viva.postMessage(text)` / `window.viva.onmessage` and
`OnMessage` / `WebView.PostMessage`. A page sees nothing else of the application.
- `Navigate` decides a navigation before it starts, the application's own `Load` included: the
@@ -143,14 +153,22 @@ The decisions are the engine's own, and each one has a limit worth knowing:
from the navigation type: a link click and a form submission are gestures, a script's navigation is not.
A form submitted by a script therefore reads as a gesture, and a redirect keeps the gesture that started
it. Downloads need macOS 11.3 (`WKDownload`); on an older system a download response is refused rather
- than saved, and `Download` is not asked.
+ than saved, and `Download` is not asked. A failed load arrives as an `NSError`: `WebLoad.Code` is mapped
+ from its domain and code, and `WebLoad.Description` is the system's own message, which is localized.
- **Linux**: WebKitGTK's navigation action names no target frame (there is no way from the action to
the frame), so `WebNavigation.MainFrame` is always true here and a subframe cannot be told apart from
the main frame. The decision still cancels the right request. The redirect flag needs WebKitGTK 2.20;
on an older engine a redirect keeps the gesture of the request that led to it. WebKitGTK starts a
download for a response it treats as a download (an attachment, or a type it cannot show); the
- application decides it in `decide-destination`, before the body is written.
+ application decides it in `decide-destination`, before the body is written. A failed load arrives as a
+ `GError` from `load-failed`: `WebLoad.Code` is mapped from its code and `WebLoad.Description` is the
+ engine's message. A certificate the engine refuses reaches the load as a cancellation rather than
+ `WebLoadBadCertificate`, because the TLS error signal is the engine's own to answer.
- **Windows**: `DownloadStarting` needs `ICoreWebView2_4`. A runtime older than that (2021) cannot report a
download before it starts, so `Download` is not asked and the engine saves the file its own way in the
user's downloads folder; a warning through `diag` says so once, when the page opens. `NewWindow` and
- `Navigate` are on the base interface and are always available.
+ `Navigate` are on the base interface and are always available. `WebLoad.Code` is mapped from
+ `WebErrorStatus`, which carries no text: `WebLoad.Description` is empty here, so show `Code`. The base
+ interface has no property for `IsLoading`, so the page follows `NavigationStarting` and
+ `NavigationCompleted` instead: it becomes true on the turn of the window's thread that reports the
+ navigation's start, not inside the call to `Load` itself.
diff --git a/examples/guides/webview/main.go b/examples/guides/webview/main.go
index 287bb85ff..714cba375 100644
--- a/examples/guides/webview/main.go
+++ b/examples/guides/webview/main.go
@@ -52,15 +52,22 @@ func (m *model) open() {
func (m *model) page(c ui.C) {
ui.Column(c).Fill().Pad(8).Gap(8).Children(func() {
ui.Row(c).Gap(8).Items(ui.Center).Children(func() {
- if ui.Button(c, "Back").Outline().Clicked() && m.view != nil {
+ // The page answers for its own history and title, and this paint asks it: Back and
+ // Forward are greyed out where the page has nowhere to go, and the label follows it.
+ title, canGoBack, canGoForward := "", false, false
+ if m.view != nil {
+ title, canGoBack, canGoForward = m.view.Title(), m.view.CanGoBack(), m.view.CanGoForward()
+ }
+ if ui.Button(c, "Back").Outline().Disabled(!canGoBack).Clicked() && m.view != nil {
m.view.Back()
}
- if ui.Button(c, "Forward").Outline().Clicked() && m.view != nil {
+ if ui.Button(c, "Forward").Outline().Disabled(!canGoForward).Clicked() && m.view != nil {
m.view.Forward()
}
if ui.Button(c, "Reload").Outline().Clicked() && m.view != nil {
m.view.Reload()
}
+ ui.Text(c, title).Muted()
menu := ui.Button(c, "Menu").Outline()
if menu.Clicked() {
m.menuOpen = !m.menuOpen
diff --git a/internal/platform/darwin/web_darwin.go b/internal/platform/darwin/web_darwin.go
index b0c12e2a1..d51104899 100644
--- a/internal/platform/darwin/web_darwin.go
+++ b/internal/platform/darwin/web_darwin.go
@@ -49,6 +49,9 @@ type darwinWeb struct {
native unsafe.Pointer
config platform.WebViewConfig
closed bool
+ // refused is a navigation the application's Navigate cancelled. The engine may report the
+ // cancellation as the navigation's end, which the application already answered.
+ refused bool
// placed is where the page was last put, to leave AppKit alone when nothing changed.
placed platform.NativeView
cutsSet []gfx.Rect
@@ -165,6 +168,34 @@ func (page *darwinWeb) Forward() {
}
}
+// Title is the title of the page's current document, which the engine keeps for the view: empty
+// before it has one, and once the page has closed.
+func (page *darwinWeb) Title() string {
+ if !page.usable() {
+ return ""
+ }
+ text := C.viva_web_title(page.native)
+ if text == nil {
+ return ""
+ }
+ defer C.free(unsafe.Pointer(text))
+ return C.GoString(text)
+}
+
+// CanGoBack and CanGoForward ask the engine about the page's history.
+func (page *darwinWeb) CanGoBack() bool {
+ return page.usable() && C.viva_web_can_go_back(page.native) != 0
+}
+
+func (page *darwinWeb) CanGoForward() bool {
+ return page.usable() && C.viva_web_can_go_forward(page.native) != 0
+}
+
+// IsLoading is the engine's own answer for the load it is in the middle of.
+func (page *darwinWeb) IsLoading() bool {
+ return page.usable() && C.viva_web_is_loading(page.native) != 0
+}
+
func (page *darwinWeb) Eval(script string) {
if page.usable() {
text := C.CString(script)
@@ -283,13 +314,36 @@ func vivaWebMessage(handle C.uintptr_t, id C.uint32_t, utf8 *C.char) {
}
}
+// vivaWebLoad reports one step of a navigation: its address, and for a navigation the engine could
+// not load, the domain, code and words of its error. domain is NULL for a navigation that loaded.
+//
//export vivaWebLoad
-func vivaWebLoad(handle C.uintptr_t, id C.uint32_t, phase C.int, url *C.char) {
+func vivaWebLoad(handle C.uintptr_t, id C.uint32_t, phase C.int, url, domain *C.char, code C.int, description *C.char) {
page := pageOf(handle, id)
- if page == nil || page.config.OnLoad == nil {
+ if page == nil {
return
}
- page.config.OnLoad(platform.WebLoad{Phase: platform.WebLoadPhase(phase), URL: C.GoString(url)})
+ loadPhase := platform.WebLoadPhase(phase)
+ // A navigation the application refused is not reported: what the engine says about it is the
+ // answer the application gave.
+ if loadPhase == platform.WebLoadFinished && page.refused {
+ page.refused = false
+ return
+ }
+ if loadPhase == platform.WebLoadStarted {
+ page.refused = false
+ }
+ if page.config.OnLoad == nil {
+ return
+ }
+ failure := platform.WebLoadNoError
+ if domain != nil {
+ failure = platform.WebLoadErrorFromDarwinError(C.GoString(domain), int(code))
+ }
+ page.config.OnLoad(platform.WebLoad{
+ Phase: loadPhase, URL: C.GoString(url), Title: page.Title(),
+ Code: failure, Description: C.GoString(description),
+ })
}
// vivaWebNavigate asks the application about a navigation before WebKit makes it. It answers 1 to
@@ -306,10 +360,20 @@ func vivaWebNavigate(handle C.uintptr_t, id C.uint32_t, url *C.char, mainFrame,
MainFrame: mainFrame != 0,
UserGesture: userGesture != 0,
}
- if !page.config.Navigate(navigation) {
- return 0
+ if page.config.Navigate(navigation) {
+ if mainFrame != 0 {
+ page.refused = false
+ }
+ return 1
}
- return 1
+ // A refused navigation that was already loading is interrupted by the engine, which reports
+ // the interruption as a failed load: the application answered it, so it is not reported.
+ // Only a main-frame refusal can end the reported load; a refused subframe leaves the main
+ // frame's load to finish and be reported as usual.
+ if mainFrame != 0 {
+ page.refused = true
+ }
+ return 0
}
// vivaWebNewWindow asks the application about a window.open or target=_blank. It answers 1 when the
diff --git a/internal/platform/darwin/web_darwin.h b/internal/platform/darwin/web_darwin.h
index 129d8db0c..ec37b2d64 100644
--- a/internal/platform/darwin/web_darwin.h
+++ b/internal/platform/darwin/web_darwin.h
@@ -23,6 +23,13 @@ void viva_web_back(void *web);
void viva_web_forward(void *web);
void viva_web_eval(void *web, const char *script);
void viva_web_focus(void *web);
+// viva_web_title is the title of the page's current document, as a malloc'd UTF-8 string which the
+// caller frees, and an empty string when it has none. viva_web_can_go_back,
+// viva_web_can_go_forward and viva_web_is_loading answer the page's history and its loading, 1 or 0.
+char *viva_web_title(void *web);
+int viva_web_can_go_back(void *web);
+int viva_web_can_go_forward(void *web);
+int viva_web_is_loading(void *web);
void viva_web_set_top_corner_radius(void *web, double radius);
// viva_web_close closes the page. Its unanswered scheme requests are let go too.
void viva_web_close(void *web);
diff --git a/internal/platform/darwin/web_darwin.m b/internal/platform/darwin/web_darwin.m
index f95366a55..e31e7e9c6 100644
--- a/internal/platform/darwin/web_darwin.m
+++ b/internal/platform/darwin/web_darwin.m
@@ -11,7 +11,7 @@
// What the page does reaches Go through these (web_darwin.go).
extern void vivaWebMessage(uintptr_t handle, uint32_t id, char *utf8);
-extern void vivaWebLoad(uintptr_t handle, uint32_t id, int phase, char *url);
+extern void vivaWebLoad(uintptr_t handle, uint32_t id, int phase, char *url, char *domain, int code, char *description);
extern int vivaWebNavigate(uintptr_t handle, uint32_t id, char *url, int mainFrame, int userGesture);
extern int vivaWebNewWindow(uintptr_t handle, uint32_t id, char *url);
extern int vivaWebDownload(uintptr_t handle, uint32_t id, char *url);
@@ -80,7 +80,18 @@ - (void)userContentController:(WKUserContentController *)controller didReceiveSc
- (void)notify:(WKWebView *)web phase:(int)phase {
NSString *address = web.URL.absoluteString;
- vivaWebLoad(_handle, _id, phase, (char *)(address != nil ? address.UTF8String : ""));
+ vivaWebLoad(_handle, _id, phase, (char *)(address != nil ? address.UTF8String : ""), NULL, 0, NULL);
+}
+
+// reportFailure reports a navigation the engine could not load, with the reason it gave: the domain
+// and code of its error, and the engine's own words for it.
+- (void)reportFailure:(WKWebView *)web error:(NSError *)error {
+ NSString *address = web.URL.absoluteString;
+ vivaWebLoad(_handle, _id, 2,
+ (char *)(address != nil ? address.UTF8String : ""),
+ (char *)(error.domain != nil ? error.domain.UTF8String : ""),
+ (int)error.code,
+ (char *)(error.localizedDescription != nil ? error.localizedDescription.UTF8String : ""));
}
// The application answers before the request leaves the engine: a refused navigation fetches
@@ -211,14 +222,12 @@ - (void)webView:(WKWebView *)web didFinishNavigation:(WKNavigation *)navigation
- (void)webView:(WKWebView *)web didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
(void)navigation;
- (void)error;
- [self notify:web phase:2];
+ [self reportFailure:web error:error];
}
- (void)webView:(WKWebView *)web didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
(void)navigation;
- (void)error;
- [self notify:web phase:2];
+ [self reportFailure:web error:error];
}
// finishTask answers task and lets it go. headers is the header block Go resolved: one "Name: value"
@@ -655,6 +664,34 @@ void viva_web_focus(void *web) {
});
}
+char *viva_web_title(void *web) {
+ __block char *title = NULL;
+ viva_web_main(^{
+ NSString *text = [(VivaWebView *)web title];
+ const char *utf8 = text != nil ? text.UTF8String : "";
+ title = strdup(utf8 != NULL ? utf8 : "");
+ });
+ return title;
+}
+
+int viva_web_can_go_back(void *web) {
+ __block int can = 0;
+ viva_web_main(^{ can = [(VivaWebView *)web canGoBack] ? 1 : 0; });
+ return can;
+}
+
+int viva_web_can_go_forward(void *web) {
+ __block int can = 0;
+ viva_web_main(^{ can = [(VivaWebView *)web canGoForward] ? 1 : 0; });
+ return can;
+}
+
+int viva_web_is_loading(void *web) {
+ __block int loading = 0;
+ viva_web_main(^{ loading = [(VivaWebView *)web isLoading] ? 1 : 0; });
+ return loading;
+}
+
void viva_web_close(void *web) {
viva_web_main(^{
VivaWebView *view = (VivaWebView *)web;
diff --git a/internal/platform/linux/gtk_app_linux.go b/internal/platform/linux/gtk_app_linux.go
index 80bdc4572..be5d04f51 100644
--- a/internal/platform/linux/gtk_app_linux.go
+++ b/internal/platform/linux/gtk_app_linux.go
@@ -318,7 +318,7 @@ func typeNameOf(g *gtkLibrary, object uintptr) string {
// frees a callback and allows a fixed number, so a window must not make its own. The window a call
// is for travels in the data pointer, as its id.
type gtkCallbacks struct {
- task, descriptor, settings, dragMotion, dragLeave, dragDrop, dragData, event, capturePress, draw, allocate, destroy, deleteEvent, mapped, unmapped, commit, preeditStart, preedit, preeditEnd, surrounding, deleteSurrounding, retireIME, releaseIME, redraw, webMessage, webLoad, webScheme, webDecide, webCreate, webDownload, webDestination uintptr
+ task, descriptor, settings, dragMotion, dragLeave, dragDrop, dragData, event, capturePress, draw, allocate, destroy, deleteEvent, mapped, unmapped, commit, preeditStart, preedit, preeditEnd, surrounding, deleteSurrounding, retireIME, releaseIME, redraw, webMessage, webLoad, webFailed, webScheme, webDecide, webCreate, webDownload, webDestination uintptr
}
var (
@@ -452,6 +452,14 @@ func callbacks() *gtkCallbacks {
}
return 0
}),
+ // gboolean load-failed(view, WebKitLoadEvent, failing URI, GError, handle). The engine
+ // shows its own error page, so the signal is left unhandled after it is read.
+ webFailed: purego.NewCallback(func(view, event, uri, failure, handle uintptr) uintptr {
+ if v := webViews[handle]; v != nil {
+ v.loadFailed(uri, failure)
+ }
+ return 0
+ }),
// void (*WebKitURISchemeRequestCallback)(request, user_data).
webScheme: purego.NewCallback(func(request, data uintptr) uintptr {
if a := gtkRunning.Load(); a != nil {
diff --git a/internal/platform/linux/gtk_web_linux.go b/internal/platform/linux/gtk_web_linux.go
index ef395e912..b9f494b7f 100644
--- a/internal/platform/linux/gtk_web_linux.go
+++ b/internal/platform/linux/gtk_web_linux.go
@@ -34,6 +34,12 @@ type webKit struct {
reload func(view uintptr)
goBack, goForward func(view uintptr)
getURI func(view uintptr) uintptr
+ // The page's own state: its document's title, and whether its history and its loading are
+ // where they are.
+ getTitle func(view uintptr) uintptr
+ canGoBack func(view uintptr) int32
+ canGoForward func(view uintptr) int32
+ isLoading func(view uintptr) int32
getContext func(view uintptr) uintptr
setZoom func(view uintptr, level float64)
registerScheme func(context uintptr, scheme *byte, callback, data, destroy uintptr)
@@ -142,7 +148,10 @@ func loadWebKit(g *gtkLibrary) (*webKit, error) {
{&k.managerAddScript, "webkit_user_content_manager_add_script"}, {&k.scriptNew, "webkit_user_script_new"},
{&k.viewNew, "webkit_web_view_new_with_user_content_manager"}, {&k.loadURI, "webkit_web_view_load_uri"},
{&k.loadHTML, "webkit_web_view_load_html"}, {&k.reload, "webkit_web_view_reload"}, {&k.goBack, "webkit_web_view_go_back"},
- {&k.goForward, "webkit_web_view_go_forward"}, {&k.getURI, "webkit_web_view_get_uri"}, {&k.getContext, "webkit_web_view_get_context"}, {&k.setZoom, "webkit_web_view_set_zoom_level"},
+ {&k.goForward, "webkit_web_view_go_forward"}, {&k.getURI, "webkit_web_view_get_uri"},
+ {&k.getTitle, "webkit_web_view_get_title"}, {&k.canGoBack, "webkit_web_view_can_go_back"},
+ {&k.canGoForward, "webkit_web_view_can_go_forward"}, {&k.isLoading, "webkit_web_view_is_loading"},
+ {&k.getContext, "webkit_web_view_get_context"}, {&k.setZoom, "webkit_web_view_set_zoom_level"},
{&k.registerScheme, "webkit_web_context_register_uri_scheme"}, {&k.schemeURI, "webkit_uri_scheme_request_get_uri"},
{&k.schemeFinish, "webkit_uri_scheme_request_finish"}, {&k.schemeFinishError, "webkit_uri_scheme_request_finish_error"},
{&k.jscString, "jsc_value_to_string"},
@@ -252,6 +261,13 @@ type gtkWebView struct {
// at is where the widget is, in widget units; zoom is the page's zoom.
at viewPlace
zoom float64
+ // failed is a navigation the load-failed signal already reported: the load-changed that follows
+ // it ends the same load, and must not be reported twice. refused is the address of a navigation
+ // the application's Navigate cancelled, whose interruption the application already answered. It
+ // is an address rather than a flag because the engine reports navigation actions for subframes
+ // too: only the interruption of that same request is the answer the application gave.
+ failed bool
+ refused string
}
// viewPlace is a rectangle in the overlay's units.
@@ -427,6 +443,7 @@ func (w *gtkWindow) openWebView(c platform.WebViewConfig) (platform.WebView, err
g.widgetSetVAlign(v.widget, 1)
g.overlayAdd(w.overlay, v.widget)
g.connect(v.widget, "load-changed", cb.webLoad, v.handle)
+ g.connect(v.widget, "load-failed", cb.webFailed, v.handle)
g.connect(v.widget, "focus-in-event", cb.event, w.id)
g.connect(v.widget, "focus-out-event", cb.event, w.id)
g.connect(v.widget, "decide-policy", cb.webDecide, v.handle)
@@ -523,6 +540,29 @@ func (v *gtkWebView) Forward() {
}
}
+// Title is the title of the page's current document, which the engine keeps for the widget: empty
+// before it has one, and once the page has closed.
+func (v *gtkWebView) Title() string {
+ if v.closed {
+ return ""
+ }
+ return goString(v.k.getTitle(v.widget))
+}
+
+// CanGoBack and CanGoForward ask the engine about the page's history.
+func (v *gtkWebView) CanGoBack() bool {
+ return !v.closed && v.k.canGoBack(v.widget) != 0
+}
+
+func (v *gtkWebView) CanGoForward() bool {
+ return !v.closed && v.k.canGoForward(v.widget) != 0
+}
+
+// IsLoading is the engine's own answer for the load it is in the middle of.
+func (v *gtkWebView) IsLoading() bool {
+ return !v.closed && v.k.isLoading(v.widget) != 0
+}
+
func (v *gtkWebView) Eval(script string) {
if v.closed {
return
@@ -630,20 +670,67 @@ func (v *gtkWebView) message(result uintptr) {
v.config.OnMessage(goString(text))
}
+// report tells the application one step of a navigation, with the title the page has at that step
+// and, when the step ends a load that failed, why it failed.
+func (v *gtkWebView) report(phase platform.WebLoadPhase, address string, code platform.WebLoadError, description string) {
+ if v.closed || v.config.OnLoad == nil {
+ return
+ }
+ v.config.OnLoad(platform.WebLoad{
+ Phase: phase, URL: address, Title: v.Title(), Code: code, Description: description,
+ })
+}
+
// loadChanged follows the page's navigation.
func (v *gtkWebView) loadChanged(event int32) {
- if v.closed || v.config.OnLoad == nil {
+ if v.closed {
return
}
address := goString(v.k.getURI(v.widget))
switch event {
case webLoadStarted:
- v.config.OnLoad(platform.WebLoad{Phase: platform.WebLoadStarted, URL: address})
+ v.failed, v.refused = false, ""
+ v.report(platform.WebLoadStarted, address, platform.WebLoadNoError, "")
case webLoadCommitted:
- v.config.OnLoad(platform.WebLoad{Phase: platform.WebLoadCommitted, URL: address})
+ v.report(platform.WebLoadCommitted, address, platform.WebLoadNoError, "")
case webLoadFinished:
- v.config.OnLoad(platform.WebLoad{Phase: platform.WebLoadFinished, URL: address})
+ // A load-failed already reported this load's end, and the interruption of a navigation the
+ // application refused is the answer the application gave.
+ failed, refused := v.failed, v.refused
+ v.failed, v.refused = false, ""
+ if failed || (refused != "" && refused == address) {
+ return
+ }
+ v.report(platform.WebLoadFinished, address, platform.WebLoadNoError, "")
+ }
+}
+
+// gerror is the part of a GError this package reads: the code names the failure and the message is
+// the engine's own words for it.
+type gerror struct {
+ domain uint32
+ code int32
+ message uintptr
+}
+
+// loadFailed reports a navigation the engine could not load, with the reason it gave. The load ends
+// here: the load-changed that follows it ends the same load, and is not reported again.
+func (v *gtkWebView) loadFailed(uri, failure uintptr) {
+ if v.closed {
+ return
+ }
+ failedAddress := goString(uri)
+ if v.refused != "" && v.refused == failedAddress {
+ v.refused = ""
+ return
+ }
+ v.failed = true
+ code, description := platform.WebLoadUnknownError, ""
+ if failure != 0 {
+ err := (*gerror)(unsafePointer(failure))
+ code, description = platform.WebLoadErrorFromWebKitError(err.code), goString(err.message)
}
+ v.report(platform.WebLoadFinished, goString(uri), code, description)
}
// navigationAllowed asks the application whether the view may make a navigation. An application
@@ -682,6 +769,9 @@ func (v *gtkWebView) decidePolicy(decision uintptr, kind int32) uintptr {
if v.navigationAllowed(address, true, gesture) {
k.decisionUse(decision)
} else {
+ // A refused navigation that was already loading is interrupted by the engine, which reports
+ // the interruption as a failed load: the application answered it, so it is not reported.
+ v.refused = address
k.decisionIgnore(decision)
}
return 1
diff --git a/internal/platform/web_host.go b/internal/platform/web_host.go
index 938565277..ba4ce231c 100644
--- a/internal/platform/web_host.go
+++ b/internal/platform/web_host.go
@@ -148,6 +148,15 @@ const (
type WebLoad struct {
Phase WebLoadPhase
URL string
+ // Title is the title of the document the engine holds at this step: empty before a page has
+ // one, and still the title of the document being left at Started.
+ Title string
+ // Code is why a navigation failed, when Phase is WebLoadFinished and the page did not load;
+ // WebLoadNoError when it did, and at every earlier step.
+ // Description is the engine's own message for it, when the engine gives one: WebView2 names
+ // a status and no text, so it is empty on Windows.
+ Code WebLoadError
+ Description string
}
// WebView is one open page.
@@ -163,5 +172,15 @@ type WebView interface {
PostMessage(text string)
// Focus gives the page the keyboard.
Focus()
+ // Title is the title of the page's current document: empty before the engine has one, and
+ // after the page closes.
+ Title() string
+ // CanGoBack and CanGoForward report whether the page's history has an entry each way.
+ CanGoBack() bool
+ CanGoForward() bool
+ // IsLoading reports whether the page is loading a navigation: from the engine's start of one
+ // until it finishes or fails. WebView2 has no property for it, so Windows follows the
+ // navigation's events.
+ IsLoading() bool
Close()
}
diff --git a/internal/platform/web_load_error.go b/internal/platform/web_load_error.go
new file mode 100644
index 000000000..65fb63d3a
--- /dev/null
+++ b/internal/platform/web_load_error.go
@@ -0,0 +1,220 @@
+package platform
+
+import "strconv"
+
+// WebLoadError is why a navigation did not load the page, in terms each engine can be held to: the
+// engines name the same failures differently, and a page that fails to load is worth reporting the
+// same way on every platform. Zero is a navigation that loaded.
+type WebLoadError uint8
+
+const (
+ // WebLoadNoError is a navigation that loaded.
+ WebLoadNoError WebLoadError = iota
+ // WebLoadUnknownError is a navigation the engine reports as failed without a reason this
+ // package classifies; Description carries whatever the engine said about it.
+ WebLoadUnknownError
+ // WebLoadCancelled is a navigation that was stopped: by the engine, or by a policy that
+ // interrupted the load it was part of.
+ WebLoadCancelled
+ // WebLoadTimeout is a server that did not answer in time.
+ WebLoadTimeout
+ // WebLoadHostNotFound is a name that did not resolve.
+ WebLoadHostNotFound
+ // WebLoadServerUnreachable is a host that could not be reached: no route, or a connection that
+ // was refused.
+ WebLoadServerUnreachable
+ // WebLoadConnectionLost is a connection that broke while the page was arriving, or a machine
+ // with no network at all.
+ WebLoadConnectionLost
+ // WebLoadBadServerResponse is an answer the engine could not read as HTTP, or one that broke its
+ // own framing.
+ WebLoadBadServerResponse
+ // WebLoadBadCertificate is a TLS certificate the engine refused, or a client certificate the
+ // server refused.
+ WebLoadBadCertificate
+ // WebLoadRedirectFailed is a redirect the engine could not follow.
+ WebLoadRedirectFailed
+ // WebLoadAuthenticationRequired is a server or proxy that stopped the navigation for credentials
+ // the engine did not have.
+ WebLoadAuthenticationRequired
+)
+
+// String names the failure, for a status line or a log.
+func (e WebLoadError) String() string {
+ switch e {
+ case WebLoadNoError:
+ return "no error"
+ case WebLoadUnknownError:
+ return "unknown error"
+ case WebLoadCancelled:
+ return "cancelled"
+ case WebLoadTimeout:
+ return "timed out"
+ case WebLoadHostNotFound:
+ return "host name not found"
+ case WebLoadServerUnreachable:
+ return "server unreachable"
+ case WebLoadConnectionLost:
+ return "connection lost"
+ case WebLoadBadServerResponse:
+ return "bad server response"
+ case WebLoadBadCertificate:
+ return "certificate refused"
+ case WebLoadRedirectFailed:
+ return "redirect failed"
+ case WebLoadAuthenticationRequired:
+ return "authentication required"
+ }
+ return "web load error " + strconv.FormatUint(uint64(e), 10)
+}
+
+// COREWEBVIEW2_WEB_ERROR_STATUS values, which ICoreWebView2NavigationCompletedEventArgs.get_
+// WebErrorStatus reports for a navigation that did not load.
+const (
+ webView2StatusCertificateCommonNameIncorrect = 1
+ webView2StatusCertificateExpired = 2
+ webView2StatusClientCertificateContainsErrors = 3
+ webView2StatusCertificateRevoked = 4
+ webView2StatusCertificateIsInvalid = 5
+ webView2StatusServerUnreachable = 6
+ webView2StatusTimeout = 7
+ webView2StatusErrorHTTPInvalidServerResponse = 8
+ webView2StatusConnectionAborted = 9
+ webView2StatusConnectionReset = 10
+ webView2StatusDisconnected = 11
+ webView2StatusCannotConnect = 12
+ webView2StatusHostNameNotResolved = 13
+ webView2StatusOperationCanceled = 14
+ webView2StatusRedirectFailed = 15
+ webView2StatusAuthenticationRequired = 17
+ webView2StatusProxyAuthenticationRequired = 18
+)
+
+// WebLoadErrorFromWebView2Status maps the status of a completed WebView2 navigation.
+func WebLoadErrorFromWebView2Status(status int32) WebLoadError {
+ switch status {
+ case webView2StatusCertificateCommonNameIncorrect, webView2StatusCertificateExpired,
+ webView2StatusClientCertificateContainsErrors, webView2StatusCertificateRevoked,
+ webView2StatusCertificateIsInvalid:
+ return WebLoadBadCertificate
+ case webView2StatusServerUnreachable, webView2StatusCannotConnect:
+ return WebLoadServerUnreachable
+ case webView2StatusTimeout:
+ return WebLoadTimeout
+ case webView2StatusErrorHTTPInvalidServerResponse:
+ return WebLoadBadServerResponse
+ case webView2StatusConnectionAborted, webView2StatusConnectionReset, webView2StatusDisconnected:
+ return WebLoadConnectionLost
+ case webView2StatusHostNameNotResolved:
+ return WebLoadHostNotFound
+ case webView2StatusOperationCanceled:
+ return WebLoadCancelled
+ case webView2StatusRedirectFailed:
+ return WebLoadRedirectFailed
+ case webView2StatusAuthenticationRequired, webView2StatusProxyAuthenticationRequired:
+ return WebLoadAuthenticationRequired
+ }
+ // Unknown (0) and UnexpectedError (16) are the statuses the runtime reaches for a failure it has
+ // no name for, so they are the same thing here; a status this package does not know is new to the
+ // runtime, and is reported as such rather than guessed at.
+ return WebLoadUnknownError
+}
+
+// The NSError codes a WKWebView reports for a navigation it could not load, in NSURLErrorDomain and
+// in WebKitErrorDomain (the engine's own errors). Only the ones that name a kind of failure above are
+// here: the rest are addresses the engine will not load at all, which stay WebLoadUnknownError.
+const (
+ nsURLErrorCancelled = -999
+ nsURLErrorTimedOut = -1001
+ nsURLErrorCannotFindHost = -1003
+ nsURLErrorCannotConnectToHost = -1004
+ nsURLErrorNetworkConnectionLost = -1005
+ nsURLErrorDNSLookupFailed = -1006
+ nsURLErrorHTTPTooManyRedirects = -1007
+ nsURLErrorNotConnectedToInternet = -1009
+ nsURLErrorRedirectToNonExistentLocation = -1010
+ nsURLErrorBadServerResponse = -1011
+ nsURLErrorUserCancelledAuthentication = -1012
+ nsURLErrorUserAuthenticationRequired = -1013
+ nsURLErrorZeroByteResource = -1014
+ nsURLErrorCannotDecodeRawData = -1015
+ nsURLErrorCannotDecodeContentData = -1016
+ nsURLErrorCannotParseResponse = -1017
+ nsURLErrorInternationalRoamingOff = -1018
+ nsURLErrorCallIsActive = -1019
+ nsURLErrorDataNotAllowed = -1020
+ nsURLErrorSecureConnectionFailed = -1200
+ nsURLErrorServerCertificateHasBadDate = -1201
+ nsURLErrorServerCertificateUntrusted = -1202
+ nsURLErrorServerCertificateHasUnknownRoot = -1203
+ nsURLErrorServerCertificateNotYetValid = -1204
+ nsURLErrorClientCertificateRejected = -1205
+ nsURLErrorClientCertificateRequired = -1206
+
+ webKitErrorFrameLoadInterruptedByPolicyChange = 102
+)
+
+// WebLoadErrorFromDarwinError maps the NSError a WKWebView reports for a navigation it could not
+// load: domain is NSError.domain ("NSURLErrorDomain" for failures of the URL loading system, and
+// "WebKitErrorDomain" for the engine's own), and code is NSError.code.
+func WebLoadErrorFromDarwinError(domain string, code int) WebLoadError {
+ switch domain {
+ case "NSURLErrorDomain":
+ switch code {
+ case nsURLErrorCancelled, nsURLErrorUserCancelledAuthentication:
+ return WebLoadCancelled
+ case nsURLErrorTimedOut:
+ return WebLoadTimeout
+ case nsURLErrorCannotFindHost, nsURLErrorDNSLookupFailed:
+ return WebLoadHostNotFound
+ case nsURLErrorCannotConnectToHost:
+ return WebLoadServerUnreachable
+ case nsURLErrorNetworkConnectionLost, nsURLErrorNotConnectedToInternet,
+ nsURLErrorInternationalRoamingOff, nsURLErrorCallIsActive, nsURLErrorDataNotAllowed:
+ return WebLoadConnectionLost
+ case nsURLErrorHTTPTooManyRedirects, nsURLErrorRedirectToNonExistentLocation:
+ return WebLoadRedirectFailed
+ case nsURLErrorBadServerResponse, nsURLErrorZeroByteResource, nsURLErrorCannotDecodeRawData,
+ nsURLErrorCannotDecodeContentData, nsURLErrorCannotParseResponse:
+ return WebLoadBadServerResponse
+ case nsURLErrorUserAuthenticationRequired, nsURLErrorClientCertificateRequired:
+ return WebLoadAuthenticationRequired
+ case nsURLErrorSecureConnectionFailed, nsURLErrorServerCertificateHasBadDate,
+ nsURLErrorServerCertificateUntrusted, nsURLErrorServerCertificateHasUnknownRoot,
+ nsURLErrorServerCertificateNotYetValid, nsURLErrorClientCertificateRejected:
+ return WebLoadBadCertificate
+ }
+ case "WebKitErrorDomain":
+ if code == webKitErrorFrameLoadInterruptedByPolicyChange {
+ return WebLoadCancelled
+ }
+ }
+ return WebLoadUnknownError
+}
+
+// The WebKitGTK error codes a load-failed signal carries: WebKitNetworkError counts from 1,
+// WebKitPolicyError from 100, WebKitPluginError from 200 (WebKitError.h). Downloads, which start at
+// 300, are not a load.
+const (
+ webKitNetworkErrorTransport = 2
+ webKitNetworkErrorCancelled = 4
+
+ webKitPolicyErrorFrameLoadInterruptedByPolicyChange = 102
+ webKitPluginErrorConnectionCancelled = 203
+)
+
+// WebLoadErrorFromWebKitError maps the code of the GError a WebKitGTK load-failed signal carries.
+func WebLoadErrorFromWebKitError(code int32) WebLoadError {
+ switch code {
+ case webKitNetworkErrorTransport:
+ return WebLoadConnectionLost
+ case webKitNetworkErrorCancelled, webKitPolicyErrorFrameLoadInterruptedByPolicyChange,
+ webKitPluginErrorConnectionCancelled:
+ return WebLoadCancelled
+ }
+ // Network failures WebKitGTK has no name for, files that are not there, and the policy and
+ // plugin errors: the engine's message says which it was. A certificate it refuses reaches the
+ // load as a cancellation, because the TLS error signal is WebKitGTK's alone to answer and this
+ // package leaves it to the engine.
+ return WebLoadUnknownError
+}
diff --git a/internal/platform/web_load_error_test.go b/internal/platform/web_load_error_test.go
new file mode 100644
index 000000000..3023ce35d
--- /dev/null
+++ b/internal/platform/web_load_error_test.go
@@ -0,0 +1,131 @@
+package platform
+
+import "testing"
+
+func TestEachWebView2StatusNamesItsFailure(t *testing.T) {
+ for _, c := range []struct {
+ status int32
+ want WebLoadError
+ }{
+ {0, WebLoadUnknownError}, // UNKNOWN
+ {1, WebLoadBadCertificate}, // CERTIFICATE_COMMON_NAME_INCORRECT
+ {2, WebLoadBadCertificate}, // CERTIFICATE_EXPIRED
+ {3, WebLoadBadCertificate}, // CLIENT_CERTIFICATE_CONTAINS_ERRORS
+ {4, WebLoadBadCertificate}, // CERTIFICATE_REVOKED
+ {5, WebLoadBadCertificate}, // CERTIFICATE_IS_INVALID
+ {6, WebLoadServerUnreachable}, // SERVER_UNREACHABLE
+ {7, WebLoadTimeout}, // TIMEOUT
+ {8, WebLoadBadServerResponse}, // ERROR_HTTP_INVALID_SERVER_RESPONSE
+ {9, WebLoadConnectionLost}, // CONNECTION_ABORTED
+ {10, WebLoadConnectionLost}, // CONNECTION_RESET
+ {11, WebLoadConnectionLost}, // DISCONNECTED
+ {12, WebLoadServerUnreachable}, // CANNOT_CONNECT
+ {13, WebLoadHostNotFound}, // HOST_NAME_NOT_RESOLVED
+ {14, WebLoadCancelled}, // OPERATION_CANCELED
+ {15, WebLoadRedirectFailed}, // REDIRECT_FAILED
+ {16, WebLoadUnknownError}, // UNEXPECTED_ERROR
+ {17, WebLoadAuthenticationRequired}, // VALID_AUTHENTICATION_CREDENTIALS_REQUIRED
+ {18, WebLoadAuthenticationRequired}, // VALID_PROXY_AUTHENTICATION_REQUIRED
+ {19, WebLoadUnknownError}, // a status newer than this package
+ {-1, WebLoadUnknownError}, // never reported, but not a crash
+ } {
+ if got := WebLoadErrorFromWebView2Status(c.status); got != c.want {
+ t.Errorf("status %d = %v, want %v", c.status, got, c.want)
+ }
+ }
+}
+
+func TestEachDarwinErrorNamesItsFailure(t *testing.T) {
+ for _, c := range []struct {
+ domain string
+ code int
+ want WebLoadError
+ }{
+ {"NSURLErrorDomain", -999, WebLoadCancelled},
+ {"NSURLErrorDomain", -1001, WebLoadTimeout},
+ {"NSURLErrorDomain", -1003, WebLoadHostNotFound},
+ {"NSURLErrorDomain", -1006, WebLoadHostNotFound},
+ {"NSURLErrorDomain", -1004, WebLoadServerUnreachable},
+ {"NSURLErrorDomain", -1005, WebLoadConnectionLost},
+ {"NSURLErrorDomain", -1009, WebLoadConnectionLost},
+ {"NSURLErrorDomain", -1020, WebLoadConnectionLost},
+ {"NSURLErrorDomain", -1007, WebLoadRedirectFailed},
+ {"NSURLErrorDomain", -1010, WebLoadRedirectFailed},
+ {"NSURLErrorDomain", -1011, WebLoadBadServerResponse},
+ {"NSURLErrorDomain", -1017, WebLoadBadServerResponse},
+ {"NSURLErrorDomain", -1013, WebLoadAuthenticationRequired},
+ {"NSURLErrorDomain", -1206, WebLoadAuthenticationRequired},
+ {"NSURLErrorDomain", -1200, WebLoadBadCertificate},
+ {"NSURLErrorDomain", -1202, WebLoadBadCertificate},
+ {"NSURLErrorDomain", -1205, WebLoadBadCertificate},
+ {"NSURLErrorDomain", -1000, WebLoadUnknownError}, // a bad URL: the engine's message tells it apart
+ {"NSURLErrorDomain", -1100, WebLoadUnknownError}, // a file that is not there
+ {"WebKitErrorDomain", 102, WebLoadCancelled}, // the load was interrupted by a policy change
+ {"WebKitErrorDomain", 101, WebLoadUnknownError},
+ {"WebKitErrorDomain", -1001, WebLoadUnknownError}, // the domain decides, not the number
+ {"NSCocoaErrorDomain", 260, WebLoadUnknownError},
+ {"", 0, WebLoadUnknownError},
+ } {
+ if got := WebLoadErrorFromDarwinError(c.domain, c.code); got != c.want {
+ t.Errorf("%s %d = %v, want %v", c.domain, c.code, got, c.want)
+ }
+ }
+}
+
+func TestEachWebKitErrorNamesItsFailure(t *testing.T) {
+ for _, c := range []struct {
+ code int32
+ want WebLoadError
+ }{
+ {0, WebLoadUnknownError},
+ {1, WebLoadUnknownError}, // NETWORK_ERROR_FAILED
+ {2, WebLoadConnectionLost},
+ {3, WebLoadUnknownError}, // UNKNOWN_PROTOCOL
+ {4, WebLoadCancelled},
+ {5, WebLoadUnknownError}, // FILE_DOES_NOT_EXIST
+ {100, WebLoadUnknownError}, // POLICY_ERROR_CANNOT_SHOW_MIME_TYPE
+ {101, WebLoadUnknownError}, // POLICY_ERROR_CANNOT_SHOW_URI
+ {102, WebLoadCancelled}, // POLICY_ERROR_FRAME_LOAD_INTERRUPTED_BY_POLICY_CHANGE
+ {199, WebLoadUnknownError}, // POLICY_ERROR_FAILED
+ {200, WebLoadUnknownError}, // PLUGIN_ERROR_CANNOT_FIND_PLUGIN
+ {203, WebLoadCancelled}, // PLUGIN_ERROR_CONNECTION_CANCELLED
+ {299, WebLoadUnknownError}, // PLUGIN_ERROR_FAILED
+ {300, WebLoadUnknownError}, // a download's error, not a load's
+ {-1, WebLoadUnknownError},
+ } {
+ if got := WebLoadErrorFromWebKitError(c.code); got != c.want {
+ t.Errorf("code %d = %v, want %v", c.code, got, c.want)
+ }
+ }
+}
+
+func TestEachLoadErrorNamesItself(t *testing.T) {
+ for _, c := range []struct {
+ code WebLoadError
+ want string
+ }{
+ {WebLoadNoError, "no error"},
+ {WebLoadUnknownError, "unknown error"},
+ {WebLoadCancelled, "cancelled"},
+ {WebLoadTimeout, "timed out"},
+ {WebLoadHostNotFound, "host name not found"},
+ {WebLoadServerUnreachable, "server unreachable"},
+ {WebLoadConnectionLost, "connection lost"},
+ {WebLoadBadServerResponse, "bad server response"},
+ {WebLoadBadCertificate, "certificate refused"},
+ {WebLoadRedirectFailed, "redirect failed"},
+ {WebLoadAuthenticationRequired, "authentication required"},
+ {WebLoadError(200), "web load error 200"},
+ } {
+ if got := c.code.String(); got != c.want {
+ t.Errorf("%d = %q, want %q", c.code, got, c.want)
+ }
+ }
+}
+
+func TestALoadedNavigationCarriesNoError(t *testing.T) {
+ var load WebLoad
+ if load.Phase != WebLoadStarted || load.Code != WebLoadNoError || load.Title != "" || load.Description != "" || load.URL != "" {
+ t.Fatalf("a zero WebLoad = %+v, want no navigation and no error", load)
+ }
+}
diff --git a/internal/platform/windows/web_windows.go b/internal/platform/windows/web_windows.go
index 4f0f20ae1..c357a81cf 100644
--- a/internal/platform/windows/web_windows.go
+++ b/internal/platform/windows/web_windows.go
@@ -114,6 +114,12 @@ type windowsWeb struct {
// the page to the application already, which then hears of a failure only from the report.
failure error
returned bool
+ // loading is a navigation the page is in the middle of. WebView2 has no property for it, so it
+ // follows the events: a main frame navigation that started, until its NavigationCompleted.
+ loading bool
+ // refused is a main frame navigation the application's Navigate cancelled. The runtime reports
+ // the cancellation as the navigation's end, which the application already answered.
+ refused bool
}
func newWebHost(state *windowState, host *platform.WebHost, initial []platform.NativeView) *webHost {
@@ -305,18 +311,14 @@ func (page *windowsWeb) attach(environment uintptr) {
return 0
}), uintptr(unsafe.Pointer(&token)))
page.addDownloadHandler()
- for _, event := range []struct {
- slot int
- phase platform.WebLoadPhase
- }{{viewAddContentLoading, platform.WebLoadCommitted}, {viewAddNavCompleted, platform.WebLoadFinished}} {
- phase := event.phase
- comCall(view, event.slot, newHandler(func(_, _ uintptr) uintptr {
- var address uintptr
- comCall(view, viewGetSource, uintptr(unsafe.Pointer(&address)))
- page.loaded(phase, wideString(address))
- return 0
- }), uintptr(unsafe.Pointer(&token)))
- }
+ comCall(view, viewAddContentLoading, newHandler(func(_, _ uintptr) uintptr {
+ page.loaded(platform.WebLoadCommitted, page.sourceAddress(), platform.WebLoadNoError, "")
+ return 0
+ }), uintptr(unsafe.Pointer(&token)))
+ comCall(view, viewAddNavCompleted, newHandler(func(_, args uintptr) uintptr {
+ page.navigationCompleted(args)
+ return 0
+ }), uintptr(unsafe.Pointer(&token)))
script := platform.WebBridgeScript
if page.config.BridgeMainFrameOnly {
script = platform.WebBridgeMainFrameOnlyScript
@@ -355,12 +357,58 @@ func (page *windowsWeb) do(action func()) {
}
// loaded reports a step of navigation, with the page's own scheme in the address as the
-// application knows it.
-func (page *windowsWeb) loaded(phase platform.WebLoadPhase, address string) {
+// application knows it and the title the page has at that step. code is why the navigation failed,
+// when the step is the one that ends it.
+func (page *windowsWeb) loaded(phase platform.WebLoadPhase, address string, code platform.WebLoadError, description string) {
if page.closed || page.config.OnLoad == nil {
return
}
- page.config.OnLoad(platform.WebLoad{Phase: phase, URL: page.appAddress(address)})
+ page.config.OnLoad(platform.WebLoad{
+ Phase: phase, URL: page.appAddress(address), Title: page.documentTitle(),
+ Code: code, Description: description,
+ })
+}
+
+// navigationCompleted reports the end of a navigation: the runtime's source for the address, and
+// its status when the page did not load. A navigation the application refused is not reported: the
+// cancellation the runtime calls its end is the answer the application gave.
+func (page *windowsWeb) navigationCompleted(args uintptr) {
+ page.loading = false
+ if page.refused {
+ page.refused = false
+ return
+ }
+ code := platform.WebLoadNoError
+ var success int32
+ if args != 0 {
+ comCall(args, navigationCompletedIsSuccess, uintptr(unsafe.Pointer(&success)))
+ if success == 0 {
+ var status int32
+ comCall(args, navigationCompletedError, uintptr(unsafe.Pointer(&status)))
+ code = platform.WebLoadErrorFromWebView2Status(status)
+ }
+ }
+ page.loaded(platform.WebLoadFinished, page.sourceAddress(), code, "")
+}
+
+// sourceAddress is the address of the document the page has, as the runtime names it.
+func (page *windowsWeb) sourceAddress() string {
+ if page.view == 0 {
+ return ""
+ }
+ var address uintptr
+ comCall(page.view, viewGetSource, uintptr(unsafe.Pointer(&address)))
+ return wideString(address)
+}
+
+// documentTitle is the title the runtime has for the page's document, empty until it has one.
+func (page *windowsWeb) documentTitle() string {
+ if page.view == 0 {
+ return ""
+ }
+ var title uintptr
+ comCall(page.view, viewGetDocumentTitle, uintptr(unsafe.Pointer(&title)))
+ return wideString(title)
}
// appAddress is an address as the application knows it: the page's own scheme is served as
@@ -394,13 +442,17 @@ func (page *windowsWeb) navigationStarting(args uintptr, mainFrame bool) {
}
if !allowed {
comCall(args, startingPutCancel, 1)
+ if mainFrame {
+ page.refused, page.loading = true, false
+ }
return
}
// Started is reported only for a navigation the application allows: macOS and Linux start a
// load after their policy decision, so a refused one must not leave a Started without a
// Committed or Finished. loaded names the address as the application knows it there too.
if mainFrame {
- page.loaded(platform.WebLoadStarted, url)
+ page.refused, page.loading = false, true
+ page.loaded(platform.WebLoadStarted, url, platform.WebLoadNoError, "")
}
}
@@ -624,6 +676,27 @@ func (page *windowsWeb) Reload() { page.do(func() { comCall(page.view, viewRelo
func (page *windowsWeb) Back() { page.do(func() { comCall(page.view, viewGoBack) }) }
func (page *windowsWeb) Forward() { page.do(func() { comCall(page.view, viewGoForward) }) }
+// Title is the title of the page's current document, which the runtime keeps for the page it made:
+// empty before it has one, and once the page has closed.
+func (page *windowsWeb) Title() string { return page.documentTitle() }
+
+// CanGoBack and CanGoForward ask the runtime about the page's history.
+func (page *windowsWeb) CanGoBack() bool { return page.canGo(viewGetCanGoBack) }
+func (page *windowsWeb) CanGoForward() bool { return page.canGo(viewGetCanGoForward) }
+
+func (page *windowsWeb) canGo(slot int) bool {
+ if page.view == 0 {
+ return false
+ }
+ var can int32
+ comCall(page.view, slot, uintptr(unsafe.Pointer(&can)))
+ return can != 0
+}
+
+// IsLoading is the navigation the runtime is in the middle of, which this page follows from the
+// events: WebView2 has no property that answers it.
+func (page *windowsWeb) IsLoading() bool { return page.loading }
+
func (page *windowsWeb) Eval(script string) {
page.do(func() { comCall(page.view, viewExecuteScript, uintptr(unsafe.Pointer(wide(script))), 0) })
}
@@ -645,6 +718,7 @@ func (page *windowsWeb) Close() {
return
}
page.closed = true
+ page.loading = false
delete(page.host.pages, page.id)
page.release()
}
diff --git a/internal/platform/windows/webview2_windows.go b/internal/platform/windows/webview2_windows.go
index 8f188896b..ee59aef5f 100644
--- a/internal/platform/windows/webview2_windows.go
+++ b/internal/platform/windows/webview2_windows.go
@@ -407,25 +407,35 @@ const (
viewGoBack = 40
viewGoForward = 41
viewGetSource = 4
- viewAddWebResourceReq = 55
- viewAddResourceFilter = 57
+ // The page's own state, in ICoreWebView2's IDL order: get_CanGoBack 38, get_CanGoForward 39,
+ // get_DocumentTitle 48 (add_DocumentTitleChanged is 46, remove_DocumentTitleChanged 47). The
+ // load's end is NavigationCompleted 15 on that same interface, and a failed one is told apart
+ // through its event args below.
+ viewGetCanGoBack = 38
+ viewGetCanGoForward = 39
+ viewGetDocumentTitle = 48
+ viewAddWebResourceReq = 55
+ viewAddResourceFilter = 57
// ICoreWebView2_4 adds DownloadStarting after every ICoreWebView2_3 method.
- viewAddDownloadStarting = 75
- messageTryGetString = 5
- startingGetURI = 3
- startingGetUserGesture = 4
- startingGetRedirected = 5
- startingPutCancel = 8
- newWindowGetURI = 3
- newWindowPutHandled = 6
- downloadArgsGetOperation = 3
- downloadArgsPutCancel = 5
- downloadArgsGetResultPath = 6
- downloadArgsPutResultPath = 7
- downloadArgsPutHandled = 9
- downloadGetURI = 9
- resourceArgsGetRequest = 3
- resourceArgsPutResponse = 5
+ viewAddDownloadStarting = 75
+ messageTryGetString = 5
+ // ICoreWebView2NavigationCompletedEventArgs: get_IsSuccess 3, get_WebErrorStatus 4.
+ navigationCompletedIsSuccess = 3
+ navigationCompletedError = 4
+ startingGetURI = 3
+ startingGetUserGesture = 4
+ startingGetRedirected = 5
+ startingPutCancel = 8
+ newWindowGetURI = 3
+ newWindowPutHandled = 6
+ downloadArgsGetOperation = 3
+ downloadArgsPutCancel = 5
+ downloadArgsGetResultPath = 6
+ downloadArgsPutResultPath = 7
+ downloadArgsPutHandled = 9
+ downloadGetURI = 9
+ resourceArgsGetRequest = 3
+ resourceArgsPutResponse = 5
// ICoreWebView2WebResourceRequestedEventArgs::GetDeferral holds the request open.
resourceArgsGetDeferral = 6
// ICoreWebView2Deferral::Complete says the request may continue.
diff --git a/website/content/guides/en/system-integration.md b/website/content/guides/en/system-integration.md
index b89cd1ed1..4fe615ee4 100644
--- a/website/content/guides/en/system-integration.md
+++ b/website/content/guides/en/system-integration.md
@@ -104,15 +104,22 @@ func (m *model) open() {
func (m *model) page(c ui.C) {
ui.Column(c).Fill().Pad(8).Gap(8).Children(func() {
ui.Row(c).Gap(8).Items(ui.Center).Children(func() {
- if ui.Button(c, "Back").Outline().Clicked() && m.view != nil {
+ // The page answers for its own history and title, and this paint asks it: Back and
+ // Forward are greyed out where the page has nowhere to go, and the label follows it.
+ title, canGoBack, canGoForward := "", false, false
+ if m.view != nil {
+ title, canGoBack, canGoForward = m.view.Title(), m.view.CanGoBack(), m.view.CanGoForward()
+ }
+ if ui.Button(c, "Back").Outline().Disabled(!canGoBack).Clicked() && m.view != nil {
m.view.Back()
}
- if ui.Button(c, "Forward").Outline().Clicked() && m.view != nil {
+ if ui.Button(c, "Forward").Outline().Disabled(!canGoForward).Clicked() && m.view != nil {
m.view.Forward()
}
if ui.Button(c, "Reload").Outline().Clicked() && m.view != nil {
m.view.Reload()
}
+ ui.Text(c, title).Muted()
menu := ui.Button(c, "Menu").Outline()
if menu.Clicked() {
m.menuOpen = !m.menuOpen
diff --git a/website/content/guides/zh/system-integration.md b/website/content/guides/zh/system-integration.md
index 17c93ca3c..7f7d71ec4 100644
--- a/website/content/guides/zh/system-integration.md
+++ b/website/content/guides/zh/system-integration.md
@@ -104,15 +104,22 @@ func (m *model) open() {
func (m *model) page(c ui.C) {
ui.Column(c).Fill().Pad(8).Gap(8).Children(func() {
ui.Row(c).Gap(8).Items(ui.Center).Children(func() {
- if ui.Button(c, "Back").Outline().Clicked() && m.view != nil {
+ // The page answers for its own history and title, and this paint asks it: Back and
+ // Forward are greyed out where the page has nowhere to go, and the label follows it.
+ title, canGoBack, canGoForward := "", false, false
+ if m.view != nil {
+ title, canGoBack, canGoForward = m.view.Title(), m.view.CanGoBack(), m.view.CanGoForward()
+ }
+ if ui.Button(c, "Back").Outline().Disabled(!canGoBack).Clicked() && m.view != nil {
m.view.Back()
}
- if ui.Button(c, "Forward").Outline().Clicked() && m.view != nil {
+ if ui.Button(c, "Forward").Outline().Disabled(!canGoForward).Clicked() && m.view != nil {
m.view.Forward()
}
if ui.Button(c, "Reload").Outline().Clicked() && m.view != nil {
m.view.Reload()
}
+ ui.Text(c, title).Muted()
menu := ui.Button(c, "Menu").Outline()
if menu.Clicked() {
m.menuOpen = !m.menuOpen
From efd9c5ceeef58f5b0309f835e8786b3336ae46f1 Mon Sep 17 00:00:00 2001
From: t8y2 <1156263951@qq.com>
Date: Sat, 21 Nov 2026 16:46:47 +0800
Subject: [PATCH 03/47] fix(windows): keep the frame constant ABI test in step
with the shader
The text shader now carries the label's shape in a fourth float4, so the
constant buffer is 80 bytes instead of 64. The test still asserted the old
size and failed the Windows material gate.
---
internal/platform/windows/api_windows_test.go | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/internal/platform/windows/api_windows_test.go b/internal/platform/windows/api_windows_test.go
index 6e2f58b1a..dabd5e1ac 100644
--- a/internal/platform/windows/api_windows_test.go
+++ b/internal/platform/windows/api_windows_test.go
@@ -49,7 +49,7 @@ func TestNativeStructureABI(t *testing.T) {
{"DWRITE_LINE_METRICS", unsafe.Sizeof(lineMetrics{}), 24},
{"DWRITE_TEXT_METRICS", unsafe.Sizeof(textMetrics{}), 36},
{"rectangle shader instance", unsafe.Sizeof(rectangleInstance{}), rectangleInstanceBytes},
- {"frame shader constants", unsafe.Sizeof(frameConstants{}), 64},
+ {"frame shader constants", unsafe.Sizeof(frameConstants{}), 80},
{"DEVMODEW", unsafe.Sizeof(displayMode{}), 220},
} {
if layout.size != layout.want {
From eedbe8d9d02e813826cd588269f473467f03640c Mon Sep 17 00:00:00 2001
From: t8y2 <1156263951@qq.com>
Date: Sat, 21 Nov 2026 17:24:15 +0800
Subject: [PATCH 04/47] docs(release): v0.6.7 notes
---
docs/releases/0.6.7.md | 71 ++++++++++++++++++++++++++++++++++++++++++
1 file changed, 71 insertions(+)
create mode 100644 docs/releases/0.6.7.md
diff --git a/docs/releases/0.6.7.md b/docs/releases/0.6.7.md
new file mode 100644
index 000000000..d1dc148d8
--- /dev/null
+++ b/docs/releases/0.6.7.md
@@ -0,0 +1,71 @@
+v0.6.7 是 v0.6.6 之后的版本:主题控件全面改由引擎驱动,Image 支持圆角与透明度,Progress 能被辅助技术识别;另有多项平台修复、输入法支持与性能改进。macOS 是参考平台。
+
+v0.6.7 comes after v0.6.6: themed controls are driven by the engine, images take a corner radius and opacity, and a labelled progress bar reaches assistive technology, alongside platform fixes, input-method support and performance work. macOS is the reference platform.
+
+## 拿到它 · Getting it
+
+`go get github.com/vivaui/viva@v0.6.7`,需要 Go 1.26 或更新;系统依赖与 v0.6.6 相同。每个 Release 附带 `viva` 命令的预编译压缩包、`SHA256SUMS`,以及 Homebrew 与 Scoop 清单(`brew install vivaui/tap/viva`,或 `scoop bucket add vivaui https://github.com/vivaui/homebrew-tap` 后 `scoop install viva`)。
+
+`go get github.com/vivaui/viva@v0.6.7` needs Go 1.26 or newer; the system requirements are those of v0.6.6. Every Release carries prebuilt archives of the `viva` command, `SHA256SUMS`, and Homebrew and Scoop manifests (`brew install vivaui/tap/viva`, or `scoop bucket add vivaui https://github.com/vivaui/homebrew-tap` then `scoop install viva`).
+
+## 有什么 · What is in it
+
+- 主题控件(`ui.Button`、`ui.Badge`、`ui.Toggle`、`ui.Tabs`、`ui.Select`、`ui.Checkbox`、`ui.Switch`)的默认外观由配方和元素属性决定,`.Pad`、`.Gap`、`.FontSize`、`.Color`、`.Radius`、`.Children` 等现在与普通元素一致生效,控件自身的勾、滑块、轨道和箭头保持不变。
+- `ui.Button` 可以用 `Children` 放调用方内容,按钮的身份、焦点、禁用、命中与键盘行为仍留在按钮上。
+- `ui.Tabs` 的 `Pad` 现在作用于四边,`PadX`、`PadY` 和不对称内边距会移动触发器;`TabIconOnly()` 让标签页只画图标,标签文字仍是它的无障碍名。
+- `ui.Table` 可以用 `.FontSize` 和 `.Color` 直接设置表头与单元格文字,`ui.Checkbox` 的显式 `Size` 会缩放方框和勾,`ui.Switch` 的 `FillWidth` 与 `WidthPercent` 可以拉伸轨道。
+- `ui.Image` 的 `Radius` 会裁剪图片圆角,`Opacity` 会淡化图片,在 CPU、Metal、Vulkan、WebGL、Web Canvas2D 与 D3D11 六条渲染路径上都生效,且是绘制期属性、不重建纹理。
+- 给了 `Label` 的 `ui.Progress` 会作为只读进度条暴露给辅助技术(0–100,indeterminate 时不报数字),不命名时仍只是装饰。
+- `ui.ButtonGroup` 支持只有图标的动作与选中态,公开按钮组可以直接组合工具栏动作。
+- `ui.Canvas.LabelHighlighted` 在成形文本后面按大小写不敏感匹配高亮搜索词,原文本和无障碍名保持不变。
+- `WebView` 新增 `Title()`、`CanGoBack()`、`CanGoForward()`、`IsLoading()`,并提供分好类的加载失败原因。
+- `app.StartFileDrag` 可以把文件从窗口拖出到其他程序,X11 上同时显示跟随指针的半透明预览窗口。
+- `Window.SetIcon` 可以在运行时替换窗口图标,并同步 Windows 任务栏的分组资源。
+- Windows 上彩色终端行的一次绘制合并为每遍一次 GDI 调用,DirectWrite 的文本格式与布局会在光栅器生命周期内复用,滚动彩色输出更顺畅。
+- Windows 的实时缩放改由定时器驱动,拖动窗口边缘时画面按自己的节奏重绘,不再被每条原生消息带着走。
+- Windows 上通过消息窗口投递的唤醒不会再被模态循环吞掉,打开状态栏菜单或对话框时后台工作不会挂起。
+- Linux 的 X11 后端加入 Fcitx 4 输入法支持,Sogou 等 Fcitx 4 桌面能正常上屏和显示预编辑文本。
+- 带外边距的列表行现在计入滚动内容高度,最后几行可以完整滚进视野;列表滚轮偏移也会夹在已测量的范围内。
+- 很长的单行文本改为从纹理窗口分段绘制,超长行不再被截断或画错。
+- X11 激活窗口时带上服务端时间戳,点击窗口能正确置顶并获得焦点。
+- 打开对话框时,滚轮不再传给对话框背后、被焦点陷阱挡住的列表。
+- 颜色选择面板在对话框内会画在对话框之上,控件可见且可以点击。
+- `ui.Select` 会先测量图标再测量标签,自动宽度的下拉触发器不再裁掉标签。
+- macOS 上从 Finder 打开注册过的文档类型会送到 `OnOpenFile`;非 UTF-8 的文本标签会替换为 U+FFFD,不再导致窗口关闭。
+- 方形线帽延伸到开放路径的端点之外,描边端点不再缺一截;抓取光标不可用时回退为手形指针。
+- Linux 的 `.deb`、RPM 与 PKGBUILD 推荐 `libxcb-cursor`,HiDPI 桌面上的指针不再明显偏小。
+
+- The default look of the themed controls (`ui.Button`, `ui.Badge`, `ui.Toggle`, `ui.Tabs`, `ui.Select`, `ui.Checkbox`, `ui.Switch`) comes from their recipes and the element's attributes: `.Pad`, `.Gap`, `.FontSize`, `.Color`, `.Radius` and `.Children` now work on them as on any other element, while the control's own check, thumb, track and chevron stay as they are.
+- `ui.Button` takes caller content through `Children` and keeps the button's identity, focus, disabled state, hit area and keyboard behavior.
+- `ui.Tabs` applies `Pad` to all four sides, so `PadX`, `PadY` and uneven padding move the triggers; `TabIconOnly()` paints icons without labels while the label stays the tab's accessible name.
+- `ui.Table` styles its header and cells with `.FontSize` and `.Color`, an explicit `Size` on `ui.Checkbox` scales the box and its mark, and `FillWidth` and `WidthPercent` on `ui.Switch` stretch the track.
+- `ui.Image` cuts its corners with `Radius` and fades with `Opacity` on all six renderers (CPU, Metal, Vulkan, WebGL, Web Canvas2D and D3D11), and both are draw-time values that do not rebuild a texture.
+- A `ui.Progress` with a `Label` is a read-only progress bar to assistive technology (0–100, no number while indeterminate); an unnamed bar stays decorative.
+- `ui.ButtonGroup` supports icon-only actions and a selected action, so a page composes toolbar actions with the public button group.
+- `ui.Canvas.LabelHighlighted` paints case-insensitive search matches behind shaped text while the original text and its accessible name stay unchanged.
+- `WebView` reports `Title()`, `CanGoBack()`, `CanGoForward()` and `IsLoading()`, and exposes classified load failures.
+- `app.StartFileDrag` drags files out of a window to other programs, with a translucent preview following the pointer on X11.
+- `Window.SetIcon` replaces the window icon at run time and keeps Windows taskbar grouping resources in step.
+- On Windows a colored terminal row is drawn with one GDI call per pass and DirectWrite formats and layouts are kept for the rasterizer's lifetime, so scrolling colored output is smoother.
+- Windows live resize is paced by its timer, so dragging a window edge redraws at its own rate instead of once per native message.
+- A wake posted through its message-only window is no longer swallowed by a modal loop, so background work does not hang while a status menu or dialog is open.
+- The Linux X11 backend supports Fcitx 4, so desktops such as Sogou on Fcitx 4 compose and show pre-edit text.
+- Rows with vertical margins now count toward a list's scrollable content, so the last rows scroll fully into view, and the list wheel offset stays within the measured extent.
+- Very long single lines are drawn from windows of their texture instead of being clipped or misdrawn.
+- X11 activation carries the server timestamp, so clicking a window raises it and gives it the focus.
+- The wheel no longer reaches lists behind a focus trap while a dialog is open.
+- A color picker inside a dialog paints its panel above the dialog, so its controls are visible and clickable.
+- `ui.Select` measures its icon before its label, so an auto-sized trigger no longer clips the label.
+- On macOS a registered document opened from Finder reaches `OnOpenFile`, and text labels with invalid UTF-8 are replaced with U+FFFD instead of closing the window.
+- Square line caps extend past an open contour's end, and a missing grabbing cursor falls back to a hand.
+- The Linux `.deb`, RPM and PKGBUILD recommend `libxcb-cursor`, so the pointer is not conspicuously small on HiDPI desktops.
+
+## 注意 · Caveats
+
+- `Frame.Progress(fraction)` 现在是 `Frame.Progress(ID, fraction)`;直接调用 `base.Frame` 的代码要补上身份,`ui.Progress(c, fraction)` 不变。
+- dev 构建会拒绝在某个元素上不生效的通用属性并给出原因;release 构建仍与以前一样忽略它们。用 `VIVA_ATTR_CHECK=warn` 可以只报告不中断,便于一次清理整页。
+- 一些以前静默无效的属性现在生效,页面外观可能变化:`Tabs` 的 `Pad` 四边都算、`PadY(0)` 不再回落到主题高度,`Checkbox` 的 `Size` 缩放方框本身,`Switch` 的宽高缩放轨道,`Image` 的 `Radius` 和 `Opacity` 会真正裁剪与淡化。
+
+- `Frame.Progress(fraction)` is now `Frame.Progress(ID, fraction)`; code calling `base.Frame` directly must pass an identity, while `ui.Progress(c, fraction)` is unchanged.
+- A dev build rejects a generic attribute that does nothing on its element and says why; release builds keep ignoring it as before. `VIVA_ATTR_CHECK=warn` reports without stopping, which helps clean a page in one pass.
+- Some attributes that were silently ignored now take effect and can change a page's look: `Tabs` pads all four sides and `PadY(0)` no longer falls back to the theme height, `Checkbox.Size` scales the box itself, `Switch` width and height scale the track, and `Image.Radius` and `Opacity` really cut and fade the picture.
From e6712a7b00a3f7993041eaaf516369b68e985a9a Mon Sep 17 00:00:00 2001
From: t8y2 <1156263951@qq.com>
Date: Sat, 21 Nov 2026 17:33:43 +0800
Subject: [PATCH 05/47] docs: point at v0.6.7
---
README.md | 2 +-
README.zh-CN.md | 2 +-
website/content/guides/en/getting-started.md | 2 +-
website/content/guides/zh/getting-started.md | 2 +-
4 files changed, 4 insertions(+), 4 deletions(-)
diff --git a/README.md b/README.md
index 4d97909a7..679172bcd 100644
--- a/README.md
+++ b/README.md
@@ -57,7 +57,7 @@ Wayland client and needs the system's GTK 3), and a Vulkan loader and driver for
and DirectWrite. Viva loads the system libraries at runtime and bundles none of
them.
-The current release is `v0.6.6`; name it explicitly (`@v0.6.6`) to pin it. Guides,
+The current release is `v0.6.7`; name it explicitly (`@v0.6.7`) to pin it. Guides,
the API reference, and a component catalog with live previews live in
[`website/`](website/); run it with `npm run dev` there, or read them on
[vivaui.dev](https://vivaui.dev/en/), which is also available in
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 81204f691..4bc4ee18a 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -34,7 +34,7 @@ viva dev . # hot reload: save a file, the window updates and keeps its st
环境要求: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 在运行时加载系统库,自身不捆绑任何一个。
-当前版本是 `v0.6.6`;要固定版本就写明(`@v0.6.6`)。指南、API 参考和带实时预览的组件目录在 [`website/`](website/) 里,本地用 `npm run dev` 运行;也已经发布在 [vivaui.dev](https://vivaui.dev/zh/)。
+当前版本是 `v0.6.7`;要固定版本就写明(`@v0.6.7`)。指南、API 参考和带实时预览的组件目录在 [`website/`](website/) 里,本地用 `npm run dev` 运行;也已经发布在 [vivaui.dev](https://vivaui.dev/zh/)。
下面的一切描述的都是这个仓库:它的测量、它自己的程序,以及如何开发框架本身,而不是如何用框架。
diff --git a/website/content/guides/en/getting-started.md b/website/content/guides/en/getting-started.md
index 6b5d93856..e6c51cd2f 100644
--- a/website/content/guides/en/getting-started.md
+++ b/website/content/guides/en/getting-started.md
@@ -22,7 +22,7 @@ go mod init example.com/hello
go get github.com/vivaui/viva
```
-`go get` without a version resolves to the latest tagged release, which is `v0.6.6`. Pin it by naming the version: `go get github.com/vivaui/viva@v0.6.6`. Viva is not yet at 1.0, so the API in `go.mod` can still change between minor releases; read the release notes before upgrading.
+`go get` without a version resolves to the latest tagged release, which is `v0.6.7`. Pin it by naming the version: `go get github.com/vivaui/viva@v0.6.7`. Viva is not yet at 1.0, so the API in `go.mod` can still change between minor releases; read the release notes before upgrading.
If you are working on Viva itself rather than using it, `replace` it with your checkout instead:
diff --git a/website/content/guides/zh/getting-started.md b/website/content/guides/zh/getting-started.md
index c5fde4f70..4ea597bcf 100644
--- a/website/content/guides/zh/getting-started.md
+++ b/website/content/guides/zh/getting-started.md
@@ -22,7 +22,7 @@ go mod init example.com/hello
go get github.com/vivaui/viva
```
-`go get` 不带版本号时取最新的正式版本,目前就是 `v0.6.6`。要固定版本就写明:`go get github.com/vivaui/viva@v0.6.6`。Viva 还没有到 1.0,所以小版本之间 `go.mod` 的 API 仍可能变化;升级前看一眼发版说明。
+`go get` 不带版本号时取最新的正式版本,目前就是 `v0.6.7`。要固定版本就写明:`go get github.com/vivaui/viva@v0.6.7`。Viva 还没有到 1.0,所以小版本之间 `go.mod` 的 API 仍可能变化;升级前看一眼发版说明。
如果你是在 Viva 仓库里改框架本身、而不是使用它,改用 `replace` 指向检出目录:
From 4e6fa275c76f01743192c42a24600774924face6 Mon Sep 17 00:00:00 2001
From: Lichenkang <2188718831@qq.com>
Date: Sat, 21 Nov 2026 02:30:41 -0800
Subject: [PATCH 06/47] test(darwin): compare Dock icon colors by dominant
channel
---
internal/platform/darwin/testdata/status_item.m | 13 ++++++++++---
1 file changed, 10 insertions(+), 3 deletions(-)
diff --git a/internal/platform/darwin/testdata/status_item.m b/internal/platform/darwin/testdata/status_item.m
index 4030f411d..a594d730b 100644
--- a/internal/platform/darwin/testdata/status_item.m
+++ b/internal/platform/darwin/testdata/status_item.m
@@ -65,11 +65,18 @@ int main(void) {
rgba[i + 2] = color == 0 ? 0 : 255;
}
check(viva_application_update_icon(icon) == 1, "Dock update accepted");
- NSBitmapImageRep *rep = [NSBitmapImageRep imageRepWithData:[[NSApp applicationIconImage] TIFFRepresentation]];
+ NSImage *dockIcon = [NSApp applicationIconImage];
+ NSSize points = NSMakeSize(icon.size / 2.0, icon.size / 2.0);
+ check(NSEqualSizes(dockIcon.size, points), "Dock keeps the expected size in points");
+ NSBitmapImageRep *rep = [NSBitmapImageRep imageRepWithData:[dockIcon TIFFRepresentation]];
NSColor *pixel = [[rep colorAtX:rep.pixelsWide / 2 y:rep.pixelsHigh / 2]
colorUsingColorSpace:[NSColorSpace deviceRGBColorSpace]];
- int matches = pixel != nil && (color == 0 ? pixel.redComponent > 0.9 && pixel.blueComponent < 0.1
- : pixel.blueComponent > 0.9 && pixel.redComponent < 0.1);
+ // AppKit can resample and color-manage the snapshot for the current display.
+ // Distinguish the two icon colors independently of scale and color profile.
+ CGFloat primary = color == 0 ? pixel.redComponent : pixel.blueComponent;
+ CGFloat other = color == 0 ? pixel.blueComponent : pixel.redComponent;
+ int matches = pixel != nil &&
+ primary > other && primary > pixel.greenComponent && pixel.alphaComponent > 0;
if (!matches) {
fprintf(stderr, "Dock image %ldx%ld center: %s\n", (long)rep.pixelsWide, (long)rep.pixelsHigh,
[[pixel description] UTF8String]);
From 1742b8fa37f1142d1067d8f3789a622aecc4840b Mon Sep 17 00:00:00 2001
From: Lichenkang <2188718831@qq.com>
Date: Sat, 21 Nov 2026 02:30:49 -0800
Subject: [PATCH 07/47] test(windows): check the frame shader field offsets
---
internal/platform/windows/api_windows_test.go | 17 +++++++++++++++--
1 file changed, 15 insertions(+), 2 deletions(-)
diff --git a/internal/platform/windows/api_windows_test.go b/internal/platform/windows/api_windows_test.go
index dabd5e1ac..eb95872b1 100644
--- a/internal/platform/windows/api_windows_test.go
+++ b/internal/platform/windows/api_windows_test.go
@@ -63,8 +63,21 @@ func TestNativeStructureABI(t *testing.T) {
if textureIID != wantTextureIID {
t.Fatal("ID3D11Texture2D GUID mismatch")
}
- if offset := unsafe.Offsetof(frameConstants{}.InstanceOffset); offset != 8 {
- t.Fatalf("frame shader instance offset = %d, want 8", offset)
+ // Match the registers of Frame in shaders/scene.hlsl.
+ for _, field := range []struct {
+ name string
+ offset uintptr
+ want uintptr
+ }{
+ {"instanceOffset", unsafe.Offsetof(frameConstants{}.InstanceOffset), 8},
+ {"textBounds", unsafe.Offsetof(frameConstants{}.Bounds), 16},
+ {"textColor", unsafe.Offsetof(frameConstants{}.TextColor), 32},
+ {"textShape", unsafe.Offsetof(frameConstants{}.TextShape), 48},
+ {"pixelSize", unsafe.Offsetof(frameConstants{}.PixelSize), 64},
+ } {
+ if field.offset != field.want {
+ t.Errorf("frame shader %s offset = %d, want %d", field.name, field.offset, field.want)
+ }
}
}
From 737c24597b3a8ed537952d7549bc1a6829bffb0d Mon Sep 17 00:00:00 2001
From: ccq <76206374+caichangqing1120@users.noreply.github.com>
Date: Sat, 21 Nov 2026 18:31:04 +0800
Subject: [PATCH 08/47] feat(components): add CodeEditor gutter and byte
decorations
---
cmd/viva/components_gen.go | 320 +++++------
cmd/viva/templates/code_editor.go.txt | 89 ++-
.../templates/code_editor_decorations.go.txt | 264 +++++++++
components/code_editor.go | 89 ++-
components/code_editor_decorations.go | 268 +++++++++
components/code_editor_decorations_test.go | 517 ++++++++++++++++++
components/doc.go | 3 +
components/doc_test.go | 2 +
.../code_editor_decorations_pixels_test.go | 138 +++++
tools/docs/catalog.go | 2 +-
10 files changed, 1500 insertions(+), 192 deletions(-)
create mode 100644 cmd/viva/templates/code_editor_decorations.go.txt
create mode 100644 components/code_editor_decorations.go
create mode 100644 components/code_editor_decorations_test.go
create mode 100644 headless/code_editor_decorations_pixels_test.go
diff --git a/cmd/viva/components_gen.go b/cmd/viva/components_gen.go
index ebdf024fb..dafe268ce 100644
--- a/cmd/viva/components_gen.go
+++ b/cmd/viva/components_gen.go
@@ -4,168 +4,170 @@ package main
// componentFiles maps the name given to `viva add` to its template.
var componentFiles = map[string]string{
- "accordion": "accordion.go.txt",
- "alert": "alert.go.txt",
- "alert-dialog": "alert_dialog.go.txt",
- "aspect-ratio": "aspect_ratio.go.txt",
- "attachment": "attachment.go.txt",
- "avatar": "avatar.go.txt",
- "avatar-editor": "avatar_editor.go.txt",
- "badge": "badge.go.txt",
- "breadcrumb": "breadcrumb.go.txt",
- "bubble": "bubble.go.txt",
- "button": "button.go.txt",
- "button-group": "button_group.go.txt",
- "calendar": "calendar.go.txt",
- "card": "card.go.txt",
- "caret-blink": "caret_blink.go.txt",
- "carousel": "carousel.go.txt",
- "chart": "chart.go.txt",
- "chart-area": "chart_area.go.txt",
- "chart-bar": "chart_bar.go.txt",
- "chart-downsample": "chart_downsample.go.txt",
- "checkbox": "checkbox.go.txt",
- "code-diff": "code_diff.go.txt",
- "code-diff-inline": "code_diff_inline.go.txt",
- "code-diff-model": "code_diff_model.go.txt",
- "code-editor": "code_editor.go.txt",
- "code-editor-layout": "code_editor_layout.go.txt",
- "code-merge": "code_merge.go.txt",
- "collapsible": "collapsible.go.txt",
- "color-picker": "color_picker.go.txt",
- "color-swatch": "color_swatch.go.txt",
- "column-resize": "column_resize.go.txt",
- "combobox": "combobox.go.txt",
- "command": "command.go.txt",
- "context-menu": "context_menu.go.txt",
- "dialog": "dialog.go.txt",
- "direction": "direction.go.txt",
- "drawer": "drawer.go.txt",
- "dropdown-menu": "dropdown_menu.go.txt",
- "empty": "empty.go.txt",
- "field": "field.go.txt",
- "find-bar": "find_bar.go.txt",
- "form": "form.go.txt",
- "go-to-line": "go_to_line.go.txt",
- "hierarchy-menu": "hierarchy_menu.go.txt",
- "hover-card": "hover_card.go.txt",
- "icon-hover": "icon_hover.go.txt",
- "image-view": "image_view.go.txt",
- "input": "input.go.txt",
- "input-group": "input_group.go.txt",
- "input-otp": "input_otp.go.txt",
- "item": "item.go.txt",
- "kbd": "kbd.go.txt",
- "label": "label.go.txt",
- "markdown": "markdown.go.txt",
- "markdown-anchor": "markdown_anchor.go.txt",
- "marker": "marker.go.txt",
- "menu-typeahead": "menu_typeahead.go.txt",
- "menubar": "menubar.go.txt",
- "message": "message.go.txt",
- "message-scroller": "message_scroller.go.txt",
- "metric-card": "metric_card.go.txt",
- "multi-select": "multi_select.go.txt",
- "native-select": "native_select.go.txt",
- "navigation-menu": "navigation_menu.go.txt",
- "pagination": "pagination.go.txt",
- "popover": "popover.go.txt",
- "progress": "progress.go.txt",
- "questionnaire": "questionnaire.go.txt",
- "radio-group": "radio_group.go.txt",
- "reorder-grid": "reorder_grid.go.txt",
- "reorder-list": "reorder_list.go.txt",
- "resizable": "resizable.go.txt",
- "scroll-area": "scroll_area.go.txt",
- "segmented-control": "segmented_control.go.txt",
- "select": "select.go.txt",
- "separator": "separator.go.txt",
- "sheet": "sheet.go.txt",
- "sidebar": "sidebar.go.txt",
- "single-select": "single_select.go.txt",
- "skeleton": "skeleton.go.txt",
- "slider": "slider.go.txt",
- "sonner": "sonner.go.txt",
- "spinner": "spinner.go.txt",
- "split-button": "split_button.go.txt",
- "switch": "switch.go.txt",
- "table": "table.go.txt",
- "tabs": "tabs.go.txt",
- "text-selection": "text_selection.go.txt",
- "textarea": "textarea.go.txt",
- "toast": "toast.go.txt",
- "toggle": "toggle.go.txt",
- "toggle-group": "toggle_group.go.txt",
- "tooltip": "tooltip.go.txt",
- "tree": "tree.go.txt",
- "tree-navigation": "tree_navigation.go.txt",
- "typography": "typography.go.txt",
+ "accordion": "accordion.go.txt",
+ "alert": "alert.go.txt",
+ "alert-dialog": "alert_dialog.go.txt",
+ "aspect-ratio": "aspect_ratio.go.txt",
+ "attachment": "attachment.go.txt",
+ "avatar": "avatar.go.txt",
+ "avatar-editor": "avatar_editor.go.txt",
+ "badge": "badge.go.txt",
+ "breadcrumb": "breadcrumb.go.txt",
+ "bubble": "bubble.go.txt",
+ "button": "button.go.txt",
+ "button-group": "button_group.go.txt",
+ "calendar": "calendar.go.txt",
+ "card": "card.go.txt",
+ "caret-blink": "caret_blink.go.txt",
+ "carousel": "carousel.go.txt",
+ "chart": "chart.go.txt",
+ "chart-area": "chart_area.go.txt",
+ "chart-bar": "chart_bar.go.txt",
+ "chart-downsample": "chart_downsample.go.txt",
+ "checkbox": "checkbox.go.txt",
+ "code-diff": "code_diff.go.txt",
+ "code-diff-inline": "code_diff_inline.go.txt",
+ "code-diff-model": "code_diff_model.go.txt",
+ "code-editor": "code_editor.go.txt",
+ "code-editor-decorations": "code_editor_decorations.go.txt",
+ "code-editor-layout": "code_editor_layout.go.txt",
+ "code-merge": "code_merge.go.txt",
+ "collapsible": "collapsible.go.txt",
+ "color-picker": "color_picker.go.txt",
+ "color-swatch": "color_swatch.go.txt",
+ "column-resize": "column_resize.go.txt",
+ "combobox": "combobox.go.txt",
+ "command": "command.go.txt",
+ "context-menu": "context_menu.go.txt",
+ "dialog": "dialog.go.txt",
+ "direction": "direction.go.txt",
+ "drawer": "drawer.go.txt",
+ "dropdown-menu": "dropdown_menu.go.txt",
+ "empty": "empty.go.txt",
+ "field": "field.go.txt",
+ "find-bar": "find_bar.go.txt",
+ "form": "form.go.txt",
+ "go-to-line": "go_to_line.go.txt",
+ "hierarchy-menu": "hierarchy_menu.go.txt",
+ "hover-card": "hover_card.go.txt",
+ "icon-hover": "icon_hover.go.txt",
+ "image-view": "image_view.go.txt",
+ "input": "input.go.txt",
+ "input-group": "input_group.go.txt",
+ "input-otp": "input_otp.go.txt",
+ "item": "item.go.txt",
+ "kbd": "kbd.go.txt",
+ "label": "label.go.txt",
+ "markdown": "markdown.go.txt",
+ "markdown-anchor": "markdown_anchor.go.txt",
+ "marker": "marker.go.txt",
+ "menu-typeahead": "menu_typeahead.go.txt",
+ "menubar": "menubar.go.txt",
+ "message": "message.go.txt",
+ "message-scroller": "message_scroller.go.txt",
+ "metric-card": "metric_card.go.txt",
+ "multi-select": "multi_select.go.txt",
+ "native-select": "native_select.go.txt",
+ "navigation-menu": "navigation_menu.go.txt",
+ "pagination": "pagination.go.txt",
+ "popover": "popover.go.txt",
+ "progress": "progress.go.txt",
+ "questionnaire": "questionnaire.go.txt",
+ "radio-group": "radio_group.go.txt",
+ "reorder-grid": "reorder_grid.go.txt",
+ "reorder-list": "reorder_list.go.txt",
+ "resizable": "resizable.go.txt",
+ "scroll-area": "scroll_area.go.txt",
+ "segmented-control": "segmented_control.go.txt",
+ "select": "select.go.txt",
+ "separator": "separator.go.txt",
+ "sheet": "sheet.go.txt",
+ "sidebar": "sidebar.go.txt",
+ "single-select": "single_select.go.txt",
+ "skeleton": "skeleton.go.txt",
+ "slider": "slider.go.txt",
+ "sonner": "sonner.go.txt",
+ "spinner": "spinner.go.txt",
+ "split-button": "split_button.go.txt",
+ "switch": "switch.go.txt",
+ "table": "table.go.txt",
+ "tabs": "tabs.go.txt",
+ "text-selection": "text_selection.go.txt",
+ "textarea": "textarea.go.txt",
+ "toast": "toast.go.txt",
+ "toggle": "toggle.go.txt",
+ "toggle-group": "toggle_group.go.txt",
+ "tooltip": "tooltip.go.txt",
+ "tree": "tree.go.txt",
+ "tree-navigation": "tree_navigation.go.txt",
+ "typography": "typography.go.txt",
}
// componentRequires lists the recipes a recipe's source calls into. `viva add`
// installs them along with it, so a recipe added on its own compiles.
var componentRequires = map[string][]string{
- "accordion": {"button", "tree"},
- "alert-dialog": {"button", "dialog"},
- "attachment": {"bubble", "button"},
- "avatar-editor": {"button", "direction", "slider"},
- "badge": {"button"},
- "breadcrumb": {"tree"},
- "bubble": {"button"},
- "button-group": {"button"},
- "calendar": {"direction", "tree"},
- "carousel": {"direction", "tree"},
- "chart-area": {"chart"},
- "chart-bar": {"chart", "chart-area"},
- "checkbox": {"button"},
- "code-diff": {"code-diff-model", "code-editor", "code-editor-layout", "scroll-area", "textarea"},
- "code-diff-model": {"code-diff-inline"},
- "code-editor": {"caret-blink", "code-editor-layout", "input", "scroll-area", "textarea", "tree"},
- "code-editor-layout": {"code-editor", "textarea"},
- "code-merge": {"code-diff", "code-diff-model", "code-editor", "code-editor-layout", "scroll-area"},
- "color-picker": {"button", "input", "popover"},
- "column-resize": {"button"},
- "combobox": {"checkbox", "dialog", "dropdown-menu", "input", "popover", "tree"},
- "command": {"checkbox", "dialog", "dropdown-menu"},
- "context-menu": {"dialog", "dropdown-menu", "popover"},
- "dialog": {"button"},
- "drawer": {"button", "dialog"},
- "dropdown-menu": {"checkbox", "dialog", "hover-card", "kbd", "popover", "tree"},
- "find-bar": {"button", "dialog", "input", "toggle", "tree"},
- "go-to-line": {"button", "find-bar", "input"},
- "hierarchy-menu": {"checkbox", "dialog", "dropdown-menu", "tree"},
- "hover-card": {"dialog", "popover"},
- "input": {"textarea"},
- "input-group": {"button", "input", "spinner", "textarea"},
- "input-otp": {"input"},
- "item": {"button"},
- "markdown": {"markdown-anchor"},
- "markdown-anchor": {"markdown"},
- "marker": {"spinner"},
- "menubar": {"dialog", "direction", "dropdown-menu", "hover-card", "popover"},
- "metric-card": {"card"},
- "multi-select": {"checkbox", "combobox", "dialog", "dropdown-menu", "input", "tree"},
- "native-select": {"input", "tree"},
- "navigation-menu": {"dialog", "direction", "hover-card", "tree"},
- "pagination": {"breadcrumb", "tree"},
- "popover": {"dialog"},
- "questionnaire": {"button", "checkbox", "input"},
- "radio-group": {"button", "direction"},
- "resizable": {"button"},
- "segmented-control": {"button", "direction"},
- "select": {"checkbox", "dialog", "dropdown-menu", "input", "popover", "tree"},
- "sheet": {"button", "dialog"},
- "sidebar": {"button"},
- "single-select": {"checkbox", "dialog", "dropdown-menu", "hierarchy-menu", "input", "tree"},
- "slider": {"button", "direction"},
- "sonner": {"toast"},
- "split-button": {"button", "button-group", "tree"},
- "switch": {"button"},
- "tabs": {"button", "direction", "segmented-control"},
- "text-selection": {"markdown"},
- "textarea": {"input"},
- "toast": {"button", "dialog", "spinner"},
- "toggle": {"button"},
- "toggle-group": {"button", "button-group", "direction", "toggle"},
- "tooltip": {"dialog", "popover"},
+ "accordion": {"button", "tree"},
+ "alert-dialog": {"button", "dialog"},
+ "attachment": {"bubble", "button"},
+ "avatar-editor": {"button", "direction", "slider"},
+ "badge": {"button"},
+ "breadcrumb": {"tree"},
+ "bubble": {"button"},
+ "button-group": {"button"},
+ "calendar": {"direction", "tree"},
+ "carousel": {"direction", "tree"},
+ "chart-area": {"chart"},
+ "chart-bar": {"chart", "chart-area"},
+ "checkbox": {"button"},
+ "code-diff": {"code-diff-model", "code-editor", "code-editor-layout", "scroll-area", "textarea"},
+ "code-diff-model": {"code-diff-inline"},
+ "code-editor": {"caret-blink", "code-editor-decorations", "code-editor-layout", "input", "scroll-area", "textarea", "tree"},
+ "code-editor-decorations": {"code-editor", "code-editor-layout"},
+ "code-editor-layout": {"code-editor", "textarea"},
+ "code-merge": {"code-diff", "code-diff-model", "code-editor", "code-editor-layout", "scroll-area"},
+ "color-picker": {"button", "input", "popover"},
+ "column-resize": {"button"},
+ "combobox": {"checkbox", "dialog", "dropdown-menu", "input", "popover", "tree"},
+ "command": {"checkbox", "dialog", "dropdown-menu"},
+ "context-menu": {"dialog", "dropdown-menu", "popover"},
+ "dialog": {"button"},
+ "drawer": {"button", "dialog"},
+ "dropdown-menu": {"checkbox", "dialog", "hover-card", "kbd", "popover", "tree"},
+ "find-bar": {"button", "dialog", "input", "toggle", "tree"},
+ "go-to-line": {"button", "find-bar", "input"},
+ "hierarchy-menu": {"checkbox", "dialog", "dropdown-menu", "tree"},
+ "hover-card": {"dialog", "popover"},
+ "input": {"textarea"},
+ "input-group": {"button", "input", "spinner", "textarea"},
+ "input-otp": {"input"},
+ "item": {"button"},
+ "markdown": {"markdown-anchor"},
+ "markdown-anchor": {"markdown"},
+ "marker": {"spinner"},
+ "menubar": {"dialog", "direction", "dropdown-menu", "hover-card", "popover"},
+ "metric-card": {"card"},
+ "multi-select": {"checkbox", "combobox", "dialog", "dropdown-menu", "input", "tree"},
+ "native-select": {"input", "tree"},
+ "navigation-menu": {"dialog", "direction", "hover-card", "tree"},
+ "pagination": {"breadcrumb", "tree"},
+ "popover": {"dialog"},
+ "questionnaire": {"button", "checkbox", "input"},
+ "radio-group": {"button", "direction"},
+ "resizable": {"button"},
+ "segmented-control": {"button", "direction"},
+ "select": {"checkbox", "dialog", "dropdown-menu", "input", "popover", "tree"},
+ "sheet": {"button", "dialog"},
+ "sidebar": {"button"},
+ "single-select": {"checkbox", "dialog", "dropdown-menu", "hierarchy-menu", "input", "tree"},
+ "slider": {"button", "direction"},
+ "sonner": {"toast"},
+ "split-button": {"button", "button-group", "tree"},
+ "switch": {"button"},
+ "tabs": {"button", "direction", "segmented-control"},
+ "text-selection": {"markdown"},
+ "textarea": {"input"},
+ "toast": {"button", "dialog", "spinner"},
+ "toggle": {"button"},
+ "toggle-group": {"button", "button-group", "direction", "toggle"},
+ "tooltip": {"dialog", "popover"},
}
diff --git a/cmd/viva/templates/code_editor.go.txt b/cmd/viva/templates/code_editor.go.txt
index 00e041016..654d25cf8 100644
--- a/cmd/viva/templates/code_editor.go.txt
+++ b/cmd/viva/templates/code_editor.go.txt
@@ -198,6 +198,9 @@ type CodeEditorSnapshot struct {
// component's formulas; a non-nil value uses its widths as given, and its
// Inset also replaces the theme's text inset.
Gutter *CodeEditorGutter
+ // Decorations supplies optional gutter bars and byte indicators. Set it to
+ // *CodeEditorDecorations, or nil to keep default drawing.
+ Decorations CodeEditorDecoration
}
// CodeEditor is the view of a code editor, held by the application next to its
@@ -375,16 +378,23 @@ func (editor *CodeEditor) Paint(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.
numberLane = float32(max(decimalDigits(lines), 2)+2) * cellWidth
}
}
- gutter := foldLane + markerLane + bookmarkLane + numberLane
+ decorationWidth := float32(0)
+ hasIndicators := false
+ if decorations := snapshot.Decorations; decorations != nil {
+ decorationWidth = decorations.codeEditorGutterWidth()
+ hasIndicators = decorations.codeEditorHasIndicators()
+ }
+ gutter := decorationWidth + foldLane + markerLane + bookmarkLane + numberLane
laneStart := bounds.X + inset
- foldX, markerX, bookmarkX, numberX := laneStart, float32(0), float32(0), float32(0)
+ lanes := laneStart + decorationWidth
+ foldX, markerX, bookmarkX, numberX := lanes, float32(0), float32(0), float32(0)
if foldLast {
- markerX = laneStart
+ markerX = lanes
bookmarkX = markerX + markerLane
numberX = bookmarkX + bookmarkLane
foldX = numberX + numberLane
} else {
- markerX = laneStart + foldLane
+ markerX = lanes + foldLane
bookmarkX = markerX + markerLane
numberX = bookmarkX + bookmarkLane
}
@@ -458,13 +468,14 @@ func (editor *CodeEditor) Paint(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.
selectionForeground.Alpha *= 0.5
}
paint := codePaint{
- canvas: canvas, theme: theme, editor: editor, value: value, size: size,
+ canvas: canvas, editor: editor, value: value, size: size,
+ background: theme.Background, muted: theme.MutedForeground, emphasis: theme.Foreground,
cellWidth: cellWidth, cellHeight: cellHeight, lineHeight: lineHeight,
foreground: foreground, selectionBackground: selectionBackground, selectionForeground: selectionForeground,
selectionStart: selectionStart, selectionEnd: selectionEnd,
selectionRanges: selectionRanges,
compositionStart: compositionStart, compositionEnd: compositionEnd,
- caret: caret, caretRow: caretRow, caretColumn: caretColumn,
+ caretRow: caretRow, caretColumn: caretColumn,
showCaret: showCaret,
caretWidth: editorCaretWidth(snapshot.CaretWidth), caretColor: caretColor(snapshot.CaretColor, foreground),
lineNumberPadding: lineNumberPadding,
@@ -473,6 +484,7 @@ func (editor *CodeEditor) Paint(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.
markLayers: snapshot.MarkLayers,
showWhitespace: snapshot.ShowWhitespace, showIndentGuides: snapshot.ShowIndentGuides, showEOL: snapshot.ShowEOL, showWrapSymbol: showWrapSymbol, eolLabel: snapshot.EOLLabel, eolLabels: snapshot.EOLLabels,
invisibleColor: snapshot.InvisibleColor,
+ deferOverlays: hasIndicators,
}
if paint.invisibleColor.Alpha == 0 {
paint.invisibleColor = theme.MutedForeground
@@ -487,6 +499,11 @@ func (editor *CodeEditor) Paint(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.
firstRow := int(editor.scrollY / lineHeight)
inner := gfx.Rect{X: bounds.X + 1, Y: content.Y, Width: content.X + content.Width - bounds.X - 1, Height: content.Height}
+ if decorationWidth > 0 {
+ // An oversized reserved lane may move content beyond this editor; its
+ // visible clip must still stop before a neighboring pane.
+ inner.Width = min(inner.Width, max(0, bounds.X+bounds.Width-inner.X))
+ }
canvas.Clip(inner)
if placeholder {
style := gfx.TextStyle{Size: size, Color: theme.MutedForeground, Mono: true, MonoFace: snapshot.MonoFace}
@@ -518,7 +535,13 @@ func (editor *CodeEditor) Paint(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.
if int(row.line) == currentLine {
tint := theme.Foreground
tint.Alpha *= 0.05
- canvas.Fill(gfx.Rect{X: inner.X, Y: y, Width: inner.Width, Height: lineHeight}, tint)
+ if decorationWidth > 0 {
+ canvas.Fill(gfx.Rect{X: inner.X, Y: y, Width: max(0, laneStart-inner.X), Height: lineHeight}, tint)
+ x := laneStart + decorationWidth
+ canvas.Fill(gfx.Rect{X: x, Y: y, Width: max(0, inner.X+inner.Width-x), Height: lineHeight}, tint)
+ } else {
+ canvas.Fill(gfx.Rect{X: inner.X, Y: y, Width: inner.Width, Height: lineHeight}, tint)
+ }
}
if markerLane > 0 && editor.firstOfLine(index) {
for markerIndex < len(snapshot.GutterMarkers) && snapshot.GutterMarkers[markerIndex].Line < int(row.line) {
@@ -538,6 +561,10 @@ func (editor *CodeEditor) Paint(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.
paint.lineNumber(row, y, numberX, numberLane, int(row.line) == int(editor.rows[caretRow].line))
}
}
+ if decorationWidth > 0 {
+ decorationPaint := codeDecorationPaint{canvas: canvas, editor: editor, size: size, cellWidth: cellWidth, lineHeight: lineHeight, face: snapshot.MonoFace}
+ snapshot.Decorations.codeEditorGutter(decorationPaint, gfx.Rect{X: laneStart, Y: content.Y, Width: decorationWidth, Height: content.Height}, firstRow)
+ }
canvas.Clip(gfx.Rect{X: content.X, Y: content.Y, Width: content.Width, Height: content.Height})
paint.markCursor = paint.firstMark(firstRow)
for index := firstRow; index < len(editor.rows); index++ {
@@ -547,6 +574,17 @@ func (editor *CodeEditor) Paint(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.
}
paint.row(index, y)
}
+ if paint.deferOverlays {
+ decorationPaint := codeDecorationPaint{canvas: canvas, editor: editor, size: size, cellWidth: cellWidth, lineHeight: lineHeight, face: snapshot.MonoFace}
+ snapshot.Decorations.codeEditorIndicators(decorationPaint, firstRow)
+ for index := firstRow; index < len(editor.rows); index++ {
+ y := content.Y + float32(index)*lineHeight - editor.scrollY
+ if y >= content.Y+content.Height {
+ break
+ }
+ paint.overlays(index, y)
+ }
+ }
canvas.Unclip()
canvas.Unclip()
@@ -565,6 +603,8 @@ func (editor *CodeEditor) Paint(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.
canvas.HitWithOptions(snapshot.ID, bounds, snapshot.Label, options)
}
if markerLane > 0 && len(snapshot.GutterMarkers) != 0 {
+ canvas.Clip(bounds)
+ canvas.Clip(gfx.Rect{X: markerX, Y: content.Y, Width: markerLane, Height: content.Height})
markerIndex := 0
if firstRow < len(editor.rows) {
firstLine := int(editor.rows[firstRow].line)
@@ -595,9 +635,15 @@ func (editor *CodeEditor) Paint(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.
canvas.HitWithOptions(marker.ID, gfx.Rect{X: markerX, Y: y, Width: markerLane, Height: lineHeight}, label, gfx.HitOptions{Role: gfx.RoleButton, Disabled: snapshot.Disabled})
}
}
+ canvas.Unclip()
+ canvas.Unclip()
}
if foldLane > 0 && len(snapshot.FoldMarkers) != 0 {
- canvas.Clip(gfx.Rect{X: foldX, Y: content.Y, Width: foldLane, Height: content.Height})
+ foldClip := gfx.Rect{X: foldX, Y: content.Y, Width: foldLane, Height: content.Height}
+ if decorationWidth > 0 {
+ foldClip.Width = min(foldClip.Width, max(0, bounds.X+bounds.Width-foldX))
+ }
+ canvas.Clip(foldClip)
markerIndex := 0
if firstRow < len(editor.rows) {
firstLine := int(editor.rows[firstRow].line)
@@ -710,17 +756,17 @@ func (editor *CodeEditor) Pointer(event gfx.PointerEvent) gfx.EventResult {
// codePaint is what painting the rows of one frame shares.
type codePaint struct {
canvas *gfx.Canvas
- theme gfx.Theme
editor *CodeEditor
value string
size, cellWidth, cellHeight, lineHeight float32
foreground gfx.Color
+ background, muted, emphasis gfx.Color
selectionBackground, selectionForeground gfx.Color
selectionStart, selectionEnd int
selectionRanges []text.Span
compositionStart, compositionEnd int
- caret, caretRow, caretColumn int
+ caretRow, caretColumn int
caretCursor int
showCaret bool
caretWidth float32
@@ -744,6 +790,7 @@ type codePaint struct {
eolLabel string
eolLabels []string
invisibleColor gfx.Color
+ deferOverlays bool
}
// firstMark is the index of the first mark that may reach the row at index.
@@ -766,9 +813,9 @@ func (paint *codePaint) firstMark(index int) int {
func (paint *codePaint) lineNumber(row codeRow, y, left, gutter float32, current bool) {
number := paint.editor.numbers.text(int(row.line))
- color := paint.theme.MutedForeground
+ color := paint.muted
if current {
- color = paint.theme.Foreground
+ color = paint.emphasis
}
if paint.editor.disabled {
color.Alpha *= 0.5
@@ -904,7 +951,7 @@ func (paint *codePaint) row(index int, y float32) {
fill(&marks, start, end, 0, color)
}
if paint.bracketsOK {
- outline := paint.theme.Foreground
+ outline := paint.emphasis
outline.Alpha *= 0.22
for _, at := range paint.brackets {
if at >= rowStart && at < rowEnd {
@@ -945,7 +992,7 @@ func (paint *codePaint) row(index int, y float32) {
spec := gridRunSpec{
tabWidth: editor.tabWidth, firstColumn: paint.firstColumn, lastColumn: paint.lastColumn,
representations: editor.reps, representationColor: paint.invisibleColor,
- foreground: paint.foreground, background: paint.theme.Background, disabled: editor.disabled,
+ foreground: paint.foreground, background: paint.background, disabled: editor.disabled,
highlight: highlight, highlightBase: rowStart - int(row.lineStart),
selectionStart: paint.selectionStart - rowStart, selectionEnd: paint.selectionEnd - rowStart,
selectionRanges: paint.selectionRanges, selectionBase: rowStart,
@@ -975,6 +1022,16 @@ func (paint *codePaint) row(index int, y float32) {
}, gfx.TextStyle{Size: paint.size * 0.75, Color: paint.invisibleColor, Mono: true, MonoFace: paint.face})
}
+ if !paint.deferOverlays {
+ paint.overlays(index, y)
+ }
+}
+
+func (paint *codePaint) overlays(index int, y float32) {
+ editor, canvas := paint.editor, paint.canvas
+ row := editor.rows[index]
+ rowStart, rowEnd := int(row.start), int(row.end)
+ left := editor.content.X - editor.scrollX
if paint.compositionEnd > paint.compositionStart && paint.compositionStart <= rowEnd && paint.compositionEnd >= rowStart {
walker := columnWalker{editor: editor, row: row, at: rowStart}
first, last := walker.column(max(paint.compositionStart, rowStart)), walker.column(min(paint.compositionEnd, rowEnd))
@@ -983,7 +1040,7 @@ func (paint *codePaint) row(index int, y float32) {
}
}
- if index == paint.caretRow {
+ if index == paint.caretRow && editor.content.Width > 0 {
x := left + float32(paint.caretColumn)*paint.cellWidth
if x >= editor.content.X-1 && x <= editor.content.X+editor.content.Width {
editor.caretRect, editor.caretShown = gfx.Rect{X: x, Y: y, Width: paint.caretWidth, Height: paint.lineHeight}, true
@@ -998,7 +1055,7 @@ func (paint *codePaint) row(index int, y float32) {
for paint.caretCursor < len(editor.extraCarets) && editor.extraCarets[paint.caretCursor].row == index {
column := editor.extraCarets[paint.caretCursor].column
x := left + float32(column)*paint.cellWidth
- if paint.showCaret && x >= editor.content.X-1 && x <= editor.content.X+editor.content.Width {
+ if paint.showCaret && editor.content.Width > 0 && x >= editor.content.X-1 && x <= editor.content.X+editor.content.Width {
canvas.Fill(gfx.Rect{X: x, Y: y + (paint.lineHeight-paint.cellHeight)/2, Width: paint.caretWidth, Height: paint.cellHeight}, paint.caretColor)
}
paint.caretCursor++
diff --git a/cmd/viva/templates/code_editor_decorations.go.txt b/cmd/viva/templates/code_editor_decorations.go.txt
new file mode 100644
index 000000000..956b39d6e
--- /dev/null
+++ b/cmd/viva/templates/code_editor_decorations.go.txt
@@ -0,0 +1,264 @@
+package {{PACKAGE}}
+
+import (
+ "math"
+ "sort"
+ "unicode/utf8"
+
+ "github.com/vivaui/viva/gfx"
+ "github.com/vivaui/viva/text"
+)
+
+// CodeEditorDecoration is the optional drawing extension of a CodeEditor.
+// Set it to *CodeEditorDecorations; its private methods keep layout in the
+// framework and let clients without decorations omit their drawing code.
+// A nil *CodeEditorDecorations draws nothing; other embedded wrappers are not
+// part of this interface's supported API.
+type CodeEditorDecoration interface {
+ codeEditorGutterWidth() float32
+ codeEditorHasIndicators() bool
+ codeEditorGutter(codeDecorationPaint, gfx.Rect, int)
+ codeEditorIndicators(codeDecorationPaint, int)
+}
+
+// Pass only existing editor/canvas state by value across the optional dispatch.
+// Passing *codePaint would make every paint escape, including undecorated ones.
+type codeDecorationPaint struct {
+ canvas *gfx.Canvas
+ editor *CodeEditor
+ size, cellWidth, lineHeight float32
+ face gfx.MonoFace
+}
+
+// CodeEditorDecorations adds caller-owned gutter bars and byte indicators.
+// Buffers stay immutable for Paint; the editor does not retain them.
+type CodeEditorDecorations struct {
+ // GutterWidth reserves a leading lane in logical pixels, even without bars.
+ // Nonpositive or nonfinite widths omit the lane. Existing gutter lanes remain.
+ GutterWidth float32
+ // GutterBackground is independent of the current-line highlight.
+ GutterBackground gfx.Color
+ // GutterBars are sorted by logical line; same-line bars paint in caller order.
+ GutterBars []CodeEditorGutterBar
+ // IndicatorLayers paint in caller order, above text and below carets.
+ IndicatorLayers []CodeEditorIndicatorLayer
+}
+
+// CodeEditorGutterBar paints a centered bar on every visible row of Line.
+// Joins omit the end caps toward adjacent logical lines; wrapped rows connect.
+type CodeEditorGutterBar struct {
+ Line int
+ Fill, Stroke gfx.Color
+ JoinBefore, JoinAfter bool
+}
+
+// CodeEditorIndicatorStyle chooses an underline or a point at a byte position.
+type CodeEditorIndicatorStyle uint8
+
+const (
+ // CodeEditorUnderline paints a square two-pixel strip below a nonempty span.
+ CodeEditorUnderline CodeEditorIndicatorStyle = iota
+ // CodeEditorPointBelow paints an upward-pointing triangle below an empty span.
+ CodeEditorPointBelow
+ // CodeEditorPointAbove paints a downward-pointing triangle above an empty span.
+ CodeEditorPointAbove
+)
+
+// CodeEditorIndicatorLayer paints sorted disjoint UTF-8 byte ranges of Value.
+// Point styles require strictly increasing empty spans. Invalid styles or ranges
+// reject the whole layer without normalizing or mutating its caller's buffer.
+type CodeEditorIndicatorLayer struct {
+ Spans []text.Span
+ Color gfx.Color
+ Style CodeEditorIndicatorStyle
+}
+
+func (decorations *CodeEditorDecorations) codeEditorGutterWidth() float32 {
+ if decorations != nil && decorations.GutterWidth > 0 && decorations.GutterWidth <= math.MaxFloat32 {
+ return decorations.GutterWidth
+ }
+ return 0
+}
+
+func (decorations *CodeEditorDecorations) codeEditorHasIndicators() bool {
+ return decorations != nil && len(decorations.IndicatorLayers) != 0
+}
+
+func (decorations *CodeEditorDecorations) codeEditorGutter(paint codeDecorationPaint, lane gfx.Rect, firstRow int) {
+ if decorations != nil {
+ paint.gutterDecorations(decorations, lane, firstRow)
+ }
+}
+
+func (decorations *CodeEditorDecorations) codeEditorIndicators(paint codeDecorationPaint, firstRow int) {
+ if decorations != nil {
+ paint.indicatorLayers(decorations.IndicatorLayers, firstRow)
+ }
+}
+
+func decorationColor(color gfx.Color, disabled bool) gfx.Color {
+ if disabled {
+ color.Alpha *= 0.5
+ }
+ return color
+}
+
+func (paint *codeDecorationPaint) gutterDecorations(decorations *CodeEditorDecorations, lane gfx.Rect, firstRow int) {
+ canvas, editor := paint.canvas, paint.editor
+ canvas.Clip(lane)
+ defer canvas.Unclip()
+ canvas.Fill(lane, decorationColor(decorations.GutterBackground, editor.disabled))
+ bars := decorations.GutterBars
+ previous := -1
+ for _, bar := range bars {
+ if bar.Line < previous || bar.Line < 0 || bar.Line >= editor.lineCount {
+ return
+ }
+ previous = bar.Line
+ }
+ if firstRow >= len(editor.rows) || len(bars) == 0 {
+ return
+ }
+ barWidth := float32(math.Ceil(float64(lane.Width / 3)))
+ x := float32(math.Floor(float64(lane.X+lane.Width/2))) - float32(math.Floor(float64(barWidth/2)))
+ first := sort.Search(len(bars), func(index int) bool { return bars[index].Line >= int(editor.rows[firstRow].line) })
+ for index := firstRow; index < len(editor.rows); index++ {
+ y := editor.content.Y + float32(index)*paint.lineHeight - editor.scrollY
+ if y >= lane.Y+lane.Height {
+ break
+ }
+ row := editor.rows[index]
+ for first < len(bars) && bars[first].Line < int(row.line) {
+ first++
+ }
+ for at := first; at < len(bars) && bars[at].Line == int(row.line); at++ {
+ bar := bars[at]
+ before := !editor.firstOfLine(index) || bar.JoinBefore
+ after := editor.softWrapped(index) || bar.JoinAfter
+ paint.gutterBar(gfx.Rect{X: x, Y: y, Width: barWidth, Height: paint.lineHeight}, bar, before, after)
+ }
+ }
+}
+
+func (paint *codeDecorationPaint) gutterBar(bounds gfx.Rect, bar CodeEditorGutterBar, before, after bool) {
+ canvas := paint.canvas
+ fill := decorationColor(bar.Fill, paint.editor.disabled)
+ stroke := decorationColor(bar.Stroke, paint.editor.disabled)
+ if fill == stroke || stroke.Alpha == 0 {
+ canvas.Fill(bounds, fill)
+ return
+ }
+ // Keep fill and outline disjoint so translucent bars have uniform opacity.
+ border := min(float32(1), bounds.Width/2, bounds.Height/2)
+ top, bottom := float32(0), float32(0)
+ if !before {
+ top = border
+ }
+ if !after {
+ bottom = border
+ }
+ canvas.Fill(gfx.Rect{X: bounds.X, Y: bounds.Y, Width: border, Height: bounds.Height}, stroke)
+ canvas.Fill(gfx.Rect{X: bounds.X + bounds.Width - border, Y: bounds.Y, Width: border, Height: bounds.Height}, stroke)
+ inner := gfx.Rect{X: bounds.X + border, Y: bounds.Y + top, Width: max(0, bounds.Width-2*border), Height: max(0, bounds.Height-top-bottom)}
+ canvas.Fill(inner, fill)
+ if top > 0 {
+ canvas.Fill(gfx.Rect{X: inner.X, Y: bounds.Y, Width: inner.Width, Height: top}, stroke)
+ }
+ if bottom > 0 {
+ canvas.Fill(gfx.Rect{X: inner.X, Y: bounds.Y + bounds.Height - bottom, Width: inner.Width, Height: bottom}, stroke)
+ }
+}
+
+func validIndicatorLayer(value string, layer CodeEditorIndicatorLayer) bool {
+ if layer.Style > CodeEditorPointAbove {
+ return false
+ }
+ point := layer.Style != CodeEditorUnderline
+ lastStart, lastEnd := -1, -1
+ for _, span := range layer.Spans {
+ if span.Start < 0 || span.End < span.Start || span.End > len(value) ||
+ span.Start < len(value) && !utf8.RuneStart(value[span.Start]) ||
+ span.End < len(value) && !utf8.RuneStart(value[span.End]) {
+ return false
+ }
+ if point {
+ if span.Start != span.End || span.Start <= lastStart {
+ return false
+ }
+ } else if span.Start == span.End || span.Start < lastEnd {
+ return false
+ }
+ lastStart, lastEnd = span.Start, span.End
+ }
+ return true
+}
+
+func (paint *codeDecorationPaint) indicatorLayers(layers []CodeEditorIndicatorLayer, firstRow int) {
+ editor := paint.editor
+ baseline := paint.canvas.MonoBaseline(paint.size, paint.face, paint.lineHeight)
+ pointHeight := float32(3)
+ if baseline > 0 {
+ pointHeight = float32(math.Floor(float64(max(float32(3), paint.lineHeight-baseline))))
+ }
+ for _, layer := range layers {
+ if layer.Color.Alpha == 0 || !validIndicatorLayer(editor.text, layer) {
+ continue
+ }
+ color := decorationColor(layer.Color, editor.disabled)
+ point := layer.Style != CodeEditorUnderline
+ for index := firstRow; index < len(editor.rows); index++ {
+ y := editor.content.Y + float32(index)*paint.lineHeight - editor.scrollY
+ if y >= editor.content.Y+editor.content.Height {
+ break
+ }
+ row := editor.rows[index]
+ start, end := int(row.start), int(row.end)
+ first := sort.Search(len(layer.Spans), func(at int) bool {
+ if point {
+ return layer.Spans[at].Start >= start
+ }
+ return layer.Spans[at].End > start
+ })
+ walker := columnWalker{editor: editor, row: row, at: start}
+ left := editor.content.X - editor.scrollX
+ for _, span := range layer.Spans[first:] {
+ if span.Start > end || span.Start == end && (!point || editor.softWrapped(index)) {
+ break
+ }
+ if point {
+ x := left + float32(walker.column(span.Start))*paint.cellWidth
+ bottom := y + paint.lineHeight
+ if baseline > 0 {
+ bottom = y + max(paint.lineHeight, baseline+3)
+ }
+ paint.indicatorPoint(x, y, bottom, pointHeight, color, layer.Style)
+ continue
+ }
+ a, b := max(start, span.Start), min(end, span.End)
+ if a >= b {
+ continue
+ }
+ x0 := left + float32(walker.column(a))*paint.cellWidth + 1
+ x1 := left + float32(walker.column(b))*paint.cellWidth - 1
+ x0, x1 = max(x0, editor.content.X), min(x1, editor.content.X+editor.content.Width)
+ if x1 > x0 {
+ paint.canvas.Fill(gfx.Rect{X: x0, Y: y + paint.lineHeight - 2, Width: x1 - x0, Height: 2}, color)
+ }
+ }
+ }
+ }
+}
+
+func (paint *codeDecorationPaint) indicatorPoint(x, top, bottom, height float32, color gfx.Color, style CodeEditorIndicatorStyle) {
+ x = float32(math.Round(float64(x))) + 0.5
+ base := float32(math.Ceil(float64(bottom))) + 0.5
+ tip := base - height
+ if style == CodeEditorPointAbove {
+ base = float32(math.Floor(float64(top))) - 0.5
+ tip = base + height
+ }
+ paint.canvas.AppendTriangle(gfx.Triangle{
+ Points: [3]gfx.Point{{X: x - height, Y: base}, {X: x + height, Y: base}, {X: x, Y: tip}},
+ Color: color, EdgeMask: 7,
+ })
+}
diff --git a/components/code_editor.go b/components/code_editor.go
index d4ed045cf..e497dcc58 100644
--- a/components/code_editor.go
+++ b/components/code_editor.go
@@ -198,6 +198,9 @@ type CodeEditorSnapshot struct {
// component's formulas; a non-nil value uses its widths as given, and its
// Inset also replaces the theme's text inset.
Gutter *CodeEditorGutter
+ // Decorations supplies optional gutter bars and byte indicators. Set it to
+ // *CodeEditorDecorations, or nil to keep default drawing.
+ Decorations CodeEditorDecoration
}
// CodeEditor is the view of a code editor, held by the application next to its
@@ -375,16 +378,23 @@ func (editor *CodeEditor) Paint(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.
numberLane = float32(max(decimalDigits(lines), 2)+2) * cellWidth
}
}
- gutter := foldLane + markerLane + bookmarkLane + numberLane
+ decorationWidth := float32(0)
+ hasIndicators := false
+ if decorations := snapshot.Decorations; decorations != nil {
+ decorationWidth = decorations.codeEditorGutterWidth()
+ hasIndicators = decorations.codeEditorHasIndicators()
+ }
+ gutter := decorationWidth + foldLane + markerLane + bookmarkLane + numberLane
laneStart := bounds.X + inset
- foldX, markerX, bookmarkX, numberX := laneStart, float32(0), float32(0), float32(0)
+ lanes := laneStart + decorationWidth
+ foldX, markerX, bookmarkX, numberX := lanes, float32(0), float32(0), float32(0)
if foldLast {
- markerX = laneStart
+ markerX = lanes
bookmarkX = markerX + markerLane
numberX = bookmarkX + bookmarkLane
foldX = numberX + numberLane
} else {
- markerX = laneStart + foldLane
+ markerX = lanes + foldLane
bookmarkX = markerX + markerLane
numberX = bookmarkX + bookmarkLane
}
@@ -458,13 +468,14 @@ func (editor *CodeEditor) Paint(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.
selectionForeground.Alpha *= 0.5
}
paint := codePaint{
- canvas: canvas, theme: theme, editor: editor, value: value, size: size,
+ canvas: canvas, editor: editor, value: value, size: size,
+ background: theme.Background, muted: theme.MutedForeground, emphasis: theme.Foreground,
cellWidth: cellWidth, cellHeight: cellHeight, lineHeight: lineHeight,
foreground: foreground, selectionBackground: selectionBackground, selectionForeground: selectionForeground,
selectionStart: selectionStart, selectionEnd: selectionEnd,
selectionRanges: selectionRanges,
compositionStart: compositionStart, compositionEnd: compositionEnd,
- caret: caret, caretRow: caretRow, caretColumn: caretColumn,
+ caretRow: caretRow, caretColumn: caretColumn,
showCaret: showCaret,
caretWidth: editorCaretWidth(snapshot.CaretWidth), caretColor: caretColor(snapshot.CaretColor, foreground),
lineNumberPadding: lineNumberPadding,
@@ -473,6 +484,7 @@ func (editor *CodeEditor) Paint(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.
markLayers: snapshot.MarkLayers,
showWhitespace: snapshot.ShowWhitespace, showIndentGuides: snapshot.ShowIndentGuides, showEOL: snapshot.ShowEOL, showWrapSymbol: showWrapSymbol, eolLabel: snapshot.EOLLabel, eolLabels: snapshot.EOLLabels,
invisibleColor: snapshot.InvisibleColor,
+ deferOverlays: hasIndicators,
}
if paint.invisibleColor.Alpha == 0 {
paint.invisibleColor = theme.MutedForeground
@@ -487,6 +499,11 @@ func (editor *CodeEditor) Paint(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.
firstRow := int(editor.scrollY / lineHeight)
inner := gfx.Rect{X: bounds.X + 1, Y: content.Y, Width: content.X + content.Width - bounds.X - 1, Height: content.Height}
+ if decorationWidth > 0 {
+ // An oversized reserved lane may move content beyond this editor; its
+ // visible clip must still stop before a neighboring pane.
+ inner.Width = min(inner.Width, max(0, bounds.X+bounds.Width-inner.X))
+ }
canvas.Clip(inner)
if placeholder {
style := gfx.TextStyle{Size: size, Color: theme.MutedForeground, Mono: true, MonoFace: snapshot.MonoFace}
@@ -518,7 +535,13 @@ func (editor *CodeEditor) Paint(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.
if int(row.line) == currentLine {
tint := theme.Foreground
tint.Alpha *= 0.05
- canvas.Fill(gfx.Rect{X: inner.X, Y: y, Width: inner.Width, Height: lineHeight}, tint)
+ if decorationWidth > 0 {
+ canvas.Fill(gfx.Rect{X: inner.X, Y: y, Width: max(0, laneStart-inner.X), Height: lineHeight}, tint)
+ x := laneStart + decorationWidth
+ canvas.Fill(gfx.Rect{X: x, Y: y, Width: max(0, inner.X+inner.Width-x), Height: lineHeight}, tint)
+ } else {
+ canvas.Fill(gfx.Rect{X: inner.X, Y: y, Width: inner.Width, Height: lineHeight}, tint)
+ }
}
if markerLane > 0 && editor.firstOfLine(index) {
for markerIndex < len(snapshot.GutterMarkers) && snapshot.GutterMarkers[markerIndex].Line < int(row.line) {
@@ -538,6 +561,10 @@ func (editor *CodeEditor) Paint(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.
paint.lineNumber(row, y, numberX, numberLane, int(row.line) == int(editor.rows[caretRow].line))
}
}
+ if decorationWidth > 0 {
+ decorationPaint := codeDecorationPaint{canvas: canvas, editor: editor, size: size, cellWidth: cellWidth, lineHeight: lineHeight, face: snapshot.MonoFace}
+ snapshot.Decorations.codeEditorGutter(decorationPaint, gfx.Rect{X: laneStart, Y: content.Y, Width: decorationWidth, Height: content.Height}, firstRow)
+ }
canvas.Clip(gfx.Rect{X: content.X, Y: content.Y, Width: content.Width, Height: content.Height})
paint.markCursor = paint.firstMark(firstRow)
for index := firstRow; index < len(editor.rows); index++ {
@@ -547,6 +574,17 @@ func (editor *CodeEditor) Paint(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.
}
paint.row(index, y)
}
+ if paint.deferOverlays {
+ decorationPaint := codeDecorationPaint{canvas: canvas, editor: editor, size: size, cellWidth: cellWidth, lineHeight: lineHeight, face: snapshot.MonoFace}
+ snapshot.Decorations.codeEditorIndicators(decorationPaint, firstRow)
+ for index := firstRow; index < len(editor.rows); index++ {
+ y := content.Y + float32(index)*lineHeight - editor.scrollY
+ if y >= content.Y+content.Height {
+ break
+ }
+ paint.overlays(index, y)
+ }
+ }
canvas.Unclip()
canvas.Unclip()
@@ -565,6 +603,8 @@ func (editor *CodeEditor) Paint(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.
canvas.HitWithOptions(snapshot.ID, bounds, snapshot.Label, options)
}
if markerLane > 0 && len(snapshot.GutterMarkers) != 0 {
+ canvas.Clip(bounds)
+ canvas.Clip(gfx.Rect{X: markerX, Y: content.Y, Width: markerLane, Height: content.Height})
markerIndex := 0
if firstRow < len(editor.rows) {
firstLine := int(editor.rows[firstRow].line)
@@ -595,9 +635,15 @@ func (editor *CodeEditor) Paint(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.
canvas.HitWithOptions(marker.ID, gfx.Rect{X: markerX, Y: y, Width: markerLane, Height: lineHeight}, label, gfx.HitOptions{Role: gfx.RoleButton, Disabled: snapshot.Disabled})
}
}
+ canvas.Unclip()
+ canvas.Unclip()
}
if foldLane > 0 && len(snapshot.FoldMarkers) != 0 {
- canvas.Clip(gfx.Rect{X: foldX, Y: content.Y, Width: foldLane, Height: content.Height})
+ foldClip := gfx.Rect{X: foldX, Y: content.Y, Width: foldLane, Height: content.Height}
+ if decorationWidth > 0 {
+ foldClip.Width = min(foldClip.Width, max(0, bounds.X+bounds.Width-foldX))
+ }
+ canvas.Clip(foldClip)
markerIndex := 0
if firstRow < len(editor.rows) {
firstLine := int(editor.rows[firstRow].line)
@@ -710,17 +756,17 @@ func (editor *CodeEditor) Pointer(event gfx.PointerEvent) gfx.EventResult {
// codePaint is what painting the rows of one frame shares.
type codePaint struct {
canvas *gfx.Canvas
- theme gfx.Theme
editor *CodeEditor
value string
size, cellWidth, cellHeight, lineHeight float32
foreground gfx.Color
+ background, muted, emphasis gfx.Color
selectionBackground, selectionForeground gfx.Color
selectionStart, selectionEnd int
selectionRanges []text.Span
compositionStart, compositionEnd int
- caret, caretRow, caretColumn int
+ caretRow, caretColumn int
caretCursor int
showCaret bool
caretWidth float32
@@ -744,6 +790,7 @@ type codePaint struct {
eolLabel string
eolLabels []string
invisibleColor gfx.Color
+ deferOverlays bool
}
// firstMark is the index of the first mark that may reach the row at index.
@@ -766,9 +813,9 @@ func (paint *codePaint) firstMark(index int) int {
func (paint *codePaint) lineNumber(row codeRow, y, left, gutter float32, current bool) {
number := paint.editor.numbers.text(int(row.line))
- color := paint.theme.MutedForeground
+ color := paint.muted
if current {
- color = paint.theme.Foreground
+ color = paint.emphasis
}
if paint.editor.disabled {
color.Alpha *= 0.5
@@ -904,7 +951,7 @@ func (paint *codePaint) row(index int, y float32) {
fill(&marks, start, end, 0, color)
}
if paint.bracketsOK {
- outline := paint.theme.Foreground
+ outline := paint.emphasis
outline.Alpha *= 0.22
for _, at := range paint.brackets {
if at >= rowStart && at < rowEnd {
@@ -945,7 +992,7 @@ func (paint *codePaint) row(index int, y float32) {
spec := gridRunSpec{
tabWidth: editor.tabWidth, firstColumn: paint.firstColumn, lastColumn: paint.lastColumn,
representations: editor.reps, representationColor: paint.invisibleColor,
- foreground: paint.foreground, background: paint.theme.Background, disabled: editor.disabled,
+ foreground: paint.foreground, background: paint.background, disabled: editor.disabled,
highlight: highlight, highlightBase: rowStart - int(row.lineStart),
selectionStart: paint.selectionStart - rowStart, selectionEnd: paint.selectionEnd - rowStart,
selectionRanges: paint.selectionRanges, selectionBase: rowStart,
@@ -975,6 +1022,16 @@ func (paint *codePaint) row(index int, y float32) {
}, gfx.TextStyle{Size: paint.size * 0.75, Color: paint.invisibleColor, Mono: true, MonoFace: paint.face})
}
+ if !paint.deferOverlays {
+ paint.overlays(index, y)
+ }
+}
+
+func (paint *codePaint) overlays(index int, y float32) {
+ editor, canvas := paint.editor, paint.canvas
+ row := editor.rows[index]
+ rowStart, rowEnd := int(row.start), int(row.end)
+ left := editor.content.X - editor.scrollX
if paint.compositionEnd > paint.compositionStart && paint.compositionStart <= rowEnd && paint.compositionEnd >= rowStart {
walker := columnWalker{editor: editor, row: row, at: rowStart}
first, last := walker.column(max(paint.compositionStart, rowStart)), walker.column(min(paint.compositionEnd, rowEnd))
@@ -983,7 +1040,7 @@ func (paint *codePaint) row(index int, y float32) {
}
}
- if index == paint.caretRow {
+ if index == paint.caretRow && editor.content.Width > 0 {
x := left + float32(paint.caretColumn)*paint.cellWidth
if x >= editor.content.X-1 && x <= editor.content.X+editor.content.Width {
editor.caretRect, editor.caretShown = gfx.Rect{X: x, Y: y, Width: paint.caretWidth, Height: paint.lineHeight}, true
@@ -998,7 +1055,7 @@ func (paint *codePaint) row(index int, y float32) {
for paint.caretCursor < len(editor.extraCarets) && editor.extraCarets[paint.caretCursor].row == index {
column := editor.extraCarets[paint.caretCursor].column
x := left + float32(column)*paint.cellWidth
- if paint.showCaret && x >= editor.content.X-1 && x <= editor.content.X+editor.content.Width {
+ if paint.showCaret && editor.content.Width > 0 && x >= editor.content.X-1 && x <= editor.content.X+editor.content.Width {
canvas.Fill(gfx.Rect{X: x, Y: y + (paint.lineHeight-paint.cellHeight)/2, Width: paint.caretWidth, Height: paint.cellHeight}, paint.caretColor)
}
paint.caretCursor++
diff --git a/components/code_editor_decorations.go b/components/code_editor_decorations.go
new file mode 100644
index 000000000..b51bad995
--- /dev/null
+++ b/components/code_editor_decorations.go
@@ -0,0 +1,268 @@
+package components
+
+import (
+ "math"
+ "sort"
+ "unicode/utf8"
+
+ "github.com/vivaui/viva/gfx"
+ "github.com/vivaui/viva/text"
+)
+
+// CodeEditorDecoration is the optional drawing extension of a CodeEditor.
+// Set it to *CodeEditorDecorations; its private methods keep layout in the
+// framework and let clients without decorations omit their drawing code.
+// A nil *CodeEditorDecorations draws nothing; other embedded wrappers are not
+// part of this interface's supported API.
+type CodeEditorDecoration interface {
+ codeEditorGutterWidth() float32
+ codeEditorHasIndicators() bool
+ codeEditorGutter(codeDecorationPaint, gfx.Rect, int)
+ codeEditorIndicators(codeDecorationPaint, int)
+}
+
+// Pass only existing editor/canvas state by value across the optional dispatch.
+// Passing *codePaint would make every paint escape, including undecorated ones.
+type codeDecorationPaint struct {
+ canvas *gfx.Canvas
+ editor *CodeEditor
+ size, cellWidth, lineHeight float32
+ face gfx.MonoFace
+}
+
+// CodeEditorDecorations adds caller-owned gutter bars and byte indicators.
+// Buffers stay immutable for Paint; the editor does not retain them. Both are
+// validated in full on every paint, so a long change history costs time per
+// frame rather than per visible row: keep the buffers to what the editor shows.
+type CodeEditorDecorations struct {
+ // GutterWidth reserves a leading lane in logical pixels, even without bars.
+ // Nonpositive or nonfinite widths omit the lane. Existing gutter lanes remain.
+ GutterWidth float32
+ // GutterBackground is independent of the current-line highlight.
+ GutterBackground gfx.Color
+ // GutterBars are sorted by logical line; same-line bars paint in caller order.
+ // An unsorted or out-of-range bar drops the whole set, as an invalid
+ // IndicatorLayer drops its layer.
+ GutterBars []CodeEditorGutterBar
+ // IndicatorLayers paint in caller order, above text and below carets.
+ IndicatorLayers []CodeEditorIndicatorLayer
+}
+
+// CodeEditorGutterBar paints a centered bar on every visible row of Line.
+// Joins omit the end caps toward adjacent logical lines; wrapped rows connect.
+type CodeEditorGutterBar struct {
+ Line int
+ Fill, Stroke gfx.Color
+ JoinBefore, JoinAfter bool
+}
+
+// CodeEditorIndicatorStyle chooses an underline or a point at a byte position.
+type CodeEditorIndicatorStyle uint8
+
+const (
+ // CodeEditorUnderline paints a square two-pixel strip below a nonempty span.
+ CodeEditorUnderline CodeEditorIndicatorStyle = iota
+ // CodeEditorPointBelow paints an upward-pointing triangle below an empty span.
+ CodeEditorPointBelow
+ // CodeEditorPointAbove paints a downward-pointing triangle above an empty span.
+ CodeEditorPointAbove
+)
+
+// CodeEditorIndicatorLayer paints sorted disjoint UTF-8 byte ranges of Value.
+// Point styles require strictly increasing empty spans. Invalid styles or ranges
+// reject the whole layer without normalizing or mutating its caller's buffer.
+type CodeEditorIndicatorLayer struct {
+ Spans []text.Span
+ Color gfx.Color
+ Style CodeEditorIndicatorStyle
+}
+
+func (decorations *CodeEditorDecorations) codeEditorGutterWidth() float32 {
+ if decorations != nil && decorations.GutterWidth > 0 && decorations.GutterWidth <= math.MaxFloat32 {
+ return decorations.GutterWidth
+ }
+ return 0
+}
+
+func (decorations *CodeEditorDecorations) codeEditorHasIndicators() bool {
+ return decorations != nil && len(decorations.IndicatorLayers) != 0
+}
+
+func (decorations *CodeEditorDecorations) codeEditorGutter(paint codeDecorationPaint, lane gfx.Rect, firstRow int) {
+ if decorations != nil {
+ paint.gutterDecorations(decorations, lane, firstRow)
+ }
+}
+
+func (decorations *CodeEditorDecorations) codeEditorIndicators(paint codeDecorationPaint, firstRow int) {
+ if decorations != nil {
+ paint.indicatorLayers(decorations.IndicatorLayers, firstRow)
+ }
+}
+
+func decorationColor(color gfx.Color, disabled bool) gfx.Color {
+ if disabled {
+ color.Alpha *= 0.5
+ }
+ return color
+}
+
+func (paint *codeDecorationPaint) gutterDecorations(decorations *CodeEditorDecorations, lane gfx.Rect, firstRow int) {
+ canvas, editor := paint.canvas, paint.editor
+ canvas.Clip(lane)
+ defer canvas.Unclip()
+ canvas.Fill(lane, decorationColor(decorations.GutterBackground, editor.disabled))
+ bars := decorations.GutterBars
+ previous := -1
+ for _, bar := range bars {
+ if bar.Line < previous || bar.Line < 0 || bar.Line >= editor.lineCount {
+ return
+ }
+ previous = bar.Line
+ }
+ if firstRow >= len(editor.rows) || len(bars) == 0 {
+ return
+ }
+ barWidth := float32(math.Ceil(float64(lane.Width / 3)))
+ x := float32(math.Floor(float64(lane.X+lane.Width/2))) - float32(math.Floor(float64(barWidth/2)))
+ first := sort.Search(len(bars), func(index int) bool { return bars[index].Line >= int(editor.rows[firstRow].line) })
+ for index := firstRow; index < len(editor.rows); index++ {
+ y := editor.content.Y + float32(index)*paint.lineHeight - editor.scrollY
+ if y >= lane.Y+lane.Height {
+ break
+ }
+ row := editor.rows[index]
+ for first < len(bars) && bars[first].Line < int(row.line) {
+ first++
+ }
+ for at := first; at < len(bars) && bars[at].Line == int(row.line); at++ {
+ bar := bars[at]
+ before := !editor.firstOfLine(index) || bar.JoinBefore
+ after := editor.softWrapped(index) || bar.JoinAfter
+ paint.gutterBar(gfx.Rect{X: x, Y: y, Width: barWidth, Height: paint.lineHeight}, bar, before, after)
+ }
+ }
+}
+
+func (paint *codeDecorationPaint) gutterBar(bounds gfx.Rect, bar CodeEditorGutterBar, before, after bool) {
+ canvas := paint.canvas
+ fill := decorationColor(bar.Fill, paint.editor.disabled)
+ stroke := decorationColor(bar.Stroke, paint.editor.disabled)
+ if fill == stroke || stroke.Alpha == 0 {
+ canvas.Fill(bounds, fill)
+ return
+ }
+ // Keep fill and outline disjoint so translucent bars have uniform opacity.
+ border := min(float32(1), bounds.Width/2, bounds.Height/2)
+ top, bottom := float32(0), float32(0)
+ if !before {
+ top = border
+ }
+ if !after {
+ bottom = border
+ }
+ canvas.Fill(gfx.Rect{X: bounds.X, Y: bounds.Y, Width: border, Height: bounds.Height}, stroke)
+ canvas.Fill(gfx.Rect{X: bounds.X + bounds.Width - border, Y: bounds.Y, Width: border, Height: bounds.Height}, stroke)
+ inner := gfx.Rect{X: bounds.X + border, Y: bounds.Y + top, Width: max(0, bounds.Width-2*border), Height: max(0, bounds.Height-top-bottom)}
+ canvas.Fill(inner, fill)
+ if top > 0 {
+ canvas.Fill(gfx.Rect{X: inner.X, Y: bounds.Y, Width: inner.Width, Height: top}, stroke)
+ }
+ if bottom > 0 {
+ canvas.Fill(gfx.Rect{X: inner.X, Y: bounds.Y + bounds.Height - bottom, Width: inner.Width, Height: bottom}, stroke)
+ }
+}
+
+func validIndicatorLayer(value string, layer CodeEditorIndicatorLayer) bool {
+ if layer.Style > CodeEditorPointAbove {
+ return false
+ }
+ point := layer.Style != CodeEditorUnderline
+ lastStart, lastEnd := -1, -1
+ for _, span := range layer.Spans {
+ if span.Start < 0 || span.End < span.Start || span.End > len(value) ||
+ span.Start < len(value) && !utf8.RuneStart(value[span.Start]) ||
+ span.End < len(value) && !utf8.RuneStart(value[span.End]) {
+ return false
+ }
+ if point {
+ if span.Start != span.End || span.Start <= lastStart {
+ return false
+ }
+ } else if span.Start == span.End || span.Start < lastEnd {
+ return false
+ }
+ lastStart, lastEnd = span.Start, span.End
+ }
+ return true
+}
+
+func (paint *codeDecorationPaint) indicatorLayers(layers []CodeEditorIndicatorLayer, firstRow int) {
+ editor := paint.editor
+ baseline := paint.canvas.MonoBaseline(paint.size, paint.face, paint.lineHeight)
+ pointHeight := float32(3)
+ if baseline > 0 {
+ pointHeight = float32(math.Floor(float64(max(float32(3), paint.lineHeight-baseline))))
+ }
+ for _, layer := range layers {
+ if layer.Color.Alpha == 0 || !validIndicatorLayer(editor.text, layer) {
+ continue
+ }
+ color := decorationColor(layer.Color, editor.disabled)
+ point := layer.Style != CodeEditorUnderline
+ for index := firstRow; index < len(editor.rows); index++ {
+ y := editor.content.Y + float32(index)*paint.lineHeight - editor.scrollY
+ if y >= editor.content.Y+editor.content.Height {
+ break
+ }
+ row := editor.rows[index]
+ start, end := int(row.start), int(row.end)
+ first := sort.Search(len(layer.Spans), func(at int) bool {
+ if point {
+ return layer.Spans[at].Start >= start
+ }
+ return layer.Spans[at].End > start
+ })
+ walker := columnWalker{editor: editor, row: row, at: start}
+ left := editor.content.X - editor.scrollX
+ for _, span := range layer.Spans[first:] {
+ if span.Start > end || span.Start == end && (!point || editor.softWrapped(index)) {
+ break
+ }
+ if point {
+ x := left + float32(walker.column(span.Start))*paint.cellWidth
+ bottom := y + paint.lineHeight
+ if baseline > 0 {
+ bottom = y + max(paint.lineHeight, baseline+3)
+ }
+ paint.indicatorPoint(x, y, bottom, pointHeight, color, layer.Style)
+ continue
+ }
+ a, b := max(start, span.Start), min(end, span.End)
+ if a >= b {
+ continue
+ }
+ x0 := left + float32(walker.column(a))*paint.cellWidth + 1
+ x1 := left + float32(walker.column(b))*paint.cellWidth - 1
+ x0, x1 = max(x0, editor.content.X), min(x1, editor.content.X+editor.content.Width)
+ if x1 > x0 {
+ paint.canvas.Fill(gfx.Rect{X: x0, Y: y + paint.lineHeight - 2, Width: x1 - x0, Height: 2}, color)
+ }
+ }
+ }
+ }
+}
+
+func (paint *codeDecorationPaint) indicatorPoint(x, top, bottom, height float32, color gfx.Color, style CodeEditorIndicatorStyle) {
+ x = float32(math.Round(float64(x))) + 0.5
+ base := float32(math.Ceil(float64(bottom))) + 0.5
+ tip := base - height
+ if style == CodeEditorPointAbove {
+ base = float32(math.Floor(float64(top))) - 0.5
+ tip = base + height
+ }
+ paint.canvas.AppendTriangle(gfx.Triangle{
+ Points: [3]gfx.Point{{X: x - height, Y: base}, {X: x + height, Y: base}, {X: x, Y: tip}},
+ Color: color, EdgeMask: 7,
+ })
+}
diff --git a/components/code_editor_decorations_test.go b/components/code_editor_decorations_test.go
new file mode 100644
index 000000000..970308a9d
--- /dev/null
+++ b/components/code_editor_decorations_test.go
@@ -0,0 +1,517 @@
+package components
+
+import (
+ "math"
+ "reflect"
+ "strings"
+ "testing"
+
+ "github.com/vivaui/viva/gfx"
+ "github.com/vivaui/viva/text"
+)
+
+func TestCodeEditorDecorationGutterReservesEmptyLane(t *testing.T) {
+ for _, custom := range []bool{false, true} {
+ fixture := newCodeFixture("one\ntwo\n")
+ fixture.snapshot.LineNumbers, fixture.snapshot.MarkerGutter, fixture.snapshot.FoldGutter = true, true, true
+ inset := fixture.theme.Metrics.TextInsetX()
+ if custom {
+ fixture.snapshot.Gutter = &CodeEditorGutter{Inset: 2, Marker: 12, Bookmark: 6, LineNumberPadding: 3, Fold: 7, FoldLast: true}
+ inset = 2
+ }
+ fixture.paint()
+ before := fixture.editor.content
+ background := gfx.RGB(224, 224, 224)
+ decorations := &CodeEditorDecorations{GutterWidth: 9, GutterBackground: background}
+ fixture.snapshot.Decorations = decorations
+ fixture.snapshot.CurrentLine = true
+ fixture.paint()
+ if !near(fixture.editor.content.X, before.X+9) || !near(fixture.editor.content.Width, before.Width-9) {
+ t.Fatalf("custom=%v: empty lane changed existing lanes: %+v -> %+v", custom, before, fixture.editor.content)
+ }
+ lane := gfx.Rect{X: fixture.bounds.X + inset, Y: before.Y, Width: 9, Height: before.Height}
+ if fills := fixture.fills(background); len(fills) != 1 || fills[0] != lane {
+ t.Fatalf("custom=%v: empty background = %+v, want %+v", custom, fills, lane)
+ }
+ tint := fixture.theme.Foreground
+ tint.Alpha *= 0.05
+ for _, rect := range fixture.fills(tint) {
+ if rect.X < lane.X+lane.Width && rect.X+rect.Width > lane.X {
+ t.Fatalf("current-line tint covers the reserved background: %+v", rect)
+ }
+ }
+ decorations.GutterBars = []CodeEditorGutterBar{{Line: 0, Fill: gfx.RGB(255, 128, 0), Stroke: gfx.RGB(255, 128, 0)}}
+ fixture.paint()
+ withBar := fixture.editor.content
+ decorations.GutterBars = nil
+ fixture.paint()
+ if fixture.editor.content != withBar {
+ t.Fatal("adding or removing history shifted the text")
+ }
+ }
+}
+
+func TestCodeEditorDecorationBarsFollowWrappedAndVisibleRows(t *testing.T) {
+ fixture := newCodeFixture("abcdefghijklmnop\nhidden\nlast\n")
+ fixture.bounds.Width = fixture.widthFor(6)
+ fixture.snapshot.Wrap = true
+ fixture.snapshot.FoldedLines = []CodeEditorFoldRange{{Header: 0, LastLine: 1}}
+ orange, green := gfx.RGB(255, 128, 0), gfx.RGB(0, 160, 0)
+ fixture.snapshot.Decorations = &CodeEditorDecorations{
+ GutterWidth: 9,
+ GutterBars: []CodeEditorGutterBar{
+ {Line: 0, Fill: orange, Stroke: orange},
+ {Line: 1, Fill: green, Stroke: green},
+ },
+ }
+ fixture.paint()
+ rows := 0
+ for _, row := range fixture.editor.rows {
+ if row.line == 0 {
+ rows++
+ }
+ }
+ if rows < 2 || len(fixture.fills(orange)) != rows || len(fixture.fills(green)) != 0 {
+ t.Fatalf("bars do not follow visible wraps: rows=%d orange=%v green=%v", rows, fixture.fills(orange), fixture.fills(green))
+ }
+ for _, bar := range fixture.fills(orange) {
+ if !near(bar.Width, 3) || bar.X+bar.Width >= fixture.editor.content.X {
+ t.Fatalf("bar did not stay centered in its 9px lane: %+v", bar)
+ }
+ }
+ _, _, height := fixture.cell()
+ fixture.bounds.Height = 3*height + 2*codeEditorPadY
+ fixture.editor.scrollY = height
+ fixture.paint()
+ if fills := fixture.fills(orange); len(fills) == 0 || len(fills) >= rows {
+ t.Fatalf("scroll did not restrict decorated wraps: %+v", fills)
+ }
+}
+
+func TestCodeEditorIndicatorSpansUseTextGeometry(t *testing.T) {
+ fixture := newCodeFixture("\t\u732bab\nlast")
+ orange, green := gfx.RGB(255, 128, 0), gfx.RGB(0, 160, 0)
+ fixture.snapshot.Decorations = &CodeEditorDecorations{IndicatorLayers: []CodeEditorIndicatorLayer{
+ {Spans: []text.Span{{Start: 1, End: 4}}, Color: orange, Style: CodeEditorUnderline},
+ {Spans: []text.Span{{Start: 4, End: 4}}, Color: green, Style: CodeEditorPointBelow},
+ }}
+ fixture.paint()
+ cell, _, line := fixture.cell()
+ fills := fixture.fills(orange)
+ if len(fills) != 1 || !near(fills[0].X, fixture.editor.content.X+4*cell+1) || !near(fills[0].Width, 2*cell-2) || !near(fills[0].Y, fixture.editor.content.Y+line-2) || fills[0].Height != 2 {
+ t.Fatalf("Unicode/tab underline = %+v", fills)
+ }
+ points := decorationTriangles(fixture, green)
+ if len(points) != 1 || !near(points[0].Points[2].X, float32(math.Round(float64(fixture.editor.content.X+6*cell)))+0.5) || points[0].Points[2].Y >= points[0].Points[0].Y {
+ t.Fatalf("deletion is not anchored at its byte position: %+v", points)
+ }
+ if fixture.snapshot.Value != "\t\u732bab\nlast" || fixture.snapshot.Caret != 0 {
+ t.Fatal("decorations mutated the source or caret")
+ }
+}
+
+func decorationTriangles(fixture *codeFixture, color gfx.Color) []gfx.Triangle {
+ var result []gfx.Triangle
+ for _, triangle := range fixture.canvas.Triangles() {
+ if triangle.Color == color {
+ result = append(result, triangle)
+ }
+ }
+ return result
+}
+
+func TestCodeEditorIndicatorPointsIgnoreCaretAffinityAndHiddenLines(t *testing.T) {
+ fixture := newCodeFixture("abcd\nhidden\nlast\n")
+ fixture.bounds.Width = fixture.widthFor(2)
+ fixture.bounds.Height = 600
+ fixture.snapshot.Wrap = true
+ fixture.snapshot.Caret = 2
+ fixture.snapshot.FoldedLines = []CodeEditorFoldRange{{Header: 0, LastLine: 1}}
+ color := gfx.RGB(200, 40, 100)
+ fixture.snapshot.Decorations = &CodeEditorDecorations{IndicatorLayers: []CodeEditorIndicatorLayer{
+ {Spans: []text.Span{{Start: 2, End: 2}, {Start: 6, End: 6}, {Start: 17, End: 17}}, Color: color, Style: CodeEditorPointAbove},
+ }}
+ fixture.paint()
+ before := decorationTriangles(fixture, color)
+ if len(before) != 2 {
+ t.Fatalf("expected a downstream wrap point and final EOF point, not a hidden-line point: %+v", before)
+ }
+ _, _, height := fixture.cell()
+ if !near(before[0].Points[0].Y, fixture.editor.content.Y+height-0.5) {
+ t.Fatalf("soft-wrap point did not belong downstream: %+v", before[0])
+ }
+ fixture.editor.setUpstream(2, true)
+ fixture.paint()
+ after := decorationTriangles(fixture, color)
+ for index := range before {
+ if before[index].Points != after[index].Points {
+ t.Fatalf("caret affinity moved a point: %+v -> %+v", before[index], after[index])
+ }
+ }
+}
+
+func TestCodeEditorMalformedIndicatorLayerIsRejected(t *testing.T) {
+ color := gfx.RGB(200, 50, 80)
+ for _, layer := range []CodeEditorIndicatorLayer{
+ {Spans: []text.Span{{Start: -1, End: 1}}, Style: CodeEditorUnderline},
+ {Spans: []text.Span{{Start: 2, End: 1}}, Style: CodeEditorUnderline},
+ {Spans: []text.Span{{Start: 0, End: 99}}, Style: CodeEditorUnderline},
+ {Spans: []text.Span{{Start: 1, End: 3}}, Style: CodeEditorUnderline},
+ {Spans: []text.Span{{Start: 0, End: 0}}, Style: CodeEditorUnderline},
+ {Spans: []text.Span{{Start: 0, End: 3}}, Style: CodeEditorPointAbove},
+ {Spans: []text.Span{{Start: 3, End: 4}, {Start: 0, End: 3}}, Style: CodeEditorUnderline},
+ {Spans: []text.Span{{Start: 0, End: 4}, {Start: 3, End: 4}}, Style: CodeEditorUnderline},
+ {Spans: []text.Span{{Start: 0, End: 0}, {Start: 0, End: 0}}, Style: CodeEditorPointBelow},
+ {Spans: []text.Span{{Start: 0, End: 3}}, Style: CodeEditorIndicatorStyle(255)},
+ } {
+ fixture := newCodeFixture("\u732ba")
+ layer.Color = color
+ before := append([]text.Span(nil), layer.Spans...)
+ fixture.snapshot.Decorations = &CodeEditorDecorations{IndicatorLayers: []CodeEditorIndicatorLayer{layer}}
+ fixture.paint()
+ if len(fixture.fills(color)) != 0 || len(decorationTriangles(fixture, color)) != 0 {
+ t.Fatalf("painted malformed layer: %+v", layer)
+ }
+ if !reflect.DeepEqual(layer.Spans, before) {
+ t.Fatal("validation modified the caller's spans")
+ }
+ }
+}
+
+func TestCodeEditorDecorationOrderKeepsCaretsAboveCrossRowPoints(t *testing.T) {
+ fixture := newCodeFixture("one\ntwo")
+ first, second, caret := gfx.RGB(0, 160, 0), gfx.RGB(255, 128, 0), gfx.RGB(1, 30, 200)
+ fixture.snapshot.Caret, fixture.snapshot.CaretColor = 4, caret
+ fixture.snapshot.CompositionStart, fixture.snapshot.CompositionEnd = 0, 2
+ fixture.snapshot.Decorations = &CodeEditorDecorations{IndicatorLayers: []CodeEditorIndicatorLayer{
+ {Spans: []text.Span{{Start: 3, End: 3}}, Color: first, Style: CodeEditorPointBelow},
+ {Spans: []text.Span{{Start: 4, End: 4}}, Color: second, Style: CodeEditorPointAbove},
+ }}
+ fixture.paint()
+ var lastText, firstPoint, secondPoint, compositionOrder, caretOrder uint32
+ for _, label := range fixture.canvas.Texts() {
+ lastText = max(lastText, label.Order)
+ }
+ for _, triangle := range fixture.canvas.Triangles() {
+ if triangle.Color == first {
+ firstPoint = triangle.Order
+ }
+ if triangle.Color == second {
+ secondPoint = triangle.Order
+ }
+ }
+ for _, rect := range fixture.canvas.Rectangles() {
+ if rect.Color == caret {
+ caretOrder = rect.Order
+ }
+ if rect.Color == fixture.theme.Foreground && rect.Bounds.Height == 1 {
+ compositionOrder = rect.Order
+ }
+ }
+ if firstPoint <= lastText || secondPoint <= firstPoint || compositionOrder <= secondPoint || caretOrder <= secondPoint {
+ t.Fatalf("base text / indicator layers / composition / caret order = %d / %d,%d / %d / %d", lastText, firstPoint, secondPoint, compositionOrder, caretOrder)
+ }
+}
+
+func TestCodeEditorDecorationWidthRejectsNonfiniteValues(t *testing.T) {
+ for _, width := range []float32{0, -1, float32(math.NaN()), float32(math.Inf(1))} {
+ fixture := newCodeFixture(strings.Repeat("x", 30))
+ fixture.paint()
+ before := fixture.editor.content
+ fixture.snapshot.Decorations = &CodeEditorDecorations{GutterWidth: width}
+ fixture.paint()
+ if fixture.editor.content != before {
+ t.Fatalf("invalid gutter width %v changed layout: %+v -> %+v", width, before, fixture.editor.content)
+ }
+ }
+}
+
+func TestCodeEditorDecorationBarLayersAndJoins(t *testing.T) {
+ fixture := newCodeFixture("one\ntwo\n")
+ fill, stroke, upper := gfx.RGB(210, 210, 210), gfx.RGB(255, 128, 0), gfx.RGB(0, 160, 0)
+ bar := CodeEditorGutterBar{Line: 0, Fill: fill, Stroke: stroke}
+ fixture.snapshot.Decorations = &CodeEditorDecorations{GutterWidth: 9, GutterBars: []CodeEditorGutterBar{bar}}
+ fixture.paint()
+ closed := fixture.fills(stroke)
+ if len(closed) != 4 || len(fixture.fills(fill)) != 1 {
+ t.Fatalf("outlined bar has no distinct caps/sides/fill: %+v", closed)
+ }
+ fixture.snapshot.Decorations.(*CodeEditorDecorations).GutterBars[0].JoinBefore = true
+ fixture.paint()
+ if joined := fixture.fills(stroke); len(joined) != 3 {
+ t.Fatalf("logical join retained an end cap: %+v", joined)
+ }
+ fixture.snapshot.Decorations.(*CodeEditorDecorations).GutterBars = []CodeEditorGutterBar{
+ {Line: 0, Fill: stroke, Stroke: stroke},
+ {Line: 0, Fill: upper, Stroke: upper},
+ }
+ fixture.paint()
+ if a, b := fixture.fills(stroke), fixture.fills(upper); len(a) != 1 || len(b) != 1 || a[0] != b[0] {
+ t.Fatalf("same-line edition layers do not share bar geometry: %v / %v", a, b)
+ }
+ var first, second uint32
+ for _, rect := range fixture.canvas.Rectangles() {
+ if rect.Color == stroke {
+ first = rect.Order
+ }
+ if rect.Color == upper {
+ second = rect.Order
+ }
+ }
+ if first == 0 || second <= first {
+ t.Fatalf("bar caller order changed: %d, %d", first, second)
+ }
+}
+
+func TestCodeEditorDecorationHorizontalScrollAndDisabledColors(t *testing.T) {
+ fixture := newCodeFixture(strings.Repeat("a", 100))
+ fixture.bounds.Width = fixture.widthFor(12)
+ fixture.snapshot.HorizontalScrollbarID = gfx.Item(9)
+ barColor, indicatorColor := gfx.RGB(0, 160, 0), gfx.RGB(255, 128, 0)
+ fixture.snapshot.Decorations = &CodeEditorDecorations{
+ GutterWidth: 9, GutterBars: []CodeEditorGutterBar{{Line: 0, Fill: barColor, Stroke: barColor}},
+ IndicatorLayers: []CodeEditorIndicatorLayer{{Spans: []text.Span{{Start: 4, End: 8}}, Color: indicatorColor}},
+ }
+ fixture.paint()
+ beforeBar, beforeIndicator := fixture.fills(barColor), fixture.fills(indicatorColor)
+ if len(beforeBar) != 1 || len(beforeIndicator) != 1 {
+ t.Fatal("fixture did not draw a bar and underline")
+ }
+ cell, _, _ := fixture.cell()
+ fixture.editor.scrollX = 2 * cell
+ fixture.paint()
+ afterBar, afterIndicator := fixture.fills(barColor), fixture.fills(indicatorColor)
+ if len(afterBar) != 1 || afterBar[0] != beforeBar[0] || len(afterIndicator) != 1 || !near(afterIndicator[0].X, beforeIndicator[0].X-2*cell) {
+ t.Fatalf("horizontal scroll moved the wrong presentation: bars=%v/%v indicators=%v/%v", beforeBar, afterBar, beforeIndicator, afterIndicator)
+ }
+ fixture.snapshot.Disabled = true
+ fixture.paint()
+ barColor.Alpha, indicatorColor.Alpha = 0.5, 0.5
+ if len(fixture.fills(barColor)) != 1 || len(fixture.fills(indicatorColor)) != 1 || fixture.snapshot.Decorations.(*CodeEditorDecorations).IndicatorLayers[0].Color.Alpha != 1 {
+ t.Fatal("disabled decorations were not uniformly dimmed without caller mutation")
+ }
+}
+
+func TestCodeEditorIndicatorsPreserveZeroWidthRepresentations(t *testing.T) {
+ fixture := newCodeFixture("e\u0301x")
+ fixture.snapshot.Representations = []CodeRepresentation{{Character: 'x', Label: ""}}
+ underline, point := gfx.RGB(255, 128, 0), gfx.RGB(0, 160, 0)
+ fixture.snapshot.Decorations = &CodeEditorDecorations{IndicatorLayers: []CodeEditorIndicatorLayer{
+ {Spans: []text.Span{{Start: 1, End: 3}, {Start: 3, End: 4}}, Color: underline},
+ {Spans: []text.Span{{Start: 1, End: 1}, {Start: 3, End: 3}}, Color: point, Style: CodeEditorPointBelow},
+ }}
+ fixture.paint()
+ triangles := decorationTriangles(fixture, point)
+ if len(fixture.fills(underline)) != 0 || len(triangles) != 2 || triangles[0].Points != triangles[1].Points {
+ t.Fatalf("zero-width source ranges invented cells or moved points: underlines=%v points=%v", fixture.fills(underline), triangles)
+ }
+}
+
+func TestCodeEditorDecorationsPaintWithoutSteadyAllocations(t *testing.T) {
+ fixture := newCodeFixture("one\ntwo\nthree\n")
+ color := gfx.RGB(0, 160, 0)
+ fixture.snapshot.Decorations = &CodeEditorDecorations{
+ GutterWidth: 9, GutterBars: []CodeEditorGutterBar{{Line: 1, Fill: color, Stroke: color}},
+ IndicatorLayers: []CodeEditorIndicatorLayer{
+ {Spans: []text.Span{{Start: 4, End: 7}}, Color: color},
+ {Spans: []text.Span{{Start: 1, End: 1}, {Start: 8, End: 8}}, Color: color, Style: CodeEditorPointAbove},
+ },
+ }
+ fixture.paint()
+ if allocations := testing.AllocsPerRun(100, fixture.paint); allocations != 0 {
+ t.Fatalf("unchanged decorated paint allocated %g times", allocations)
+ }
+}
+
+func TestCodeEditorTypedNilDecorationKeepsDefaultDrawing(t *testing.T) {
+ fixture := newCodeFixture("one\ntwo\n")
+ fixture.paint()
+ content := fixture.editor.content
+ var decorations *CodeEditorDecorations
+ fixture.snapshot.Decorations = decorations
+ fixture.paint()
+ if fixture.editor.content != content {
+ t.Fatal("a typed nil decoration changed the default layout")
+ }
+ if allocations := testing.AllocsPerRun(100, fixture.paint); allocations != 0 {
+ t.Fatalf("typed nil decoration allocated %g times", allocations)
+ }
+}
+
+func TestCodeEditorOversizedDecorationCannotCoverAdjacentEditor(t *testing.T) {
+ var canvas gfx.Canvas
+ var left, right CodeEditor
+ theme := gfx.LightTheme()
+ right.Paint(&canvas, theme, gfx.Rect{X: 100, Width: 100, Height: 200}, CodeEditorSnapshot{Value: "right"})
+ background, bar := gfx.RGB(234, 56, 78), gfx.RGB(88, 99, 11)
+ left.Paint(&canvas, theme, gfx.Rect{Width: 100, Height: 200}, CodeEditorSnapshot{
+ Value: "left", LineNumbers: true,
+ Decorations: &CodeEditorDecorations{
+ GutterWidth: 200, GutterBackground: background,
+ GutterBars: []CodeEditorGutterBar{{Line: 0, Fill: bar, Stroke: bar}},
+ },
+ })
+ for _, rect := range canvas.Rectangles() {
+ if rect.Color != background && rect.Color != bar {
+ continue
+ }
+ if !rect.HasClip || min(rect.Bounds.X+rect.Bounds.Width, rect.ClipOf.X+rect.ClipOf.Width) > 100 {
+ t.Fatalf("left decoration can paint over the right editor: bounds=%+v clip=%+v", rect.Bounds, rect.ClipOf)
+ }
+ }
+ for _, label := range canvas.Texts() {
+ if label.Value == "1" && (!label.HasClip || label.ClipOf.X+label.ClipOf.Width > 100) {
+ t.Fatalf("oversized decoration exposed a neighboring gutter label: %+v", label)
+ }
+ }
+}
+
+func TestCodeEditorOversizedDecorationClipsFoldPaintingAndHits(t *testing.T) {
+ for _, width := range []float32{80, 120} {
+ var canvas gfx.Canvas
+ var editor CodeEditor
+ fold := gfx.Item(1)
+ editor.Paint(&canvas, gfx.LightTheme(), gfx.Rect{Width: 100, Height: 200}, CodeEditorSnapshot{
+ Value: "left",
+ FoldMarkers: []CodeEditorFoldMarker{{Line: 0, ID: fold}},
+ Decorations: &CodeEditorDecorations{GutterWidth: width},
+ })
+ if len(canvas.Triangles()) == 0 {
+ t.Fatal("fixture did not draw the fold chevron")
+ }
+ for _, triangle := range canvas.Triangles() {
+ if !triangle.HasClip || triangle.ClipOf.Width > 0 && triangle.ClipOf.X+triangle.ClipOf.Width > 100 {
+ t.Errorf("width=%v: fold chevron escaped editor: %+v", width, triangle)
+ }
+ }
+ for _, hit := range canvas.Hits() {
+ if hit.ID == fold && hit.Bounds.X+hit.Bounds.Width > 100 {
+ t.Errorf("width=%v: fold hit escaped editor: %+v", width, hit.Bounds)
+ }
+ }
+ if len(canvas.Clips()) != 0 {
+ t.Fatal("editor left an unbalanced clip")
+ }
+ }
+}
+
+func TestCodeEditorDecorationClipsMarkerHitsToEditorWidth(t *testing.T) {
+ for _, scenario := range []struct {
+ width float32
+ visible bool
+ }{
+ {80, true},
+ {120, false},
+ } {
+ fixture := newCodeFixture("left")
+ fixture.bounds.Width = 100
+ fixture.snapshot.Decorations = &CodeEditorDecorations{GutterWidth: scenario.width}
+ marker := gfx.Item(20)
+ fixture.snapshot.GutterMarkers = []CodeEditorGutterMarker{{Line: 0, ID: marker}}
+ fixture.paint()
+ found := false
+ for _, hit := range fixture.canvas.Hits() {
+ if hit.ID != marker {
+ continue
+ }
+ found = true
+ if hit.Bounds.X < fixture.bounds.X || hit.Bounds.X+hit.Bounds.Width > fixture.bounds.X+100 || hit.Bounds.Width <= 0 {
+ t.Errorf("gutter width=%v: invisible marker hit escaped the editor: %+v", scenario.width, hit.Bounds)
+ }
+ }
+ if found != scenario.visible {
+ t.Errorf("gutter width=%v: marker visible=%t, want %t", scenario.width, found, scenario.visible)
+ }
+ if len(fixture.canvas.Clips()) != 0 {
+ t.Fatal("marker hit left an unbalanced clip")
+ }
+ }
+}
+
+func TestCodeEditorDecorationClipsScrolledMarkerHitsToContent(t *testing.T) {
+ fixture := newCodeFixture("first\nsecond\nthird\nfourth")
+ fixture.snapshot.Decorations = &CodeEditorDecorations{GutterWidth: 9}
+ first, last := gfx.Item(20), gfx.Item(21)
+ fixture.snapshot.GutterMarkers = []CodeEditorGutterMarker{{Line: 0, ID: first}, {Line: 3, ID: last}}
+ fixture.paint()
+ lineHeight := fixture.editor.lineHeight
+ fixture.bounds.Height = 3*lineHeight + 2*codeEditorPadY
+ fixture.paint()
+ fixture.editor.scrollY = lineHeight / 2
+ fixture.paint()
+ if !near(fixture.editor.scrollY, lineHeight/2) {
+ t.Fatal("fixture did not preserve the partial-row scroll")
+ }
+ found := 0
+ content := fixture.editor.content
+ for _, hit := range fixture.canvas.Hits() {
+ if hit.ID != first && hit.ID != last {
+ continue
+ }
+ found++
+ if hit.Bounds.Y < content.Y || hit.Bounds.Y+hit.Bounds.Height > content.Y+content.Height || !near(hit.Bounds.Height, lineHeight/2) {
+ t.Errorf("marker hit escaped the visible partial row: id=%v hit=%+v content=%+v", hit.ID, hit.Bounds, content)
+ }
+ }
+ if found != 2 {
+ t.Fatalf("visible partial-row markers=%d, want 2", found)
+ }
+ if len(fixture.canvas.Clips()) != 0 {
+ t.Fatal("marker hit left an unbalanced clip")
+ }
+}
+
+func TestCodeEditorOversizedDecorationHidesCaretOutsideEditor(t *testing.T) {
+ for _, value := range []string{"", "left"} {
+ fixture := newCodeFixture(value)
+ fixture.bounds.Width = 100
+ fixture.snapshot.Wrap = true
+ fixture.snapshot.Decorations = &CodeEditorDecorations{GutterWidth: 120}
+ fixture.paint()
+ if caret, visible := fixture.editor.CaretBounds(); visible {
+ t.Errorf("value=%q: an invisible text area exposed an IME caret outside the editor: %+v", value, caret)
+ }
+ }
+}
+
+type decorationFontMetrics struct {
+ gfx.TextEngine
+ metrics gfx.MonoCellMetrics
+}
+
+func (engine *decorationFontMetrics) MonoCell(float32, gfx.MonoFace) gfx.MonoCellMetrics {
+ return engine.metrics
+}
+
+func TestCodeEditorIndicatorPointsUseMeasuredBaseline(t *testing.T) {
+ for _, test := range []struct {
+ size float32
+ metrics gfx.MonoCellMetrics
+ lineHeight, base float32
+ pointHeight float32
+ }{
+ {20, gfx.MonoCellMetrics{Advance: 10, Ascent: 14, Descent: 6}, 30, 19, 11},
+ {24, gfx.MonoCellMetrics{Advance: 12, Ascent: 34, Descent: 2}, 36, 34, 3},
+ } {
+ fixture := newCodeFixture("ab")
+ fixture.snapshot.FontSize = test.size
+ fixture.canvas.SetTextEngine(&decorationFontMetrics{TextEngine: gfx.ReferenceTextEngine(), metrics: test.metrics})
+ below, above := gfx.RGB(0, 160, 0), gfx.RGB(255, 128, 0)
+ fixture.snapshot.Decorations = &CodeEditorDecorations{IndicatorLayers: []CodeEditorIndicatorLayer{
+ {Spans: []text.Span{{Start: 1, End: 1}}, Color: below, Style: CodeEditorPointBelow},
+ {Spans: []text.Span{{Start: 1, End: 1}}, Color: above, Style: CodeEditorPointAbove},
+ }}
+ fixture.paint()
+ if actual := fixture.canvas.MonoBaseline(test.size, gfx.MonoSystem, test.lineHeight); actual != test.base {
+ t.Fatalf("baseline fixture = %v, want %v", actual, test.base)
+ }
+ bottomPoints, topPoints := decorationTriangles(fixture, below), decorationTriangles(fixture, above)
+ if len(bottomPoints) != 1 || len(topPoints) != 1 {
+ t.Fatal("measured-font point was not drawn")
+ }
+ bottom := fixture.editor.content.Y + max(test.lineHeight, test.base+3)
+ if bottomPoints[0].Points[0].Y != bottom+0.5 || bottomPoints[0].Points[0].Y-bottomPoints[0].Points[2].Y != test.pointHeight || topPoints[0].Points[2].Y-topPoints[0].Points[0].Y != test.pointHeight {
+ t.Fatalf("point ignored font descent/minimum height: bottom=%+v top=%+v", bottomPoints[0], topPoints[0])
+ }
+ }
+}
diff --git a/components/doc.go b/components/doc.go
index 5130076e7..8003da205 100644
--- a/components/doc.go
+++ b/components/doc.go
@@ -139,6 +139,9 @@
// `CodeRepresentation` labels and inverted blobs, optional indentation
// guides, soft wrap with optional end markers, sideways scrolling and
// draggable scrollbars, with native selection and IME geometry retained.
+// Optional `CodeEditorDecorations` reserve a leading gutter for layered bars
+// and paint caller-colored byte underlines and insertion-position points;
+// the component owns their wrap, fold, scroll and caret-layer geometry.
// `CodeEditorCommandForKey` maps key events to the editing commands of a
// text.Editor given code options (SetCode), and
// `TextareaMovementForKey` with `CodeEditor.Move` moves by row. The scroll
diff --git a/components/doc_test.go b/components/doc_test.go
index fc9224e7b..92977d8f7 100644
--- a/components/doc_test.go
+++ b/components/doc_test.go
@@ -42,6 +42,8 @@ var docPrimaryEntries = map[string][]string{
"text_selection.go": {"TextSelection"},
"tree_navigation.go": {"NavigateTree"},
"typography.go": {"Typography"},
+
+ "code_editor_decorations.go": {"CodeEditor"},
}
// TestDocCatalogCoversEveryComponent keeps the package catalog in doc.go in
diff --git a/headless/code_editor_decorations_pixels_test.go b/headless/code_editor_decorations_pixels_test.go
new file mode 100644
index 000000000..8e8810f81
--- /dev/null
+++ b/headless/code_editor_decorations_pixels_test.go
@@ -0,0 +1,138 @@
+//go:build darwin && vivahead
+
+package headless
+
+import (
+ "math"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/vivaui/viva/app"
+ "github.com/vivaui/viva/components"
+ "github.com/vivaui/viva/gfx"
+ "github.com/vivaui/viva/text"
+)
+
+func TestCodeEditorDecorationsPixels(t *testing.T) {
+ for _, size := range []struct {
+ name string
+ width, height int
+ }{{"desktop", 1280, 800}, {"compact", 640, 400}} {
+ t.Run(size.name, func(t *testing.T) {
+ var editor components.CodeEditor
+ var invalidator app.Invalidator
+ theme := gfx.LightTheme()
+ green, orange, cyan := gfx.RGB(0, 160, 0), gfx.RGB(255, 128, 0), gfx.RGB(64, 160, 191)
+ decorations := &components.CodeEditorDecorations{
+ GutterWidth: 9, GutterBackground: gfx.RGB(224, 224, 224),
+ GutterBars: []components.CodeEditorGutterBar{{Line: 1, Fill: green, Stroke: green}},
+ IndicatorLayers: []components.CodeEditorIndicatorLayer{
+ {Spans: []text.Span{{Start: 7, End: 9}}, Color: orange},
+ {Spans: []text.Span{{Start: 10, End: 10}}, Color: cyan, Style: components.CodeEditorPointAbove},
+ },
+ }
+ var cell, line float32
+ config := app.Config{
+ Title: size.name, Width: size.width, Height: size.height,
+ Invalidator: &invalidator, ClearColor: app.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1},
+ Paint: func(canvas *gfx.Canvas, frame gfx.Size) {
+ var height float32
+ cell, height = canvas.MonoCellSize(14, gfx.MonoSystem)
+ line = max(height, 21)
+ editor.Paint(canvas, theme, gfx.Rect{Width: frame.Width, Height: frame.Height}, components.CodeEditorSnapshot{
+ ID: gfx.Item(1), Label: "Code editor", Value: "alpha\nbravo\ncharlie\n", FontSize: 14,
+ CurrentLine: true, Decorations: decorations,
+ })
+ },
+ }
+ session, err := Open(config, nil, Options{Scale: 1})
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(session.Close)
+ picture, err := session.Image()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if picture.Bounds().Dx() != size.width || picture.Bounds().Dy() != size.height {
+ t.Fatalf("screenshot dimensions = %v", picture.Bounds())
+ }
+ content := decorationContentBounds(t, session.Snapshot())
+ if content.Width <= 0 || cell <= 0 || line <= 0 {
+ t.Fatal("the editor did not publish text geometry")
+ }
+ barPixels, underlinePixels, pointPixels := 0, 0, 0
+ for y := 0; y < picture.Bounds().Dy(); y++ {
+ for x := 0; x < picture.Bounds().Dx(); x++ {
+ r, g, b := pixelAt(picture, x, y)
+ switch [3]uint8{r, g, b} {
+ case [3]uint8{0, 160, 0}:
+ barPixels++
+ if float32(x) >= content.X {
+ t.Fatalf("gutter bar covers text at (%d,%d)", x, y)
+ }
+ case [3]uint8{255, 128, 0}:
+ underlinePixels++
+ if float32(x) < content.X+cell || float32(y) < content.Y+2*line-2 || float32(y) >= content.Y+2*line {
+ t.Fatalf("byte underline has glyph-covering or wrong-position pixels at (%d,%d), content=%+v cell=%v line=%v", x, y, content, cell, line)
+ }
+ case [3]uint8{64, 160, 191}:
+ pointPixels++
+ }
+ }
+ }
+ if barPixels == 0 || underlinePixels == 0 || pointPixels == 0 {
+ t.Fatalf("blank decorations: bar=%d underline=%d point=%d", barPixels, underlinePixels, pointPixels)
+ }
+ x := int(math.Floor(float64(theme.Metrics.TextInsetX()))) + 1
+ y := int(content.Y + line/2)
+ if r, g, b := pixelAt(picture, x, y); r != 224 || g != 224 || b != 224 {
+ t.Fatalf("empty lane background was tinted: %d,%d,%d", r, g, b)
+ }
+ if output := os.Getenv("VIVA_DECORATIONS_SHOTS"); output != "" {
+ if err := os.MkdirAll(output, 0700); err != nil {
+ t.Fatal(err)
+ }
+ if err := session.Screenshot(filepath.Join(output, "code-decorations-"+size.name+".png")); err != nil {
+ t.Fatal(err)
+ }
+ }
+ decorations.GutterBars, decorations.IndicatorLayers = nil, nil
+ invalidator.Invalidate()
+ if err := session.Driver().Pump(); err != nil {
+ t.Fatal(err)
+ }
+ plain, err := session.Image()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if decorationContentBounds(t, session.Snapshot()) != content {
+ t.Fatal("clearing change markers shifted text")
+ }
+ // The first letter of bravo has no indicator. Its glyph body must stay
+ // identical when the later byte span and deletion point are removed.
+ for y := int(content.Y + line*1.25); y < int(content.Y+line*1.75); y++ {
+ for x := int(content.X); x < int(content.X+cell); x++ {
+ if picture.RGBAAt(x, y) != plain.RGBAAt(x, y) {
+ t.Fatalf("indicator obscured the unmarked first glyph at (%d,%d)", x, y)
+ }
+ }
+ }
+ t.Logf("%dx%d: bar=%d underline=%d point=%d pixels; clearing decorations preserved text geometry and unmarked glyphs", size.width, size.height, barPixels, underlinePixels, pointPixels)
+ })
+ }
+}
+
+func decorationContentBounds(t *testing.T, snapshot app.Snapshot) gfx.Rect {
+ t.Helper()
+ for index, hit := range snapshot.Hits {
+ if hit.ID == gfx.Item(1) {
+ if geometry, ok := snapshot.HitTextAt(index); ok {
+ return geometry.Bounds
+ }
+ }
+ }
+ t.Fatal("the editor has no declared text geometry")
+ return gfx.Rect{}
+}
diff --git a/tools/docs/catalog.go b/tools/docs/catalog.go
index c91183d63..ab6f1bc00 100644
--- a/tools/docs/catalog.go
+++ b/tools/docs/catalog.go
@@ -127,7 +127,7 @@ func loadPages(root string) ([]Page, Manifest, error) {
// bars its examples show.
if file.Name() == "doc.go" || file.Name() == "direction.go" ||
file.Name() == "menu_typeahead.go" || file.Name() == "code_diff_model.go" || file.Name() == "code_diff_inline.go" ||
- file.Name() == "code_editor_layout.go" || file.Name() == "caret_blink.go" || file.Name() == "find_bar.go" || file.Name() == "go_to_line.go" || file.Name() == "hierarchy_menu.go" ||
+ file.Name() == "code_editor_layout.go" || file.Name() == "code_editor_decorations.go" || file.Name() == "caret_blink.go" || file.Name() == "find_bar.go" || file.Name() == "go_to_line.go" || file.Name() == "hierarchy_menu.go" ||
file.Name() == "markdown_anchor.go" || file.Name() == "text_selection.go" {
continue
}
From 3a4c3719c68faa11cb866545ac87fbfb4a3f2b50 Mon Sep 17 00:00:00 2001
From: MYCF711 <1451895195@qq.com>
Date: Sat, 21 Nov 2026 18:31:15 +0800
Subject: [PATCH 09/47] feat(app): let a host put an image on the clipboard
---
.github/workflows/ci.yml | 4 +-
app/capabilities.go | 8 ++
app/capabilities_native.go | 2 +
app/capabilities_web.go | 1 +
app/clipboard_image.go | 33 ++++-
app/clipboard_image_write_test.go | 121 ++++++++++++++++++
app/clipboard_image_write_windows_test.go | 70 ++++++++++
app/driver_system.go | 12 ++
app/driver_system_unsupported.go | 2 +
app/system_async.go | 26 ++++
app/system_async_js.go | 6 +
app/system_async_other.go | 5 +
app/system_darwin.go | 2 +
app/system_js.go | 6 +
app/system_linux.go | 4 +
app/system_unsupported.go | 1 +
app/system_windows.go | 2 +
docs/system-integrations.md | 30 ++++-
docs/web-deployment.md | 1 +
internal/platform/clipboard_dib_windows.go | 62 +++++++++
.../clipboard_dib_write_windows_test.go | 109 ++++++++++++++++
internal/platform/clipboard_image.go | 15 ++-
internal/platform/clipboard_png_test.go | 44 ++++++-
.../platform/darwin/clipboard_image_darwin.go | 19 +++
internal/platform/darwin/system_darwin.h | 5 +
internal/platform/darwin/system_darwin.m | 38 ++++++
.../linux/clipboard_files_write_linux.go | 1 +
.../linux/clipboard_html_write_linux.go | 1 +
.../linux/clipboard_image_write_linux.go | 48 +++++++
.../linux/clipboard_image_write_linux_test.go | 118 +++++++++++++++++
internal/platform/linux/gtk_app_linux.go | 8 ++
.../linux/gtk_clipboard_image_linux_test.go | 63 +++++++++
internal/platform/linux/gtk_system_linux.go | 104 +++++++++++----
internal/platform/linux/selection_linux.go | 30 ++++-
internal/platform/linux/shell_hooks_linux.go | 1 +
internal/platform/linux/system_linux.go | 28 +++-
internal/platform/linux/window_linux.go | 2 +
internal/platform/web/clipboard_async_js.go | 56 ++++++++
internal/platform/web/system_js.go | 6 +
.../windows/clipboard_image_windows.go | 76 +++++++++++
.../clipboard_image_write_windows_test.go | 82 ++++++++++++
41 files changed, 1217 insertions(+), 35 deletions(-)
create mode 100644 app/clipboard_image_write_test.go
create mode 100644 app/clipboard_image_write_windows_test.go
create mode 100644 internal/platform/clipboard_dib_write_windows_test.go
create mode 100644 internal/platform/linux/clipboard_image_write_linux.go
create mode 100644 internal/platform/linux/clipboard_image_write_linux_test.go
create mode 100644 internal/platform/linux/gtk_clipboard_image_linux_test.go
create mode 100644 internal/platform/windows/clipboard_image_windows.go
create mode 100644 internal/platform/windows/clipboard_image_write_windows_test.go
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 8def9d5b5..2237bf1a4 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -157,11 +157,11 @@ jobs:
- name: GTK optional capability contracts
run: |
go vet -tags vivagtk ./app ./internal/platform/linux
- go test -tags vivagtk ./internal/platform/linux -run '^TestGTK(WaylandAlwaysOnTopReportsUnsupported|ClipboardFileWriteReportsUnsupportedWithoutASetter)$' -count=1
+ go test -tags vivagtk ./internal/platform/linux -run '^TestGTK(WaylandAlwaysOnTopReportsUnsupported|ClipboardFileWriteReportsUnsupportedWithoutASetter|ClipboardImageWriteReportsUnsupportedWithoutSetWithData)$' -count=1
# The Linux package is not part of the sharded run (it drives X11), so the
# titlebar contracts that do not need a server name their tests here.
- name: Titlebar and window contracts
- run: go test ./internal/platform/linux -run '^Test(MaximizeButtonSetsBothDirections|PreviewMovePreservesSizeAndFocus)$' -count=1 -v
+ run: go test ./internal/platform/linux -run '^Test(MaximizeButtonSetsBothDirections|PreviewMovePreservesSizeAndFocus|AClipboardImageIsOfferedAsPNGAndNoText|SetClipboardImageClaimsTheClipboardAndDropsOtherFlavours)$' -count=1 -v
- name: Native X11 drag preview
env:
VIVA_TEST_PREVIEW_XVFB: '1'
diff --git a/app/capabilities.go b/app/capabilities.go
index 12b6c3012..50e83c66a 100644
--- a/app/capabilities.go
+++ b/app/capabilities.go
@@ -43,6 +43,14 @@ const (
// proxy settings. Linux reads the environment only, and macOS reports a
// PAC policy as an error.
CapabilitySystemProxy
+ // CapabilityClipboardImageWrite means SetClipboardImage can put a picture on
+ // the clipboard synchronously. The browser offers the write only through a
+ // Promise, so it reports CapabilityClipboardImageWriteAsync instead.
+ CapabilityClipboardImageWrite
+ // CapabilityClipboardImageWriteAsync means SetClipboardImageAsync can put a
+ // picture on the clipboard, completing before the call returns on a desktop
+ // and on the event loop in a browser.
+ CapabilityClipboardImageWriteAsync
)
// Capabilities is a set of platform integrations.
diff --git a/app/capabilities_native.go b/app/capabilities_native.go
index 31281cb49..8746dd9b7 100644
--- a/app/capabilities_native.go
+++ b/app/capabilities_native.go
@@ -12,6 +12,8 @@ func nativeCapabilities() Capabilities {
CapabilityClipboardTextAsync |
CapabilityClipboardImage |
CapabilityClipboardImageAsync |
+ CapabilityClipboardImageWrite |
+ CapabilityClipboardImageWriteAsync |
CapabilityClipboardFiles |
CapabilityClipboardHTML |
CapabilityFileDialogs |
diff --git a/app/capabilities_web.go b/app/capabilities_web.go
index 8b6468fbd..a5f3b4c3f 100644
--- a/app/capabilities_web.go
+++ b/app/capabilities_web.go
@@ -8,6 +8,7 @@ func nativeCapabilities() Capabilities {
CapabilityClipboardTextAsync |
CapabilityClipboardHTML |
CapabilityClipboardImageAsync |
+ CapabilityClipboardImageWriteAsync |
CapabilityFileDialogsAsync |
CapabilitySecretStoreAsync |
CapabilityNotifications |
diff --git a/app/clipboard_image.go b/app/clipboard_image.go
index 1ad5de708..f5d5f6ccd 100644
--- a/app/clipboard_image.go
+++ b/app/clipboard_image.go
@@ -1,6 +1,10 @@
package app
-import "github.com/vivaui/viva/internal/platform"
+import (
+ "fmt"
+
+ "github.com/vivaui/viva/internal/platform"
+)
var (
// ErrNoImage reports that the clipboard holds no image.
@@ -52,3 +56,30 @@ func ClipboardImagePNG() ([]byte, error) {
func RequestClipboardImage(done func(png []byte, err error)) {
nativeRequestClipboardImage(done)
}
+
+// SetClipboardImage makes png the picture the clipboard holds, as copying an
+// image in a browser or a photo viewer does, so that any application's Paste
+// puts it there. It replaces whatever the clipboard held, text included: one
+// clipboard holds one copy. This is the write side of ClipboardImagePNG, and a
+// paste of what it wrote reads back as the same picture.
+//
+// Each platform offers the picture in the flavours its readers ask for: macOS
+// public.png beside its TIFF conversion, Windows the registered "PNG" format
+// beside CF_DIB, and Linux the X11 CLIPBOARD's image/png target (the GTK shell
+// serves the same target through GTK). png must be a PNG within
+// MaxClipboardImageBytes and must carry a picture the platform can hold; a PNG
+// that fails either check is an error and leaves the clipboard as it was. The
+// Web target writes through a Promise and returns ErrAsyncRequired;
+// SetClipboardImageAsync writes there.
+func SetClipboardImage(png []byte) error {
+ if len(png) == 0 {
+ return fmt.Errorf("app: no image to put on the clipboard")
+ }
+ if err := platform.CheckClipboardPNG(png); err != nil {
+ return err
+ }
+ if err, handled := driverSetClipboardImage(png); handled {
+ return err
+ }
+ return nativeSetClipboardImage(png)
+}
diff --git a/app/clipboard_image_write_test.go b/app/clipboard_image_write_test.go
new file mode 100644
index 000000000..7219126b1
--- /dev/null
+++ b/app/clipboard_image_write_test.go
@@ -0,0 +1,121 @@
+//go:build darwin || windows || linux
+
+package app
+
+import (
+ "bytes"
+ "errors"
+ "image"
+ "image/color"
+ "image/png"
+ "testing"
+)
+
+// clipboardPicturePNG encodes a picture whose colours and edges a round trip has
+// to keep apart: a grid that differs in every channel along both axes.
+func clipboardPicturePNG(t *testing.T, width, height int) []byte {
+ t.Helper()
+ picture := image.NewNRGBA(image.Rect(0, 0, width, height))
+ for y := range height {
+ for x := range width {
+ picture.SetNRGBA(x, y, color.NRGBA{R: uint8(30 + 50*x), G: uint8(10 + 60*y), B: 200, A: 255})
+ }
+ }
+ var out bytes.Buffer
+ if err := png.Encode(&out, picture); err != nil {
+ t.Fatal(err)
+ }
+ return out.Bytes()
+}
+
+// TestSetClipboardImageCopiesOntoTheDriverClipboard checks the write against the
+// driver's private clipboard, which answers the same reads as the system one:
+// the picture is there, the reads see it, and the text a copy replaces is gone.
+func TestSetClipboardImageCopiesOntoTheDriverClipboard(t *testing.T) {
+ driver, err := NewDriver(Config{}, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer driver.Close()
+ driver.SetClipboard("text the copy replaces")
+
+ picture := clipboardPicturePNG(t, 3, 2)
+ if err := SetClipboardImage(picture); err != nil {
+ t.Fatal(err)
+ }
+ if got := driver.ClipboardImage(); !bytes.Equal(got, picture) {
+ t.Fatalf("driver clipboard holds %d bytes, want the %d written", len(got), len(picture))
+ }
+ if driver.Clipboard() != "" {
+ t.Fatalf("the text stayed on the clipboard: %q", driver.Clipboard())
+ }
+ if !HasClipboardImage() {
+ t.Fatal("HasClipboardImage = false after a copy")
+ }
+ read, err := ClipboardImagePNG()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(read, picture) {
+ t.Fatalf("read back %d bytes, want the %d written", len(read), len(picture))
+ }
+}
+
+// TestSetClipboardImageAsyncCopiesOnce checks the asynchronous form of the same
+// write on a native target: done runs before the call returns, exactly once, and
+// the clipboard holds the picture.
+func TestSetClipboardImageAsyncCopiesOnce(t *testing.T) {
+ driver, err := NewDriver(Config{}, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer driver.Close()
+ picture := clipboardPicturePNG(t, 2, 2)
+ completions, completion := 0, errors.New("done never ran")
+ if err := SetClipboardImageAsync(picture, func(err error) {
+ completions++
+ completion = err
+ }); err != nil {
+ t.Fatal(err)
+ }
+ if completions != 1 || completion != nil {
+ t.Fatalf("done ran %d times with %v, want once with nil", completions, completion)
+ }
+ if !bytes.Equal(driver.ClipboardImage(), picture) {
+ t.Fatal("the asynchronous copy left the clipboard without the picture")
+ }
+}
+
+// TestSetClipboardImageRefusesWhatItCannotCopy keeps a failed write from lying
+// about the clipboard: an empty image, a file that is not a PNG and one above
+// the cap are errors, and the copy already there stays.
+func TestSetClipboardImageRefusesWhatItCannotCopy(t *testing.T) {
+ driver, err := NewDriver(Config{}, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer driver.Close()
+ picture := clipboardPicturePNG(t, 2, 1)
+ if err := SetClipboardImage(picture); err != nil {
+ t.Fatal(err)
+ }
+ if err := SetClipboardImage(nil); err == nil {
+ t.Fatal("an empty image was copied")
+ }
+ if err := SetClipboardImage([]byte("GIF89a, not a PNG")); err == nil {
+ t.Fatal("bytes that are not a PNG were copied")
+ }
+ aboveCap := append([]byte("\x89PNG\r\n\x1a\n"), make([]byte, MaxClipboardImageBytes)...)
+ if err := SetClipboardImage(aboveCap); !errors.Is(err, ErrTooLarge) {
+ t.Fatalf("error = %v, want ErrTooLarge", err)
+ }
+ if got := driver.ClipboardImage(); !bytes.Equal(got, picture) {
+ t.Fatal("a refused copy replaced the picture on the clipboard")
+ }
+ if err := SetClipboardImageAsync(nil, func(error) {}); err == nil {
+ t.Fatal("an empty image was accepted asynchronously")
+ }
+ if err := SetClipboardImageAsync(picture, nil); err == nil {
+ t.Fatal("a nil callback was accepted")
+ }
+}
diff --git a/app/clipboard_image_write_windows_test.go b/app/clipboard_image_write_windows_test.go
new file mode 100644
index 000000000..fd1c048ed
--- /dev/null
+++ b/app/clipboard_image_write_windows_test.go
@@ -0,0 +1,70 @@
+//go:build windows
+
+package app
+
+import (
+ "bytes"
+ "os"
+ "testing"
+)
+
+// TestSetClipboardImageRoundTripsThroughTheSystemClipboard copies a picture to
+// the real clipboard and reads it back with ClipboardImagePNG, the pair an
+// application's copy and its paste use. It replaces the clipboard, so it runs
+// only on request, on a machine whose clipboard may be overwritten.
+func TestSetClipboardImageRoundTripsThroughTheSystemClipboard(t *testing.T) {
+ if os.Getenv("VIVA_WINDOWS_CLIPBOARD") == "" {
+ t.Skip("set VIVA_WINDOWS_CLIPBOARD=1 to overwrite the real clipboard")
+ }
+ picture := clipboardPicturePNG(t, 5, 3)
+ if err := SetClipboardImage(picture); err != nil {
+ t.Fatal(err)
+ }
+ if !HasClipboardImage() {
+ t.Fatal("HasClipboardImage = false after copying a picture")
+ }
+ read, err := ClipboardImagePNG()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(read, picture) {
+ t.Fatalf("read back %d bytes, wrote %d: the clipboard did not keep the copy", len(read), len(picture))
+ }
+
+ // A copy replaces what the clipboard held, as the Windows clipboard does
+ // after any copy.
+ if err := SetClipboardText("text the picture replaces"); err != nil {
+ t.Fatal(err)
+ }
+ if HasClipboardImage() {
+ t.Fatal("HasClipboardImage = true with text on the clipboard")
+ }
+ if err := SetClipboardImage(picture); err != nil {
+ t.Fatal(err)
+ }
+ if text, err := ClipboardText(); err != nil || text != "" {
+ t.Fatalf("text = %q, %v after copying a picture, want none", text, err)
+ }
+
+ // The asynchronous form writes the same picture.
+ if err := SetClipboardText("text the asynchronous copy replaces"); err != nil {
+ t.Fatal(err)
+ }
+ completions, completion := 0, error(nil)
+ if err := SetClipboardImageAsync(picture, func(err error) {
+ completions++
+ completion = err
+ }); err != nil {
+ t.Fatal(err)
+ }
+ if completions != 1 || completion != nil {
+ t.Fatalf("done ran %d times with %v, want once with nil", completions, completion)
+ }
+ read, err = ClipboardImagePNG()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(read, picture) {
+ t.Fatal("the asynchronous copy did not put the same picture on the clipboard")
+ }
+}
diff --git a/app/driver_system.go b/app/driver_system.go
index ad9d8f90a..21289fc27 100644
--- a/app/driver_system.go
+++ b/app/driver_system.go
@@ -136,6 +136,18 @@ func driverSetClipboardFiles(paths []string) (error, bool) {
return nil, true
}
+// driverSetClipboardImage answers the image copy of a driver-backed run: the
+// driver's private clipboard holds the PNG and loses its text, html, files and
+// rectangular marker, as the system clipboard takes the same copy. A PNG the
+// driver refuses, one above the cap, replaces nothing and reports its error.
+func driverSetClipboardImage(png []byte) (error, bool) {
+ system := activeDriverSystem.Load()
+ if system == nil {
+ return nil, false
+ }
+ return system.driver.SetClipboardImage(png), true
+}
+
// driverStartFileDrag answers a drag of files out of a driver-backed run: the
// driver records what the application asked and takes the effect a folder window
// takes, with no native drag and no pointer to move.
diff --git a/app/driver_system_unsupported.go b/app/driver_system_unsupported.go
index 9b693860e..9f578cfcf 100644
--- a/app/driver_system_unsupported.go
+++ b/app/driver_system_unsupported.go
@@ -24,6 +24,8 @@ func driverClipboardFiles() (paths []string, err error, handled bool) { return n
func driverSetClipboardFiles([]string) (error, bool) { return nil, false }
+func driverSetClipboardImage([]byte) (error, bool) { return nil, false }
+
func driverStartFileDrag([]string, platform.DragEffect) (platform.DragEffect, error, bool) {
return platform.DragEffectNone, nil, false
}
diff --git a/app/system_async.go b/app/system_async.go
index 3bf11ac56..d82dd9a97 100644
--- a/app/system_async.go
+++ b/app/system_async.go
@@ -3,6 +3,8 @@ package app
import (
"fmt"
"strings"
+
+ "github.com/vivaui/viva/internal/platform"
)
// NotificationPermission is the browser's answer to a notification permission
@@ -62,6 +64,30 @@ func SetClipboardHTMLAsync(html, alt string, done func(error)) error {
return nativeSetClipboardHTMLAsync(html, alt, done)
}
+// SetClipboardImageAsync starts SetClipboardImage's write and calls done with
+// nil once the platform accepted it. The call returns immediately when the
+// request starts; an error means it could not start and done is not called. A
+// PNG the write refuses is such an error, not a completion: png must be one
+// within MaxClipboardImageBytes. Native targets complete before the call
+// returns; the browser writes one ClipboardItem with the "image/png" flavour,
+// which needs a user gesture.
+func SetClipboardImageAsync(png []byte, done func(error)) error {
+ if done == nil {
+ return fmt.Errorf("app: nil clipboard callback")
+ }
+ if len(png) == 0 {
+ return fmt.Errorf("app: no image to put on the clipboard")
+ }
+ if err := platform.CheckClipboardPNG(png); err != nil {
+ return err
+ }
+ if err, handled := driverSetClipboardImage(png); handled {
+ done(err)
+ return nil
+ }
+ return nativeSetClipboardImageAsync(png, done)
+}
+
// RequestNotificationPermission asks the browser for permission to show
// notifications. On desktop it calls done with Granted because the operating
// system asks for permission when a notification is delivered. done runs
diff --git a/app/system_async_js.go b/app/system_async_js.go
index 7e8f7ca0f..a535db599 100644
--- a/app/system_async_js.go
+++ b/app/system_async_js.go
@@ -22,6 +22,12 @@ func nativeSetClipboardHTMLAsync(html, alt string, done func(error)) error {
}))
}
+func nativeSetClipboardImageAsync(png []byte, done func(error)) error {
+ return webSystemError("write clipboard image", webplatform.SetClipboardImageAsync(png, func(err error) {
+ done(webSystemError("write clipboard image", err))
+ }))
+}
+
func nativeRequestNotificationPermission(done func(NotificationPermission, error)) error {
return webSystemError("request notification permission", webplatform.RequestNotificationPermission(func(granted bool, err error) {
if err != nil {
diff --git a/app/system_async_other.go b/app/system_async_other.go
index 5a74bea4e..69d2492e1 100644
--- a/app/system_async_other.go
+++ b/app/system_async_other.go
@@ -18,6 +18,11 @@ func nativeSetClipboardHTMLAsync(html, alt string, done func(error)) error {
return nil
}
+func nativeSetClipboardImageAsync(png []byte, done func(error)) error {
+ done(nativeSetClipboardImage(png))
+ return nil
+}
+
func nativeRequestNotificationPermission(done func(NotificationPermission, error)) error {
done(NotificationPermissionGranted, nil)
return nil
diff --git a/app/system_darwin.go b/app/system_darwin.go
index 120ed41c0..04427ae52 100644
--- a/app/system_darwin.go
+++ b/app/system_darwin.go
@@ -16,6 +16,8 @@ func nativeHasClipboardImage() bool { return darwinplatform.HasClipboardImage()
func nativeClipboardImagePNG() ([]byte, error) { return darwinplatform.ClipboardImagePNG() }
+func nativeSetClipboardImage(png []byte) error { return darwinplatform.SetClipboardImage(png) }
+
func nativeClipboardFiles() ([]string, error) { return darwinplatform.ClipboardFiles() }
func nativeSetClipboardFiles(paths []string) error { return darwinplatform.SetClipboardFiles(paths) }
diff --git a/app/system_js.go b/app/system_js.go
index ca4b2ff88..eaf4ba3be 100644
--- a/app/system_js.go
+++ b/app/system_js.go
@@ -39,6 +39,12 @@ func nativeClipboardFiles() ([]string, error) { return nil, ErrUnsupported }
func nativeSetClipboardFiles([]string) error { return ErrUnsupported }
+// nativeSetClipboardImage cannot answer synchronously: Clipboard.write returns a
+// Promise, so use SetClipboardImageAsync.
+func nativeSetClipboardImage(png []byte) error {
+ return webSystemError("write clipboard image", webplatform.SetClipboardImage(png))
+}
+
func nativeStartFileDrag(paths []string, allowed FileDragEffect) (FileDragEffect, error) {
return webplatform.StartFileDrag(paths, allowed)
}
diff --git a/app/system_linux.go b/app/system_linux.go
index ac1f0a51c..8d0da1956 100644
--- a/app/system_linux.go
+++ b/app/system_linux.go
@@ -54,6 +54,10 @@ func nativeClipboardImagePNG() ([]byte, error) {
return png, linuxSystemError(err)
}
+func nativeSetClipboardImage(png []byte) error {
+ return linuxSystemError(linuxplatform.SetClipboardImage(png))
+}
+
func nativeSetCursor(cursor Cursor) error {
return linuxSystemError(linuxplatform.SetCursorShape(uint8(cursor)))
}
diff --git a/app/system_unsupported.go b/app/system_unsupported.go
index a1cde86aa..91c69a44a 100644
--- a/app/system_unsupported.go
+++ b/app/system_unsupported.go
@@ -15,6 +15,7 @@ func nativeClipboardText() (string, error) { return "", ErrU
func nativeSetClipboardText(string) error { return ErrUnsupported }
func nativeHasClipboardImage() bool { return false }
func nativeClipboardImagePNG() ([]byte, error) { return nil, ErrUnsupported }
+func nativeSetClipboardImage([]byte) error { return ErrUnsupported }
func nativeClipboardFiles() ([]string, error) { return nil, ErrUnsupported }
func nativeSetClipboardFiles([]string) error { return ErrUnsupported }
func nativeOnClipboardChange(func()) error { return ErrUnsupported }
diff --git a/app/system_windows.go b/app/system_windows.go
index 92f4bfba0..90714fa4f 100644
--- a/app/system_windows.go
+++ b/app/system_windows.go
@@ -13,6 +13,8 @@ func nativeHasClipboardImage() bool { return windowsplatform.HasClipboardImage()
func nativeClipboardImagePNG() ([]byte, error) { return windowsplatform.ClipboardImagePNG() }
+func nativeSetClipboardImage(png []byte) error { return windowsplatform.SetClipboardImage(png) }
+
func nativeClipboardFiles() ([]string, error) { return windowsplatform.ClipboardFiles() }
func nativeSetClipboardFiles(paths []string) error { return windowsplatform.SetClipboardFiles(paths) }
diff --git a/docs/system-integrations.md b/docs/system-integrations.md
index 259d9583e..580fefff6 100644
--- a/docs/system-integrations.md
+++ b/docs/system-integrations.md
@@ -13,6 +13,7 @@ synchronous forms report `ErrAsyncRequired`, `ErrSecretStoreUnavailable` or
| Column-selection clipboard (`SetRectangularClipboardText`, `ClipboardTextWithFormat`; `TextInput.CopyRectangular`, `TextEvent.Rectangular`) | no platform format; reads report `false` | Unicode text beside `MSDEVColumnSelect` (presence) and `Borland IDE Block Type` (one byte, `0x02`); an advertised marker whose data cannot be read is pasted as stream text | reads report `false` | reads report `false` |
| Rich copy (`SetClipboardHTML`, html + plain alt) | `NSPasteboard`: `public.html` beside `public.utf8-plain-text` | registered `HTML Format` (CF_HTML, with its header of byte offsets) beside `CF_UNICODETEXT` | X11 `CLIPBOARD`: `text/html` target beside `UTF8_STRING`; the GTK shell serves the same pair through `gtk_clipboard_set_with_data` | synchronous calls return `ErrAsyncRequired`; `SetClipboardHTMLAsync` writes one `ClipboardItem` with both MIME flavours and needs a user gesture |
| Copied files (`ClipboardFiles`, returns `[]string`) | the pasteboard's file URLs, file reference URLs resolved to paths; promised files have no path and are not listed | the `CF_HDROP` list (UTF-16 form) | X11 `CLIPBOARD`: `x-special/gnome-copied-files` (Nautilus, Nemo, Caja, Thunar) or `text/uri-list` (Dolphin, most toolkits); the GTK shell asks GTK for `text/uri-list` | `ErrUnsupported` |
+| Copying a picture (`SetClipboardImage`, the write side of `ClipboardImagePNG`) | `NSPasteboard`: `public.png` beside its `public.tiff` conversion, so a reader that asks only for TIFF (Mail, TextEdit, Notes) pastes too | registered `PNG` format beside `CF_DIB` (32-bit, bottom-up); Windows synthesises `CF_DIBV5` and `CF_BITMAP` for the readers that ask for those. The bitmap is composited on white because a DIB carries no alpha | X11 `CLIPBOARD`: `image/png` target served from the window's own copy, INCR above one property; the GTK shell serves the same target through `gtk_clipboard_set_with_data`. Needs a running window (GTK does not) | synchronous calls return `ErrAsyncRequired`; `SetClipboardImageAsync` writes one `ClipboardItem` with the `image/png` flavour and needs a user gesture |
| Dragging files out (`StartFileDrag`, returns `FileDragEffect`) | `ErrUnsupported`: needs an `NSDraggingSession`, which the adapter does not bind yet | an OLE drag: an `IDataObject` offering the paths as `CF_HDROP` and an `IDropSource` that ends the drag when the pointer is released and cancels it on Escape, run by `DoDragDrop` on the window's event-loop thread. `SetClipboardFiles` is the copy a paste makes, not this | `ErrUnsupported`: needs XDND as a source, which the adapter does not speak yet | `ErrUnsupported`: a canvas has no DOM `DataTransfer` |
| Primary selection (`SetPrimarySelection`, `PrimarySelection`) | `ErrUnsupported` | `ErrUnsupported` | X11 `PRIMARY`: selected text, pasted with a middle click | `ErrUnsupported` |
| Cursor shape | AppKit cursor; wait unsupported, diagonal resize requires macOS 15 | Win32 system cursors; running window required | XCB cursor font; running window required | CSS cursor on `documentElement` |
@@ -78,6 +79,33 @@ single running copy should pass those arguments through
Callers should use `errors.Is` rather than matching error strings.
+## Copying a picture onto the clipboard
+
+`SetClipboardImage` is the write side of `ClipboardImagePNG`: it makes a PNG the
+picture the clipboard holds, so another application's Paste puts it there, and a
+later read of what it wrote returns the same picture. It replaces everything the
+clipboard held, text included, because one clipboard holds one copy.
+
+Each platform offers the picture in the flavours its readers ask for. Windows
+puts the registered `PNG` format, which is the exact file, beside `CF_DIB`, which
+is what Paint, Word and Explorer's preview ask for; the DIB is composited on
+white because that format has no alpha, so the transparency of the original
+survives only in the `PNG` flavour. macOS puts `public.png` beside its
+`public.tiff` conversion, for the applications that ask for TIFF alone. Linux
+serves the `image/png` target from the window's own copy, which means a copy
+needs a running window: a selection lives as long as its owner does, and the GTK
+shell is the exception because GTK keeps it. The browser writes one
+`ClipboardItem` with the `image/png` flavour through `SetClipboardImageAsync`;
+the synchronous call reports `ErrAsyncRequired` there, as every other clipboard
+write does.
+
+The bytes are checked before anything is written: an empty image, one that is
+not a PNG, one above `MaxClipboardImageBytes`, and on Windows one whose pixels
+would not fit a bitmap are errors, and a refused copy leaves the clipboard as it
+was. The headless driver keeps the picture in its private clipboard
+(`Driver.SetClipboardImage`) and answers the same reads, so a copy and the paste
+that follows it can be exercised without a desktop.
+
## Pasting a picture into a text field
A text field cannot hold a picture, so a paste (Command or Control+V, Shift+Insert)
@@ -145,7 +173,7 @@ through Promises. They are intentionally not started from the synchronous API:
returning before the Promise settles would lie about success, and waiting would
deadlock the WASM event loop. The typed asynchronous counterparts are
`ClipboardTextAsync`, `SetClipboardTextAsync`, `SetClipboardHTMLAsync`, `RequestClipboardImage`,
-`OpenFilesAsync`, `SaveFileAsync`, `StoreSecretAsync`, `LoadSecretAsync`,
+`SetClipboardImageAsync`, `OpenFilesAsync`, `SaveFileAsync`, `StoreSecretAsync`, `LoadSecretAsync`,
`DeleteSecretAsync`, `RegisterFontAsync` and `RequestNotificationPermission`.
Each calls its completion exactly once; native targets complete before the call
returns, browsers complete on the event loop.
diff --git a/docs/web-deployment.md b/docs/web-deployment.md
index 16dea2b7a..170923e0c 100644
--- a/docs/web-deployment.md
+++ b/docs/web-deployment.md
@@ -123,6 +123,7 @@ The browser reports these integrations:
| `CapabilityFileDrop` | Dropped files arrive with `gfx.FileDropEvent.Files`; no paths |
| `CapabilityClipboardTextAsync` | `navigator.clipboard.readText` / `writeText` |
| `CapabilityClipboardImageAsync` | `navigator.clipboard.read`; PNG only |
+| `CapabilityClipboardImageWriteAsync` | `navigator.clipboard.write` with `ClipboardItem`; PNG only |
| `CapabilityFileDialogsAsync` | `showOpenFilePicker`, or an `` fallback |
| `CapabilitySecretStoreAsync` | AES-GCM through WebCrypto, ciphertext in IndexedDB |
| `CapabilityNotifications` | `Notification` after the page has permission |
diff --git a/internal/platform/clipboard_dib_windows.go b/internal/platform/clipboard_dib_windows.go
index 2bdd1c390..fe932b36e 100644
--- a/internal/platform/clipboard_dib_windows.go
+++ b/internal/platform/clipboard_dib_windows.go
@@ -11,6 +11,7 @@ import (
"encoding/binary"
"fmt"
"image"
+ "image/draw"
"image/png"
)
@@ -262,3 +263,64 @@ func EncodePNG(picture image.Image) ([]byte, error) {
}
return out.Bytes(), nil
}
+
+// PNGToDIB converts PNG bytes to the packed bitmap the CF_DIB format carries: a
+// BITMAPINFOHEADER and 32-bit bottom-up BGRX rows, top-left origin. The picture
+// is composited on white, because a CF_DIB has no alpha to carry: a reader that
+// keeps transparency takes the registered "PNG" format the clipboard offers
+// beside it. A PNG with too many pixels or a bitmap above MaxClipboardRawBytes
+// is ErrClipboardImageTooLarge.
+func PNGToDIB(encoded []byte) ([]byte, error) {
+ picture, err := png.Decode(bytes.NewReader(encoded))
+ if err != nil {
+ return nil, fmt.Errorf("clipboard PNG cannot be decoded: %w", err)
+ }
+ bounds := picture.Bounds()
+ width, height := bounds.Dx(), bounds.Dy()
+ if width <= 0 || height <= 0 {
+ return nil, fmt.Errorf("clipboard PNG has no pixels")
+ }
+ if width > maxDIBPixels || height > maxDIBPixels || width*height > maxDIBPixels {
+ return nil, ErrClipboardImageTooLarge
+ }
+ stride := width * 4
+ size := dibInfoHeader + stride*height
+ if size > MaxClipboardRawBytes {
+ return nil, ErrClipboardImageTooLarge
+ }
+ pixels := image.NewNRGBA(image.Rect(0, 0, width, height))
+ draw.Draw(pixels, pixels.Bounds(), picture, bounds.Min, draw.Src)
+ dib := make([]byte, size)
+ binary.LittleEndian.PutUint32(dib[0:], dibInfoHeader)
+ binary.LittleEndian.PutUint32(dib[4:], uint32(width))
+ binary.LittleEndian.PutUint32(dib[8:], uint32(height)) // a positive height is bottom-up
+ binary.LittleEndian.PutUint16(dib[12:], 1) // planes
+ binary.LittleEndian.PutUint16(dib[14:], 32) // bits per pixel
+ // BI_RGB and the palette fields stay the zero the block already holds.
+ binary.LittleEndian.PutUint32(dib[20:], uint32(stride*height)) // the pixels' size
+ binary.LittleEndian.PutUint32(dib[24:], 2835) // 72 dpi
+ binary.LittleEndian.PutUint32(dib[28:], 2835)
+ for row := range height {
+ source := pixels.Pix[row*pixels.Stride:]
+ target := dib[dibInfoHeader+(height-1-row)*stride:]
+ for column := range width {
+ red, green, blue, alpha := source[column*4], source[column*4+1], source[column*4+2], uint32(source[column*4+3])
+ target[column*4] = compositeOnWhite(blue, alpha)
+ target[column*4+1] = compositeOnWhite(green, alpha)
+ target[column*4+2] = compositeOnWhite(red, alpha)
+ // A reader that takes the unused byte for alpha sees an opaque
+ // picture, which is what the composited colours already are.
+ target[column*4+3] = 0xff
+ }
+ }
+ return dib, nil
+}
+
+// compositeOnWhite layers a straight-alpha channel value over white, the
+// background a CF_DIB reader draws where the picture is transparent.
+func compositeOnWhite(value uint8, alpha uint32) uint8 {
+ if alpha == 255 {
+ return value
+ }
+ return uint8((uint32(value)*alpha + 255*(255-alpha) + 127) / 255)
+}
diff --git a/internal/platform/clipboard_dib_write_windows_test.go b/internal/platform/clipboard_dib_write_windows_test.go
new file mode 100644
index 000000000..23f4213d1
--- /dev/null
+++ b/internal/platform/clipboard_dib_write_windows_test.go
@@ -0,0 +1,109 @@
+//go:build windows
+
+package platform
+
+import (
+ "bytes"
+ "image"
+ "image/color"
+ "image/png"
+ "testing"
+)
+
+// picturePNG encodes a picture whose channels and edges a round trip has to keep
+// apart: a grid of colours that differ in every channel and in every direction.
+func picturePNG(t *testing.T, width, height int) []byte {
+ t.Helper()
+ picture := image.NewNRGBA(image.Rect(0, 0, width, height))
+ for y := range height {
+ for x := range width {
+ picture.SetNRGBA(x, y, color.NRGBA{R: uint8(30 + 50*x), G: uint8(10 + 60*y), B: 200, A: 255})
+ }
+ }
+ var out bytes.Buffer
+ if err := png.Encode(&out, picture); err != nil {
+ t.Fatal(err)
+ }
+ return out.Bytes()
+}
+
+// TestPNGToDIBRoundTripsThroughDIBToPNG converts a PNG to the bitmap CF_DIB
+// carries and reads it back with the DIB reader, the two halves of one clipboard
+// format: a picture that survives both is what a paste of the copy shows.
+func TestPNGToDIBRoundTripsThroughDIBToPNG(t *testing.T) {
+ encoded := picturePNG(t, 5, 3)
+ dib, err := PNGToDIB(encoded)
+ if err != nil {
+ t.Fatal(err)
+ }
+ read, err := DIBToPNG(dib)
+ if err != nil {
+ t.Fatal(err)
+ }
+ got, err := png.Decode(bytes.NewReader(read))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if bounds := got.Bounds(); bounds.Dx() != 5 || bounds.Dy() != 3 {
+ t.Fatalf("size = %dx%d, want 5x3 (rows upside down?)", bounds.Dx(), bounds.Dy())
+ }
+ want, err := png.Decode(bytes.NewReader(encoded))
+ if err != nil {
+ t.Fatal(err)
+ }
+ for y := range 3 {
+ for x := range 5 {
+ expected := color.NRGBAModel.Convert(want.At(x, y)).(color.NRGBA)
+ if actual := color.NRGBAModel.Convert(got.At(x, y)).(color.NRGBA); actual != expected {
+ t.Fatalf("pixel (%d,%d) = %v, want %v", x, y, actual, expected)
+ }
+ }
+ }
+}
+
+// TestPNGToDIBCompositesTransparencyOnWhite pins the one thing the bitmap
+// flavour cannot carry: a transparent pixel reaches a CF_DIB reader as the white
+// its background is, not as black and not as a colour without alpha.
+func TestPNGToDIBCompositesTransparencyOnWhite(t *testing.T) {
+ picture := image.NewNRGBA(image.Rect(0, 0, 2, 1))
+ picture.SetNRGBA(0, 0, color.NRGBA{R: 10, G: 20, B: 30, A: 0})
+ picture.SetNRGBA(1, 0, color.NRGBA{R: 10, G: 20, B: 30, A: 128})
+ var encoded bytes.Buffer
+ if err := png.Encode(&encoded, picture); err != nil {
+ t.Fatal(err)
+ }
+ dib, err := PNGToDIB(encoded.Bytes())
+ if err != nil {
+ t.Fatal(err)
+ }
+ read, err := DIBToPNG(dib)
+ if err != nil {
+ t.Fatal(err)
+ }
+ decoded, err := png.Decode(bytes.NewReader(read))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := color.NRGBAModel.Convert(decoded.At(0, 0)).(color.NRGBA); got != (color.NRGBA{R: 255, G: 255, B: 255, A: 255}) {
+ t.Fatalf("fully transparent pixel = %v, want white", got)
+ }
+ // (10,20,30) at half alpha over white: 10*128+255*127 rounded, and so on.
+ if got := color.NRGBAModel.Convert(decoded.At(1, 0)).(color.NRGBA); got != (color.NRGBA{R: 132, G: 137, B: 142, A: 255}) {
+ t.Fatalf("half-transparent pixel = %v, want the colour layered on white", got)
+ }
+}
+
+// TestPNGToDIBRefusesWhatIsNotAPicture keeps the write path from putting bytes
+// on the clipboard that no reader can open.
+func TestPNGToDIBRefusesWhatIsNotAPicture(t *testing.T) {
+ if _, err := PNGToDIB([]byte("GIF89a, not a PNG")); err == nil {
+ t.Fatal("bytes that are not a PNG were converted")
+ }
+ truncated := picturePNG(t, 4, 4)
+ if _, err := PNGToDIB(truncated[:len(truncated)/2]); err == nil {
+ t.Fatal("a truncated PNG was converted")
+ }
+ if _, err := PNGToDIB(nil); err == nil {
+ t.Fatal("an empty image was converted")
+ }
+}
diff --git a/internal/platform/clipboard_image.go b/internal/platform/clipboard_image.go
index cf2769da2..0c8529ea8 100644
--- a/internal/platform/clipboard_image.go
+++ b/internal/platform/clipboard_image.go
@@ -5,6 +5,7 @@ import (
"encoding/binary"
"errors"
"fmt"
+ "image/png"
)
// Errors every platform's clipboard image reader returns; app re-exports them.
@@ -27,8 +28,10 @@ const (
var pngSignature = []byte("\x89PNG\r\n\x1a\n")
// CheckClipboardPNG validates data a clipboard owner offered as PNG: it must be
-// within the size cap and start with the PNG signature. The pixels are not
-// decoded here.
+// within the size cap, start with the PNG signature, and name a picture whose
+// pixels fit MaxClipboardRawBytes. The pixels are not decoded here, so a PNG
+// that expands to more memory than the platform can hold is refused before any
+// platform allocates it.
func CheckClipboardPNG(data []byte) error {
switch {
case len(data) == 0:
@@ -38,6 +41,14 @@ func CheckClipboardPNG(data []byte) error {
case !bytes.HasPrefix(data, pngSignature):
return fmt.Errorf("clipboard image is not a PNG")
}
+ config, err := png.DecodeConfig(bytes.NewReader(data))
+ if err != nil {
+ return fmt.Errorf("clipboard image is not a PNG: %w", err)
+ }
+ if config.Width <= 0 || config.Height <= 0 ||
+ int64(config.Width)*int64(config.Height) > int64(MaxClipboardRawBytes)/4 {
+ return ErrClipboardImageTooLarge
+ }
return nil
}
diff --git a/internal/platform/clipboard_png_test.go b/internal/platform/clipboard_png_test.go
index ef1e0dd98..2b5651fad 100644
--- a/internal/platform/clipboard_png_test.go
+++ b/internal/platform/clipboard_png_test.go
@@ -2,7 +2,9 @@ package platform
import (
"bytes"
+ "encoding/binary"
"errors"
+ "hash/crc32"
"image"
"image/png"
"testing"
@@ -28,8 +30,48 @@ func TestCheckClipboardPNG(t *testing.T) {
}
}
+// A PNG small enough to hand over but naming a picture too large to hold is
+// refused before a platform decodes it: the encoded size says nothing about the
+// memory the pixels need.
+func TestCheckClipboardPNGRejectsTooManyPixels(t *testing.T) {
+ if err := CheckClipboardPNG(pngHeader(1000, 1000)); err != nil {
+ t.Fatalf("a 1000x1000 PNG was refused: %v", err)
+ }
+ if err := CheckClipboardPNG(pngHeader(20000, 20000)); !errors.Is(err, ErrClipboardImageTooLarge) {
+ t.Fatalf("a 20000x20000 PNG = %v, want ErrClipboardImageTooLarge", err)
+ }
+}
+
+// pngHeader builds a PNG that stops after its IHDR chunk, which is everything
+// DecodeConfig reads: width and height are what the test chooses.
+func pngHeader(width, height uint32) []byte {
+ ihdr := make([]byte, 13)
+ binary.BigEndian.PutUint32(ihdr[0:], width)
+ binary.BigEndian.PutUint32(ihdr[4:], height)
+ ihdr[8] = 8 // bit depth
+ ihdr[9] = 6 // colour type: RGBA
+ var out bytes.Buffer
+ out.Write(pngSignature)
+ var length [4]byte
+ binary.BigEndian.PutUint32(length[:], uint32(len(ihdr)))
+ out.Write(length[:])
+ out.WriteString("IHDR")
+ out.Write(ihdr)
+ crc := crc32.NewIEEE()
+ crc.Write([]byte("IHDR"))
+ crc.Write(ihdr)
+ var sum [4]byte
+ binary.BigEndian.PutUint32(sum[:], crc.Sum32())
+ out.Write(sum[:])
+ return out.Bytes()
+}
+
func BenchmarkCheckClipboardPNG(b *testing.B) {
- data := append(append([]byte{}, pngSignature...), make([]byte, 1<<20)...)
+ var encoded bytes.Buffer
+ if err := png.Encode(&encoded, image.NewNRGBA(image.Rect(0, 0, 64, 64))); err != nil {
+ b.Fatal(err)
+ }
+ data := encoded.Bytes()
b.ReportAllocs()
for b.Loop() {
if err := CheckClipboardPNG(data); err != nil {
diff --git a/internal/platform/darwin/clipboard_image_darwin.go b/internal/platform/darwin/clipboard_image_darwin.go
index 76395b762..ad65f2a32 100644
--- a/internal/platform/darwin/clipboard_image_darwin.go
+++ b/internal/platform/darwin/clipboard_image_darwin.go
@@ -13,6 +13,8 @@ import (
"path/filepath"
"strings"
"unsafe"
+
+ "github.com/vivaui/viva/internal/platform"
)
// The conversion is exercised on private pasteboards, never the user's
@@ -43,6 +45,23 @@ func putPrivatePasteboardImage(name string, png []byte, asTIFF bool) error {
return nil
}
+// SetClipboardImage puts png on the general pasteboard, as copying a picture in
+// Preview does: public.png as it is beside its public.tiff conversion, because
+// an application that asks only for TIFF (Mail, TextEdit, Notes) pastes the
+// picture from that one and an application that knows PNG keeps the original
+// bytes. Everything the pasteboard held is gone, as after any copy. png must be
+// a PNG within platform.MaxClipboardImageBytes and one AppKit reads into a
+// picture; anything else is an error and the pasteboard is left as it was.
+func SetClipboardImage(png []byte) error {
+ if err := platform.CheckClipboardPNG(png); err != nil {
+ return err
+ }
+ if C.viva_system_pasteboard_put_image_flavours(nil, (*C.uint8_t)(unsafe.Pointer(&png[0])), C.size_t(len(png))) != 0 {
+ return fmt.Errorf("darwin: put image on the clipboard failed")
+ }
+ return nil
+}
+
func privatePasteboardFiles(name string) ([]string, error) {
cName := C.CString(name)
defer C.free(unsafe.Pointer(cName))
diff --git a/internal/platform/darwin/system_darwin.h b/internal/platform/darwin/system_darwin.h
index a0b9d930b..bd5de21b5 100644
--- a/internal/platform/darwin/system_darwin.h
+++ b/internal/platform/darwin/system_darwin.h
@@ -19,6 +19,11 @@ int viva_system_clipboard_has_image(const char *pasteboard);
int viva_system_clipboard_image_png(const char *pasteboard, size_t max_png, size_t max_raw, uint8_t **data, size_t *length, char **error_message);
// Puts an image (PNG bytes) on a named pasteboard, as TIFF when as_tiff is set.
int viva_system_pasteboard_put_image(const char *pasteboard, const uint8_t *png, size_t length, int as_tiff);
+// Puts an image (PNG bytes) on a named pasteboard as public.png beside its
+// public.tiff conversion, the pair a copy leaves for readers that know only one
+// of them; NULL is the general pasteboard (main thread). Status: 0 written,
+// -1 the bytes are not a picture AppKit can convert.
+int viva_system_pasteboard_put_image_flavours(const char *pasteboard, const uint8_t *png, size_t length);
// Copied files. A NULL pasteboard name is the general pasteboard (main thread).
// Status: 0 paths returned in *paths (free with viva_system_free_string_array),
// 1 no files, -1 failure with *error_message. At most max paths are returned.
diff --git a/internal/platform/darwin/system_darwin.m b/internal/platform/darwin/system_darwin.m
index bd15c259b..0bf9a839f 100644
--- a/internal/platform/darwin/system_darwin.m
+++ b/internal/platform/darwin/system_darwin.m
@@ -457,6 +457,44 @@ int viva_system_pasteboard_put_image(const char *pasteboard, const uint8_t *png,
}
}
+// viva_system_pasteboard_put_image_flavours writes png as public.png beside its
+// public.tiff conversion, the pair an image copy leaves: a reader that knows PNG
+// takes the original bytes, and an application that asks only for TIFF (Mail,
+// TextEdit, Notes) still pastes the picture.
+int viva_system_pasteboard_put_image_flavours(const char *pasteboard, const uint8_t *png, size_t length) {
+ __block char *failure = NULL;
+ dispatch_block_t operation = ^{
+ @autoreleasepool {
+ NSData *bytes = [NSData dataWithBytes:png length:length];
+ NSBitmapImageRep *representation = [NSBitmapImageRep imageRepWithData:bytes];
+ NSData *tiff = representation.TIFFRepresentation;
+ if (tiff == nil) {
+ failure = viva_copy_utf8(@"clipboard image is not a picture AppKit reads");
+ return;
+ }
+ NSPasteboard *board = viva_pasteboard_named(pasteboard);
+ [board clearContents];
+ if (![board setData:bytes forType:NSPasteboardTypePNG]) {
+ failure = viva_copy_utf8(@"AppKit refused clipboard PNG");
+ return;
+ }
+ // The conversion is the flavour older readers ask for; the PNG stays
+ // the original, so a refusal here only costs that compatibility.
+ [board setData:tiff forType:NSPasteboardTypeTIFF];
+ }
+ };
+ if (pasteboard == NULL) {
+ viva_on_main_sync(operation);
+ } else {
+ operation();
+ }
+ if (failure != NULL) {
+ free(failure);
+ return -1;
+ }
+ return 0;
+}
+
int viva_system_clipboard_files(const char *pasteboard, size_t max, viva_system_string_array *paths, char **error_message) {
if (paths == NULL) {
viva_set_error(error_message, @"clipboard files output is missing");
diff --git a/internal/platform/linux/clipboard_files_write_linux.go b/internal/platform/linux/clipboard_files_write_linux.go
index bcf155ec5..9d6019457 100644
--- a/internal/platform/linux/clipboard_files_write_linux.go
+++ b/internal/platform/linux/clipboard_files_write_linux.go
@@ -46,6 +46,7 @@ func SetClipboardFiles(paths []string) error {
win.clipboard = strings.Join(names, "\n")
win.clipboardHTML = ""
win.clipboardFiles = append([]string(nil), paths...)
+ win.clipboardImage = nil
win.ownsClipboard = true
return nil
}
diff --git a/internal/platform/linux/clipboard_html_write_linux.go b/internal/platform/linux/clipboard_html_write_linux.go
index ccc726dd7..8fe296b14 100644
--- a/internal/platform/linux/clipboard_html_write_linux.go
+++ b/internal/platform/linux/clipboard_html_write_linux.go
@@ -42,6 +42,7 @@ func SetClipboardHTML(html, alt string) error {
win.clipboard = alt
win.clipboardHTML = html
win.clipboardFiles = nil
+ win.clipboardImage = nil
win.ownsClipboard = true
return nil
}
diff --git a/internal/platform/linux/clipboard_image_write_linux.go b/internal/platform/linux/clipboard_image_write_linux.go
new file mode 100644
index 000000000..fc705d96a
--- /dev/null
+++ b/internal/platform/linux/clipboard_image_write_linux.go
@@ -0,0 +1,48 @@
+package linux
+
+import (
+ "fmt"
+
+ "github.com/vivaui/viva/internal/platform"
+)
+
+// SetClipboardImage makes png the CLIPBOARD selection, as copying a picture in
+// an image viewer does: the X11 owner serves the image/png target while this
+// window lives; GTK, which owns the display connection on Wayland, serves the
+// same target through its own clipboard. The picture is passed on as the PNG its
+// owner wrote, so it keeps the exact bytes and their transparency. Everything
+// the clipboard held is gone, as after any copy.
+//
+// png must be a PNG within platform.MaxClipboardImageBytes, and a clipboard
+// selection needs a running window: it lives as long as the process that owns it
+// does. The GTK shell serves it without one, because GTK keeps the selection
+// itself.
+func SetClipboardImage(png []byte) error {
+ if err := platform.CheckClipboardPNG(png); err != nil {
+ return err
+ }
+ if hooks := shellHooks.Load(); hooks != nil {
+ if hooks.setClipboardImage == nil {
+ return ErrUnsupported
+ }
+ return hooks.setClipboardImage(png)
+ }
+ win := activeWindow.Load()
+ if win == nil {
+ return fmt.Errorf("linux: clipboard ownership requires a running window")
+ }
+ win.mu.Lock()
+ defer win.mu.Unlock()
+ if activeWindow.Load() != win || win.connection == 0 {
+ return fmt.Errorf("linux: clipboard ownership requires a running window")
+ }
+ if err := win.claimClipboardLocked(); err != nil {
+ return err
+ }
+ win.clipboard = ""
+ win.clipboardHTML = ""
+ win.clipboardFiles = nil
+ win.clipboardImage = append([]byte(nil), png...)
+ win.ownsClipboard = true
+ return nil
+}
diff --git a/internal/platform/linux/clipboard_image_write_linux_test.go b/internal/platform/linux/clipboard_image_write_linux_test.go
new file mode 100644
index 000000000..83fd3e130
--- /dev/null
+++ b/internal/platform/linux/clipboard_image_write_linux_test.go
@@ -0,0 +1,118 @@
+package linux
+
+import (
+ "bytes"
+ "encoding/binary"
+ "image"
+ "image/png"
+ "slices"
+ "testing"
+)
+
+// picturePNG is a real PNG, the shape of what SetClipboardImage is given: the
+// checks read its header, so the bytes must decode as one.
+func picturePNG(t *testing.T) []byte {
+ t.Helper()
+ var encoded bytes.Buffer
+ if err := png.Encode(&encoded, image.NewNRGBA(image.Rect(0, 0, 2, 2))); err != nil {
+ t.Fatal(err)
+ }
+ return encoded.Bytes()
+}
+
+// newSelectionWindowWithImage is newSelectionWindow holding a picture and no
+// text, the shape of an image copy.
+func newSelectionWindowWithImage(recorder *selectionRecorder, picture []byte) *window {
+ win := newSelectionWindow(recorder, "")
+ win.clipboardImage = picture
+ win.pngAtom = 19
+ return win
+}
+
+func offeredTargets(t *testing.T, write propertyWrite) []uint32 {
+ t.Helper()
+ var offered []uint32
+ for offset := 0; offset+4 <= len(write.data); offset += 4 {
+ offered = append(offered, binary.LittleEndian.Uint32(write.data[offset:]))
+ }
+ return offered
+}
+
+// An image copy is offered as image/png and as nothing else: the CLIPBOARD holds
+// a picture, so TARGETS names no text target, the png target hands over the exact
+// bytes the owner wrote, and another copy drops the picture.
+func TestAClipboardImageIsOfferedAsPNGAndNoText(t *testing.T) {
+ picture := []byte("\x89PNG\r\n\x1a\npicture bytes")
+ recorder := &selectionRecorder{}
+ win := newSelectionWindowWithImage(recorder, picture)
+ request := func(target uint32) propertyWrite {
+ t.Helper()
+ before := len(recorder.writes)
+ if err := win.handleSelectionRequest(&xcbSelectionRequestEvent{Requestor: 3, Selection: 10, Target: target, Property: 14}); err != nil {
+ t.Fatal(err)
+ }
+ if len(recorder.writes) != before+1 {
+ t.Fatalf("target %d wrote no property", target)
+ }
+ return recorder.writes[before]
+ }
+ targets := offeredTargets(t, request(win.targetsAtom))
+ if !slices.Contains(targets, win.pngAtom) {
+ t.Fatalf("TARGETS = %v, want image/png=%d among them", targets, win.pngAtom)
+ }
+ for _, atom := range []uint32{win.utf8Atom, win.textAtom, xcbAtomString} {
+ if slices.Contains(targets, atom) {
+ t.Fatalf("TARGETS = %v names the text target %d beside a picture", targets, atom)
+ }
+ }
+ if write := request(win.pngAtom); write.kind != win.pngAtom || !bytes.Equal(write.data, picture) {
+ t.Fatalf("image/png = kind %d data %q", write.kind, write.data)
+ }
+
+ // Another copy drops the picture: TARGETS stops naming it, and asking for it
+ // anyway is refused (the notify carries no property).
+ win.clipboard, win.clipboardImage = "typed", nil
+ before := len(recorder.writes)
+ recorder.sent = nil
+ if err := win.handleSelectionRequest(&xcbSelectionRequestEvent{Requestor: 3, Selection: 10, Target: win.pngAtom, Property: 14}); err != nil {
+ t.Fatal(err)
+ }
+ if len(recorder.writes) != before {
+ t.Fatal("image/png was served after a copy that holds no picture")
+ }
+ if len(recorder.sent) != 1 || recorder.sent[0].Property != 0 {
+ t.Fatalf("refusal notify = %v, want no property", recorder.sent)
+ }
+}
+
+// SetClipboardImage claims the CLIPBOARD, drops every other flavour the window
+// held, and refuses input that is not a PNG before it claims anything.
+func TestSetClipboardImageClaimsTheClipboardAndDropsOtherFlavours(t *testing.T) {
+ picture := picturePNG(t)
+ recorder := &selectionRecorder{masks: map[uint32]uint32{}, incrAtom: 77}
+ win := &window{
+ api: recorder.api(), connection: 1, id: 2, pngAtom: 19,
+ clipboardAtom: 10, utf8Atom: 11, textAtom: 12, targetsAtom: 13, uriListAtom: 15, gnomeFilesAtom: 16,
+ clipboard: "old text", clipboardHTML: "old", clipboardFiles: []string{"old.txt"},
+ }
+ activeWindow.Store(win)
+ t.Cleanup(func() { activeWindow.Store(nil) })
+
+ if err := SetClipboardImage([]byte("not a PNG")); err == nil {
+ t.Fatal("a non-PNG was accepted")
+ }
+ if len(recorder.ownerCalls) != 0 {
+ t.Fatal("a refused write claimed the clipboard")
+ }
+ if err := SetClipboardImage(picture); err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(win.clipboardImage, picture) || win.clipboard != "" || win.clipboardHTML != "" ||
+ win.clipboardFiles != nil || !win.ownsClipboard {
+ t.Fatalf("after the copy: image %d bytes, text %q, html %q, files %v, ownsClipboard %t",
+ len(win.clipboardImage), win.clipboard, win.clipboardHTML, win.clipboardFiles, win.ownsClipboard)
+ }
+ if len(recorder.ownerCalls) != 1 || recorder.ownerCalls[0] != [2]uint32{2, 10} {
+ t.Fatalf("ownership calls = %v, want the window taking CLIPBOARD", recorder.ownerCalls)
+ }
+}
diff --git a/internal/platform/linux/gtk_app_linux.go b/internal/platform/linux/gtk_app_linux.go
index be5d04f51..68a555e88 100644
--- a/internal/platform/linux/gtk_app_linux.go
+++ b/internal/platform/linux/gtk_app_linux.go
@@ -53,6 +53,14 @@ type gtkApplication struct {
watched map[int]uint32
// Retired input contexts stay alive until the native callback stack returns.
retiredIMESources []uint32
+ // clipboardGet and clipboardClear answer the clipboard's data callbacks, made
+ // once: purego keeps every callback it makes, so a pair per copy would retain
+ // what the user copied for the life of the process. clipboardBytes is what they
+ // answer now, by target atom, and clipboardGeneration tells a clear from an
+ // older copy apart from the current one.
+ clipboardGet, clipboardClear uintptr
+ clipboardBytes map[uintptr][]byte
+ clipboardGeneration uintptr
}
// gtkTasks are the functions other goroutines asked the loop to run.
diff --git a/internal/platform/linux/gtk_clipboard_image_linux_test.go b/internal/platform/linux/gtk_clipboard_image_linux_test.go
new file mode 100644
index 000000000..b7d52b853
--- /dev/null
+++ b/internal/platform/linux/gtk_clipboard_image_linux_test.go
@@ -0,0 +1,63 @@
+//go:build linux && vivagtk
+
+package linux
+
+import (
+ "bytes"
+ "errors"
+ "image"
+ "image/png"
+ "runtime"
+ "syscall"
+ "testing"
+)
+
+// The picture is an optional GTK capability, like the rich pair: without
+// gtk_clipboard_set_with_data its absence must reach callers as the Linux
+// unsupported sentinel, and with it the copy goes through one call advertising
+// the single image/png target.
+func TestGTKClipboardImageWriteReportsUnsupportedWithoutSetWithData(t *testing.T) {
+ runtime.LockOSThread()
+ t.Cleanup(runtime.UnlockOSThread)
+ previousClipboards, previousHooks := clipboards, shellHooks.Load()
+ t.Cleanup(func() {
+ clipboards = previousClipboards
+ shellHooks.Store(previousHooks)
+ })
+ var encoded bytes.Buffer
+ if err := png.Encode(&encoded, image.NewNRGBA(image.Rect(0, 0, 2, 2))); err != nil {
+ t.Fatal(err)
+ }
+ picture := encoded.Bytes()
+ clipboards = gtkClipboards{
+ ok: true, clipboard: 17,
+ atomIntern: func(*byte, int32) uintptr { return 1 },
+ }
+ application := >kApplication{mainThread: syscall.Gettid()}
+ application.installHooks()
+ if err := SetClipboardImage(picture); !errors.Is(err, ErrUnsupported) {
+ t.Fatalf("GTK without set_with_data returned %v, want ErrUnsupported", err)
+ }
+ imageWrites := 0
+ var gets []uintptr
+ clipboards.setWithData = func(clipboard, targets uintptr, count int32, get, clear, data uintptr) int32 {
+ if clipboard != 17 || targets == 0 || count != 1 || get == 0 || clear == 0 {
+ t.Fatalf("unexpected set_with_data call: clipboard=%d targets=%d count=%d", clipboard, targets, count)
+ }
+ gets = append(gets, get)
+ imageWrites++
+ return 1
+ }
+ if err := SetClipboardImage(picture); err != nil || imageWrites != 1 {
+ t.Fatalf("GTK picture write returned error=%v writes=%d", err, imageWrites)
+ }
+ if err := SetClipboardImage(picture); err != nil || imageWrites != 2 {
+ t.Fatalf("second GTK picture write returned error=%v writes=%d", err, imageWrites)
+ }
+ if gets[0] != gets[1] {
+ t.Fatal("a second copy made a new callback, which purego never releases")
+ }
+ if err := SetClipboardImage([]byte("not a PNG")); err == nil || imageWrites != 2 {
+ t.Fatalf("a non-PNG reached GTK: error=%v writes=%d", err, imageWrites)
+ }
+}
diff --git a/internal/platform/linux/gtk_system_linux.go b/internal/platform/linux/gtk_system_linux.go
index 7c8b88542..191cd69c0 100644
--- a/internal/platform/linux/gtk_system_linux.go
+++ b/internal/platform/linux/gtk_system_linux.go
@@ -167,6 +167,12 @@ func (a *gtkApplication) installHooks() {
}
return
},
+ setClipboardImage: func(png []byte) (err error) {
+ if e := a.onMain(func() { err = a.writeImage(png) }); e != nil {
+ return e
+ }
+ return
+ },
setCursorShape: func(shape uint8) (err error) {
if e := a.onMain(func() { err = a.setCursor(shape) }); e != nil {
return e
@@ -228,10 +234,41 @@ type gtkTargetEntry struct {
info uint32
}
-// writeHTML makes the clipboard hold html as text/html beside alt as plain
-// text. GTK owns the pair through gtk_clipboard_set_with_data, whose get
-// callback answers whichever target the requestor asked for; the flavour lives
-// as long as the clipboard does, as it does on X11.
+// clipboardCallbacks returns the get and clear callbacks the clipboard is given,
+// making them the first time: purego never releases a callback, so each copy
+// replaces what the callbacks answer (clipboardBytes) instead of making a pair
+// that would retain its bytes for the life of the process.
+func (a *gtkApplication) clipboardCallbacks(c *gtkClipboards) (get, clear uintptr) {
+ if a.clipboardGet != 0 {
+ return a.clipboardGet, a.clipboardClear
+ }
+ a.clipboardGet = purego.NewCallback(func(clipboard, selection, data uintptr) uintptr {
+ kind := c.selectionGet(data)
+ value, ok := a.clipboardBytes[kind]
+ if !ok {
+ return 0
+ }
+ if len(value) == 0 {
+ c.selectionSet(data, kind, 8, nil, 0)
+ return 0
+ }
+ c.selectionSet(data, kind, 8, &value[0], int32(len(value)))
+ return 0
+ })
+ a.clipboardClear = purego.NewCallback(func(clipboard, userData uintptr) uintptr {
+ // A clear from an older copy arrives after the bytes of the new one are in
+ // place; only the current copy's clear may drop them.
+ if userData == a.clipboardGeneration {
+ a.clipboardBytes = nil
+ }
+ return 0
+ })
+ return a.clipboardGet, a.clipboardClear
+}
+
+// writeHTML makes the clipboard hold html as text/html with alt as its plain
+// text. GTK owns it through gtk_clipboard_set_with_data, whose get callback
+// answers the target the requestor asked for by the atom of its name.
func (a *gtkApplication) writeHTML(html, alt string) error {
c, err := a.clipboardAPI()
if err != nil {
@@ -247,28 +284,51 @@ func (a *gtkApplication) writeHTML(html, alt string) error {
{target: uintptr(unsafe.Pointer(&textName[0]))},
}
htmlAtom := c.atomIntern(&htmlName[0], 0)
- htmlBytes, textBytes := cString(html), cString(alt)
- // The get callback runs on GTK's thread with the pair this closure captured,
- // answering the target the requestor asked for by the atom of its name.
- get := purego.NewCallback(func(clipboard, selection, data uintptr) uintptr {
- kind := c.selectionGet(data)
- value := textBytes
- if kind == htmlAtom {
- value = htmlBytes
- }
- c.selectionSet(data, kind, 8, &value[0], int32(len(value)))
- return 0
- })
- clearCallback := purego.NewCallback(func(clipboard, userData uintptr) uintptr { return 0 })
- if c.setWithData(c.clipboard, uintptr(unsafe.Pointer(&targets[0])), 2, get, clearCallback, 0) == 0 {
+ textAtom := c.atomIntern(&textName[0], 0)
+ // The get callback answers the pair by atom; replacing it drops the pair the
+ // previous copy left without making another callback.
+ a.clipboardGeneration++
+ a.clipboardBytes = map[uintptr][]byte{htmlAtom: []byte(html), textAtom: []byte(alt)}
+ get, clear := a.clipboardCallbacks(c)
+ if c.setWithData(c.clipboard, uintptr(unsafe.Pointer(&targets[0])), 2, get, clear, a.clipboardGeneration) == 0 {
return fmt.Errorf("linux: gtk_clipboard_set_with_data failed")
}
- // gtk_clipboard_set_with_data reads the entries in the call; the get callback
- // keeps the two flavours for as long as GTK may ask for them.
+ // gtk_clipboard_set_with_data reads the entries in the call; the callbacks keep
+ // the pair for as long as GTK may ask for them.
runtime.KeepAlive(htmlName)
runtime.KeepAlive(textName)
- runtime.KeepAlive(htmlBytes)
- runtime.KeepAlive(textBytes)
+ return nil
+}
+
+// writeImage makes the clipboard hold png as the image/png target, the one an
+// image viewer answers and Viva itself reads. GTK owns it through
+// gtk_clipboard_set_with_data, whose get callback passes the owner's own bytes
+// on, so the copy keeps its exact bytes and their transparency; the picture
+// lives as long as the clipboard does, as it does on X11.
+func (a *gtkApplication) writeImage(png []byte) error {
+ c, err := a.clipboardAPI()
+ if err != nil {
+ return err
+ }
+ if c.setWithData == nil {
+ return ErrUnsupported
+ }
+ pngName := cString("image/png")
+ targets := [1]gtkTargetEntry{
+ {target: uintptr(unsafe.Pointer(&pngName[0]))},
+ }
+ pngAtom := c.atomIntern(&pngName[0], 0)
+ // The get callback answers the picture by atom; replacing it drops the one the
+ // previous copy left without making another callback.
+ a.clipboardGeneration++
+ a.clipboardBytes = map[uintptr][]byte{pngAtom: append([]byte(nil), png...)}
+ get, clear := a.clipboardCallbacks(c)
+ if c.setWithData(c.clipboard, uintptr(unsafe.Pointer(&targets[0])), 1, get, clear, a.clipboardGeneration) == 0 {
+ return fmt.Errorf("linux: gtk_clipboard_set_with_data failed")
+ }
+ // gtk_clipboard_set_with_data reads the entry in the call; the callbacks keep
+ // the picture for as long as GTK may ask for it.
+ runtime.KeepAlive(pngName)
return nil
}
diff --git a/internal/platform/linux/selection_linux.go b/internal/platform/linux/selection_linux.go
index 8fd86259b..770c80a2a 100644
--- a/internal/platform/linux/selection_linux.go
+++ b/internal/platform/linux/selection_linux.go
@@ -61,6 +61,9 @@ func (win *window) ensureClipboardAtoms() error {
if win.htmlAtom, err = win.api.atom(win.connection, "text/html"); err != nil {
return err
}
+ if win.pngAtom, err = win.api.atom(win.connection, "image/png"); err != nil {
+ return err
+ }
return nil
}
@@ -162,16 +165,32 @@ func (win *window) handleSelectionRequest(request *xcbSelectionRequestEvent) err
}
switch request.Target {
case win.targetsAtom:
- targets := make([]uint32, 0, 7)
- targets = append(targets, win.targetsAtom, win.utf8Atom, win.textAtom, xcbAtomString)
+ targets := make([]uint32, 0, 8)
+ targets = append(targets, win.targetsAtom)
+ // A clipboard that holds only a picture has no text to paste.
+ pictureOnly := request.Selection == win.clipboardAtom && len(win.clipboardImage) > 0 &&
+ win.clipboard == "" && win.clipboardHTML == "" && len(win.clipboardFiles) == 0
+ if !pictureOnly {
+ targets = append(targets, win.utf8Atom, win.textAtom, xcbAtomString)
+ }
if request.Selection == win.clipboardAtom && win.clipboardHTML != "" {
targets = append(targets, win.htmlAtom)
}
if request.Selection == win.clipboardAtom && len(win.clipboardFiles) > 0 {
targets = append(targets, win.uriListAtom, win.gnomeFilesAtom)
}
+ if request.Selection == win.clipboardAtom && len(win.clipboardImage) > 0 {
+ targets = append(targets, win.pngAtom)
+ }
win.api.changeProperty(win.connection, xcbPropertyReplace, request.Requestor, property, xcbAtomAtom, 32, uint32(len(targets)), unsafe.Pointer(&targets[0]))
notify.Property = property
+ case win.pngAtom:
+ // The picture of an image copy, passed on as the PNG its owner wrote;
+ // only the CLIPBOARD holds one, and only until another copy.
+ if request.Selection == win.clipboardAtom && len(win.clipboardImage) > 0 &&
+ win.writeSelection(request.Requestor, property, request.Target, win.clipboardImage) {
+ notify.Property = property
+ }
case win.htmlAtom:
// The rich flavour of a rich copy, beside the text its plain readers
// take; only the CLIPBOARD holds one, and only until another copy.
@@ -283,7 +302,7 @@ func (win *window) handleSelectionClear(event *xcbSelectionClearEvent) {
defer win.mu.Unlock()
switch {
case event.Selection == win.clipboardAtom && win.clipboardAtom != 0:
- win.clipboard, win.clipboardHTML, win.clipboardFiles = "", "", nil
+ win.clipboard, win.clipboardHTML, win.clipboardFiles, win.clipboardImage = "", "", nil, nil
win.ownsClipboard = false
case event.Selection == xcbAtomPrimary:
win.selections.primary = ""
@@ -299,7 +318,7 @@ func (win *window) handleSelectionClear(event *xcbSelectionClearEvent) {
func (win *window) saveClipboardToManager() {
win.mu.Lock()
connection, api := win.connection, win.api
- owned := connection != 0 && win.ownsClipboard && (win.clipboard != "" || len(win.clipboardFiles) > 0)
+ owned := connection != 0 && win.ownsClipboard && (win.clipboard != "" || len(win.clipboardFiles) > 0 || len(win.clipboardImage) > 0)
win.mu.Unlock()
if !owned || api.convertSelection == nil {
return
@@ -329,6 +348,9 @@ func (win *window) saveClipboardToManager() {
if len(win.clipboardFiles) > 0 {
targets = append(targets, win.uriListAtom, win.gnomeFilesAtom)
}
+ if len(win.clipboardImage) > 0 {
+ targets = append(targets, win.pngAtom)
+ }
win.mu.Unlock()
if err != nil {
return
diff --git a/internal/platform/linux/shell_hooks_linux.go b/internal/platform/linux/shell_hooks_linux.go
index 2e1389950..bba8a6062 100644
--- a/internal/platform/linux/shell_hooks_linux.go
+++ b/internal/platform/linux/shell_hooks_linux.go
@@ -18,6 +18,7 @@ type desktopHooks struct {
setClipboardHTML func(html, alt string) error
hasClipboardImage func() bool
clipboardImagePNG func() ([]byte, error)
+ setClipboardImage func([]byte) error
clipboardFiles func() ([]string, error)
setClipboardFiles func([]string) error
primaryText func() (string, error)
diff --git a/internal/platform/linux/system_linux.go b/internal/platform/linux/system_linux.go
index d10f031c2..9e350073b 100644
--- a/internal/platform/linux/system_linux.go
+++ b/internal/platform/linux/system_linux.go
@@ -94,11 +94,14 @@ func readSelectionTextX11(name string) (string, error) {
// HasClipboardImage reports whether the X11 CLIPBOARD owner offers image/png.
// It asks the owner for its TARGETS, so it waits for another application for up
-// to clipboardWait; a clipboard this process owns holds text only.
+// to clipboardWait; a clipboard this process owns answers without asking.
func HasClipboardImage() bool {
if hooks := shellHooks.Load(); hooks != nil {
return hooks.hasClipboardImage()
}
+ if _, owned := ownedClipboardImage(); owned {
+ return true
+ }
has, _ := clipboardOffersImage()
return has
}
@@ -149,6 +152,11 @@ func ClipboardImagePNG() ([]byte, error) {
if hooks := shellHooks.Load(); hooks != nil {
return hooks.clipboardImagePNG()
}
+ // A clipboard this window owns answers from what it holds; asking the X
+ // server would need the event loop that is calling here.
+ if png, owned := ownedClipboardImage(); owned {
+ return png, nil
+ }
if ownsClipboardText() {
return nil, platform.ErrNoClipboardImage
}
@@ -268,7 +276,7 @@ func ClipboardFiles() ([]string, error) {
}
// ownsClipboardText reports whether this process's window is the CLIPBOARD
-// owner. The clipboard holds the window's text, files, or both.
+// owner. The clipboard holds the window's text, files, picture, or several.
func ownsClipboardText() bool {
win := activeWindow.Load()
if win == nil {
@@ -279,6 +287,21 @@ func ownsClipboardText() bool {
return activeWindow.Load() == win && win.connection != 0 && win.ownsClipboard
}
+// ownedClipboardImage is the picture this window's clipboard holds, and whether
+// it holds one at all: it is the CLIPBOARD owner, with an image on it.
+func ownedClipboardImage() ([]byte, bool) {
+ win := activeWindow.Load()
+ if win == nil {
+ return nil, false
+ }
+ win.mu.Lock()
+ defer win.mu.Unlock()
+ if activeWindow.Load() != win || win.connection == 0 || !win.ownsClipboard || len(win.clipboardImage) == 0 {
+ return nil, false
+ }
+ return append([]byte(nil), win.clipboardImage...), true
+}
+
// ownedClipboardFiles is the file list this window owns, and whether it owns
// the clipboard at all (with text or files).
func ownedClipboardFiles() ([]string, bool) {
@@ -477,6 +500,7 @@ func SetClipboardText(value string) error {
win.clipboard = value
win.clipboardHTML = ""
win.clipboardFiles = nil
+ win.clipboardImage = nil
win.ownsClipboard = true
return nil
}
diff --git a/internal/platform/linux/window_linux.go b/internal/platform/linux/window_linux.go
index 6db989b6f..7e529a29f 100644
--- a/internal/platform/linux/window_linux.go
+++ b/internal/platform/linux/window_linux.go
@@ -53,6 +53,7 @@ type window struct {
clipboard string
clipboardHTML string
clipboardFiles []string
+ clipboardImage []byte
clipboardAtom uint32
htmlAtom uint32
utf8Atom uint32
@@ -60,6 +61,7 @@ type window struct {
targetsAtom uint32
uriListAtom uint32
gnomeFilesAtom uint32
+ pngAtom uint32
ownsClipboard bool
// selections is the PRIMARY selection and the streams of data too large for one
// property (selection_linux.go).
diff --git a/internal/platform/web/clipboard_async_js.go b/internal/platform/web/clipboard_async_js.go
index d1721dcb5..cbdbc9061 100644
--- a/internal/platform/web/clipboard_async_js.go
+++ b/internal/platform/web/clipboard_async_js.go
@@ -145,6 +145,62 @@ func SetClipboardHTMLAsync(html, alt string, done func(error)) error {
return nil
}
+// SetClipboardImageAsync writes png as the "image/png" flavour of one
+// ClipboardItem, the entry a browser copies: an application that pastes a
+// picture takes these exact bytes, transparency included. The browser resolves a
+// Promise; done runs on the event loop, exactly once. The call retains the user
+// gesture, so invoke it from an input handler when the browser asks for
+// permission.
+func SetClipboardImageAsync(png []byte, done func(error)) error {
+ if done == nil {
+ return fmt.Errorf("%w: nil clipboard callback", ErrUnavailable)
+ }
+ item := js.Global().Get("ClipboardItem")
+ if item.Type() != js.TypeFunction {
+ return fmt.Errorf("%w: ClipboardItem is missing", ErrUnavailable)
+ }
+ if js.Global().Get("Blob").Type() != js.TypeFunction {
+ return fmt.Errorf("%w: Blob is missing", ErrUnavailable)
+ }
+ var entry js.Value
+ if err := catchJS("write clipboard image", func() {
+ bytes := js.Global().Get("Uint8Array").New(len(png))
+ js.CopyBytesToJS(bytes, png)
+ blob := js.Global().Get("Blob").New([]any{bytes}, map[string]any{"type": "image/png"})
+ entry = item.New(map[string]any{"image/png": blob})
+ }); err != nil {
+ return err
+ }
+ promise, err := clipboardCall("write", js.Global().Get("Array").New(entry))
+ if err != nil {
+ return err
+ }
+ var release []js.Func
+ finish := func(err error) {
+ for _, function := range release {
+ function.Release()
+ }
+ done(err)
+ }
+ callback := func(handler func([]js.Value) any) js.Func {
+ function := js.FuncOf(func(_ js.Value, args []js.Value) any { return handler(args) })
+ release = append(release, function)
+ return function
+ }
+ fail := callback(func(args []js.Value) any {
+ finish(clipboardError(args))
+ return nil
+ })
+ then := callback(func([]js.Value) any {
+ finish(nil)
+ return nil
+ })
+ if err := catchJS("write clipboard image", func() { promise.Call("then", then, fail) }); err != nil {
+ finish(err)
+ }
+ return nil
+}
+
func clipboardCall(name string, arguments ...any) (js.Value, error) {
navigator := js.Global().Get("navigator")
if navigator.Type() != js.TypeObject || navigator.IsNull() {
diff --git a/internal/platform/web/system_js.go b/internal/platform/web/system_js.go
index f3315db76..cae7e031f 100644
--- a/internal/platform/web/system_js.go
+++ b/internal/platform/web/system_js.go
@@ -39,6 +39,12 @@ func ClipboardImagePNG() error {
return fmt.Errorf("%w: Clipboard.read returns a Promise", ErrAsyncRequired)
}
+// SetClipboardImage is the synchronous form of a picture copy: the browser
+// answers it through a Promise, so use SetClipboardImageAsync.
+func SetClipboardImage([]byte) error {
+ return fmt.Errorf("%w: Clipboard.write returns a Promise", ErrAsyncRequired)
+}
+
// ReadClipboardImagePNG reads the first image/png of navigator.clipboard.read()
// and calls done with its bytes once the browser has delivered them: with
// platform.ErrNoClipboardImage when the clipboard holds none,
diff --git a/internal/platform/windows/clipboard_image_windows.go b/internal/platform/windows/clipboard_image_windows.go
new file mode 100644
index 000000000..f281a0222
--- /dev/null
+++ b/internal/platform/windows/clipboard_image_windows.go
@@ -0,0 +1,76 @@
+package windows
+
+import (
+ "time"
+
+ "github.com/vivaui/viva/internal/platform"
+)
+
+const (
+ // clipboardOpenAttempts is how often a write tries to open the clipboard
+ // before giving up: another program holds it only for the moment it takes to
+ // put its own data there.
+ clipboardOpenAttempts = 5
+ // clipboardOpenWait is the pause between those attempts.
+ clipboardOpenWait = 10 * time.Millisecond
+)
+
+// SetClipboardImage makes png the picture the clipboard holds, as copying an
+// image in a browser or Paint does: the registered "PNG" format as it is, and
+// CF_DIB converted, so a reader takes the exact copy if it knows PNG and the
+// bitmap if it does not. Windows serves the other bitmap formats a reader asks
+// for from that CF_DIB block. Everything else the clipboard held is gone, as
+// after any copy.
+//
+// png must be a PNG within platform.MaxClipboardImageBytes and must carry a
+// picture a bitmap can hold; platform.CheckClipboardPNG decides the first and
+// platform.PNGToDIB the second, and a PNG that fails either leaves the clipboard
+// untouched. The bitmap flavour is composited on white, the background a CF_DIB
+// reader draws where the picture is transparent; the "PNG" flavour keeps the
+// original bytes and their transparency.
+func SetClipboardImage(png []byte) error {
+ if err := platform.CheckClipboardPNG(png); err != nil {
+ return err
+ }
+ dib, err := platform.PNGToDIB(png)
+ if err != nil {
+ return err
+ }
+ clipboardMu.Lock()
+ defer clipboardMu.Unlock()
+ owner := uintptr(0)
+ if state := active.Load(); state != nil {
+ owner = state.window
+ }
+ if err := openClipboardForWrite(owner); err != nil {
+ return err
+ }
+ defer closeClipboard.Call()
+ if emptied, _, callErr := emptyClipboard.Call(); emptied == 0 {
+ return windowsCallError("empty clipboard", callErr)
+ }
+ if err := setClipboardBlock(clipboardDIB, dib); err != nil {
+ return err
+ }
+ // A clipboard that already holds the bitmap is still a picture without the
+ // encoded copy, so a failed registration is not a failed copy; it costs only
+ // the transparency the bitmap cannot carry.
+ if format := registeredPNGFormat(); format != 0 {
+ _ = setClipboardBlock(format, png)
+ }
+ return nil
+}
+
+// openClipboardForWrite opens the clipboard with owner as the window it is held
+// for, waiting out the moment another program holds it while it writes.
+func openClipboardForWrite(owner uintptr) error {
+ var opened uintptr
+ var callErr error
+ for attempt := 0; attempt < clipboardOpenAttempts; attempt++ {
+ if opened, _, callErr = openClipboard.Call(owner); opened != 0 {
+ return nil
+ }
+ time.Sleep(clipboardOpenWait)
+ }
+ return windowsCallError("open clipboard", callErr)
+}
diff --git a/internal/platform/windows/clipboard_image_write_windows_test.go b/internal/platform/windows/clipboard_image_write_windows_test.go
new file mode 100644
index 000000000..08f700bd7
--- /dev/null
+++ b/internal/platform/windows/clipboard_image_write_windows_test.go
@@ -0,0 +1,82 @@
+package windows
+
+import (
+ "bytes"
+ "fmt"
+ "image"
+ "image/color"
+ "image/png"
+ "os"
+ "os/exec"
+ "strings"
+ "testing"
+)
+
+// TestSetClipboardImageRoundTripsThroughTheRealClipboard writes a picture with
+// SetClipboardImage and takes it back with ClipboardImagePNG, then asks the .NET
+// clipboard for the same picture: that reader asks Windows for a bitmap, which
+// the copy offers as CF_DIB, so it proves an application that does not know the
+// registered "PNG" format still gets the picture and its colours. It replaces
+// the clipboard, so it runs only on request, on a machine whose clipboard may be
+// overwritten.
+func TestSetClipboardImageRoundTripsThroughTheRealClipboard(t *testing.T) {
+ if os.Getenv("VIVA_WINDOWS_CLIPBOARD") == "" {
+ t.Skip("set VIVA_WINDOWS_CLIPBOARD=1 to overwrite the real clipboard")
+ }
+ fill := color.NRGBA{R: 0, G: 128, B: 0, A: 255}
+ topLeft := color.NRGBA{R: 255, G: 0, B: 0, A: 255}
+ bottomRight := color.NRGBA{R: 0, G: 0, B: 255, A: 255}
+ picture := image.NewNRGBA(image.Rect(0, 0, 4, 3))
+ for y := range 3 {
+ for x := range 4 {
+ picture.SetNRGBA(x, y, fill)
+ }
+ }
+ picture.SetNRGBA(0, 0, topLeft)
+ picture.SetNRGBA(3, 2, bottomRight)
+ var encoded bytes.Buffer
+ if err := png.Encode(&encoded, picture); err != nil {
+ t.Fatal(err)
+ }
+
+ if err := SetClipboardImage(encoded.Bytes()); err != nil {
+ t.Fatal(err)
+ }
+ read, err := ClipboardImagePNG()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(read, encoded.Bytes()) {
+ t.Fatalf("read back %d bytes, wrote %d: the clipboard did not keep the copy", len(read), encoded.Len())
+ }
+
+ script := `Add-Type -AssemblyName System.Windows.Forms
+$picture = [System.Windows.Forms.Clipboard]::GetImage()
+if ($picture -eq $null) { 'none' } else {
+ $formats = ([System.Windows.Forms.Clipboard]::GetDataObject().GetFormats() -join ',')
+ "$($picture.Width)x$($picture.Height)|$formats|$($picture.GetPixel(0,0).ToArgb())|$($picture.GetPixel(3,2).ToArgb())|$($picture.GetPixel(1,1).ToArgb())"
+}`
+ output, err := exec.Command("powershell", "-NoProfile", "-STA", "-Command", script).CombinedOutput()
+ if err != nil {
+ t.Fatalf("read the clipboard with .NET: %v: %s", err, output)
+ }
+ fields := strings.Split(strings.TrimSpace(string(output)), "|")
+ if len(fields) != 5 {
+ t.Fatalf(".NET answered %q, want a size, the formats and three pixels", output)
+ }
+ if fields[0] != "4x3" {
+ t.Fatalf("the bitmap a .NET reader takes is %s, want 4x3", fields[0])
+ }
+ t.Logf("formats on the clipboard: %s", fields[1])
+ argb := func(value color.NRGBA) string {
+ return fmt.Sprint(int32(uint32(value.A)<<24 | uint32(value.R)<<16 | uint32(value.G)<<8 | uint32(value.B)))
+ }
+ for index, check := range []struct {
+ position string
+ want color.NRGBA
+ }{{"top left", topLeft}, {"bottom right", bottomRight}, {"middle", fill}} {
+ if fields[index+2] != argb(check.want) {
+ t.Fatalf(".NET %s pixel = %s, want %s (%v)", check.position, fields[index+2], argb(check.want), check.want)
+ }
+ }
+}
From 6b58fd14f48c77708101f093004034900770e50b Mon Sep 17 00:00:00 2001
From: MYCF711 <1451895195@qq.com>
Date: Sat, 21 Nov 2026 18:31:31 +0800
Subject: [PATCH 10/47] feat(base): break a long word when the box has no room
---
base/absolute.go | 15 +
base/frame.go | 1 +
base/layout.go | 28 +-
base/overflow_wrap_test.go | 333 ++++++++++++++++++
base/text_wrap.go | 39 ++
cmd/viva/initfiles/AGENTS.md.txt | 7 +-
ui/doc.go | 5 +-
ui/engine.go | 1 +
ui/facade.go | 158 +++++----
ui/overflow_wrap_page_test.go | 52 +++
.../content/guides/en/declarative-layout.md | 2 +-
.../content/guides/zh/declarative-layout.md | 2 +-
12 files changed, 557 insertions(+), 86 deletions(-)
create mode 100644 base/overflow_wrap_test.go
create mode 100644 ui/overflow_wrap_page_test.go
diff --git a/base/absolute.go b/base/absolute.go
index 657e5dcc5..87ed194ba 100644
--- a/base/absolute.go
+++ b/base/absolute.go
@@ -92,6 +92,7 @@ func (f *Frame) solveAbsolute(i int32, axis int) {
edgeStart, edgeEnd = f.Exts[a.Ext].edges[startEdge(axis)], f.Exts[a.Ext].edges[endEdge(axis)]
}
var size float32
+ content := false // size is the one the content wants
switch d := a.Size[axis]; {
case d.Kind == dimPx:
size = d.Value
@@ -107,8 +108,22 @@ func (f *Frame) solveAbsolute(i int32, axis int) {
}
default:
size = a.Pref[axis]
+ content = true
}
size = clamp(size, a.MinS[axis], a.MaxS[axis])
+ if content && axis == AxisX && breaksAnywhere(a, &f.Exts[a.Ext]) {
+ // An absolute box is as wide as its content wants, but a text that may break
+ // inside a word has a narrowest line of one character, so the width it wants
+ // reaches no further than the room it has, as CSS overflow-wrap: anywhere says.
+ room := span - ms - me
+ if hasStart {
+ room -= edgeStart
+ }
+ if hasEnd {
+ room -= edgeEnd
+ }
+ size = clamp(min(size, max(room, 0)), a.MinS[axis], a.MaxS[axis])
+ }
at := lo + ms
switch {
case hasStart:
diff --git a/base/frame.go b/base/frame.go
index 6682e4237..af095b597 100644
--- a/base/frame.go
+++ b/base/frame.go
@@ -192,6 +192,7 @@ type Extra struct {
States int32 // 1 + the index of the element's Hover, Pressed and Focus looks in frame.states, or 0 for none
scrollState *ScrollState // the state a ScrollArea reports its extent to
maxPct [2]float32 // MaxWidthPercent and MaxHeightPercent; zero is none
+ overflowWrap OverflowWrap // how a wrapped Text breaks a word too wide for its line, OverflowWrap
hitOut [4]float32 // how far the hit region reaches beyond the rectangle: top, right, bottom, left
hitExact bool // a styled control targets its laid-out rectangle, not its enlarged desktop target
edges [4]float32 // an absolute element's distance from its container's top, right, bottom, left
diff --git a/base/layout.go b/base/layout.go
index 059de141b..7e642c9cc 100644
--- a/base/layout.go
+++ b/base/layout.go
@@ -333,19 +333,41 @@ func crossSize(child *Node, axis int, avail float32, align Align, hi float32) fl
}
// maxOn is the largest size an element may have along axis in a container with avail
-// room for it: its MaxWidth or MaxHeight, or the share of avail MaxWidthPercent or
-// MaxHeightPercent gives, whichever is smaller. Zero is no limit.
+// room for it: its MaxWidth or MaxHeight, the share of avail MaxWidthPercent or
+// MaxHeightPercent gives, or, for a wrapped Text that may break inside a word, the
+// room itself, whichever is smaller. Zero is no limit.
func (f *Frame) maxOn(n *Node, axis int, avail float32) float32 {
hi := n.MaxS[axis]
- if pct := f.Exts[n.Ext].maxPct[axis]; pct > 0 {
+ extra := &f.Exts[n.Ext]
+ if pct := extra.maxPct[axis]; pct > 0 {
share := max(avail, 0) * pct / 100
if hi == 0 || share < hi {
hi = max(share, 0.001) // zero would mean no limit
}
}
+ if axis == AxisX && shrinksToRoom(n, extra) && (hi == 0 || avail < hi) {
+ // A text that may break inside a word is one character wide at its narrowest,
+ // so the width it asks for is the room it has, not its widest line, as CSS
+ // overflow-wrap: anywhere says.
+ hi = max(avail, 0.001) // zero would mean no limit
+ }
return hi
}
+// breaksAnywhere reports whether n, whose Extra is extra, asks to break inside a word
+// too wide for its line: a wrapped Text given OverflowWrapAnywhere (see Box.OverflowWrap).
+func breaksAnywhere(n *Node, extra *Extra) bool {
+ return n.Kind == kindText && n.Flags&flagWrap != 0 && extra.overflowWrap == OverflowWrapAnywhere
+}
+
+// shrinksToRoom reports whether the width n asks for is the room it is given rather
+// than its widest line. CSS overflow-wrap: anywhere lowers the min-content contribution
+// only: a specified width, a percentage or a flex basis is still the size the caller
+// asked for, so the room caps only a width the content itself derives.
+func shrinksToRoom(n *Node, extra *Extra) bool {
+ return breaksAnywhere(n, extra) && n.Size[AxisX].Kind == dimAuto && n.Flags&flagBasis == 0
+}
+
func offset(align Align, free float32) float32 {
switch align {
case Center:
diff --git a/base/overflow_wrap_test.go b/base/overflow_wrap_test.go
new file mode 100644
index 000000000..6d4f3a081
--- /dev/null
+++ b/base/overflow_wrap_test.go
@@ -0,0 +1,333 @@
+package base
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/vivaui/viva/gfx"
+ "github.com/vivaui/viva/internal/grapheme"
+)
+
+// overflowWord is one word no line is wide enough for, the shape of a long URL or
+// path someone pasted into a label.
+const overflowWord = "https://example.com/a/b/c/d/e/f/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
+
+// graphemeCanvas measures one character as Size wide, a character being what a
+// reader sees: a base with its marks, an emoji sequence, a flag. A width is then a
+// count of characters, so a test does not depend on a font.
+func graphemeCanvas() *gfx.Canvas {
+ canvas := &gfx.Canvas{}
+ canvas.SetTree(&tree)
+ canvas.SetMeasurer(func(Value string, Size, Weight float32) float32 {
+ count := 0
+ for index := 0; index < len(Value); index = grapheme.Next(Value, index) {
+ count++
+ }
+ return float32(count) * Size
+ })
+ return canvas
+}
+
+// centredParagraph lays text out as a paragraph of a Column as wide as width, centred
+// across it: the shape a label takes when it is not stretched to its container, such
+// as the title of a card. wrap is what the caller writes after f.Wrap.
+func centredParagraph(width float32, value string, wrap func(Box) Box) (lines []string, text Rect, column Rect) {
+ return centredParagraphOn(graphemeCanvas(), width, value, wrap)
+}
+
+// centredParagraphOn is centredParagraph measured by canvas: a font whose one rune is
+// wider than the next cuts a character in half if the break is not kept to a boundary of
+// whole characters, so the tests run the same text through both.
+func centredParagraphOn(canvas *gfx.Canvas, width float32, value string, wrap func(Box) Box) (lines []string, text Rect, column Rect) {
+ var view View
+ var paragraph, columnBox Box
+ f := view.Begin(canvas, gfx.LightTheme(), gfx.Rect{Width: width, Height: 400})
+ columnBox = f.Column().Items(Center).Children(func() {
+ paragraph = wrap(f.Wrap(value).FontSize(1))
+ })
+ f.End()
+ n := paragraph.N()
+ for k := int32(0); k < n.LineCount; k++ {
+ lines = append(lines, f.Lines[n.LineFirst+k])
+ }
+ return lines, paragraph.Rect(), columnBox.Rect()
+}
+
+// A paragraph that fits: OverflowWrapAnywhere changes nothing at all, neither a line
+// nor a rectangle, because its narrowest line is already its widest one.
+func TestOverflowWrapLeavesATextThatFitsExactlyAsItWas(t *testing.T) {
+ const value = "short and sweet"
+ plain, plainRect, plainColumn := centredParagraph(40, value, func(b Box) Box { return b })
+ anywhere, anywhereRect, anywhereColumn := centredParagraph(40, value, func(b Box) Box {
+ return b.OverflowWrap(OverflowWrapAnywhere)
+ })
+ if strings.Join(plain, "|") != value || strings.Join(anywhere, "|") != value {
+ t.Fatalf("a text that fits wrapped: %q and %q", plain, anywhere)
+ }
+ if plainRect != anywhereRect || plainColumn != anywhereColumn {
+ t.Errorf("a text that fits moved: %v then %v, column %v then %v", plainRect, anywhereRect, plainColumn, anywhereColumn)
+ }
+ near(t, "the text", plainRect, gfx.Rect{X: 12.5, Width: 15, Height: 8})
+}
+
+// A word no line is wide enough for keeps the behaviour it had: without the property
+// the paragraph asks for the width of its longest line and runs out over both edges of
+// a centred column. This is the default path, and it is pinned here so that no later
+// change can move it by a byte.
+func TestOverflowWrapIsOffByDefault(t *testing.T) {
+ lines, rect, column := centredParagraph(5, "aaaaaaaaaaaaaaaaaaaa", func(b Box) Box { return b })
+ if len(lines) != 1 || lines[0] != "aaaaaaaaaaaaaaaaaaaa" {
+ t.Fatalf("a long word without OverflowWrap broke into %q", lines)
+ }
+ if rect.Width != 20 {
+ t.Errorf("a long word without OverflowWrap is %v wide, want 20 (its own width, not the room)", rect.Width)
+ }
+ if rect.X >= 0 || rect.X+rect.Width <= column.Width {
+ t.Errorf("a long word without OverflowWrap sits at %v in a column %v wide: want it to run out over both edges", rect, column)
+ }
+}
+
+// With OverflowWrapAnywhere the same paragraph asks for the room it is given and breaks
+// the word: the column's width is never exceeded, and the last line is not cut.
+func TestOverflowWrapKeepsALongWordInsideItsColumn(t *testing.T) {
+ lines, rect, column := centredParagraph(5, "aaaaaaaaaaaaaaaaaaaa", func(b Box) Box {
+ return b.OverflowWrap(OverflowWrapAnywhere)
+ })
+ if strings.Join(lines, "") != "aaaaaaaaaaaaaaaaaaaa" {
+ t.Fatalf("the word came out as %q", lines)
+ }
+ if rect.Width != column.Width {
+ t.Errorf("the paragraph is %v wide in a column %v wide, want the column's width", rect.Width, column.Width)
+ }
+ if rect.X != 0 {
+ t.Errorf("the paragraph starts at %v, want 0: it is as wide as its column", rect.X)
+ }
+ for _, line := range lines {
+ if width := float32(len(line)); width > column.Width {
+ t.Errorf("line %q is %v wide, wider than the column (%v)", line, width, column.Width)
+ }
+ }
+ if want := []string{"aaaaa", "aaaaa", "aaaaa", "aaaaa"}; strings.Join(lines, "|") != strings.Join(want, "|") {
+ t.Errorf("the word broke as %q, want %q", lines, want)
+ }
+}
+
+// A break falls between whole characters, never inside one as a reader sees it: an
+// emoji sequence, a letter with its combining marks, a flag. Each cut is a UAX #29
+// grapheme cluster boundary, and the characters are all still there.
+func TestOverflowWrapBreaksBetweenWholeCharacters(t *testing.T) {
+ for _, value := range []string{
+ strings.Repeat("👨👩👧", 5), // family: ZWJ sequences
+ strings.Repeat("e\u0301", 6), // e + combining acute
+ strings.Repeat("🇨🇳", 5), // flags: pairs of regional indicators
+ strings.Repeat("👍🏽", 4), // skin tone modifier
+ strings.Repeat("अ\u0300", 4), // Devanagari with a combining mark
+ "漢字\u0308" + strings.Repeat("中", 4), // CJK with a combining voiced mark
+ } {
+ // A font whose marks and joiner add width breaks a character at a rune boundary
+ // unless the cut is kept to a boundary of whole characters.
+ for _, canvas := range []*gfx.Canvas{graphemeCanvas(), testCanvas()} {
+ for _, width := range []float32{1, 2, 3} {
+ lines, rect, column := centredParagraphOn(canvas, width, value, func(b Box) Box {
+ return b.OverflowWrap(OverflowWrapAnywhere)
+ })
+ if strings.Join(lines, "") != value {
+ t.Fatalf("%q at %v became %q: characters were lost", value, width, lines)
+ }
+ if rect.Width > column.Width {
+ t.Errorf("%q at %v is %v wide in a column %v wide", value, width, rect.Width, column.Width)
+ }
+ offset := 0
+ for _, line := range lines {
+ if offset > 0 && !grapheme.Boundary(value, offset) {
+ t.Errorf("%q at %v breaks at byte %d, inside a character: %q", value, width, offset, lines)
+ }
+ offset += len(line)
+ }
+ }
+ }
+ }
+}
+
+// The room a paragraph is given caps it whether it is in the flow of its container or
+// out of it: an absolute one is as wide as its text wants, unless the text may break
+// inside a word, when it is as wide as the room it has.
+func TestOverflowWrapCapsAnAbsoluteTextAtItsContainer(t *testing.T) {
+ for _, test := range []struct {
+ name string
+ wrap func(Box) Box
+ width float32
+ lines int
+ }{
+ {"without", func(b Box) Box { return b }, 20, 1},
+ {"anywhere", func(b Box) Box { return b.OverflowWrap(OverflowWrapAnywhere) }, 8, 3},
+ } {
+ var view View
+ var text, stack Box
+ f := view.Begin(graphemeCanvas(), gfx.LightTheme(), gfx.Rect{Width: 8, Height: 400})
+ stack = f.Stack().Children(func() {
+ text = test.wrap(f.Wrap("aaaaaaaaaaaaaaaaaaaa").FontSize(1)).Absolute()
+ })
+ f.End()
+ if stack.Rect().Width != 8 {
+ t.Fatalf("%s: the container is %v wide, want 8", test.name, stack.Rect().Width)
+ }
+ if text.Rect().Width != test.width || int(text.N().LineCount) != test.lines {
+ t.Errorf("%s: the text is %v in %d lines, want %v in %d", test.name, text.Rect().Width, text.N().LineCount, test.width, test.lines)
+ }
+ }
+}
+
+// A Row already shares a shortage among the texts in it, so asking to break anywhere
+// leaves the line it takes and the width it ends with as they were.
+func TestOverflowWrapChangesNothingInARowThatAlreadyShrinksIt(t *testing.T) {
+ const value = "aaaaaaaaaaaaaaaaaaaa"
+ layout := func(wrap func(Box) Box) (lines []string, rect gfx.Rect) {
+ var view View
+ var text Box
+ f := view.Begin(graphemeCanvas(), gfx.LightTheme(), gfx.Rect{Width: 6, Height: 400})
+ f.Row().Children(func() {
+ text = wrap(f.Wrap(value).FontSize(1))
+ })
+ f.End()
+ n := text.N()
+ for k := int32(0); k < n.LineCount; k++ {
+ lines = append(lines, f.Lines[n.LineFirst+k])
+ }
+ return lines, text.Rect()
+ }
+ plain, plainRect := layout(func(b Box) Box { return b })
+ anywhere, anywhereRect := layout(func(b Box) Box { return b.OverflowWrap(OverflowWrapAnywhere) })
+ if strings.Join(plain, "|") != strings.Join(anywhere, "|") || plainRect != anywhereRect {
+ t.Errorf("a row laid the text out as %q at %v, and as %q at %v with the property", plain, plainRect, anywhere, anywhereRect)
+ }
+}
+
+// OverflowWrapAnywhere asks for at most the room the text has, not for a size of its
+// own: an explicit MaxWidth that is smaller still wins, and one that is larger does not
+// push the text past the room.
+func TestOverflowWrapTakesTheSmallerOfItsMaxWidthAndItsRoom(t *testing.T) {
+ for _, test := range []struct {
+ name string
+ max float32
+ want float32
+ }{
+ {"narrower max", 3, 3},
+ {"wider max", 15, 10},
+ } {
+ lines, rect, column := centredParagraph(10, "aaaaaaaaaaaaaaaaaaaa", func(b Box) Box {
+ return b.OverflowWrap(OverflowWrapAnywhere).MaxWidth(test.max)
+ })
+ if rect.Width != test.want {
+ t.Errorf("%s: the paragraph is %v wide, want %v", test.name, rect.Width, test.want)
+ }
+ if strings.Join(lines, "") != "aaaaaaaaaaaaaaaaaaaa" {
+ t.Errorf("%s: the word came out as %q", test.name, lines)
+ }
+ for _, line := range lines {
+ if float32(len(line)) > column.Width {
+ t.Errorf("%s: line %q is wider than the column", test.name, line)
+ }
+ }
+ }
+}
+
+// A Text that does not wrap is one line and is clipped, so the property has nothing to
+// do on it: it stays exactly as wide as its text, as it was before.
+func TestOverflowWrapDoesNothingToOneLineText(t *testing.T) {
+ const value = "aaaaaaaaaaaaaaaaaaaa"
+ layout := func(wrap func(Box) Box) gfx.Rect {
+ var view View
+ var text Box
+ f := view.Begin(graphemeCanvas(), gfx.LightTheme(), gfx.Rect{Width: 5, Height: 400})
+ f.Column().Items(Center).Children(func() {
+ text = wrap(f.Text(value).FontSize(1))
+ })
+ f.End()
+ return text.Rect()
+ }
+ plain := layout(func(b Box) Box { return b })
+ anywhere := layout(func(b Box) Box { return b.OverflowWrap(OverflowWrapAnywhere) })
+ if plain != anywhere {
+ t.Errorf("a one-line text moved: %v then %v", plain, anywhere)
+ }
+}
+
+// A URL breaks where it can first: after its separators, and only then inside the run
+// that has none.
+func TestOverflowWrapStillPrefersTheSeparatorsOfAUrl(t *testing.T) {
+ lines, rect, _ := centredParagraph(20, overflowWord, func(b Box) Box {
+ return b.OverflowWrap(OverflowWrapAnywhere)
+ })
+ if strings.Join(lines, "") != overflowWord {
+ t.Fatalf("the URL came out as %q", lines)
+ }
+ if rect.Width != 20 {
+ t.Errorf("the URL is %v wide, want its column's 20", rect.Width)
+ }
+ if !strings.HasSuffix(lines[0], "/") && !strings.HasPrefix(lines[1], "/") {
+ t.Errorf("the URL broke as %q, want the first line to end at one of its separators", lines)
+ }
+}
+
+// CSS overflow-wrap: anywhere lowers the min-content contribution only: a specified
+// width, a percentage and a flex basis are still the sizes the caller asked for, so
+// the property leaves each of them alone.
+func TestOverflowWrapDoesNotShrinkASpecifiedWidth(t *testing.T) {
+ const value = "aaaaaaaaaaaaaaaaaaaa" // 20 characters, wider than every container here
+ for _, test := range []struct {
+ name string
+ layout func(f *Frame) Box
+ want float32
+ }{
+ {"Width", func(f *Frame) Box {
+ var text Box
+ f.Column().Items(Center).Children(func() {
+ text = f.Wrap(value).FontSize(1).Width(100).OverflowWrap(OverflowWrapAnywhere)
+ })
+ return text
+ }, 100},
+ {"WidthPercent", func(f *Frame) Box {
+ var text Box
+ f.Column().Items(Center).Children(func() {
+ text = f.Wrap(value).FontSize(1).WidthPercent(150).OverflowWrap(OverflowWrapAnywhere)
+ })
+ return text
+ }, 60}, // 150% of the 40-wide container
+ {"Basis", func(f *Frame) Box {
+ var text Box
+ f.Row().Children(func() {
+ text = f.Wrap(value).FontSize(1).Basis(100).Shrink(0).OverflowWrap(OverflowWrapAnywhere)
+ })
+ return text
+ }, 100},
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ var view View
+ f := view.Begin(graphemeCanvas(), gfx.LightTheme(), gfx.Rect{Width: 40, Height: 400})
+ text := test.layout(f)
+ f.End()
+ if got := text.Rect().Width; got != test.want {
+ t.Fatalf("the text is %v wide, want the %v it asked for", got, test.want)
+ }
+ })
+ }
+}
+
+// An anchored absolute text has only the room from its edge to the far side, as CSS
+// shrink-to-fit gives it: the cap is the room past the edge, not the whole container.
+func TestOverflowWrapCapsAnAnchoredAbsoluteTextToTheRoomPastItsEdge(t *testing.T) {
+ var view View
+ var text Box
+ f := view.Begin(graphemeCanvas(), gfx.LightTheme(), gfx.Rect{Width: 8, Height: 400})
+ f.Stack().Children(func() {
+ text = f.Wrap("aaaaaaaaaaaaaaaaaaaa").FontSize(1).OverflowWrap(OverflowWrapAnywhere).Absolute().Left(6)
+ })
+ f.End()
+ if got := text.Rect(); got.X != 6 || got.Width != 2 {
+ t.Fatalf("the anchored text is %v, want x 6 and the 2 characters of room past its edge", got)
+ }
+ if lines := int(text.N().LineCount); lines != 10 {
+ t.Errorf("the anchored text has %d lines, want 10", lines)
+ }
+}
diff --git a/base/text_wrap.go b/base/text_wrap.go
index 4da66e3fd..bcbd2b9fa 100644
--- a/base/text_wrap.go
+++ b/base/text_wrap.go
@@ -78,3 +78,42 @@ func (b Box) MaxLines(n int) Box {
node.MaxLines = int32(n)
return b
}
+
+// OverflowWrap is how a wrapped Text breaks a word that is too wide for its line,
+// as CSS's overflow-wrap property says.
+type OverflowWrap uint8
+
+const (
+ // OverflowWrapBreakWord breaks a line inside a word too wide for it, which is what
+ // a wrapped Text already does and what CSS calls overflow-wrap: break-word: the
+ // width a Text asks for is its widest line, so a word wider than the room the Text
+ // is given is broken rather than overflow it. It is the zero value and the answer
+ // of every Text that is not given OverflowWrap. CSS overflow-wrap: normal, where
+ // the word overflows instead, is not expressible.
+ OverflowWrapBreakWord OverflowWrap = iota
+ // OverflowWrapAnywhere may break inside a word, at any character boundary, when the
+ // word does not fit its line. As with CSS overflow-wrap: anywhere, the width the
+ // Text asks for is then the room it is given rather than its widest line, because
+ // its narrowest line is one character: a paragraph centred in a Column stays inside
+ // the Column and breaks its long URL instead of running out over both edges. A break
+ // never falls inside a character as a reader sees it (UAX #29: a base with its
+ // marks, an emoji sequence, a flag, an Indic conjunct), and while the text fits the
+ // room it is given nothing about it changes.
+ OverflowWrapAnywhere
+)
+
+// OverflowWrap sets how a wrapped Text breaks a word too wide for its line (see Wrap,
+// Paragraph and MaxLines); it has no effect on a Text that does not wrap, which is one
+// line and is clipped.
+//
+// f.Column().Items(Center).Children(func() {
+// f.Wrap(url).OverflowWrap(OverflowWrapAnywhere)
+// })
+func (b Box) OverflowWrap(v OverflowWrap) Box {
+ n := b.N()
+ if v == OverflowWrapBreakWord && n.Ext == 0 {
+ return b // the zero value says it already; no Extra is made to say it again
+ }
+ b.f.Extra(b.i).overflowWrap = v
+ return b
+}
diff --git a/cmd/viva/initfiles/AGENTS.md.txt b/cmd/viva/initfiles/AGENTS.md.txt
index 0ac6f5aa5..e8f2da591 100644
--- a/cmd/viva/initfiles/AGENTS.md.txt
+++ b/cmd/viva/initfiles/AGENTS.md.txt
@@ -432,8 +432,11 @@ func (m *model) page(c ui.C) {
- Text: `FontSize`, `Weight`, `Bold`, `Color`, `Highlight`, `Muted`, `Mono`, `MonoFace`, `TextCenter`, `TextEnd`, `TextDirection`, `LineHeight`;
`Ellipsis()` keeps a Text to one line and ends it with … when it does not fit; `MaxLines(n)` lets a Text
- break into at most n lines (the last ends with …), `ui.Wrap(c, text)` into as many as the width needs. Lines
- break where Unicode (UAX #14) allows: at spaces, after hyphens and slashes, between CJK characters (kinsoku
+ break into at most n lines (the last ends with …), `ui.Wrap(c, text)` into as many as the width needs. A
+ paragraph its container does not stretch asks for its widest line, so a long URL or path runs out over the
+ container; `OverflowWrap(ui.OverflowWrapAnywhere)` makes it ask for the room it has instead and break that
+ word between whole characters. Lines break where Unicode (UAX #14) allows: at spaces, after hyphens and
+ slashes, between CJK characters (kinsoku
rules apply), between the syllables of Thai, Lao, Khmer and Myanmar, at the spaces of Korean; a word wider than
the line breaks after a `/ - _ .` or between characters, never inside an emoji, a conjunct or a letter with its
marks. Hebrew, Arabic and other right-to-left text is reordered (UAX #9), aligned to the start of its paragraph
diff --git a/ui/doc.go b/ui/doc.go
index 1278b61de..6158a96f4 100644
--- a/ui/doc.go
+++ b/ui/doc.go
@@ -67,7 +67,10 @@
// the separators of a long path or URL, and as a last resort between whole
// characters (an emoji sequence or a letter with its marks is never split); its
// height follows its width, and the last line of one that is cut ends with an
-// ellipsis.
+// ellipsis. A paragraph its container does not stretch asks for its own width, so a
+// word no line is wide enough for runs out over the container; OverflowWrap with
+// OverflowWrapAnywhere makes it ask for the room it has instead, and break that word
+// between whole characters.
//
// How an element looks under the pointer, held down and focused is declared on it (Hover,
// Pressed, Focus, each a Look, with StateFrom to follow a container and Transition to fade
diff --git a/ui/engine.go b/ui/engine.go
index 6515edf48..6f4f5f7a5 100644
--- a/ui/engine.go
+++ b/ui/engine.go
@@ -66,6 +66,7 @@ type MenuRow = base.MenuRow
type MenuRowKind = base.MenuRowKind
type ModalSpec = base.ModalSpec
type Node = base.Node
+type OverflowWrap = base.OverflowWrap
type OverlaySpec = base.OverlaySpec
type Page = base.Page
type PageConfig = base.PageConfig
diff --git a/ui/facade.go b/ui/facade.go
index 78711ce49..08f04d5fe 100644
--- a/ui/facade.go
+++ b/ui/facade.go
@@ -17,84 +17,86 @@ type EffectState[T any, K comparable] = base.EffectState[T, K]
// The words of a page that base declares as constants.
const (
- Alt = base.Alt
- Baseline = base.Baseline
- Between = base.Between
- Ctrl = base.Ctrl
- DimFill = base.DimFill
- DimPercent = base.DimPercent
- DirectionColumn = base.DirectionColumn
- DirectionCustom = base.DirectionCustom
- DirectionFlow = base.DirectionFlow
- DirectionGrid = base.DirectionGrid
- DirectionRow = base.DirectionRow
- DirectionStack = base.DirectionStack
- DrawerRight = base.DrawerRight
- FlagAlertDialog = base.FlagAlertDialog
- FlagBasis = base.FlagBasis
- FlagChildren = base.FlagChildren
- FlagClip = base.FlagClip
- FlagDrawer = base.FlagDrawer
- FlagGrowSet = base.FlagGrowSet
- FlagHasHit = base.FlagHasHit
- FlagHasRadius = base.FlagHasRadius
- FlagLabelFor = base.FlagLabelFor
- FlagOpen = base.FlagOpen
- FlagOutline = base.FlagOutline
- FlagScroll = base.FlagScroll
- FlagSelected = base.FlagSelected
- FlagSetBackground = base.FlagSetBackground
- FlagSetBorder = base.FlagSetBorder
- FlagSetPad = base.FlagSetPad
- FlagSetShadow = base.FlagSetShadow
- FlagShrinkSet = base.FlagShrinkSet
- FlagTextCenter = base.FlagTextCenter
- FlagVeto = base.FlagVeto
- FlagWrap = base.FlagWrap
- FocusBoth = base.FocusBoth
- FocusHorizontal = base.FocusHorizontal
- FocusVertical = base.FocusVertical
- KindContainer = base.KindContainer
- KindToggle = base.KindToggle
- KindIcon = base.KindIcon
- KindImage = base.KindImage
- KindSlot = base.KindSlot
- KindSpacer = base.KindSpacer
- KindText = base.KindText
- ListCenter = base.ListCenter
- ListEnd = base.ListEnd
- ListStart = base.ListStart
- PaginationEllipsis = base.PaginationEllipsis
- PaginationNext = base.PaginationNext
- PaginationPage = base.PaginationPage
- PaginationPrevious = base.PaginationPrevious
- Primary = base.Primary
- Shift = base.Shift
- Start = base.Start
- Stretch = base.Stretch
- ScrollAreaBarSize = base.ScrollAreaBarSize
- ToBottom = base.ToBottom
- ToBottomLeft = base.ToBottomLeft
- ToBottomRight = base.ToBottomRight
- ToLeft = base.ToLeft
- ToRight = base.ToRight
- ToTop = base.ToTop
- ToTopLeft = base.ToTopLeft
- ToTopRight = base.ToTopRight
- ToastBottomCenter = base.ToastBottomCenter
- ToastBottomLeft = base.ToastBottomLeft
- ToastBottomRight = base.ToastBottomRight
- ToastDefault = base.ToastDefault
- ToastTopCenter = base.ToastTopCenter
- ToastTopLeft = base.ToastTopLeft
- ToastTopRight = base.ToastTopRight
- TooltipBottom = base.TooltipBottom
- TooltipLeft = base.TooltipLeft
- TooltipRight = base.TooltipRight
- TooltipTop = base.TooltipTop
- TreeDropAfter = base.TreeDropAfter
- TreeDropBefore = base.TreeDropBefore
- TreeDropInside = base.TreeDropInside
+ Alt = base.Alt
+ Baseline = base.Baseline
+ Between = base.Between
+ Ctrl = base.Ctrl
+ DimFill = base.DimFill
+ DimPercent = base.DimPercent
+ DirectionColumn = base.DirectionColumn
+ DirectionCustom = base.DirectionCustom
+ DirectionFlow = base.DirectionFlow
+ DirectionGrid = base.DirectionGrid
+ DirectionRow = base.DirectionRow
+ DirectionStack = base.DirectionStack
+ DrawerRight = base.DrawerRight
+ FlagAlertDialog = base.FlagAlertDialog
+ FlagBasis = base.FlagBasis
+ FlagChildren = base.FlagChildren
+ FlagClip = base.FlagClip
+ FlagDrawer = base.FlagDrawer
+ FlagGrowSet = base.FlagGrowSet
+ FlagHasHit = base.FlagHasHit
+ FlagHasRadius = base.FlagHasRadius
+ FlagLabelFor = base.FlagLabelFor
+ FlagOpen = base.FlagOpen
+ FlagOutline = base.FlagOutline
+ FlagScroll = base.FlagScroll
+ FlagSelected = base.FlagSelected
+ FlagSetBackground = base.FlagSetBackground
+ FlagSetBorder = base.FlagSetBorder
+ FlagSetPad = base.FlagSetPad
+ FlagSetShadow = base.FlagSetShadow
+ FlagShrinkSet = base.FlagShrinkSet
+ FlagTextCenter = base.FlagTextCenter
+ FlagVeto = base.FlagVeto
+ FlagWrap = base.FlagWrap
+ FocusBoth = base.FocusBoth
+ FocusHorizontal = base.FocusHorizontal
+ FocusVertical = base.FocusVertical
+ KindContainer = base.KindContainer
+ KindToggle = base.KindToggle
+ KindIcon = base.KindIcon
+ KindImage = base.KindImage
+ KindSlot = base.KindSlot
+ KindSpacer = base.KindSpacer
+ KindText = base.KindText
+ ListCenter = base.ListCenter
+ ListEnd = base.ListEnd
+ ListStart = base.ListStart
+ OverflowWrapAnywhere = base.OverflowWrapAnywhere
+ OverflowWrapBreakWord = base.OverflowWrapBreakWord
+ PaginationEllipsis = base.PaginationEllipsis
+ PaginationNext = base.PaginationNext
+ PaginationPage = base.PaginationPage
+ PaginationPrevious = base.PaginationPrevious
+ Primary = base.Primary
+ Shift = base.Shift
+ Start = base.Start
+ Stretch = base.Stretch
+ ScrollAreaBarSize = base.ScrollAreaBarSize
+ ToBottom = base.ToBottom
+ ToBottomLeft = base.ToBottomLeft
+ ToBottomRight = base.ToBottomRight
+ ToLeft = base.ToLeft
+ ToRight = base.ToRight
+ ToTop = base.ToTop
+ ToTopLeft = base.ToTopLeft
+ ToTopRight = base.ToTopRight
+ ToastBottomCenter = base.ToastBottomCenter
+ ToastBottomLeft = base.ToastBottomLeft
+ ToastBottomRight = base.ToastBottomRight
+ ToastDefault = base.ToastDefault
+ ToastTopCenter = base.ToastTopCenter
+ ToastTopLeft = base.ToastTopLeft
+ ToastTopRight = base.ToastTopRight
+ TooltipBottom = base.TooltipBottom
+ TooltipLeft = base.TooltipLeft
+ TooltipRight = base.TooltipRight
+ TooltipTop = base.TooltipTop
+ TreeDropAfter = base.TreeDropAfter
+ TreeDropBefore = base.TreeDropBefore
+ TreeDropInside = base.TreeDropInside
)
// Leaves and layout.
diff --git a/ui/overflow_wrap_page_test.go b/ui/overflow_wrap_page_test.go
new file mode 100644
index 000000000..aa05ef242
--- /dev/null
+++ b/ui/overflow_wrap_page_test.go
@@ -0,0 +1,52 @@
+package ui_test
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/vivaui/viva/ui"
+)
+
+// A page paragraph given OverflowWrapAnywhere asks for the room of the column it is
+// centred in rather than for its longest line, so a word no line is wide enough for is
+// broken and every line stays inside the column. Without it the same paragraph is one
+// long line that reaches past both edges, which is the behaviour it has always had.
+func TestPageParagraphBreaksAnywhereInsideItsColumn(t *testing.T) {
+ const value = "https://example.com/a/b/c/d/e/f/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
+ const width = 120
+ draw := func(wrap func(b ui.Box) ui.Box) (lines []string, widest float32, start float32) {
+ view := func(c ui.C) {
+ ui.Column(c).Width(width).Items(ui.Center).Children(func() {
+ wrap(ui.Wrap(c, value).FontSize(14))
+ })
+ }
+ page := ui.NewPage(ui.PageConfig{View: view})
+ canvas := benchCanvas()
+ drawPage(page, canvas, view)
+ start = width // the left edge of the leftmost line
+ for _, text := range canvas.Texts() {
+ lines = append(lines, text.Value)
+ widest = max(widest, text.Bounds.Width)
+ start = min(start, text.Bounds.X)
+ }
+ if strings.Join(lines, "") != value {
+ t.Errorf("the paragraph painted %q, want the URL back whole", lines)
+ }
+ return lines, widest, start
+ }
+
+ plain, plainWidest, plainStart := draw(func(b ui.Box) ui.Box { return b })
+ if len(plain) != 1 || plainWidest <= width || plainStart >= 0 {
+ t.Errorf("without OverflowWrap the URL painted in %d lines up to %v wide from %v, want one line that runs out over the column", len(plain), plainWidest, plainStart)
+ }
+
+ anywhere, anywhereWidest, anywhereStart := draw(func(b ui.Box) ui.Box {
+ return b.OverflowWrap(ui.OverflowWrapAnywhere)
+ })
+ if len(anywhere) < 2 {
+ t.Errorf("with OverflowWrapAnywhere the URL painted in %d lines, want it broken into the column", len(anywhere))
+ }
+ if anywhereWidest > width || anywhereStart < 0 {
+ t.Errorf("with OverflowWrapAnywhere the widest line is %v wide from %v, want every line inside the %v wide column", anywhereWidest, anywhereStart, float32(width))
+ }
+}
diff --git a/website/content/guides/en/declarative-layout.md b/website/content/guides/en/declarative-layout.md
index bb55a9004..aa905ccd5 100644
--- a/website/content/guides/en/declarative-layout.md
+++ b/website/content/guides/en/declarative-layout.md
@@ -31,7 +31,7 @@ func (m *model) page(c ui.C) {
- `Basis(px)` is what an element starts from before free room is shared, and `WidthPercent` and `HeightPercent` take a share of the container. `MinWidth`, `MaxWidth`, `MinHeight` and `MaxHeight` bound a size; room a capped element cannot take goes to the others, as in CSS, so `Grow(1).MaxWidth(470)` beside a `Spacer()` keeps what follows against the far edge.
- `Items(ui.Baseline)` lines a Row's children up on their first line of text, so a large heading, a small caption and a button sit on one baseline. A `Text` shrinks and clips before a fixed-size sibling does.
- `Background`, `Radius`, `Border`, `Shadow` and `Clip` style a container. On a control such as an `Input`, `Select` or `Button`, `Radius` and `FontSize` give that control its own corner radius and text size, and a `Height` on a `Button` is how tall the button is painted.
-- `Paragraph(text, maxLines)` is text that wraps to the width it gets, so a longer label makes the row taller and pushes what follows down. `LineHeight` sets its leading.
+- `Paragraph(text, maxLines)` is text that wraps to the width it gets, so a longer label makes the row taller and pushes what follows down. `LineHeight` sets its leading. A paragraph its container does not stretch asks for the width of its widest line, so a word no line is wide enough for, such as a long URL or path, runs out over the edges of what holds it; `OverflowWrap(ui.OverflowWrapAnywhere)` makes it ask for the room it is given instead and break that word between whole characters (never inside an emoji sequence or a letter with its marks) where it does not fit. While the text fits, nothing changes.
- `Grid(minCell)` fits as many equal columns as the width allows and wraps onto new rows.
- `Flow()` is a Row that wraps: children of their own widths go left to right and start a new line when the next one does not fit, as CSS's `flex-wrap` does. Each line shares its room as a Row does, so `Grow` and `Justify` apply to every line alone, and `Items` lines the children up within their line. `Gap` is the space between children and between lines, unless `LineGap` sets the latter. Tags, chips and toolbars that wrap are Flows.
- `Scroll(offset)` is a clipped column taller than itself. You own the offset (the wheel arrives in `Config.OnScroll`); after `End`, `Content()` is how tall the children are, so the offset can be clamped.
diff --git a/website/content/guides/zh/declarative-layout.md b/website/content/guides/zh/declarative-layout.md
index 1d874a65f..5650ccd1b 100644
--- a/website/content/guides/zh/declarative-layout.md
+++ b/website/content/guides/zh/declarative-layout.md
@@ -31,7 +31,7 @@ func (m *model) page(c ui.C) {
- `Basis(px)` 是在分配剩余空间之前元素的起始尺寸,`WidthPercent`、`HeightPercent` 取容器的一个比例。`MinWidth`、`MaxWidth`、`MinHeight`、`MaxHeight` 限定尺寸;被上限卡住的元素吃不下的空间会分给其他元素(和 CSS 一样),所以 `Grow(1).MaxWidth(470)` 旁边放一个 `Spacer()`,后面的元素仍然贴着远端。
- `Items(ui.Baseline)` 让一行里的子元素按第一行文字的基线对齐,大标题、小说明和按钮可以落在同一条基线上。`Text` 会先于固定尺寸的兄弟元素收缩并裁剪。
- `Background`、`Radius`、`Border`、`Shadow`、`Clip` 为容器设置样式。在 `Input`、`Select`、`Button` 等控件上,`Radius` 和 `FontSize` 为该控件设置它自己的圆角和字号;`Button` 上的 `Height` 就是按钮画出来的高度。
-- `Paragraph(text, maxLines)` 是会按所得宽度换行的文字,所以标签变长会让这一行变高,并把后面的内容往下推。`LineHeight` 设置行高。
+- `Paragraph(text, maxLines)` 是会按所得宽度换行的文字,所以标签变长会让这一行变高,并把后面的内容往下推。`LineHeight` 设置行高。容器没有拉伸它时,它要的是自己最宽那一行的宽度,所以没有哪一行放得下的长词(比如长 URL、长路径)会溢出到容器的两边;`OverflowWrap(ui.OverflowWrapAnywhere)` 让它改为要它实际得到的宽度,并在放不下时把那个词按完整字符断开(绝不会切碎 emoji 序列或带附加符号的字母)。文字放得下时一切不变。
- `Grid(minCell)` 按宽度放下尽可能多的等宽列,并换到新的行。
- `Flow()` 是会换行的 Row:子元素保持各自的宽度从左到右排列,放不下下一个时就换到新的一行,和 CSS 的 `flex-wrap` 一样。每一行像 Row 一样分配自己的空间,所以 `Grow` 和 `Justify` 对每一行单独生效,`Items` 在各自的行内对齐子元素。`Gap` 是子元素之间的间距,也是行与行之间的间距,除非用 `LineGap` 另行设置。会换行的标签、徽章和工具栏都用 Flow。
- `Scroll(offset)` 是比自己更高的、带裁剪的列。偏移量由你持有(滚轮事件到 `Config.OnScroll`);`End` 之后 `Content()` 是子元素的总高度,可据此限制偏移量。
From 619c3549570f6af2c06386e81f8c8b8bdf747a7b Mon Sep 17 00:00:00 2001
From: t8y2
Date: Sat, 21 Nov 2026 18:32:02 +0800
Subject: [PATCH 11/47] test(darwin): share the Dock icon size rule and require
a color margin
The dominant-channel check passed a near-black or desaturated center, and
the size expectation copied the implementation's /2 formula. Expose the
points rule beside viva_application_update_icon and require the dominant
channel to stand out.
---
internal/platform/darwin/status_item_darwin.h | 3 +++
internal/platform/darwin/status_item_darwin.m | 6 +++++-
internal/platform/darwin/testdata/status_item.m | 6 +++---
3 files changed, 11 insertions(+), 4 deletions(-)
diff --git a/internal/platform/darwin/status_item_darwin.h b/internal/platform/darwin/status_item_darwin.h
index be6d005c4..ebc524646 100644
--- a/internal/platform/darwin/status_item_darwin.h
+++ b/internal/platform/darwin/status_item_darwin.h
@@ -25,6 +25,9 @@ typedef struct {
int viva_application_set_icon(viva_status_icon icon);
/* Replaces the Dock icon even in an .app bundle. Marshals to the main thread. */
int viva_application_update_icon(viva_status_icon icon);
+/* The points an icon of this many pixels is declared at: the Dock draws it at
+ * half its pixel size. The test beside the implementation asserts it too. */
+double viva_dock_icon_points(viva_status_icon icon);
void *viva_status_item_create(const char *tooltip, viva_status_icon icon, uintptr_t callback_handle, int has_menu);
int viva_status_item_set_icon(void *item, viva_status_icon icon);
void viva_status_item_set_tooltip(void *item, const char *tooltip);
diff --git a/internal/platform/darwin/status_item_darwin.m b/internal/platform/darwin/status_item_darwin.m
index 36422da08..75b3d3de2 100644
--- a/internal/platform/darwin/status_item_darwin.m
+++ b/internal/platform/darwin/status_item_darwin.m
@@ -216,13 +216,17 @@ - (void)clicked:(id)sender {
static void viva_status_item_remove_now(void *item);
static void viva_status_items_remove_all(void);
+double viva_dock_icon_points(viva_status_icon icon) {
+ return (double)icon.size / 2.0;
+}
+
int viva_application_update_icon(viva_status_icon icon) {
__block int result = 0;
void (^work)(void) = ^{
@autoreleasepool {
/* The Dock draws an icon at up to 128 points, on a 2x screen from twice
* the pixels, so the image is declared at half its pixel size. */
- NSImage *image = viva_icon_image(icon, icon.size / 2.0);
+ NSImage *image = viva_icon_image(icon, (CGFloat)viva_dock_icon_points(icon));
if (image == nil) {
return;
}
diff --git a/internal/platform/darwin/testdata/status_item.m b/internal/platform/darwin/testdata/status_item.m
index a594d730b..8d69a4521 100644
--- a/internal/platform/darwin/testdata/status_item.m
+++ b/internal/platform/darwin/testdata/status_item.m
@@ -66,7 +66,7 @@ int main(void) {
}
check(viva_application_update_icon(icon) == 1, "Dock update accepted");
NSImage *dockIcon = [NSApp applicationIconImage];
- NSSize points = NSMakeSize(icon.size / 2.0, icon.size / 2.0);
+ NSSize points = NSMakeSize(viva_dock_icon_points(icon), viva_dock_icon_points(icon));
check(NSEqualSizes(dockIcon.size, points), "Dock keeps the expected size in points");
NSBitmapImageRep *rep = [NSBitmapImageRep imageRepWithData:[dockIcon TIFFRepresentation]];
NSColor *pixel = [[rep colorAtX:rep.pixelsWide / 2 y:rep.pixelsHigh / 2]
@@ -75,8 +75,8 @@ int main(void) {
// Distinguish the two icon colors independently of scale and color profile.
CGFloat primary = color == 0 ? pixel.redComponent : pixel.blueComponent;
CGFloat other = color == 0 ? pixel.blueComponent : pixel.redComponent;
- int matches = pixel != nil &&
- primary > other && primary > pixel.greenComponent && pixel.alphaComponent > 0;
+ int matches = pixel != nil && primary > 0.5 && primary - other > 0.2 &&
+ primary > pixel.greenComponent && pixel.alphaComponent > 0;
if (!matches) {
fprintf(stderr, "Dock image %ldx%ld center: %s\n", (long)rep.pixelsWide, (long)rep.pixelsHigh,
[[pixel description] UTF8String]);
From 30e3c0d9fe5690ce27b262a43841c40fac715246 Mon Sep 17 00:00:00 2001
From: t8y2 <1156263951@qq.com>
Date: Sat, 21 Nov 2026 20:20:33 +0800
Subject: [PATCH 12/47] fix(windows): reuse complete text pictures during
resize
Keep reusable text rasterization in Viva instead of quantizing Motty layout.
Refs: t8y2/motty#1290
---
internal/platform/windows/direct_windows.go | 1 +
.../platform/windows/label_picture_windows.go | 25 +++-
.../windows/label_picture_windows_test.go | 133 ++++++++++++++++++
internal/platform/windows/text_windows.go | 5 +-
4 files changed, 162 insertions(+), 2 deletions(-)
diff --git a/internal/platform/windows/direct_windows.go b/internal/platform/windows/direct_windows.go
index 26df93e5d..c5a5ef4c9 100644
--- a/internal/platform/windows/direct_windows.go
+++ b/internal/platform/windows/direct_windows.go
@@ -36,6 +36,7 @@ const (
writeSetReadingDirection = 6
writeGetLineMetrics = 59
writeGetMetrics = 60
+ writeGetOverhangMetrics = 61
writeGetClusterMetrics = 62
writeSetCharacterSpacing = 69
writeSetUnderline = 36
diff --git a/internal/platform/windows/label_picture_windows.go b/internal/platform/windows/label_picture_windows.go
index c7435beac..932071aa8 100644
--- a/internal/platform/windows/label_picture_windows.go
+++ b/internal/platform/windows/label_picture_windows.go
@@ -25,6 +25,7 @@ type labelPicture struct {
texture, view uintptr
x, y, width, height int
lcd bool
+ complete bool
refs int
bytes int
previous, next *labelPicture
@@ -127,10 +128,32 @@ func (renderer *renderer) pictureChanged(label *labelTexture, scale float32, ski
return false
}
height := int(math.Ceil(float64(label.label.Height * scale)))
+ if label.picture.complete && skip == 0 && width >= label.picture.x+label.picture.width {
+ key, eligible := renderer.pictureKey(label, scale, 0, label.picture.key.width, height)
+ return !eligible || label.picture.key != key
+ }
key, eligible := renderer.pictureKey(label, scale, skip, width, height)
return !eligible || label.picture.key != key
}
+func (renderer *renderer) pictureHasCompleteInk(label *labelTexture, scale float32, skip, width int) bool {
+ if skip != 0 || renderer.direct == nil || renderer.direct.engine == nil {
+ return false
+ }
+ complete := false
+ value := label.label
+ err := renderer.direct.engine.drawStyle(value.Value, value.FontSize*scale, value.Weight, value.Italic, func(line *shapedLine) error {
+ var overhang [4]float32
+ if err := hresult(comCall(line.layout, writeGetOverhangMetrics, uintptr(unsafe.Pointer(&overhang[0])))); err != nil {
+ return err
+ }
+ right := float64(1<<20) + float64(overhang[2]) - float64(line.left)
+ complete = right >= 0 && right+2 <= float64(width)
+ return nil
+ })
+ return err == nil && complete
+}
+
func (renderer *renderer) invalidateText() {
renderer.textGeneration++
for index := range renderer.labels {
@@ -201,7 +224,7 @@ func (renderer *renderer) uploadLabelPicture(label *labelTexture, key labelPictu
return nil
}
left, top, right, bottom := picturePixelBounds(pixels, width, height)
- picture := &labelPicture{key: key, x: left, y: top, width: right - left, height: bottom - top, lcd: label.lcd}
+ picture := &labelPicture{key: key, x: left, y: top, width: right - left, height: bottom - top, lcd: label.lcd, complete: renderer.pictureHasCompleteInk(label, key.scale, key.skip, width)}
description := textureDesc{Width: uint32(picture.width), Height: uint32(picture.height), Mips: 1, Array: 1, Format: 87, Samples: 1, Usage: 1, Bind: 8}
data := resourceData{Data: unsafe.Pointer(&pixels[(top*width+left)*4]), Pitch: uint32(width * 4)}
if err := hresult(comCall(renderer.device, 5, uintptr(unsafe.Pointer(&description)), uintptr(unsafe.Pointer(&data)), uintptr(unsafe.Pointer(&picture.texture)))); err != nil {
diff --git a/internal/platform/windows/label_picture_windows_test.go b/internal/platform/windows/label_picture_windows_test.go
index 0c4d0082b..bbad955b8 100644
--- a/internal/platform/windows/label_picture_windows_test.go
+++ b/internal/platform/windows/label_picture_windows_test.go
@@ -175,6 +175,139 @@ func TestLabelPictureSharingAndInvalidation(t *testing.T) {
}
}
+func TestLabelPictureWidthChangesPreservePixelsAndReuseCompleteInk(t *testing.T) {
+ for _, scale := range []float64{1, 1.25, 1.5, 2} {
+ t.Run(fmt.Sprint(scale), func(t *testing.T) {
+ background := platform.Color{Alpha: 1}
+ reference, err := NewOffscreen(680, 250, scale, background)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer reference.Close()
+ reference.renderer.noLabelPictures = true
+ candidate, err := NewOffscreen(680, 250, scale, background)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer candidate.Close()
+ labels := pictureLabels(platform.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1})[:5]
+ for index := range labels {
+ labels[index].Width = 300
+ }
+ draw := func(width float32) {
+ for index := range labels {
+ labels[index].Width = width
+ }
+ if err := reference.Set(nil, labels); err != nil {
+ t.Fatal(err)
+ }
+ if err := candidate.Set(nil, labels); err != nil {
+ t.Fatal(err)
+ }
+ want, err := reference.Image()
+ if err != nil {
+ t.Fatal(err)
+ }
+ got, err := candidate.Image()
+ if err != nil {
+ t.Fatal(err)
+ }
+ comparePixels(t, want, got)
+ }
+ draw(300)
+ built := candidate.renderer.labelRebuilds
+ draw(350)
+ if candidate.renderer.labelRebuilds != built {
+ t.Fatal("resizing labels whose ink already fits rebuilt their pictures")
+ }
+ draw(15)
+ if candidate.renderer.labelRebuilds == built {
+ t.Fatal("shrinking into visible text did not rebuild its picture")
+ }
+ draw(300)
+ for _, width := range []float32{19.25, 23.5, 29.75, 38.25, 55.5, 83.25, 105.75, 140.5, 200.25, 350.75} {
+ draw(width)
+ }
+ })
+ }
+}
+
+func TestLabelPictureWidthChangesRespectMovingClip(t *testing.T) {
+ for _, scale := range []float64{1, 1.25, 1.5, 2} {
+ t.Run(fmt.Sprint(scale), func(t *testing.T) {
+ background := platform.Color{Alpha: 1}
+ reference, err := NewOffscreen(680, 250, scale, background)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer reference.Close()
+ reference.renderer.noLabelPictures = true
+ candidate, err := NewOffscreen(680, 250, scale, background)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer candidate.Close()
+ labels := pictureLabels(platform.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1})[5:]
+ for _, size := range []float32{600, 300, 15, 500} {
+ for _, left := range []float32{0, 45.5, 80} {
+ labels[0].Width = size
+ labels[0].Clip = gfx.Rect{X: left, Y: 0, Width: 150, Height: 250}
+ if err := reference.Set(nil, labels); err != nil {
+ t.Fatal(err)
+ }
+ if err := candidate.Set(nil, labels); err != nil {
+ t.Fatal(err)
+ }
+ want, err := reference.Image()
+ if err != nil {
+ t.Fatal(err)
+ }
+ got, err := candidate.Image()
+ if err != nil {
+ t.Fatal(err)
+ }
+ comparePixels(t, want, got)
+ }
+ }
+ })
+ }
+}
+
+func BenchmarkLabelPictureWidthChanges(b *testing.B) {
+ for _, cached := range []bool{false, true} {
+ b.Run(fmt.Sprintf("pictures=%t", cached), func(b *testing.B) {
+ offscreen, err := NewOffscreen(680, 250, 2, platform.Color{Alpha: 1})
+ if err != nil {
+ b.Fatal(err)
+ }
+ defer offscreen.Close()
+ offscreen.renderer.noLabelPictures = !cached
+ labels := pictureLabels(platform.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1})[:5]
+ width, height := offscreen.size()
+ draw := func(value float32) {
+ for index := range labels {
+ labels[index].Width = value
+ }
+ if err := offscreen.Set(nil, labels); err != nil {
+ b.Fatal(err)
+ }
+ if err := offscreen.renderer.draw(width, height, 2); err != nil {
+ b.Fatal(err)
+ }
+ }
+ draw(300)
+ built := offscreen.renderer.labelRebuilds
+ b.ReportAllocs()
+ b.ResetTimer()
+ for index := 0; index < b.N; index++ {
+ draw(300 + float32(index%2))
+ }
+ b.StopTimer()
+ b.ReportMetric(float64(offscreen.renderer.labelRebuilds-built)/float64(b.N), "uploads/op")
+ })
+ }
+}
+
func TestLabelPictureCacheBoundsIdleMemoryAndPinsBorrowers(t *testing.T) {
var cache labelPictureCache
pinned := &labelPicture{key: labelPictureKey{value: "visible"}, width: 100, height: 20}
diff --git a/internal/platform/windows/text_windows.go b/internal/platform/windows/text_windows.go
index 35153e68e..d6d57046b 100644
--- a/internal/platform/windows/text_windows.go
+++ b/internal/platform/windows/text_windows.go
@@ -322,7 +322,7 @@ func (label *labelTexture) update(next platform.TextLabel) {
func labelContentChanged(previous, next platform.TextLabel) bool {
isBitmap := len(previous.Bitmap) > 0 || len(next.Bitmap) > 0
- return previous.Value != next.Value || (!isBitmap && (previous.Width != next.Width || previous.Height != next.Height)) || previous.FontSize != next.FontSize || previous.Weight != next.Weight || previous.Italic != next.Italic || previous.Color != next.Color || previous.FontGeneration != next.FontGeneration ||
+ return previous.Value != next.Value || (!isBitmap && previous.Height != next.Height) || previous.FontSize != next.FontSize || previous.Weight != next.Weight || previous.Italic != next.Italic || previous.Color != next.Color || previous.FontGeneration != next.FontGeneration ||
previous.Mono != next.Mono || previous.MonoFace != next.MonoFace || previous.CellWidth != next.CellWidth || !sameRuns(previous.Runs, next.Runs) ||
previous.Baseline != next.Baseline ||
previous.BitmapID != next.BitmapID || previous.BitmapVersion != next.BitmapVersion || previous.BitmapWidth != next.BitmapWidth ||
@@ -359,6 +359,9 @@ func (renderer *renderer) needsRaster(label *labelTexture, scale float32, skip,
if len(label.label.Bitmap) > 0 {
return platform.BitmapTextureStale(label.label, scale, label.width, label.height)
}
+ if label.picture != nil && label.picture.complete && skip == 0 && width >= label.picture.x+label.picture.width {
+ return renderer.pictureChanged(label, scale, skip, width)
+ }
return label.skip != skip || label.width != width || renderer.pictureChanged(label, scale, skip, width)
}
From 4d05db5ad44db2dce0f9dc0c7e3cf31b0912fb03 Mon Sep 17 00:00:00 2001
From: MYCF711 <1451895195@qq.com>
Date: Sat, 21 Nov 2026 22:34:28 +0800
Subject: [PATCH 13/47] feat(app): let a web view keep its data in a named
partition
---
.github/workflows/ci.yml | 4 +-
app/web.go | 60 ++++++
app/web_test.go | 87 +++++++++
docs/web-views.md | 27 +++
internal/platform/darwin/web_darwin.go | 21 +-
internal/platform/darwin/web_darwin.h | 9 +-
internal/platform/darwin/web_darwin.m | 55 +++++-
internal/platform/linux/gtk_web_linux.go | 180 +++++++++++++++++-
.../linux/gtk_web_partition_linux_test.go | 69 +++++++
internal/platform/web_host.go | 27 ++-
internal/platform/web_host_test.go | 42 ++++
.../windows/web_partition_windows_test.go | 56 ++++++
internal/platform/windows/web_windows.go | 87 +++++----
13 files changed, 676 insertions(+), 48 deletions(-)
create mode 100644 internal/platform/linux/gtk_web_partition_linux_test.go
create mode 100644 internal/platform/web_host_test.go
create mode 100644 internal/platform/windows/web_partition_windows_test.go
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 2237bf1a4..5eead527c 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -157,7 +157,7 @@ jobs:
- name: GTK optional capability contracts
run: |
go vet -tags vivagtk ./app ./internal/platform/linux
- go test -tags vivagtk ./internal/platform/linux -run '^TestGTK(WaylandAlwaysOnTopReportsUnsupported|ClipboardFileWriteReportsUnsupportedWithoutASetter|ClipboardImageWriteReportsUnsupportedWithoutSetWithData)$' -count=1
+ go test -tags vivagtk ./internal/platform/linux -run '^Test(GTK(WaylandAlwaysOnTopReportsUnsupported|ClipboardFileWriteReportsUnsupportedWithoutASetter|ClipboardImageWriteReportsUnsupportedWithoutSetWithData)|APartition(KeepsItsStoreInTheUsersDirectories|FollowsTheXdgDirectories|IsNamedAfterTheApplicationWithoutAClass))$' -count=1
# The Linux package is not part of the sharded run (it drives X11), so the
# titlebar contracts that do not need a server name their tests here.
- name: Titlebar and window contracts
@@ -345,6 +345,8 @@ jobs:
# on Windows.
- name: Material contracts and controls (WARP)
run: go test ./internal/platform/windows ./ui ./components ./headless ./app -run 'Test(Backdrop|WindowBackdrop|Notification|TaskbarCreated|CompositionClear|CompositionFallback|CompositionCreation|CustomBackdrop|AcrylicAccent|LegacyAcrylic|RoundedOutline|Translucent|MonospaceFamilies|FontWeights|(The)?MonoWeights|(The)?InterfaceWeights|EveryListedFamilyResolves|EngineReportsTheFontsUnderline|AlwaysOnTop|SaveDialogCheckbox|FileIcon|NativeStructureABI|ResizePresents|WindowSwapChain|LiveResize|FlipWindowResize|RedrawWaits|ContinuousRedraw|NoOpFrame|SameSize|ZeroSize|ResizeTimer|RedrawQueue|NativeRedrawMessage|CompositionSupersededFrame|DragPreview)' -count=1 -v
+ - name: Web view partitions
+ run: go test ./internal/platform/windows -run '^Test(APageWithoutAPartitionAsksForNoProfileOfItsOwn|APartitionNamesTheWebView2Profile|AnEphemeralPartitionIsAnOffTheRecordProfile|EphemeralPagesWithoutAPartitionEachGetAProfileOfTheirOwn)$' -count=1 -v
- name: Terminal keyboard routing
run: go test ./internal/platform/windows -run '^TestATerminalGetsEditingKeysAndChordsAsRawKeys$' -count=1 -v
- name: Native window and grouped taskbar icons
diff --git a/app/web.go b/app/web.go
index f8431c00e..d80b42669 100644
--- a/app/web.go
+++ b/app/web.go
@@ -5,6 +5,7 @@ import (
"fmt"
"math"
"net/netip"
+ "strings"
"sync/atomic"
"github.com/vivaui/viva/gfx"
@@ -124,6 +125,23 @@ type WebViewConfig struct {
// that persists. On Windows it needs WebView2 Runtime 101 (SDK 1.0.1210.39) or newer; on Linux,
// WebKitGTK 2.16 or newer.
Ephemeral bool
+ // Partition names the store the page keeps its cookies, localStorage, IndexedDB and caches in:
+ // pages that name the same partition share them, pages that name different partitions do not,
+ // and neither shares with the pages that name none. Empty keeps the application's default store,
+ // which every page without a partition shares, and with no partition an Ephemeral page keeps its
+ // own store in memory.
+ // A named partition is persistent: it is still there after the application exits. With Ephemeral
+ // it is memory-only instead, shared by the pages of that name and gone when the application
+ // exits; macOS has no way to name a non-persistent store and refuses that page with
+ // ErrUnsupported. A name is at most 64 ASCII letters, digits or # @ $ ( ) + - _ ~ . or space, does
+ // not end in a period or a space, and is matched without case (both rules are WebView2's, kept
+ // everywhere so a name means the same store on every engine). On Windows it needs WebView2
+ // Runtime 101 (SDK 1.0.1210.39) or newer; on macOS, 14 or newer; on Linux, WebKitGTK 2.10 or
+ // newer. A named partition cannot be combined with Proxy on macOS or Linux, where the proxy
+ // belongs to the store the partition names: Open fails with ErrUnsupported rather than let two
+ // pages of one partition disagree about it. On Linux a name already open as the other kind of
+ // store is refused as well, since one WebKit context per name can only be one of the two.
+ Partition string
}
// WebNavigation is one navigation the page wants to make.
@@ -249,12 +267,53 @@ func loopbackAddress(address string) bool {
return err == nil && parsed.Addr().IsLoopback() && parsed.Port() != 0
}
+// webPartitionNameLength is the longest name a WebView2 profile accepts, which is the longest name a
+// partition may carry: a name is refused here rather than on one engine only, so that a name an
+// application uses means the same store wherever it runs.
+const webPartitionNameLength = 64
+
+// webPartitionRune reports whether an engine accepts r in the name of a store. The set is WebView2's
+// profile name set; WebKit takes any name, but a name is portable or it is not worth having.
+func webPartitionRune(r rune) bool {
+ switch {
+ case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9':
+ return true
+ }
+ return strings.ContainsRune("#@$()+-_~. ", r)
+}
+
+// partitionName checks a storage partition's name and returns the name the platform is given. Case
+// is folded: Windows maps a WebView2 profile name to a folder that ignores case, so two partitions
+// whose names differ only in case are one store there, and are one store everywhere rather than a
+// store on one engine and two on another.
+func partitionName(name string) (string, error) {
+ if name == "" {
+ return "", nil
+ }
+ if len(name) > webPartitionNameLength {
+ return "", fmt.Errorf("app: web view partition name %q is longer than %d characters", name, webPartitionNameLength)
+ }
+ if strings.HasSuffix(name, ".") || strings.HasSuffix(name, " ") {
+ return "", fmt.Errorf("app: web view partition name %q must not end with a period or a space", name)
+ }
+ for _, r := range name {
+ if !webPartitionRune(r) {
+ return "", fmt.Errorf("app: web view partition name %q carries %q, which is not a letter, a digit, or one of # @ $ ( ) + - _ ~ . space", name, r)
+ }
+ }
+ return strings.ToLower(name), nil
+}
+
// Open opens a page. It fails with ErrUnsupported when the platform cannot host pages or the system
// has no web engine installed.
func (host *WebHost) Open(config WebViewConfig) (*WebView, error) {
if config.TopCornerRadius < 0 || math.IsNaN(float64(config.TopCornerRadius)) || math.IsInf(float64(config.TopCornerRadius), 0) {
return nil, fmt.Errorf("app: invalid web view top corner radius")
}
+ partition, err := partitionName(config.Partition)
+ if err != nil {
+ return nil, err
+ }
if host == nil || host.native == nil || host.native.Open == nil {
return nil, fmt.Errorf("%w: web views", ErrUnsupported)
@@ -267,6 +326,7 @@ func (host *WebHost) Open(config WebViewConfig) (*WebView, error) {
ID: uint32(id), URL: config.URL, HTML: config.HTML, BaseURL: config.BaseURL, Proxy: config.Proxy,
TopCornerRadius: config.TopCornerRadius,
Ephemeral: config.Ephemeral,
+ Partition: partition,
}
// What a page tells the application usually changes what it shows, so a callback is followed
// by a paint.
diff --git a/app/web_test.go b/app/web_test.go
index 063f0b565..b5cb00ab9 100644
--- a/app/web_test.go
+++ b/app/web_test.go
@@ -3,6 +3,8 @@ package app
import (
"errors"
"math"
+ "reflect"
+ "strings"
"testing"
"github.com/vivaui/viva/gfx"
@@ -324,3 +326,88 @@ func TestALoadReportCarriesTheTitleAndTheFailure(t *testing.T) {
t.Fatalf("a load that failed = %+v, want the title and the engine's reason", got)
}
}
+
+func TestAPartitionReachesThePlatformFoldedToLowerCase(t *testing.T) {
+ var opened platform.WebViewConfig
+ host := &WebHost{native: &platform.WebHost{Open: func(config platform.WebViewConfig) (platform.WebView, error) {
+ opened = config
+ return nil, platform.ErrWebViewUnsupported
+ }}}
+ if _, err := host.Open(WebViewConfig{Partition: "Workspace-1"}); !errors.Is(err, ErrUnsupported) {
+ t.Fatalf("err = %v", err)
+ }
+ // Windows maps a WebView2 profile name to a folder that ignores case, so a name is folded before
+ // any platform sees it: two names that differ only in case are one store everywhere.
+ if opened.Partition != "workspace-1" {
+ t.Fatalf("the platform got partition %q, want it folded", opened.Partition)
+ }
+}
+
+// A page that names no partition asks the platform for nothing it did not ask for before, down to
+// every field of the configuration: a field added later that such a page leaves at its zero value
+// must stay there, or the store of every page in the application changes with it.
+func TestAPageWithoutAPartitionAsksForNoStore(t *testing.T) {
+ var opened platform.WebViewConfig
+ host := &WebHost{native: &platform.WebHost{Open: func(config platform.WebViewConfig) (platform.WebView, error) {
+ opened = config
+ return nil, platform.ErrWebViewUnsupported
+ }}}
+ if _, err := host.Open(WebViewConfig{URL: "https://example.com/"}); !errors.Is(err, ErrUnsupported) {
+ t.Fatalf("err = %v", err)
+ }
+ want := platform.WebViewConfig{ID: 1, URL: "https://example.com/"}
+ if !reflect.DeepEqual(opened, want) {
+ t.Fatalf("the platform got %+v, want %+v", opened, want)
+ }
+}
+
+func TestAPartitionNameIsOneEveryEngineAccepts(t *testing.T) {
+ accepted := []string{
+ "a",
+ "workspace-1",
+ "Acct@Home",
+ "12#ab$cd(ef)+gh_ij~kl.mn",
+ "with a space",
+ strings.Repeat("n", 64),
+ }
+ refused := []string{
+ strings.Repeat("n", 65),
+ "trailing.",
+ "trailing ",
+ "slash/name",
+ "back\\slash",
+ "colon:name",
+ "star*name",
+ "quote\"name",
+ "ümlaut",
+ }
+ for _, name := range accepted {
+ if _, err := partitionName(name); err != nil {
+ t.Fatalf("partition %q was refused: %v", name, err)
+ }
+ }
+ for _, name := range refused {
+ if _, err := partitionName(name); err == nil {
+ t.Fatalf("partition %q was accepted", name)
+ }
+ }
+ if name, err := partitionName(""); err != nil || name != "" {
+ t.Fatalf("no partition = %q, %v", name, err)
+ }
+}
+
+// A name WebView2 would refuse is refused before the platform is asked, on every platform, rather than
+// failing late on one engine and meaning something else on another.
+func TestARefusedPartitionNameNeverReachesThePlatform(t *testing.T) {
+ asked := false
+ host := &WebHost{native: &platform.WebHost{Open: func(config platform.WebViewConfig) (platform.WebView, error) {
+ asked = true
+ return nil, platform.ErrWebViewUnsupported
+ }}}
+ if _, err := host.Open(WebViewConfig{URL: "https://example.com/", Partition: strings.Repeat("n", 65)}); err == nil || errors.Is(err, ErrUnsupported) {
+ t.Fatalf("err = %v, want the name refused by the application", err)
+ }
+ if asked {
+ t.Fatal("the platform was asked to open a page whose partition name was refused")
+ }
+}
diff --git a/docs/web-views.md b/docs/web-views.md
index 3b07e42a0..f3edd7925 100644
--- a/docs/web-views.md
+++ b/docs/web-views.md
@@ -121,6 +121,33 @@ scheme, a message in each direction and a menu that stands over the page.
in it, and the context ends with the page (WebKitGTK 2.16 or newer); a page that also asks for a `Proxy` gets
its own ephemeral context with the proxy's settings, not the context shared behind that proxy. Where the engine
cannot do it, the page is refused or closed rather than opened with a store that persists.
+- `Partition` names the store the page keeps its cookies, `localStorage`, IndexedDB and caches in. Pages that
+ name the same partition share them, pages that name different partitions do not, and neither shares with the
+ pages that name none: one window can show two accounts of one site, or a workspace's page apart from every
+ other workspace's. A named partition persists across runs, and with `Ephemeral` it is memory-only instead,
+ shared by the pages of that name and gone when the application exits. Empty keeps the store of every page
+ without a partition, which is the whole of the behaviour before partitions existed: nothing about a page that
+ names no partition changes.
+ A name is at most 64 characters of ASCII letters, digits and `# @ $ ( ) + - _ ~ .` or space, does not end in a
+ period or a space, and is matched without case. Those are WebView2's rules for a profile name, and Viva keeps
+ them on every engine so that a name means one store wherever the application runs: a name WebView2 would refuse
+ is refused by `Open` with an error of its own, before any engine sees it. Windows needs WebView2 Runtime 101
+ (SDK 1.0.1210.39, the first runtime with `ICoreWebView2ControllerOptions`) or newer, and opens the page in a
+ controller whose options name the profile: WebView2 keeps that profile's cookies, storage and caches in a
+ folder of the user data folder that only that name reaches, and an `Ephemeral` partition of the same name is a
+ separate off-the-record profile, so its pages never see what the persistent one kept. macOS needs 14 or newer
+ and gives the configuration `WKWebsiteDataStore`'s store for an identifier derived from the name
+ (`dataStoreForIdentifier:`), so the store is the same one in every run; older systems, and a name asked for as
+ a non-persistent store, are refused with `ErrUnsupported`, because `WKWebsiteDataStore` has one non-persistent
+ store and no way to name a second. Linux makes a `WebKitWebsiteDataManager` per partition (WebKitGTK 2.10 or
+ newer) whose `base-data-directory` and `base-cache-directory` are folders of the partition's name under the
+ user's data and cache directories, and creates the page's `WebKitWebContext` over it
+ (`webkit_web_context_new_with_website_data_manager`); the manager is asked what it took before a page is put in
+ it, and the page is refused if the engine did not take the directory; a name already open as the other kind of
+ store is refused there too, since one WebKit context per name can only be one of the two. A page of one partition that asks for a
+ different proxy than the rest cannot be served on macOS or Linux, where the proxy is a setting of the store the
+ partition names, so the combination is refused with `ErrUnsupported` rather than served with a route another
+ page of its partition picked; Windows keeps the proxy in the page's environment, so both work there.
- `Canvas.NativeView` declares where the page is, on the current layer and inside the current clip. What Viva
paints on that layer or below is hidden by the page; what it paints on a higher layer (a menu, a tooltip,
`ui`'s `f.PopupLayer`) stands over it, and a hit region on a higher layer takes the pointer where it lies
diff --git a/internal/platform/darwin/web_darwin.go b/internal/platform/darwin/web_darwin.go
index d51104899..7e7806c1f 100644
--- a/internal/platform/darwin/web_darwin.go
+++ b/internal/platform/darwin/web_darwin.go
@@ -70,6 +70,17 @@ func newWebState(run *runState, host *platform.WebHost, initial []platform.Nativ
// open is WebHost.Open.
func (w *webState) open(config platform.WebViewConfig) (platform.WebView, error) {
+ if config.Partition != "" && config.Ephemeral {
+ // A non-persistent store cannot be named: WKWebsiteDataStore has one, shared by every page
+ // that asks for it, so a page of a named partition that must keep nothing is refused rather
+ // than opened in the named store, which persists.
+ return nil, fmt.Errorf("%w: macOS cannot name a store that keeps nothing: a named storage partition persists on WKWebView", platform.ErrWebViewUnsupported)
+ }
+ if config.Partition != "" && config.Proxy != "" {
+ // The proxy is a setting of the store, and one store cannot carry two: two pages of one
+ // partition could not disagree about it.
+ return nil, fmt.Errorf("%w: macOS cannot combine a named storage partition with a proxy: the proxy belongs to the store the partition names", platform.ErrWebViewUnsupported)
+ }
direct := C.int(0)
if config.Proxy != "" {
if config.Proxy != platform.WebProxyDirect {
@@ -114,8 +125,16 @@ func (w *webState) open(config platform.WebViewConfig) (platform.WebView, error)
if config.Ephemeral {
ephemeral = 1
}
+ var partition *C.char
+ if config.Partition != "" {
+ if C.viva_web_partition_supported() == 0 {
+ return nil, fmt.Errorf("darwin: a named storage partition needs macOS 14 or newer: %w", platform.ErrWebViewUnsupported)
+ }
+ partition = C.CString(platform.PartitionIdentifier(config.Partition))
+ defer C.free(unsafe.Pointer(partition))
+ }
var failure *C.char
- native := C.viva_web_open(view, C.uint32_t(config.ID), C.uintptr_t(w.run.callbackHandle), url, html, base, script, mainFrameOnly, scheme, ephemeral, direct, &failure)
+ native := C.viva_web_open(view, C.uint32_t(config.ID), C.uintptr_t(w.run.callbackHandle), url, html, base, script, mainFrameOnly, scheme, ephemeral, direct, partition, &failure)
if native == nil {
message := "the page could not be created"
if failure != nil {
diff --git a/internal/platform/darwin/web_darwin.h b/internal/platform/darwin/web_darwin.h
index ec37b2d64..06db1fb49 100644
--- a/internal/platform/darwin/web_darwin.h
+++ b/internal/platform/darwin/web_darwin.h
@@ -11,11 +11,16 @@ void *viva_application_window_view(void *token);
// viva_web_open puts a page over the view and returns it, or NULL with error (a malloc'd message)
// set. The page is owned by the view's hierarchy until viva_web_close. main_frame_only says the
// bridge script is for the main frame alone (WebKit is also told to inject it there only). An
-// ephemeral page keeps its data in a store in memory, which goes with the page.
+// ephemeral page keeps its data in a store in memory, which goes with the page. partition, when not
+// NULL, is the UUID of the persistent store the page keeps its cookies and storage in: pages of one
+// identifier share it, pages of another do not. A named partition needs macOS 14, and is refused
+// with an error on an older system rather than opened in the default store.
void *viva_web_open(void *view, uint32_t id, uintptr_t handle, const char *url, const char *html,
const char *base, const char *script, int main_frame_only, const char *scheme, int ephemeral, int direct,
- char **error);
+ const char *partition, char **error);
int viva_web_direct_supported(void);
+// viva_web_partition_supported answers whether this system can name the persistent store a partition uses.
+int viva_web_partition_supported(void);
void viva_web_load(void *web, const char *url);
void viva_web_load_html(void *web, const char *html, const char *base);
void viva_web_reload(void *web);
diff --git a/internal/platform/darwin/web_darwin.m b/internal/platform/darwin/web_darwin.m
index e31e7e9c6..9ed7dd4ab 100644
--- a/internal/platform/darwin/web_darwin.m
+++ b/internal/platform/darwin/web_darwin.m
@@ -537,9 +537,52 @@ int viva_web_direct_supported(void) {
return 0;
}
+// viva_web_partition_supported answers whether this system can name a persistent
+// storage store, which is what a partition needs.
+int viva_web_partition_supported(void) {
+#if defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 140000
+ if (@available(macOS 14.0, *)) {
+ return 1;
+ }
+#endif
+ return 0;
+}
+
+// viva_web_named_store gives the configuration the persistent store of the identifier, and says
+// whether it did: a system too old to name a store, or an identifier that is not one, is reported
+// through error, and no page is opened in a store the application did not ask for.
+static int viva_web_named_store(WKWebViewConfiguration *configuration, const char *identifier, char **error) {
+#if defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 140000
+ if (@available(macOS 14.0, *)) {
+ NSString *text = [NSString stringWithUTF8String:identifier];
+ NSUUID *uuid = text == nil ? nil : [[NSUUID alloc] initWithUUIDString:text];
+ if (uuid == nil) {
+ if (error != NULL) {
+ *error = strdup("the storage partition is not an identifier");
+ }
+ return 0;
+ }
+ WKWebsiteDataStore *store = [WKWebsiteDataStore dataStoreForIdentifier:uuid];
+ [uuid release];
+ if (store == nil) {
+ if (error != NULL) {
+ *error = strdup("the system made no store for the storage partition");
+ }
+ return 0;
+ }
+ configuration.websiteDataStore = store;
+ return 1;
+ }
+#endif
+ if (error != NULL) {
+ *error = strdup("a named storage partition needs macOS 14 or newer");
+ }
+ return 0;
+}
+
void *viva_web_open(void *view, uint32_t id, uintptr_t handle, const char *url, const char *html,
const char *base, const char *script, int mainFrameOnly, const char *scheme, int ephemeral, int direct,
- char **error) {
+ const char *partition, char **error) {
__block VivaWebView *web = nil;
viva_web_main(^{
NSView *host = (NSView *)view;
@@ -550,7 +593,15 @@ int viva_web_direct_supported(void) {
bridge->_handle = handle;
bridge->_id = id;
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
- if (ephemeral || direct) {
+ if (partition != NULL && partition[0] != 0) {
+ // A named partition is a store of its own, which WebKit keeps under an identifier: pages
+ // of one identifier share their cookies and storage, pages of another do not.
+ if (!viva_web_named_store(configuration, partition, error)) {
+ [configuration release];
+ [bridge release];
+ return;
+ }
+ } else if (ephemeral || direct) {
// Ephemeral pages keep nothing on disk. Direct pages also need a private store so
// their proxy policy cannot change another page's in-flight requests or data store.
configuration.websiteDataStore = [WKWebsiteDataStore nonPersistentDataStore];
diff --git a/internal/platform/linux/gtk_web_linux.go b/internal/platform/linux/gtk_web_linux.go
index b9f494b7f..bd4b24738 100644
--- a/internal/platform/linux/gtk_web_linux.go
+++ b/internal/platform/linux/gtk_web_linux.go
@@ -8,8 +8,11 @@ import (
"math"
"net/url"
"os"
+ "path/filepath"
+ "runtime"
"strings"
"sync"
+ "unsafe"
"github.com/ebitengine/purego"
"github.com/vivaui/viva/gfx"
@@ -68,6 +71,12 @@ type webKit struct {
contextDataManager func(context uintptr) uintptr
managerSetProxy func(manager uintptr, mode int32, settings uintptr)
contextSetProxy func(context uintptr, mode int32, settings uintptr)
+ // For a store of a page's own: a context over a website data manager of the partition's, the
+ // manager itself, and the directories it took (WebKitGTK 2.10); nil without.
+ contextWithDataManager func(manager uintptr) uintptr
+ dataManagerNew func(name1, value1, name2, value2, terminator uintptr) uintptr
+ dataManagerBaseData func(manager uintptr) uintptr
+ dataManagerBaseCache func(manager uintptr) uintptr
// The 2.36 answer, which carries a status and headers; nil on an engine that has only the stream
// and type form, where a scheme's status and headers are dropped.
schemeResponse bool
@@ -198,6 +207,12 @@ func loadWebKit(g *gtkLibrary) (*webKit, error) {
!g.lookup(&k.proxySettingsFree, "webkit_network_proxy_settings_free") {
k.contextEphemeral = nil
}
+ if !g.lookup(&k.contextWithDataManager, "webkit_web_context_new_with_website_data_manager") ||
+ !g.lookup(&k.dataManagerNew, "webkit_website_data_manager_new") ||
+ !g.lookup(&k.dataManagerBaseData, "webkit_website_data_manager_get_base_data_directory") ||
+ !g.lookup(&k.dataManagerBaseCache, "webkit_website_data_manager_get_base_cache_directory") {
+ k.contextWithDataManager = nil
+ }
if !g.lookup(&k.contextDataManager, "webkit_web_context_get_website_data_manager") ||
!g.lookup(&k.managerSetProxy, "webkit_website_data_manager_set_network_proxy_settings") {
k.managerSetProxy = nil
@@ -279,6 +294,7 @@ var (
webSchemes = map[string]*platform.WebScheme{}
webSchemeDone = map[webSchemeKey]bool{}
webProxies = map[string]*webContext{}
+ webPartitions = map[string]*webContext{}
)
// webSchemeKey is a scheme registered with one context: the default, or a context of a page's own.
@@ -287,13 +303,17 @@ type webSchemeKey struct {
name string
}
-// webContext is an ephemeral WebKit context a page runs in. The pages held to one proxy share one;
-// a page that asked to keep nothing, or both to keep nothing and to use a proxy, has one of its
-// own. Nothing it keeps outlives it, and it goes with its last page.
+// webContext is a WebKit context a page runs in besides the default one. The pages held to one proxy
+// share one; a page that asked to keep nothing, or both to keep nothing and to use a proxy, has one
+// of its own. The pages of a named storage partition share one too, which keeps what they save
+// together and apart from every other partition's. What an ephemeral one keeps does not outlive it,
+// and it goes with its last page.
type webContext struct {
- proxy string
- object uintptr
- pages int
+ proxy string
+ partition string
+ ephemeral bool
+ object uintptr
+ pages int
}
// WebKitNetworkProxyMode.
@@ -361,18 +381,150 @@ func newEphemeralContext(k *webKit) (*webContext, error) {
return &webContext{object: object, pages: 1}, nil
}
+// partitionContext is the context of a named storage partition, shared by the pages that name it and
+// made the first time one opens. A name is one store: a page that asks for it keeping nothing when
+// the open one persists, or the other way round, is refused rather than given a store of its own
+// under the same name.
+func partitionContext(g *gtkLibrary, k *webKit, class, name string, ephemeral bool) (*webContext, error) {
+ if context := webPartitions[name]; context != nil {
+ if context.ephemeral != ephemeral {
+ return nil, fmt.Errorf("linux: partition %q is open as a %s store, and a page cannot ask for the other kind under the same name", name, partitionKind(context.ephemeral))
+ }
+ context.pages++
+ return context, nil
+ }
+ var context *webContext
+ var err error
+ if ephemeral {
+ context, err = newEphemeralContext(k)
+ } else {
+ context, err = newPartitionContext(g, k, class, name)
+ }
+ if err != nil {
+ return nil, err
+ }
+ context.partition, context.ephemeral = name, ephemeral
+ webPartitions[name] = context
+ return context, nil
+}
+
+// partitionKind names a partition's store in an error.
+func partitionKind(ephemeral bool) string {
+ if ephemeral {
+ return "memory-only"
+ }
+ return "persistent"
+}
+
+// newPartitionContext makes a context over a website data manager of the partition's own: the manager
+// keeps the partition's cookies, storage and caches in a directory of its name, so the pages of
+// another partition, and the pages of none, do not see them.
+func newPartitionContext(g *gtkLibrary, k *webKit, class, name string) (*webContext, error) {
+ if k.contextWithDataManager == nil || k.dataManagerNew == nil || k.dataManagerBaseData == nil || k.dataManagerBaseCache == nil {
+ return nil, fmt.Errorf("%w: WebKitGTK cannot give a page a store of its own (2.10 or newer is required)", platform.ErrWebViewUnsupported)
+ }
+ data, cache, err := partitionDirectories(class, name)
+ if err != nil {
+ return nil, err
+ }
+ manager := makeDataManager(k, data, cache)
+ if manager == 0 {
+ return nil, fmt.Errorf("%w: WebKitGTK made no store for partition %q", platform.ErrWebViewUnsupported, name)
+ }
+ // A manager given no directories keeps the engine's defaults, which are the default store under
+ // another name: a partition whose directory the engine did not take is refused rather than opened
+ // over the pages it must not share with.
+ if got := goString(k.dataManagerBaseData(manager)); got != data {
+ g.objectUnref(manager)
+ return nil, fmt.Errorf("%w: WebKitGTK kept %q as the data directory of partition %q, not %q", platform.ErrWebViewUnsupported, got, name, data)
+ }
+ if got := goString(k.dataManagerBaseCache(manager)); got != cache {
+ g.objectUnref(manager)
+ return nil, fmt.Errorf("%w: WebKitGTK kept %q as the cache directory of partition %q, not %q", platform.ErrWebViewUnsupported, got, name, cache)
+ }
+ object := k.contextWithDataManager(manager)
+ g.objectUnref(manager) // the context holds the reference it was given
+ if object == 0 {
+ return nil, fmt.Errorf("%w: WebKitGTK made no context for partition %q", platform.ErrWebViewUnsupported, name)
+ }
+ return &webContext{object: object, pages: 1}, nil
+}
+
+// makeDataManager makes a website data manager that keeps its data in data and its caches in cache.
+// webkit_website_data_manager_new has no non-variadic form and the two properties that carry the
+// directories are construct-only, so the names and values go as its varargs, NUL-terminated:
+// pointers only, which is what the C ABI's variadic call takes on every architecture Viva builds for.
+// What the manager took is read back before a page is put in it.
+func makeDataManager(k *webKit, data, cache string) uintptr {
+ dataName, cacheName := cString("base-data-directory"), cString("base-cache-directory")
+ dataValue, cacheValue := cString(data), cString(cache)
+ manager := k.dataManagerNew(
+ uintptr(unsafe.Pointer(&dataName[0])), uintptr(unsafe.Pointer(&dataValue[0])),
+ uintptr(unsafe.Pointer(&cacheName[0])), uintptr(unsafe.Pointer(&cacheValue[0])), 0)
+ runtime.KeepAlive(dataName)
+ runtime.KeepAlive(dataValue)
+ runtime.KeepAlive(cacheName)
+ runtime.KeepAlive(cacheValue)
+ return manager
+}
+
+// partitionDirectories is where a named partition keeps its data and its caches: in the user's data
+// and cache directories, under a folder of the application's own name and then of the partition's, so
+// that two applications that name a partition alike do not share one store.
+func partitionDirectories(class, name string) (data, cache string, err error) {
+ if class == "" {
+ if executable, executableErr := os.Executable(); executableErr == nil {
+ class = strings.TrimSuffix(filepath.Base(executable), filepath.Ext(executable))
+ }
+ }
+ if class == "" {
+ class = "viva"
+ }
+ data, err = userDirectory("XDG_DATA_HOME", ".local/share", class, name)
+ if err != nil {
+ return "", "", err
+ }
+ cache, err = userDirectory("XDG_CACHE_HOME", ".cache", class, name)
+ if err != nil {
+ return "", "", err
+ }
+ return data, cache, nil
+}
+
+// userDirectory is environment's directory when it names one, else the fallback under the user's home
+// directory, with webkit and parts added; it is made, since the engine writes into it before the page
+// loads.
+func userDirectory(environment, fallback, class, name string) (string, error) {
+ base := os.Getenv(environment)
+ if base == "" {
+ home, err := os.UserHomeDir()
+ if err != nil {
+ return "", fmt.Errorf("%w: a storage partition has nowhere to keep its data: %v", platform.ErrWebViewUnsupported, err)
+ }
+ base = filepath.Join(home, filepath.FromSlash(fallback))
+ }
+ directory := filepath.Join(base, class, "webkit", name)
+ if err := os.MkdirAll(directory, 0o700); err != nil {
+ return "", fmt.Errorf("%w: a storage partition has nowhere to keep its data: %v", platform.ErrWebViewUnsupported, err)
+ }
+ return directory, nil
+}
+
// leave lets go of the context for one page; the last page ends it.
func (context *webContext) leave(g *gtkLibrary) {
context.pages--
if context.pages > 0 {
return
}
- // Only a shared context is in webProxies. A page that asked for a proxy and to keep nothing has
- // a context of its own with the proxy's settings, and must not drop the shared one behind the
- // same proxy.
+ // Only a shared context is in webProxies or webPartitions. A page that asked for a proxy and to
+ // keep nothing has a context of its own with the proxy's settings, and must not drop the shared
+ // one behind the same proxy.
if context.proxy != "" && webProxies[context.proxy] == context {
delete(webProxies, context.proxy)
}
+ if context.partition != "" && webPartitions[context.partition] == context {
+ delete(webPartitions, context.partition)
+ }
for key := range webSchemeDone {
if key.context == context.object {
delete(webSchemeDone, key)
@@ -400,8 +552,18 @@ func (w *gtkWindow) openWebView(c platform.WebViewConfig) (platform.WebView, err
if err != nil {
return nil, err
}
+ if c.Partition != "" && c.Proxy != "" {
+ // The proxy is the store's own setting here, and one store cannot carry two: two pages of one
+ // partition could not disagree about it, so the page is refused rather than opened with a
+ // route another page of its partition chose.
+ return nil, fmt.Errorf("%w: WebKitGTK cannot combine a named storage partition with a proxy: the proxy belongs to the store the partition names", platform.ErrWebViewUnsupported)
+ }
var private *webContext
switch {
+ case c.Partition != "":
+ if private, err = partitionContext(g, k, w.config.Class, c.Partition, c.Ephemeral); err != nil {
+ return nil, err
+ }
case c.Proxy != "" && c.Ephemeral:
// A page that asks for both needs its own ephemeral context with the proxy's settings. The
// shared context behind the same proxy would do the proxy but would also share its cookies
diff --git a/internal/platform/linux/gtk_web_partition_linux_test.go b/internal/platform/linux/gtk_web_partition_linux_test.go
new file mode 100644
index 000000000..e420921ca
--- /dev/null
+++ b/internal/platform/linux/gtk_web_partition_linux_test.go
@@ -0,0 +1,69 @@
+//go:build linux && vivagtk
+
+package linux
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+// A partition's store goes under the user's data and cache directories, in a folder of the
+// application's own and then of the partition's: two applications that name a partition alike keep
+// two stores, and two partitions of one application keep two more.
+func TestAPartitionKeepsItsStoreInTheUsersDirectories(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ t.Setenv("XDG_DATA_HOME", "")
+ t.Setenv("XDG_CACHE_HOME", "")
+ data, cache, err := partitionDirectories("app", "workspace-1")
+ if err != nil {
+ t.Fatal(err)
+ }
+ wantData := filepath.Join(home, ".local", "share", "app", "webkit", "workspace-1")
+ wantCache := filepath.Join(home, ".cache", "app", "webkit", "workspace-1")
+ if data != wantData || cache != wantCache {
+ t.Fatalf("partition store = %q, %q, want %q, %q", data, cache, wantData, wantCache)
+ }
+ for _, directory := range []string{data, cache} {
+ if info, err := os.Stat(directory); err != nil || !info.IsDir() {
+ t.Fatalf("%q was not made: %v", directory, err)
+ }
+ }
+ if other, _, err := partitionDirectories("app", "workspace-2"); err != nil || other == data {
+ t.Fatalf("two partitions share %q: %v", other, err)
+ }
+}
+
+func TestAPartitionFollowsTheXdgDirectories(t *testing.T) {
+ root := t.TempDir()
+ t.Setenv("XDG_DATA_HOME", filepath.Join(root, "data"))
+ t.Setenv("XDG_CACHE_HOME", filepath.Join(root, "cache"))
+ data, cache, err := partitionDirectories("app", "workspace-1")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if data != filepath.Join(root, "data", "app", "webkit", "workspace-1") ||
+ cache != filepath.Join(root, "cache", "app", "webkit", "workspace-1") {
+ t.Fatalf("partition store = %q, %q", data, cache)
+ }
+}
+
+// Without a name to put in the path the application's own executable names its folder, so that two
+// applications do not share a partition by accident.
+func TestAPartitionIsNamedAfterTheApplicationWithoutAClass(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ t.Setenv("XDG_DATA_HOME", "")
+ t.Setenv("XDG_CACHE_HOME", "")
+ data, _, err := partitionDirectories("", "workspace-1")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if filepath.Base(filepath.Dir(filepath.Dir(data))) == "" || filepath.Base(filepath.Dir(filepath.Dir(data))) == "webkit" {
+ t.Fatalf("partition %q carries no application folder of its own", data)
+ }
+ if filepath.Base(data) != "workspace-1" {
+ t.Fatalf("partition %q does not end in its name", data)
+ }
+}
diff --git a/internal/platform/web_host.go b/internal/platform/web_host.go
index ba4ce231c..80565f32f 100644
--- a/internal/platform/web_host.go
+++ b/internal/platform/web_host.go
@@ -1,7 +1,10 @@
package platform
import (
+ "crypto/sha1"
+ "encoding/hex"
"errors"
+ "strings"
"github.com/vivaui/viva/gfx"
)
@@ -18,6 +21,18 @@ var ErrWebViewUnsupported = errors.New("platform: this window cannot host web pa
// WebProxyDirect explicitly bypasses system proxies for one page's network context.
const WebProxyDirect = "direct"
+// PartitionIdentifier is the identifier a platform that names a store by an identifier gives a storage
+// partition: a UUID made from the name, the same for a name in every run of the application, so a name
+// is one store. macOS's WKWebsiteDataStore names its persistent stores this way; WebView2 names a
+// profile by the partition's name itself, and WebKitGTK by the directory it keeps, one of the name.
+func PartitionIdentifier(name string) string {
+ sum := sha1.Sum([]byte("viva-storage-partition:" + name))
+ sum[6] = sum[6]&0x0f | 0x50 // a name-based UUID, version 5
+ sum[8] = sum[8]&0x3f | 0x80 // the variant a UUID carries
+ text := hex.EncodeToString(sum[:])
+ return strings.ToUpper(text[0:8] + "-" + text[8:12] + "-" + text[12:16] + "-" + text[16:20] + "-" + text[20:32])
+}
+
// NativeView is a place in the window that a native view fills.
type NativeView struct {
// ID is the WebView it belongs to (WebViewConfig.ID).
@@ -83,8 +98,18 @@ type WebViewConfig struct {
// Ephemeral keeps the page's cookies, storage and caches in memory only, separate from every
// other page, and drops them when the page closes: a run of the application leaves nothing the
// page kept on disk. A platform without such a store must refuse the page rather than open one
- // that persists.
+ // that persists. On Windows it needs WebView2 Runtime 101 (SDK 1.0.1210.39) or newer; on Linux,
+ // WebKitGTK 2.16 or newer.
Ephemeral bool
+ // Partition names the store the page keeps its cookies, storage and caches in: pages of the same
+ // partition share them, pages of different partitions do not, and neither shares with the pages
+ // that name none. Empty keeps the platform's default store, which is the whole of the behaviour
+ // without a partition. A platform that cannot give a page a store of its own returns
+ // ErrWebViewUnsupported rather than open a page that shares the default one.
+ // The name is already validated and folded to lower case: the application layer does that, once,
+ // so that a name means the same store on every engine. A name is persistent unless Ephemeral is
+ // also set, which makes it a memory-only store shared by the pages of that name.
+ Partition string
}
// WebNavigation is one navigation the page wants to make.
diff --git a/internal/platform/web_host_test.go b/internal/platform/web_host_test.go
new file mode 100644
index 000000000..360c440c8
--- /dev/null
+++ b/internal/platform/web_host_test.go
@@ -0,0 +1,42 @@
+package platform
+
+import (
+ "strings"
+ "testing"
+)
+
+// A storage partition's name is the same store in every run, so the identifier it is named by on the
+// platform that wants one has to be the same too.
+func TestAPartitionIdentifierIsTheSameForEveryNameEveryTime(t *testing.T) {
+ first, second := PartitionIdentifier("workspace-1"), PartitionIdentifier("workspace-1")
+ if first != second {
+ t.Fatalf("%q and %q name the same partition", first, second)
+ }
+ if other := PartitionIdentifier("workspace-2"); other == first {
+ t.Fatalf("two partitions share the identifier %q", other)
+ }
+}
+
+func TestAPartitionIdentifierIsAUUID(t *testing.T) {
+ identifier := PartitionIdentifier("workspace-1")
+ if len(identifier) != 36 {
+ t.Fatalf("identifier %q is %d characters, want 36", identifier, len(identifier))
+ }
+ for i, r := range identifier {
+ switch i {
+ case 8, 13, 18, 23:
+ if r != '-' {
+ t.Fatalf("identifier %q has %q at %d, want a hyphen", identifier, r, i)
+ }
+ default:
+ if !strings.ContainsRune("0123456789ABCDEF", r) {
+ t.Fatalf("identifier %q has %q at %d, want an upper-case hex digit", identifier, r, i)
+ }
+ }
+ }
+ // WKWebsiteDataStore takes the canonical form and nothing else, so the version and the variant
+ // have to be the ones it validates.
+ if identifier[14] != '5' || !strings.ContainsRune("89AB", rune(identifier[19])) {
+ t.Fatalf("identifier %q is not a version 5 UUID with an RFC 4122 variant", identifier)
+ }
+}
diff --git a/internal/platform/windows/web_partition_windows_test.go b/internal/platform/windows/web_partition_windows_test.go
new file mode 100644
index 000000000..4af8d181b
--- /dev/null
+++ b/internal/platform/windows/web_partition_windows_test.go
@@ -0,0 +1,56 @@
+package windows
+
+import (
+ "os"
+ "strconv"
+ "strings"
+ "testing"
+
+ "github.com/vivaui/viva/internal/platform"
+)
+
+// A page that names no partition and keeps nothing asks for the default profile through the plain
+// controller: that is the way every page was made before partitions, and it must not change.
+func TestAPageWithoutAPartitionAsksForNoProfileOfItsOwn(t *testing.T) {
+ name, inPrivate, options := controllerProfile(platform.WebViewConfig{})
+ if options || inPrivate || name != "" {
+ t.Fatalf("a page with nothing to ask for got profile %q, in private %v, options %v", name, inPrivate, options)
+ }
+}
+
+func TestAPartitionNamesTheWebView2Profile(t *testing.T) {
+ name, inPrivate, options := controllerProfile(platform.WebViewConfig{Partition: "workspace-1"})
+ if !options || inPrivate || name != "workspace-1" {
+ t.Fatalf("partition workspace-1 got profile %q, in private %v, options %v", name, inPrivate, options)
+ }
+}
+
+// A partition that must keep nothing is an off-the-record profile of the partition's name, so its
+// pages share it and the pages of another partition do not.
+func TestAnEphemeralPartitionIsAnOffTheRecordProfile(t *testing.T) {
+ name, inPrivate, options := controllerProfile(platform.WebViewConfig{Partition: "workspace-1", Ephemeral: true})
+ if !options || !inPrivate || name != "workspace-1" {
+ t.Fatalf("ephemeral partition workspace-1 got profile %q, in private %v, options %v", name, inPrivate, options)
+ }
+}
+
+// An ephemeral page with no partition keeps its own store: WebView2 derives one off-the-record
+// profile from the default profile's name, so two of them without a name of their own would share it.
+func TestEphemeralPagesWithoutAPartitionEachGetAProfileOfTheirOwn(t *testing.T) {
+ first, inPrivate, options := controllerProfile(platform.WebViewConfig{Ephemeral: true})
+ second, _, _ := controllerProfile(platform.WebViewConfig{Ephemeral: true})
+ if !options || !inPrivate {
+ t.Fatalf("an ephemeral page got in private %v, options %v", inPrivate, options)
+ }
+ if first == second {
+ t.Fatalf("two ephemeral pages share the profile %q", first)
+ }
+ for _, name := range []string{first, second} {
+ if !strings.HasPrefix(name, "viva-ephemeral-"+strconv.Itoa(os.Getpid())+"-") {
+ t.Fatalf("profile %q is not this process's own", name)
+ }
+ if len(name) > 64 {
+ t.Fatalf("profile %q is longer than the 64 characters WebView2 accepts", name)
+ }
+ }
+}
diff --git a/internal/platform/windows/web_windows.go b/internal/platform/windows/web_windows.go
index c357a81cf..358256bf8 100644
--- a/internal/platform/windows/web_windows.go
+++ b/internal/platform/windows/web_windows.go
@@ -162,17 +162,17 @@ func (w *webHost) open(config platform.WebViewConfig) (platform.WebView, error)
if err != nil {
return nil, fmt.Errorf("%w: %v", platform.ErrWebViewUnsupported, err)
}
- if config.Ephemeral && version != "" {
+ if (config.Ephemeral || config.Partition != "") && version != "" {
// ICoreWebView2Environment10 and ICoreWebView2ControllerOptions first ship with Runtime 101
// (WebView2 SDK 1.0.1210.39). The version is the one in the install folder the client library
- // was found in, so it describes the runtime that will load. An older runtime cannot make an
- // ephemeral page, so it is refused here, synchronously, rather than after Open has handed a
- // live page to the application: a runtime between 96 and 100 would otherwise accept the
- // install and only fail the QueryInterface for ICoreWebView2Environment10 later. When the
- // folder does not name a version, that QueryInterface in createPrivateController is still the
- // fallback.
+ // was found in, so it describes the runtime that will load. An older runtime cannot make a
+ // page in an off-the-record profile or in a profile of its own, so it is refused here,
+ // synchronously, rather than after Open has handed a live page to the application: a runtime
+ // between 96 and 100 would otherwise accept the install and only fail the QueryInterface for
+ // ICoreWebView2Environment10 later. When the folder does not name a version, that
+ // QueryInterface in createOptionsController is still the fallback.
if parsed, valid := parseWebViewVersion(version); valid && !webViewVersionAtLeast(parsed, webViewEphemeralMinimum) {
- return nil, fmt.Errorf("%w: an ephemeral page needs WebView2 Runtime 101 (SDK 1.0.1210.39) or newer, and the runtime is %s", platform.ErrWebViewUnsupported, version)
+ return nil, fmt.Errorf("%w: a page in a storage partition or an ephemeral page needs WebView2 Runtime 101 (SDK 1.0.1210.39) or newer, and the runtime is %s", platform.ErrWebViewUnsupported, version)
}
}
webHostRegister.Do(func() {
@@ -213,6 +213,34 @@ func (w *webHost) open(config platform.WebViewConfig) (platform.WebView, error)
return page, nil
}
+// controllerProfile is the WebView2 profile a page is made in: the name the controller options carry,
+// whether that profile is off the record, and whether the options are needed at all. A page with
+// neither a partition nor Ephemeral asks for none, and is made through the plain
+// CreateCoreWebView2Controller in the default profile of the user data folder: the behaviour every
+// page had before there were partitions.
+func controllerProfile(config platform.WebViewConfig) (name string, inPrivate, options bool) {
+ switch {
+ case config.Partition != "" && config.Ephemeral:
+ // The name is the partition, so pages of one partition share the off-the-record profile and
+ // pages of another do not. WebView2 keeps an InPrivate profile's metadata under the user data
+ // folder, but its cookies, storage and caches stay in memory.
+ return config.Partition, true, true
+ case config.Partition != "":
+ // A profile name selects a profile of the user data folder: WebView2 keeps that profile's
+ // cookies, storage and caches in a folder of its own, apart from the default profile's.
+ return config.Partition, false, true
+ case config.Ephemeral:
+ // InPrivate belongs to the controller, not to the environment, and InPrivate alone would use
+ // the default profile name, from which WebView2 derives one off-the-record profile, so every
+ // ephemeral page would share one store. A name of its own per page keeps them apart, and the
+ // process id keeps two instances of the application apart as well: they share the user data
+ // folder, and with it one browser process, so a counter alone would name both first pages
+ // alike. Every name formed is far under the 64 characters WebView2 accepts.
+ return "viva-ephemeral-" + strconv.Itoa(os.Getpid()) + "-" + strconv.FormatUint(uint64(ephemeralProfiles.Add(1)), 10), true, true
+ }
+ return "", false, false
+}
+
// createController makes the page's controller in its window.
func (page *windowsWeb) createController(environment uintptr) {
handler := newHandler(func(status, controller uintptr) uintptr {
@@ -228,28 +256,26 @@ func (page *windowsWeb) createController(environment uintptr) {
page.attach(environment)
return 0
})
- if !page.config.Ephemeral {
+ name, inPrivate, options := controllerProfile(page.config)
+ if !options {
comCall(environment, envCreateController, page.window, handler)
return
}
- // InPrivate belongs to the controller, not to the environment: the environment is shared by
- // every page of the user data folder, and the controller is the page's own. InPrivate alone
- // would still use the default profile name, from which WebView2 derives one off-the-record
- // profile, so the options also name a profile per page. A runtime too old to offer the options
- // cannot make an ephemeral page, and must not fall back to a controller that keeps the page's
- // data on disk.
- if err := page.createPrivateController(environment, handler); err != nil {
+ // A runtime too old to offer the options cannot make a page in a profile of its own, and must not
+ // fall back to a controller that keeps the page's data in the default profile.
+ if err := page.createOptionsController(environment, handler, name, inPrivate); err != nil {
page.fail(err)
}
}
-// createPrivateController makes the page's controller for an InPrivate profile of its own, through
-// the options of ICoreWebView2Environment10 (WebView2 SDK 1.0.1210.39, Runtime 101 and newer).
-func (page *windowsWeb) createPrivateController(environment, handler uintptr) error {
+// createOptionsController makes the page's controller through the options of
+// ICoreWebView2Environment10 (WebView2 SDK 1.0.1210.39, Runtime 101 and newer), in the profile named,
+// off the record when inPrivate is set.
+func (page *windowsWeb) createOptionsController(environment, handler uintptr, name string, inPrivate bool) error {
var environment10 uintptr
status := comCall(environment, 0, uintptr(unsafe.Pointer(&iidEnvironment10)), uintptr(unsafe.Pointer(&environment10)))
if int32(uint32(status)) < 0 || environment10 == 0 {
- return fmt.Errorf("%w: an ephemeral page needs WebView2 Runtime 101 (SDK 1.0.1210.39) or newer", platform.ErrWebViewUnsupported)
+ return fmt.Errorf("%w: a page in a storage partition or an ephemeral page needs WebView2 Runtime 101 (SDK 1.0.1210.39) or newer", platform.ErrWebViewUnsupported)
}
defer comCall(environment10, 2)
var options uintptr
@@ -257,20 +283,17 @@ func (page *windowsWeb) createPrivateController(environment, handler uintptr) er
return fmt.Errorf("windows: make the WebView2 controller options: HRESULT %#x", uint32(status))
}
defer comCall(options, 2)
- // The profile's metadata lives in the application's user data folder, but its cookies, storage
- // and caches stay in memory and go with the page. The distinct name is what keeps two ephemeral
- // pages apart: with the default name WebView2 would derive both from the same regular profile.
- // The process id keeps two instances of the application apart as well: they share the user data
- // folder, and with it one browser process, so a counter alone would name both first pages alike.
- name := wide("viva-ephemeral-" + strconv.Itoa(os.Getpid()) + "-" + strconv.FormatUint(uint64(ephemeralProfiles.Add(1)), 10))
- if status := comCall(options, optionsPutProfileName, uintptr(unsafe.Pointer(name))); int32(uint32(status)) < 0 {
- return fmt.Errorf("windows: name the WebView2 InPrivate profile: HRESULT %#x", uint32(status))
- }
- if status := comCall(options, optionsPutInPrivateMode, 1); int32(uint32(status)) < 0 {
- return fmt.Errorf("windows: turn on WebView2 InPrivate mode: HRESULT %#x", uint32(status))
+ profile := wide(name)
+ if status := comCall(options, optionsPutProfileName, uintptr(unsafe.Pointer(profile))); int32(uint32(status)) < 0 {
+ return fmt.Errorf("windows: name the WebView2 profile %q: HRESULT %#x", name, uint32(status))
+ }
+ if inPrivate {
+ if status := comCall(options, optionsPutInPrivateMode, 1); int32(uint32(status)) < 0 {
+ return fmt.Errorf("windows: turn on WebView2 InPrivate mode: HRESULT %#x", uint32(status))
+ }
}
if status := comCall(environment10, envCreateControllerWithOptions, page.window, options, handler); int32(uint32(status)) < 0 {
- return fmt.Errorf("windows: create the InPrivate WebView2 controller: HRESULT %#x", uint32(status))
+ return fmt.Errorf("windows: create the WebView2 controller in profile %q: HRESULT %#x", name, uint32(status))
}
return nil
}
From a590e31fbe4a40911944c608c1b8bef6e77bb841 Mon Sep 17 00:00:00 2001
From: t8y2
Date: Sat, 21 Nov 2026 22:35:43 +0800
Subject: [PATCH 14/47] chore(components): regenerate the CodeEditor
decorations recipe
The doc sentence added to CodeEditorDecorations did not reach the
installable recipe that componentgen copies from it.
---
cmd/viva/templates/code_editor_decorations.go.txt | 6 +++++-
1 file changed, 5 insertions(+), 1 deletion(-)
diff --git a/cmd/viva/templates/code_editor_decorations.go.txt b/cmd/viva/templates/code_editor_decorations.go.txt
index 956b39d6e..0a3ee7385 100644
--- a/cmd/viva/templates/code_editor_decorations.go.txt
+++ b/cmd/viva/templates/code_editor_decorations.go.txt
@@ -31,7 +31,9 @@ type codeDecorationPaint struct {
}
// CodeEditorDecorations adds caller-owned gutter bars and byte indicators.
-// Buffers stay immutable for Paint; the editor does not retain them.
+// Buffers stay immutable for Paint; the editor does not retain them. Both are
+// validated in full on every paint, so a long change history costs time per
+// frame rather than per visible row: keep the buffers to what the editor shows.
type CodeEditorDecorations struct {
// GutterWidth reserves a leading lane in logical pixels, even without bars.
// Nonpositive or nonfinite widths omit the lane. Existing gutter lanes remain.
@@ -39,6 +41,8 @@ type CodeEditorDecorations struct {
// GutterBackground is independent of the current-line highlight.
GutterBackground gfx.Color
// GutterBars are sorted by logical line; same-line bars paint in caller order.
+ // An unsorted or out-of-range bar drops the whole set, as an invalid
+ // IndicatorLayer drops its layer.
GutterBars []CodeEditorGutterBar
// IndicatorLayers paint in caller order, above text and below carets.
IndicatorLayers []CodeEditorIndicatorLayer
From 0c6e2d253b9bff5ceda2b115540b4149a91e3b12 Mon Sep 17 00:00:00 2001
From: Lan-zk <68137514+Lan-zk@users.noreply.github.com>
Date: Sat, 21 Nov 2026 22:52:47 +0800
Subject: [PATCH 15/47] feat(components): add a force-directed link graph
---
cmd/viva/components_gen.go | 3 +
cmd/viva/templates/graph.go.txt | 530 +++++++++++++++++++++++
cmd/viva/templates/graph_sim.go.txt | 282 ++++++++++++
components/doc.go | 10 +
components/doc_test.go | 1 +
components/graph.go | 530 +++++++++++++++++++++++
components/graph_sim.go | 282 ++++++++++++
components/graph_sim_test.go | 132 ++++++
components/graph_test.go | 389 +++++++++++++++++
internal/componentdemo/catalog_a.go | 1 +
internal/componentdemo/catalog_a_test.go | 2 +-
internal/componentdemo/graph.go | 329 ++++++++++++++
internal/componentdemo/state.go | 3 +
tools/docs/catalog.go | 2 +-
14 files changed, 2494 insertions(+), 2 deletions(-)
create mode 100644 cmd/viva/templates/graph.go.txt
create mode 100644 cmd/viva/templates/graph_sim.go.txt
create mode 100644 components/graph.go
create mode 100644 components/graph_sim.go
create mode 100644 components/graph_sim_test.go
create mode 100644 components/graph_test.go
create mode 100644 internal/componentdemo/graph.go
diff --git a/cmd/viva/components_gen.go b/cmd/viva/components_gen.go
index dafe268ce..3663142e3 100644
--- a/cmd/viva/components_gen.go
+++ b/cmd/viva/components_gen.go
@@ -48,6 +48,8 @@ var componentFiles = map[string]string{
"find-bar": "find_bar.go.txt",
"form": "form.go.txt",
"go-to-line": "go_to_line.go.txt",
+ "graph": "graph.go.txt",
+ "graph-sim": "graph_sim.go.txt",
"hierarchy-menu": "hierarchy_menu.go.txt",
"hover-card": "hover_card.go.txt",
"icon-hover": "icon_hover.go.txt",
@@ -135,6 +137,7 @@ var componentRequires = map[string][]string{
"dropdown-menu": {"checkbox", "dialog", "hover-card", "kbd", "popover", "tree"},
"find-bar": {"button", "dialog", "input", "toggle", "tree"},
"go-to-line": {"button", "find-bar", "input"},
+ "graph": {"graph-sim"},
"hierarchy-menu": {"checkbox", "dialog", "dropdown-menu", "tree"},
"hover-card": {"dialog", "popover"},
"input": {"textarea"},
diff --git a/cmd/viva/templates/graph.go.txt b/cmd/viva/templates/graph.go.txt
new file mode 100644
index 000000000..84054dd2f
--- /dev/null
+++ b/cmd/viva/templates/graph.go.txt
@@ -0,0 +1,530 @@
+package {{PACKAGE}}
+
+import (
+ "math"
+ "time"
+
+ "github.com/vivaui/viva/gfx"
+)
+
+// The animation clock: one simulation tick is a fixed 1/120 of a second — the
+// anneal of ~300 ticks settles in about two and a half — and a paint whose
+// frames arrive late catches up through at most graphCatchUpTicks of them, so
+// a sparse canvas still converges while a dense one never spends a frame on
+// an unbounded burst of O(n²) ticks.
+const (
+ graphTickSpan = time.Second / 120
+ graphCatchUpTicks = 64
+)
+
+// GraphNode is one node's display data: what it is called, the color group it
+// belongs to, and whether the note it stands for exists. Where it lies and
+// how big it gets belong to the simulation, which sizes a node by its link
+// count.
+type GraphNode struct {
+ Label string
+ Group int
+ // Resolved is false for the target of a link whose note does not exist
+ // yet: painted small and dim, the way an unresolved link is.
+ Resolved bool
+}
+
+// GraphOptions configures one graph painting.
+type GraphOptions struct {
+ // Nodes is the identity list the graph declares its nodes in: hit and
+ // focus identities are Nodes.At(i), so a click reads as the item number.
+ // The zero scope paints a static preview with no interaction.
+ Nodes gfx.Scope
+ // SurfaceID names the graph's whole area, so an application can pan by
+ // dragging the background. The zero ID paints no surface hit.
+ SurfaceID gfx.ID
+ // NodeColor overrides the color of a group. Nil paints the theme's chart
+ // palette.
+ NodeColor func(theme gfx.Theme, group int) gfx.Color
+}
+
+// GraphState is the caller-owned state of one graph: the viewport and the
+// caches that keep a steady graph from allocating. Keep it as long as the
+// graph lives and pass the same one every paint. A nil state paints from the
+// simulation's current positions with the fitting viewport.
+type GraphState struct {
+ // Zoom scales graph units to pixels. Zero keeps the whole graph in view,
+ // following the layout while it settles and freezing the fit the moment
+ // the layout goes quiet or a node is grabbed — reheating the layout
+ // afterwards swings the graph's bounds around, and a view recomputed from
+ // them would drift under the pointer. The application writes a value when
+ // the user zoomes, and Pan then moves the view in window pixels. Writing
+ // zero back refits the view.
+ Zoom float32
+ Pan gfx.Point
+
+ // anchorX/anchorY is the graph-space point the view centers on: followed
+ // while zoom stays zero, frozen with the fit.
+ anchorX, anchorY float32
+
+ // clock/clockSet is the wall time of the last animated paint, and anneal
+ // the unspent part of it owed to the simulation, in tick units of time.
+ clock time.Duration
+ clockSet bool
+ anneal time.Duration
+
+ selected int
+ selectedSeen bool
+ // sim and nodeCount describe the caches below: a rebuilt simulation or a
+ // new node list makes hover and its neighbors name nodes that may no
+ // longer exist, so they start over.
+ sim *GraphSim
+ nodeCount int
+ hover int
+ neighbors []int
+ adjacent []bool
+ screen []gfx.Point
+ radii []float32
+ edgeBuilders [3]gfx.PathBuilder
+}
+
+// Select makes node i the selection, which paints a ring and keeps the
+// keyboard's tab stop.
+func (state *GraphState) Select(i int) {
+ state.selected, state.selectedSeen = i, true
+}
+
+// ClearSelection removes the selection.
+func (state *GraphState) ClearSelection() {
+ state.selectedSeen = false
+}
+
+// Selection is the selected node, and false while none is.
+func (state *GraphState) Selection() (int, bool) {
+ return state.selected, state.selectedSeen
+}
+
+// GraphLayout reports where a painted graph put its nodes, in window pixels,
+// and is the coordinate bridge an application's pointer and wheel handlers
+// use: FromScreen turns a pointer position into graph units for the
+// simulation, NodeAt finds the node a pointer is over, and ToScreen places a
+// label or a preview beside one.
+type GraphLayout struct {
+ Bounds gfx.Rect
+ Scale float32
+
+ points []gfx.Point
+ radii []float32
+ cx, cy float32
+ ox, oy float32
+ clicked int
+ wasClicked bool
+}
+
+// ToScreen places a graph-space point in window pixels.
+func (layout GraphLayout) ToScreen(x, y float32) (float32, float32) {
+ return layout.ox + (x-layout.cx)*layout.Scale, layout.oy + (y-layout.cy)*layout.Scale
+}
+
+// FromScreen is ToScreen's inverse: the graph-space point under a window
+// position.
+func (layout GraphLayout) FromScreen(x, y float32) (float32, float32) {
+ return (x-layout.ox)/layout.Scale + layout.cx, (y-layout.oy)/layout.Scale + layout.cy
+}
+
+// NodeAt is the node a window position is over, within its radius plus a
+// little slack, and false for empty space. It reads the positions of the last
+// paint, so a pointer handler calls it between repaints.
+func (layout GraphLayout) NodeAt(x, y float32) (int, bool) {
+ for index, point := range layout.points {
+ radius := layout.radii[index] + 4
+ if (x-point.X)*(x-point.X)+(y-point.Y)*(y-point.Y) <= radius*radius {
+ return index, true
+ }
+ }
+ return 0, false
+}
+
+// Clicked is the node whose click this paint is delivering; the application
+// opens the note here.
+func (layout GraphLayout) Clicked() (int, bool) {
+ return layout.clicked, layout.wasClicked
+}
+
+// PaintGraph paints a force-directed link graph: edges as straight lines in
+// one path per color, nodes as circles sized by their link count, labels for
+// the nodes the pointer explores, and a hit region per visible node. Hovering
+// a node highlights its edges and dims the rest. The simulation advances one
+// tick per painted frame until it cools below its minimum alpha, and then the
+// graph paints the same picture until something reheats it — the caller never
+// schedules frames for it. A reduced-motion session, or a canvas with no
+// frame clock, settles the layout in full at the first paint instead of
+// animating: about a tenth of a second at three hundred nodes, growing with
+// the square of the count, so an application showing thousands of notes wants
+// a clocked canvas.
+func PaintGraph(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, sim *GraphSim, nodes []GraphNode, state *GraphState, options GraphOptions) GraphLayout {
+ if bounds.Width <= 0 || bounds.Height <= 0 {
+ bounds = gfx.Rect{Width: 320, Height: 200}
+ }
+ if sim == nil {
+ sim = NewGraphSim(0, nil)
+ }
+ if len(nodes) < sim.Len() {
+ nodes = append(nodes, make([]GraphNode, sim.Len()-len(nodes))...)
+ }
+ if state == nil {
+ state = &GraphState{}
+ }
+ if state.sim != sim || state.nodeCount != len(nodes) {
+ // The graph was rebuilt or given another node list: what the caches
+ // name may be gone, so drop the hover, its neighbors and their marks.
+ state.sim, state.nodeCount = sim, len(nodes)
+ state.hover, state.neighbors, state.adjacent = -1, nil, nil
+ }
+ if !sim.Settled() {
+ if canvas != nil && canvas.HasClock() && !canvas.ReduceMotion() {
+ // The anneal runs on wall time at a fixed timestep — two ticks
+ // per animation frame's worth of elapsed time, catching up when
+ // frames are sparse — so the layout settles within about two and
+ // a half seconds however the canvas paints, and a settled graph
+ // asks for nothing. caret_blink runs its phase this same way.
+ now := canvas.Now()
+ elapsed := time.Duration(0)
+ if state.clockSet {
+ elapsed = max(now-state.clock, 0)
+ } else {
+ state.clockSet = true
+ }
+ state.clock = now
+ state.anneal += elapsed
+ for ticks := 0; ticks < graphCatchUpTicks && state.anneal >= graphTickSpan && sim.Tick(); ticks++ {
+ state.anneal -= graphTickSpan
+ }
+ if sim.Settled() {
+ // A quiet graph owes the clock nothing: a later reheat — a
+ // drag — starts its anneal from that moment, not from a gap
+ // of idle time that would burst out as catch-up ticks.
+ state.anneal, state.clockSet = 0, false
+ } else {
+ canvas.RequestFrame()
+ }
+ } else {
+ for ticks := 0; ticks < 1000 && sim.Tick(); ticks++ {
+ }
+ state.anneal, state.clockSet = 0, false
+ }
+ } else {
+ state.clockSet = false
+ }
+
+ // The viewport: a zero zoom keeps the whole graph in view, following the
+ // layout while it settles. The moment the layout goes quiet — or a node is
+ // grabbed — the followed fit freezes into Zoom and the anchor with it: a
+ // drag reheats the layout and swings its bounds, and a view still
+ // recomputed from those bounds would rescale and recenter under the
+ // pointer until the graph looked pinned. An explicit zoom never follows,
+ // and Pan moves the view.
+ minX, minY, maxX, maxY := sim.Bounds()
+ cx, cy := (minX+maxX)/2, (maxY+minY)/2
+ scale := state.Zoom
+ if scale <= 0 {
+ scale = 0.9 * min(bounds.Width/(maxX-minX), bounds.Height/(maxY-minY))
+ state.anchorX, state.anchorY = cx, cy
+ grabbed := false
+ if canvas != nil && !options.Nodes.IsZero() {
+ _, grabbed = canvas.Pressed().In(options.Nodes)
+ }
+ if sim.Settled() || grabbed {
+ state.Zoom = scale
+ }
+ }
+ ox := bounds.X + bounds.Width/2 + state.Pan.X
+ oy := bounds.Y + bounds.Height/2 + state.Pan.Y
+ uiScale := theme.Metrics.ControlHeight / 32
+
+ state.screen = growPoints(state.screen, sim.Len())
+ state.radii = growFloats(state.radii, sim.Len())
+ for index := 0; index < sim.Len(); index++ {
+ x, y := sim.Position(index)
+ radius := 2.2*float32(math.Sqrt(float64(sim.Degree(index))))*uiScale + 3*uiScale
+ if !nodes[index].Resolved {
+ radius = 2 * uiScale
+ }
+ radius = max(min(radius, 22*uiScale), 1.5*uiScale)
+ state.screen[index] = gfx.Point{X: ox + (x-state.anchorX)*scale, Y: oy + (y-state.anchorY)*scale}
+ state.radii[index] = radius
+ }
+
+ // Hover belongs to the pointer only while no press holds it: dragging a
+ // node through a crowd would otherwise light up every node it passes. A
+ // held node keeps its own edges lit (the drag shows what it is attached
+ // to), a held background — a pan — keeps the graph quiet, and an idle
+ // pointer or a press elsewhere leaves hover to the pointer.
+ hover := -1
+ if canvas != nil && !options.Nodes.IsZero() {
+ pressed := canvas.Pressed()
+ if node, dragging := pressed.In(options.Nodes); dragging {
+ hover = node
+ } else if pressed.IsZero() || pressed != options.SurfaceID {
+ if index, ok := canvas.Hovered().In(options.Nodes); ok {
+ hover = index
+ }
+ }
+ }
+ // A pointer index past the simulation would index the labels below.
+ if hover >= sim.Len() {
+ hover = -1
+ }
+ if state.hover >= sim.Len() {
+ state.hover, state.neighbors = -1, nil
+ }
+ // The neighbor marks of the previous hover clear before the new ones set,
+ // so a steady hover leaves the cache untouched.
+ if len(state.adjacent) < len(nodes) {
+ state.adjacent = make([]bool, len(nodes))
+ }
+ for _, neighbor := range state.neighbors {
+ if neighbor >= 0 && neighbor < len(state.adjacent) {
+ state.adjacent[neighbor] = false
+ }
+ }
+ if hover != state.hover {
+ state.hover = hover
+ state.neighbors = sim.Neighbors(hover)
+ }
+ for _, neighbor := range state.neighbors {
+ if neighbor >= 0 && neighbor < len(nodes) {
+ state.adjacent[neighbor] = true
+ }
+ }
+
+ layout := GraphLayout{
+ Bounds: bounds, Scale: scale,
+ points: state.screen[:sim.Len()], radii: state.radii[:sim.Len()],
+ cx: state.anchorX, cy: state.anchorY, ox: ox, oy: oy,
+ }
+ if canvas == nil {
+ return layout
+ }
+
+ canvas.Clip(bounds)
+ if !options.SurfaceID.IsZero() {
+ // The pan surface is not a control: it joins no focus order, so Tab
+ // never stops on an invisible button covering the graph.
+ canvas.HitWithOptions(options.SurfaceID, bounds, "Pan graph", gfx.HitOptions{SkipFocus: true})
+ }
+ if sim.Len() == 0 {
+ canvas.LabelCenter("No linked notes", bounds, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Color: theme.MutedForeground})
+ canvas.Unclip()
+ return layout
+ }
+ if !options.Nodes.IsZero() {
+ if index, ok := canvas.ClickedIn(options.Nodes); ok {
+ layout.clicked, layout.wasClicked = index, true
+ state.Select(index)
+ }
+ }
+ selected, selectedSeen := state.Selection()
+ // A state kept across a rebuilt, smaller simulation can hold a selection
+ // naming a node that no longer exists; drop it rather than let the label
+ // path index past the nodes.
+ if selectedSeen && (selected < 0 || selected >= sim.Len()) {
+ state.ClearSelection()
+ selected, selectedSeen = 0, false
+ }
+
+ // Edges, one path per color, drawn dimmed first and the hovered node's
+ // edges last so they sit on top. Coordinates are relative to the bounds,
+ // which DrawPath maps back onto themselves. ponytail: beyond a few
+ // thousand visible edges, batch them as instanced line geometry instead of
+ // per-frame tessellation.
+ ordinary := theme.Border
+ dimmed := theme.Border.Mix(theme.Background, 0.7)
+ for bucket := 2; bucket >= 0; bucket-- {
+ builder := &state.edgeBuilders[bucket]
+ builder.Reset()
+ for at := range sim.links {
+ link := &sim.links[at]
+ from, to := state.screen[link.Source], state.screen[link.Target]
+ if !segmentNear(bounds, from, to) {
+ continue
+ }
+ if hover >= 0 {
+ if link.Source != hover && link.Target != hover {
+ if bucket != 2 {
+ continue
+ }
+ } else if bucket != 0 {
+ continue
+ }
+ } else if bucket != 1 {
+ continue
+ }
+ builder.MoveTo(from.X-bounds.X, from.Y-bounds.Y)
+ builder.LineTo(to.X-bounds.X, to.Y-bounds.Y)
+ }
+ path := builder.Path(bounds.Width, bounds.Height)
+ if path.Size().Width == 0 {
+ continue
+ }
+ style := gfx.PathStyle{Stroke: ordinary, StrokeWidth: uiScale}
+ switch bucket {
+ case 0:
+ style.Stroke, style.StrokeWidth = graphNodeColor(theme, options, nodes, hover), 1.8*uiScale
+ case 2:
+ style.Stroke = dimmed
+ }
+ canvas.DrawPath(path, bounds, style)
+ }
+
+ // Nodes: filled circles in their group color; a ring on the hovered, the
+ // focused and the selected node, drawn before the hits below them.
+ for index := 0; index < sim.Len(); index++ {
+ point, radius := state.screen[index], state.radii[index]
+ if !pointNear(bounds, point, radius) {
+ continue
+ }
+ box := gfx.Rect{X: point.X - radius, Y: point.Y - radius, Width: radius * 2, Height: radius * 2}
+ color := graphNodeColor(theme, options, nodes, index)
+ if hover >= 0 && !state.adjacent[index] && index != hover {
+ color = color.Mix(theme.Background, 0.65)
+ }
+ if !nodes[index].Resolved {
+ color = theme.MutedForeground.Mix(theme.Background, 0.5)
+ }
+ canvas.Rounded(box, radius, color)
+ if index == hover || (selectedSeen && index == selected) || (!options.Nodes.IsZero() && canvas.FocusVisible() == options.Nodes.At(index)) {
+ ring := radius + 2*uiScale
+ ringBox := gfx.Rect{X: point.X - ring, Y: point.Y - ring, Width: ring * 2, Height: ring * 2}
+ canvas.RoundedBorder(ringBox, ring, max(1.5*uiScale, 1), theme.Ring, gfx.Color{})
+ }
+ }
+
+ // Labels: the hovered node, its neighbors and the selection carry words;
+ // a quiet graph shows none, which keeps a large one readable.
+ labelStyle := gfx.TextStyle{Size: theme.Metrics.FontSizeS, Color: theme.Foreground}
+ label := func(index int) {
+ point, radius := state.screen[index], state.radii[index]
+ width := canvas.TextWidth(nodes[index].Label, labelStyle.Size)
+ box := gfx.Rect{
+ X: point.X - width/2, Y: point.Y + radius + 2*uiScale,
+ Width: width + 4, Height: labelStyle.Size + 2,
+ }
+ if box.X < bounds.X {
+ box.X = bounds.X
+ }
+ if box.X+box.Width > bounds.X+bounds.Width {
+ box.X = bounds.X + bounds.Width - box.Width
+ }
+ if box.Y+box.Height > bounds.Y+bounds.Height {
+ box.Y = point.Y - radius - box.Height - 2*uiScale
+ }
+ canvas.LabelCenter(nodes[index].Label, box, labelStyle)
+ }
+ if hover >= 0 {
+ label(hover)
+ for _, neighbor := range state.neighbors {
+ if neighbor >= 0 && neighbor < sim.Len() {
+ label(neighbor)
+ }
+ }
+ }
+ if selectedSeen && selected != hover {
+ label(selected)
+ }
+
+ // Hits: every visible node is a focusable link, its hit region the circle
+ // itself — hit regions of one list never overlap, so a dense graph
+ // resolves by node radius and the pointer finds the node it covers. The
+ // selected node holds the tab stop and the rest stay out of Tab
+ // traversal, reachable by pointer and by the application's arrow-key
+ // handler (GraphStepForKey).
+ for index := 0; index < sim.Len(); index++ {
+ point, radius := state.screen[index], state.radii[index]
+ if !pointNear(bounds, point, radius) || options.Nodes.IsZero() {
+ continue
+ }
+ box := gfx.Rect{X: point.X - radius, Y: point.Y - radius, Width: radius * 2, Height: radius * 2}
+ tabStop := (selectedSeen && index == selected) || (!selectedSeen && index == 0)
+ canvas.HitWithOptions(options.Nodes.At(index), box, nodes[index].Label, gfx.HitOptions{
+ Role: gfx.RoleLink,
+ Cursor: gfx.PointerCursorHand,
+ Selected: selectedSeen && index == selected,
+ SkipTab: !tabStop,
+ })
+ }
+ canvas.Unclip()
+ return layout
+}
+
+// GraphStepForKey is a graph's keyboard movement: the arrow keys step from
+// the current node through its neighbors, wrapping at the ends, and Home and
+// End go to the first and last neighbor. neighbors is the node's own list
+// (GraphSim.Neighbors); with none, no key does anything.
+func GraphStepForKey(key gfx.Key, current int, neighbors []int) (int, bool) {
+ if len(neighbors) == 0 {
+ return current, false
+ }
+ step := func(delta int) (int, bool) {
+ for index, neighbor := range neighbors {
+ if neighbor == current {
+ next := (index + delta + len(neighbors)) % len(neighbors)
+ return neighbors[next], true
+ }
+ }
+ if delta > 0 {
+ return neighbors[0], true
+ }
+ return neighbors[len(neighbors)-1], true
+ }
+ switch key {
+ case gfx.KeyHome:
+ return neighbors[0], true
+ case gfx.KeyEnd:
+ return neighbors[len(neighbors)-1], true
+ case gfx.KeyRight, gfx.KeyDown:
+ return step(1)
+ case gfx.KeyLeft, gfx.KeyUp:
+ return step(-1)
+ }
+ return current, false
+}
+
+// graphNodeColor is the color of node index's group.
+func graphNodeColor(theme gfx.Theme, options GraphOptions, nodes []GraphNode, index int) gfx.Color {
+ if index < 0 || index >= len(nodes) {
+ return theme.Chart[0]
+ }
+ if options.NodeColor != nil {
+ return options.NodeColor(theme, nodes[index].Group)
+ }
+ // A negative Group keeps its sign under Go's remainder; fold it into the
+ // palette so caller-owned data cannot index out of range.
+ palette := len(theme.Chart)
+ group := nodes[index].Group % palette
+ if group < 0 {
+ group += palette
+ }
+ return theme.Chart[group]
+}
+
+// segmentNear reports whether an edge from one point to another can touch the
+// bounds: both endpoints culled is invisible.
+func segmentNear(bounds gfx.Rect, from, to gfx.Point) bool {
+ return pointNear(bounds, from, 0) || pointNear(bounds, to, 0)
+}
+
+// pointNear reports whether a circle of radius at a point reaches the bounds.
+func pointNear(bounds gfx.Rect, point gfx.Point, radius float32) bool {
+ return point.X+radius >= bounds.X && point.X-radius <= bounds.X+bounds.Width &&
+ point.Y+radius >= bounds.Y && point.Y-radius <= bounds.Y+bounds.Height
+}
+
+func growPoints(values []gfx.Point, size int) []gfx.Point {
+ if len(values) >= size {
+ return values[:size]
+ }
+ return append(values, make([]gfx.Point, size-len(values))...)
+}
+
+func growFloats(values []float32, size int) []float32 {
+ if len(values) >= size {
+ return values[:size]
+ }
+ return append(values, make([]float32, size-len(values))...)
+}
diff --git a/cmd/viva/templates/graph_sim.go.txt b/cmd/viva/templates/graph_sim.go.txt
new file mode 100644
index 000000000..5064d214e
--- /dev/null
+++ b/cmd/viva/templates/graph_sim.go.txt
@@ -0,0 +1,282 @@
+package {{PACKAGE}}
+
+import "math"
+
+// GraphLink is one edge of a GraphSim, by node index. Distance zero takes the
+// simulation's LinkDistance; Strength zero takes the spring default of one
+// over the smaller endpoint degree, so a busy hub pulls its neighbors less,
+// as d3-force's link force does.
+type GraphLink struct {
+ Source, Target int
+ Distance float32
+ Strength float32
+}
+
+// The d3-force tick constants: alpha falls from one to graphAlphaMin in about
+// three hundred ticks, friction damps velocity to sixty percent per tick, and
+// the layout goes quiet on its own.
+const (
+ graphAlphaMin float32 = 0.001
+ graphAlphaDecay float32 = 0.0228
+ graphVelocityDecay float32 = 0.4
+ // graphGoldenAngle is the angle of d3's phyllotaxis spiral, which spaces
+ // the initial positions deterministically and uniformly without a random
+ // number generator.
+ graphGoldenAngle float32 = 2.399963229728653
+ // graphSpiralStep scales the spiral's radius per node against the link
+ // distance, matching d3's 10.6·√i at its default distance of thirty.
+ graphSpiralStep float32 = 10.6 / 30
+)
+
+// graphBody is one node's simulation state. Fixed holds a dragged position:
+// each tick resets x to fx and zeroes the velocity, which is d3's fx/fy
+// pinning.
+type graphBody struct {
+ x, y float32
+ vx, vy float32
+ fx, fy float32
+ fixed bool
+}
+
+// GraphSim is the caller-owned force-directed layout of one graph. It is
+// d3-force's model — velocity-Verlet integration over composable forces with
+// an alpha that anneals to rest. The simulation is pure layout: it knows no
+// canvas, allocates nothing
+// per tick, and a fixed run of ticks from construction is bit-reproducible,
+// which makes golden tests possible.
+//
+// The application owns one beside its graph data and re-declares the graph
+// component with it every paint. While Settled reports false, one Tick per
+// painted frame advances the layout and it cools to zero work on its own;
+// dragging a node or changing data calls Reheat to warm it back up. The
+// topology is fixed at construction: build a new simulation when notes and
+// links change, seeding nothing — a fresh spiral start keeps runs comparable.
+type GraphSim struct {
+ // LinkDistance is each edge's rest length in graph units.
+ LinkDistance float32
+ // RepelStrength is the charge every node carries; negative values push
+ // nodes apart.
+ RepelStrength float32
+ // CenterStrength is how hard nodes are pulled toward the origin.
+ CenterStrength float32
+
+ bodies []graphBody
+ links []GraphLink
+ degree []int
+ alpha float32
+}
+
+// NewGraphSim lays out nodeCount nodes joined by links, starting them on
+// d3's phyllotaxis spiral. Links naming a node outside the graph, or a node
+// joined to itself, are dropped.
+func NewGraphSim(nodeCount int, links []GraphLink) *GraphSim {
+ sim := &GraphSim{
+ LinkDistance: 30,
+ RepelStrength: -30,
+ CenterStrength: 0.1,
+ bodies: make([]graphBody, nodeCount),
+ degree: make([]int, nodeCount),
+ alpha: 1,
+ }
+ for index := range sim.bodies {
+ step := float32(index + 1)
+ radius := graphSpiralStep * sim.LinkDistance * float32(math.Sqrt(float64(step)))
+ angle := step * graphGoldenAngle
+ sim.bodies[index].x = radius * float32(math.Cos(float64(angle)))
+ sim.bodies[index].y = radius * float32(math.Sin(float64(angle)))
+ }
+ sim.links = make([]GraphLink, 0, len(links))
+ for _, link := range links {
+ if link.Source < 0 || link.Source >= nodeCount || link.Target < 0 || link.Target >= nodeCount || link.Source == link.Target {
+ continue
+ }
+ if link.Distance <= 0 {
+ link.Distance = sim.LinkDistance
+ }
+ sim.degree[link.Source]++
+ sim.degree[link.Target]++
+ sim.links = append(sim.links, link)
+ }
+ // The default spring strength is one over the smaller endpoint's final
+ // link count, d3's rule, so a hub's many springs are each weak enough to
+ // leave it in place while its spokes travel.
+ for at := range sim.links {
+ link := &sim.links[at]
+ if link.Strength <= 0 {
+ link.Strength = 1 / float32(min(sim.degree[link.Source], sim.degree[link.Target]))
+ }
+ }
+ return sim
+}
+
+// Len is the number of nodes the simulation lays out.
+func (sim *GraphSim) Len() int {
+ if sim == nil {
+ return 0
+ }
+ return len(sim.bodies)
+}
+
+// Degree is how many links node i carries.
+func (sim *GraphSim) Degree(i int) int {
+ if sim == nil || i < 0 || i >= len(sim.degree) {
+ return 0
+ }
+ return sim.degree[i]
+}
+
+// Position is node i's graph-space position.
+func (sim *GraphSim) Position(i int) (x, y float32) {
+ if sim == nil || i < 0 || i >= len(sim.bodies) {
+ return 0, 0
+ }
+ return sim.bodies[i].x, sim.bodies[i].y
+}
+
+// SetFixed pins node i at a graph-space position, as a drag does; the layout
+// moves everything else around it. Unpin with SetFree.
+func (sim *GraphSim) SetFixed(i int, x, y float32) {
+ if sim == nil || i < 0 || i >= len(sim.bodies) {
+ return
+ }
+ sim.bodies[i].fx, sim.bodies[i].fy, sim.bodies[i].fixed = x, y, true
+}
+
+// SetFree releases a pinned node and lets the layout move it again.
+func (sim *GraphSim) SetFree(i int) {
+ if sim == nil || i < 0 || i >= len(sim.bodies) {
+ return
+ }
+ sim.bodies[i].fixed = false
+}
+
+// Reheat warms the layout to at least alpha so it moves again, as a drag or a
+// changed graph should. The value d3 uses while dragging is 0.3.
+func (sim *GraphSim) Reheat(alpha float32) {
+ if sim == nil {
+ return
+ }
+ sim.alpha = max(sim.alpha, max(alpha, 0))
+}
+
+// Settled reports whether the layout has cooled below its minimum alpha and
+// Tick would do nothing.
+func (sim *GraphSim) Settled() bool {
+ return sim == nil || sim.alpha < graphAlphaMin
+}
+
+// Tick advances the simulation one step, in d3-force's order: anneal alpha,
+// apply the link, repulsion and centering forces to the velocities, damp
+// them, integrate the positions, and pin fixed bodies. It reports whether
+// the layout is still moving, so a caller can stop asking for frames.
+func (sim *GraphSim) Tick() bool {
+ if sim == nil || sim.Settled() {
+ return false
+ }
+ sim.tickLinks()
+ sim.tickRepel()
+ sim.tickCenter()
+ for index := range sim.bodies {
+ body := &sim.bodies[index]
+ body.vx *= 1 - graphVelocityDecay
+ body.vy *= 1 - graphVelocityDecay
+ if body.fixed {
+ body.x, body.y, body.vx, body.vy = body.fx, body.fy, 0, 0
+ continue
+ }
+ body.x += body.vx
+ body.y += body.vy
+ }
+ sim.alpha += (0 - sim.alpha) * graphAlphaDecay
+ return !sim.Settled()
+}
+
+// tickLinks springs each edge toward its rest length. d3 splits the
+// correction between the endpoints by their link counts, so a node joined to
+// many others moves less than its sparse neighbor.
+func (sim *GraphSim) tickLinks() {
+ strength := sim.alpha
+ for at := range sim.links {
+ link := &sim.links[at]
+ source, target := &sim.bodies[link.Source], &sim.bodies[link.Target]
+ dx, dy := target.x-source.x, target.y-source.y
+ length := float32(math.Hypot(float64(dx), float64(dy)))
+ if length < 0.01 {
+ // Coincident endpoints have no direction to spring along; part
+ // them a hair deterministically, as d3 does with a jiggle.
+ dx, dy, length = 0.01, -0.01, 0.0142
+ }
+ bias := float32(sim.degree[link.Source]) / float32(sim.degree[link.Source]+sim.degree[link.Target])
+ correction := (length - link.Distance) / length * strength * link.Strength
+ source.vx += dx * correction * (1 - bias)
+ source.vy += dy * correction * (1 - bias)
+ target.vx -= dx * correction * bias
+ target.vy -= dy * correction * bias
+ }
+}
+
+// tickRepel pushes every pair of nodes apart with a Coulomb force: a negative
+// RepelStrength repels, so the coefficient here is its negation. It is O(n²),
+// which a backlink graph of a few thousand notes does not notice.
+// ponytail: past ~2000 nodes swap in a Barnes-Hut quadtree (theta 0.9), as
+// d3-force's manyBody does, and reuse it across a few ticks.
+func (sim *GraphSim) tickRepel() {
+ strength := -sim.alpha * sim.RepelStrength
+ for i := 0; i < len(sim.bodies); i++ {
+ for j := i + 1; j < len(sim.bodies); j++ {
+ a, b := &sim.bodies[i], &sim.bodies[j]
+ dx, dy := a.x-b.x, a.y-b.y
+ distance := max(float32(math.Hypot(float64(dx), float64(dy))), 1)
+ force := strength / (distance * distance * distance)
+ a.vx += dx * force
+ a.vy += dy * force
+ b.vx -= dx * force
+ b.vy -= dy * force
+ }
+ }
+}
+
+// tickCenter pulls every node toward the origin, keeping disconnected pieces
+// on the canvas the way a forceX/forceY(0) pair does.
+func (sim *GraphSim) tickCenter() {
+ strength := sim.alpha * sim.CenterStrength
+ for index := range sim.bodies {
+ body := &sim.bodies[index]
+ body.vx -= body.x * strength
+ body.vy -= body.y * strength
+ }
+}
+
+// Neighbors lists the nodes node i is joined to, in link order. It allocates,
+// so a caller keeps the answer while it has the keyboard.
+func (sim *GraphSim) Neighbors(i int) []int {
+ if sim == nil || i < 0 || i >= len(sim.bodies) {
+ return nil
+ }
+ neighbors := make([]int, 0, sim.degree[i])
+ for _, link := range sim.links {
+ switch {
+ case link.Source == i:
+ neighbors = append(neighbors, link.Target)
+ case link.Target == i:
+ neighbors = append(neighbors, link.Source)
+ }
+ }
+ return neighbors
+}
+
+// Bounds is the graph-space rectangle the nodes occupy: the viewport a
+// fit-to-view transform computes from. A graph of no nodes, or of nodes piled
+// on one point, reports a unit box so a fit scale stays finite.
+func (sim *GraphSim) Bounds() (minX, minY, maxX, maxY float32) {
+ if sim == nil || len(sim.bodies) == 0 {
+ return -0.5, -0.5, 0.5, 0.5
+ }
+ minX, minY, maxX, maxY = math.MaxFloat32, math.MaxFloat32, -math.MaxFloat32, -math.MaxFloat32
+ for _, body := range sim.bodies {
+ minX, minY = min(minX, body.x), min(minY, body.y)
+ maxX, maxY = max(maxX, body.x), max(maxY, body.y)
+ }
+ maxX, maxY = max(maxX, minX+1), max(maxY, minY+1)
+ return minX, minY, maxX, maxY
+}
diff --git a/components/doc.go b/components/doc.go
index 8003da205..407fa8107 100644
--- a/components/doc.go
+++ b/components/doc.go
@@ -322,6 +322,16 @@
// `ChartState` holds the hovered point and the label caches,
// `ChartStepForKey` maps the arrow keys, and `ChartDownsample` reduces a
// long series to the points a plot can show.
+// - Graph: `PaintGraph` paints a force-directed link graph (the link view
+// note applications show) from a `GraphSim` layout and `GraphNode` display data:
+// edges as batched paths, nodes as circles sized by link count, neighbor
+// highlighting and labels on hover, one hit region per node.
+// `GraphState` holds the caller-owned viewport (Zoom zero keeps the
+// whole graph in view) and selection, `GraphStepForKey` steps the
+// keyboard through a node's neighbors, and a `GraphLayout` maps between
+// window and graph coordinates for the application's pointer and wheel
+// handlers. The simulation advances one tick per painted frame until it
+// settles and then costs nothing.
// - Message: `Message` paints one chat row; `BeginMessageGroup` stacks the
// rows of consecutive messages; `BeginMessageScroller` paints the
// scrollback viewport with jump controls, and `MessageScrollState` holds
diff --git a/components/doc_test.go b/components/doc_test.go
index 92977d8f7..7d329427f 100644
--- a/components/doc_test.go
+++ b/components/doc_test.go
@@ -30,6 +30,7 @@ var docPrimaryEntries = map[string][]string{
"code_merge.go": {"CodeMerge"},
"direction.go": {"Direction"},
"empty.go": {"Empty"},
+ "graph_sim.go": {"GraphSim"},
"icon_hover.go": {"IconHover"},
"kbd.go": {"Kbd"},
"markdown.go": {"MarkdownView"},
diff --git a/components/graph.go b/components/graph.go
new file mode 100644
index 000000000..e62375f23
--- /dev/null
+++ b/components/graph.go
@@ -0,0 +1,530 @@
+package components
+
+import (
+ "math"
+ "time"
+
+ "github.com/vivaui/viva/gfx"
+)
+
+// The animation clock: one simulation tick is a fixed 1/120 of a second — the
+// anneal of ~300 ticks settles in about two and a half — and a paint whose
+// frames arrive late catches up through at most graphCatchUpTicks of them, so
+// a sparse canvas still converges while a dense one never spends a frame on
+// an unbounded burst of O(n²) ticks.
+const (
+ graphTickSpan = time.Second / 120
+ graphCatchUpTicks = 64
+)
+
+// GraphNode is one node's display data: what it is called, the color group it
+// belongs to, and whether the note it stands for exists. Where it lies and
+// how big it gets belong to the simulation, which sizes a node by its link
+// count.
+type GraphNode struct {
+ Label string
+ Group int
+ // Resolved is false for the target of a link whose note does not exist
+ // yet: painted small and dim, the way an unresolved link is.
+ Resolved bool
+}
+
+// GraphOptions configures one graph painting.
+type GraphOptions struct {
+ // Nodes is the identity list the graph declares its nodes in: hit and
+ // focus identities are Nodes.At(i), so a click reads as the item number.
+ // The zero scope paints a static preview with no interaction.
+ Nodes gfx.Scope
+ // SurfaceID names the graph's whole area, so an application can pan by
+ // dragging the background. The zero ID paints no surface hit.
+ SurfaceID gfx.ID
+ // NodeColor overrides the color of a group. Nil paints the theme's chart
+ // palette.
+ NodeColor func(theme gfx.Theme, group int) gfx.Color
+}
+
+// GraphState is the caller-owned state of one graph: the viewport and the
+// caches that keep a steady graph from allocating. Keep it as long as the
+// graph lives and pass the same one every paint. A nil state paints from the
+// simulation's current positions with the fitting viewport.
+type GraphState struct {
+ // Zoom scales graph units to pixels. Zero keeps the whole graph in view,
+ // following the layout while it settles and freezing the fit the moment
+ // the layout goes quiet or a node is grabbed — reheating the layout
+ // afterwards swings the graph's bounds around, and a view recomputed from
+ // them would drift under the pointer. The application writes a value when
+ // the user zoomes, and Pan then moves the view in window pixels. Writing
+ // zero back refits the view.
+ Zoom float32
+ Pan gfx.Point
+
+ // anchorX/anchorY is the graph-space point the view centers on: followed
+ // while zoom stays zero, frozen with the fit.
+ anchorX, anchorY float32
+
+ // clock/clockSet is the wall time of the last animated paint, and anneal
+ // the unspent part of it owed to the simulation, in tick units of time.
+ clock time.Duration
+ clockSet bool
+ anneal time.Duration
+
+ selected int
+ selectedSeen bool
+ // sim and nodeCount describe the caches below: a rebuilt simulation or a
+ // new node list makes hover and its neighbors name nodes that may no
+ // longer exist, so they start over.
+ sim *GraphSim
+ nodeCount int
+ hover int
+ neighbors []int
+ adjacent []bool
+ screen []gfx.Point
+ radii []float32
+ edgeBuilders [3]gfx.PathBuilder
+}
+
+// Select makes node i the selection, which paints a ring and keeps the
+// keyboard's tab stop.
+func (state *GraphState) Select(i int) {
+ state.selected, state.selectedSeen = i, true
+}
+
+// ClearSelection removes the selection.
+func (state *GraphState) ClearSelection() {
+ state.selectedSeen = false
+}
+
+// Selection is the selected node, and false while none is.
+func (state *GraphState) Selection() (int, bool) {
+ return state.selected, state.selectedSeen
+}
+
+// GraphLayout reports where a painted graph put its nodes, in window pixels,
+// and is the coordinate bridge an application's pointer and wheel handlers
+// use: FromScreen turns a pointer position into graph units for the
+// simulation, NodeAt finds the node a pointer is over, and ToScreen places a
+// label or a preview beside one.
+type GraphLayout struct {
+ Bounds gfx.Rect
+ Scale float32
+
+ points []gfx.Point
+ radii []float32
+ cx, cy float32
+ ox, oy float32
+ clicked int
+ wasClicked bool
+}
+
+// ToScreen places a graph-space point in window pixels.
+func (layout GraphLayout) ToScreen(x, y float32) (float32, float32) {
+ return layout.ox + (x-layout.cx)*layout.Scale, layout.oy + (y-layout.cy)*layout.Scale
+}
+
+// FromScreen is ToScreen's inverse: the graph-space point under a window
+// position.
+func (layout GraphLayout) FromScreen(x, y float32) (float32, float32) {
+ return (x-layout.ox)/layout.Scale + layout.cx, (y-layout.oy)/layout.Scale + layout.cy
+}
+
+// NodeAt is the node a window position is over, within its radius plus a
+// little slack, and false for empty space. It reads the positions of the last
+// paint, so a pointer handler calls it between repaints.
+func (layout GraphLayout) NodeAt(x, y float32) (int, bool) {
+ for index, point := range layout.points {
+ radius := layout.radii[index] + 4
+ if (x-point.X)*(x-point.X)+(y-point.Y)*(y-point.Y) <= radius*radius {
+ return index, true
+ }
+ }
+ return 0, false
+}
+
+// Clicked is the node whose click this paint is delivering; the application
+// opens the note here.
+func (layout GraphLayout) Clicked() (int, bool) {
+ return layout.clicked, layout.wasClicked
+}
+
+// PaintGraph paints a force-directed link graph: edges as straight lines in
+// one path per color, nodes as circles sized by their link count, labels for
+// the nodes the pointer explores, and a hit region per visible node. Hovering
+// a node highlights its edges and dims the rest. The simulation advances one
+// tick per painted frame until it cools below its minimum alpha, and then the
+// graph paints the same picture until something reheats it — the caller never
+// schedules frames for it. A reduced-motion session, or a canvas with no
+// frame clock, settles the layout in full at the first paint instead of
+// animating: about a tenth of a second at three hundred nodes, growing with
+// the square of the count, so an application showing thousands of notes wants
+// a clocked canvas.
+func PaintGraph(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, sim *GraphSim, nodes []GraphNode, state *GraphState, options GraphOptions) GraphLayout {
+ if bounds.Width <= 0 || bounds.Height <= 0 {
+ bounds = gfx.Rect{Width: 320, Height: 200}
+ }
+ if sim == nil {
+ sim = NewGraphSim(0, nil)
+ }
+ if len(nodes) < sim.Len() {
+ nodes = append(nodes, make([]GraphNode, sim.Len()-len(nodes))...)
+ }
+ if state == nil {
+ state = &GraphState{}
+ }
+ if state.sim != sim || state.nodeCount != len(nodes) {
+ // The graph was rebuilt or given another node list: what the caches
+ // name may be gone, so drop the hover, its neighbors and their marks.
+ state.sim, state.nodeCount = sim, len(nodes)
+ state.hover, state.neighbors, state.adjacent = -1, nil, nil
+ }
+ if !sim.Settled() {
+ if canvas != nil && canvas.HasClock() && !canvas.ReduceMotion() {
+ // The anneal runs on wall time at a fixed timestep — two ticks
+ // per animation frame's worth of elapsed time, catching up when
+ // frames are sparse — so the layout settles within about two and
+ // a half seconds however the canvas paints, and a settled graph
+ // asks for nothing. caret_blink runs its phase this same way.
+ now := canvas.Now()
+ elapsed := time.Duration(0)
+ if state.clockSet {
+ elapsed = max(now-state.clock, 0)
+ } else {
+ state.clockSet = true
+ }
+ state.clock = now
+ state.anneal += elapsed
+ for ticks := 0; ticks < graphCatchUpTicks && state.anneal >= graphTickSpan && sim.Tick(); ticks++ {
+ state.anneal -= graphTickSpan
+ }
+ if sim.Settled() {
+ // A quiet graph owes the clock nothing: a later reheat — a
+ // drag — starts its anneal from that moment, not from a gap
+ // of idle time that would burst out as catch-up ticks.
+ state.anneal, state.clockSet = 0, false
+ } else {
+ canvas.RequestFrame()
+ }
+ } else {
+ for ticks := 0; ticks < 1000 && sim.Tick(); ticks++ {
+ }
+ state.anneal, state.clockSet = 0, false
+ }
+ } else {
+ state.clockSet = false
+ }
+
+ // The viewport: a zero zoom keeps the whole graph in view, following the
+ // layout while it settles. The moment the layout goes quiet — or a node is
+ // grabbed — the followed fit freezes into Zoom and the anchor with it: a
+ // drag reheats the layout and swings its bounds, and a view still
+ // recomputed from those bounds would rescale and recenter under the
+ // pointer until the graph looked pinned. An explicit zoom never follows,
+ // and Pan moves the view.
+ minX, minY, maxX, maxY := sim.Bounds()
+ cx, cy := (minX+maxX)/2, (maxY+minY)/2
+ scale := state.Zoom
+ if scale <= 0 {
+ scale = 0.9 * min(bounds.Width/(maxX-minX), bounds.Height/(maxY-minY))
+ state.anchorX, state.anchorY = cx, cy
+ grabbed := false
+ if canvas != nil && !options.Nodes.IsZero() {
+ _, grabbed = canvas.Pressed().In(options.Nodes)
+ }
+ if sim.Settled() || grabbed {
+ state.Zoom = scale
+ }
+ }
+ ox := bounds.X + bounds.Width/2 + state.Pan.X
+ oy := bounds.Y + bounds.Height/2 + state.Pan.Y
+ uiScale := theme.Metrics.ControlHeight / 32
+
+ state.screen = growPoints(state.screen, sim.Len())
+ state.radii = growFloats(state.radii, sim.Len())
+ for index := 0; index < sim.Len(); index++ {
+ x, y := sim.Position(index)
+ radius := 2.2*float32(math.Sqrt(float64(sim.Degree(index))))*uiScale + 3*uiScale
+ if !nodes[index].Resolved {
+ radius = 2 * uiScale
+ }
+ radius = max(min(radius, 22*uiScale), 1.5*uiScale)
+ state.screen[index] = gfx.Point{X: ox + (x-state.anchorX)*scale, Y: oy + (y-state.anchorY)*scale}
+ state.radii[index] = radius
+ }
+
+ // Hover belongs to the pointer only while no press holds it: dragging a
+ // node through a crowd would otherwise light up every node it passes. A
+ // held node keeps its own edges lit (the drag shows what it is attached
+ // to), a held background — a pan — keeps the graph quiet, and an idle
+ // pointer or a press elsewhere leaves hover to the pointer.
+ hover := -1
+ if canvas != nil && !options.Nodes.IsZero() {
+ pressed := canvas.Pressed()
+ if node, dragging := pressed.In(options.Nodes); dragging {
+ hover = node
+ } else if pressed.IsZero() || pressed != options.SurfaceID {
+ if index, ok := canvas.Hovered().In(options.Nodes); ok {
+ hover = index
+ }
+ }
+ }
+ // A pointer index past the simulation would index the labels below.
+ if hover >= sim.Len() {
+ hover = -1
+ }
+ if state.hover >= sim.Len() {
+ state.hover, state.neighbors = -1, nil
+ }
+ // The neighbor marks of the previous hover clear before the new ones set,
+ // so a steady hover leaves the cache untouched.
+ if len(state.adjacent) < len(nodes) {
+ state.adjacent = make([]bool, len(nodes))
+ }
+ for _, neighbor := range state.neighbors {
+ if neighbor >= 0 && neighbor < len(state.adjacent) {
+ state.adjacent[neighbor] = false
+ }
+ }
+ if hover != state.hover {
+ state.hover = hover
+ state.neighbors = sim.Neighbors(hover)
+ }
+ for _, neighbor := range state.neighbors {
+ if neighbor >= 0 && neighbor < len(nodes) {
+ state.adjacent[neighbor] = true
+ }
+ }
+
+ layout := GraphLayout{
+ Bounds: bounds, Scale: scale,
+ points: state.screen[:sim.Len()], radii: state.radii[:sim.Len()],
+ cx: state.anchorX, cy: state.anchorY, ox: ox, oy: oy,
+ }
+ if canvas == nil {
+ return layout
+ }
+
+ canvas.Clip(bounds)
+ if !options.SurfaceID.IsZero() {
+ // The pan surface is not a control: it joins no focus order, so Tab
+ // never stops on an invisible button covering the graph.
+ canvas.HitWithOptions(options.SurfaceID, bounds, "Pan graph", gfx.HitOptions{SkipFocus: true})
+ }
+ if sim.Len() == 0 {
+ canvas.LabelCenter("No linked notes", bounds, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Color: theme.MutedForeground})
+ canvas.Unclip()
+ return layout
+ }
+ if !options.Nodes.IsZero() {
+ if index, ok := canvas.ClickedIn(options.Nodes); ok {
+ layout.clicked, layout.wasClicked = index, true
+ state.Select(index)
+ }
+ }
+ selected, selectedSeen := state.Selection()
+ // A state kept across a rebuilt, smaller simulation can hold a selection
+ // naming a node that no longer exists; drop it rather than let the label
+ // path index past the nodes.
+ if selectedSeen && (selected < 0 || selected >= sim.Len()) {
+ state.ClearSelection()
+ selected, selectedSeen = 0, false
+ }
+
+ // Edges, one path per color, drawn dimmed first and the hovered node's
+ // edges last so they sit on top. Coordinates are relative to the bounds,
+ // which DrawPath maps back onto themselves. ponytail: beyond a few
+ // thousand visible edges, batch them as instanced line geometry instead of
+ // per-frame tessellation.
+ ordinary := theme.Border
+ dimmed := theme.Border.Mix(theme.Background, 0.7)
+ for bucket := 2; bucket >= 0; bucket-- {
+ builder := &state.edgeBuilders[bucket]
+ builder.Reset()
+ for at := range sim.links {
+ link := &sim.links[at]
+ from, to := state.screen[link.Source], state.screen[link.Target]
+ if !segmentNear(bounds, from, to) {
+ continue
+ }
+ if hover >= 0 {
+ if link.Source != hover && link.Target != hover {
+ if bucket != 2 {
+ continue
+ }
+ } else if bucket != 0 {
+ continue
+ }
+ } else if bucket != 1 {
+ continue
+ }
+ builder.MoveTo(from.X-bounds.X, from.Y-bounds.Y)
+ builder.LineTo(to.X-bounds.X, to.Y-bounds.Y)
+ }
+ path := builder.Path(bounds.Width, bounds.Height)
+ if path.Size().Width == 0 {
+ continue
+ }
+ style := gfx.PathStyle{Stroke: ordinary, StrokeWidth: uiScale}
+ switch bucket {
+ case 0:
+ style.Stroke, style.StrokeWidth = graphNodeColor(theme, options, nodes, hover), 1.8*uiScale
+ case 2:
+ style.Stroke = dimmed
+ }
+ canvas.DrawPath(path, bounds, style)
+ }
+
+ // Nodes: filled circles in their group color; a ring on the hovered, the
+ // focused and the selected node, drawn before the hits below them.
+ for index := 0; index < sim.Len(); index++ {
+ point, radius := state.screen[index], state.radii[index]
+ if !pointNear(bounds, point, radius) {
+ continue
+ }
+ box := gfx.Rect{X: point.X - radius, Y: point.Y - radius, Width: radius * 2, Height: radius * 2}
+ color := graphNodeColor(theme, options, nodes, index)
+ if hover >= 0 && !state.adjacent[index] && index != hover {
+ color = color.Mix(theme.Background, 0.65)
+ }
+ if !nodes[index].Resolved {
+ color = theme.MutedForeground.Mix(theme.Background, 0.5)
+ }
+ canvas.Rounded(box, radius, color)
+ if index == hover || (selectedSeen && index == selected) || (!options.Nodes.IsZero() && canvas.FocusVisible() == options.Nodes.At(index)) {
+ ring := radius + 2*uiScale
+ ringBox := gfx.Rect{X: point.X - ring, Y: point.Y - ring, Width: ring * 2, Height: ring * 2}
+ canvas.RoundedBorder(ringBox, ring, max(1.5*uiScale, 1), theme.Ring, gfx.Color{})
+ }
+ }
+
+ // Labels: the hovered node, its neighbors and the selection carry words;
+ // a quiet graph shows none, which keeps a large one readable.
+ labelStyle := gfx.TextStyle{Size: theme.Metrics.FontSizeS, Color: theme.Foreground}
+ label := func(index int) {
+ point, radius := state.screen[index], state.radii[index]
+ width := canvas.TextWidth(nodes[index].Label, labelStyle.Size)
+ box := gfx.Rect{
+ X: point.X - width/2, Y: point.Y + radius + 2*uiScale,
+ Width: width + 4, Height: labelStyle.Size + 2,
+ }
+ if box.X < bounds.X {
+ box.X = bounds.X
+ }
+ if box.X+box.Width > bounds.X+bounds.Width {
+ box.X = bounds.X + bounds.Width - box.Width
+ }
+ if box.Y+box.Height > bounds.Y+bounds.Height {
+ box.Y = point.Y - radius - box.Height - 2*uiScale
+ }
+ canvas.LabelCenter(nodes[index].Label, box, labelStyle)
+ }
+ if hover >= 0 {
+ label(hover)
+ for _, neighbor := range state.neighbors {
+ if neighbor >= 0 && neighbor < sim.Len() {
+ label(neighbor)
+ }
+ }
+ }
+ if selectedSeen && selected != hover {
+ label(selected)
+ }
+
+ // Hits: every visible node is a focusable link, its hit region the circle
+ // itself — hit regions of one list never overlap, so a dense graph
+ // resolves by node radius and the pointer finds the node it covers. The
+ // selected node holds the tab stop and the rest stay out of Tab
+ // traversal, reachable by pointer and by the application's arrow-key
+ // handler (GraphStepForKey).
+ for index := 0; index < sim.Len(); index++ {
+ point, radius := state.screen[index], state.radii[index]
+ if !pointNear(bounds, point, radius) || options.Nodes.IsZero() {
+ continue
+ }
+ box := gfx.Rect{X: point.X - radius, Y: point.Y - radius, Width: radius * 2, Height: radius * 2}
+ tabStop := (selectedSeen && index == selected) || (!selectedSeen && index == 0)
+ canvas.HitWithOptions(options.Nodes.At(index), box, nodes[index].Label, gfx.HitOptions{
+ Role: gfx.RoleLink,
+ Cursor: gfx.PointerCursorHand,
+ Selected: selectedSeen && index == selected,
+ SkipTab: !tabStop,
+ })
+ }
+ canvas.Unclip()
+ return layout
+}
+
+// GraphStepForKey is a graph's keyboard movement: the arrow keys step from
+// the current node through its neighbors, wrapping at the ends, and Home and
+// End go to the first and last neighbor. neighbors is the node's own list
+// (GraphSim.Neighbors); with none, no key does anything.
+func GraphStepForKey(key gfx.Key, current int, neighbors []int) (int, bool) {
+ if len(neighbors) == 0 {
+ return current, false
+ }
+ step := func(delta int) (int, bool) {
+ for index, neighbor := range neighbors {
+ if neighbor == current {
+ next := (index + delta + len(neighbors)) % len(neighbors)
+ return neighbors[next], true
+ }
+ }
+ if delta > 0 {
+ return neighbors[0], true
+ }
+ return neighbors[len(neighbors)-1], true
+ }
+ switch key {
+ case gfx.KeyHome:
+ return neighbors[0], true
+ case gfx.KeyEnd:
+ return neighbors[len(neighbors)-1], true
+ case gfx.KeyRight, gfx.KeyDown:
+ return step(1)
+ case gfx.KeyLeft, gfx.KeyUp:
+ return step(-1)
+ }
+ return current, false
+}
+
+// graphNodeColor is the color of node index's group.
+func graphNodeColor(theme gfx.Theme, options GraphOptions, nodes []GraphNode, index int) gfx.Color {
+ if index < 0 || index >= len(nodes) {
+ return theme.Chart[0]
+ }
+ if options.NodeColor != nil {
+ return options.NodeColor(theme, nodes[index].Group)
+ }
+ // A negative Group keeps its sign under Go's remainder; fold it into the
+ // palette so caller-owned data cannot index out of range.
+ palette := len(theme.Chart)
+ group := nodes[index].Group % palette
+ if group < 0 {
+ group += palette
+ }
+ return theme.Chart[group]
+}
+
+// segmentNear reports whether an edge from one point to another can touch the
+// bounds: both endpoints culled is invisible.
+func segmentNear(bounds gfx.Rect, from, to gfx.Point) bool {
+ return pointNear(bounds, from, 0) || pointNear(bounds, to, 0)
+}
+
+// pointNear reports whether a circle of radius at a point reaches the bounds.
+func pointNear(bounds gfx.Rect, point gfx.Point, radius float32) bool {
+ return point.X+radius >= bounds.X && point.X-radius <= bounds.X+bounds.Width &&
+ point.Y+radius >= bounds.Y && point.Y-radius <= bounds.Y+bounds.Height
+}
+
+func growPoints(values []gfx.Point, size int) []gfx.Point {
+ if len(values) >= size {
+ return values[:size]
+ }
+ return append(values, make([]gfx.Point, size-len(values))...)
+}
+
+func growFloats(values []float32, size int) []float32 {
+ if len(values) >= size {
+ return values[:size]
+ }
+ return append(values, make([]float32, size-len(values))...)
+}
diff --git a/components/graph_sim.go b/components/graph_sim.go
new file mode 100644
index 000000000..6a209631a
--- /dev/null
+++ b/components/graph_sim.go
@@ -0,0 +1,282 @@
+package components
+
+import "math"
+
+// GraphLink is one edge of a GraphSim, by node index. Distance zero takes the
+// simulation's LinkDistance; Strength zero takes the spring default of one
+// over the smaller endpoint degree, so a busy hub pulls its neighbors less,
+// as d3-force's link force does.
+type GraphLink struct {
+ Source, Target int
+ Distance float32
+ Strength float32
+}
+
+// The d3-force tick constants: alpha falls from one to graphAlphaMin in about
+// three hundred ticks, friction damps velocity to sixty percent per tick, and
+// the layout goes quiet on its own.
+const (
+ graphAlphaMin float32 = 0.001
+ graphAlphaDecay float32 = 0.0228
+ graphVelocityDecay float32 = 0.4
+ // graphGoldenAngle is the angle of d3's phyllotaxis spiral, which spaces
+ // the initial positions deterministically and uniformly without a random
+ // number generator.
+ graphGoldenAngle float32 = 2.399963229728653
+ // graphSpiralStep scales the spiral's radius per node against the link
+ // distance, matching d3's 10.6·√i at its default distance of thirty.
+ graphSpiralStep float32 = 10.6 / 30
+)
+
+// graphBody is one node's simulation state. Fixed holds a dragged position:
+// each tick resets x to fx and zeroes the velocity, which is d3's fx/fy
+// pinning.
+type graphBody struct {
+ x, y float32
+ vx, vy float32
+ fx, fy float32
+ fixed bool
+}
+
+// GraphSim is the caller-owned force-directed layout of one graph. It is
+// d3-force's model — velocity-Verlet integration over composable forces with
+// an alpha that anneals to rest. The simulation is pure layout: it knows no
+// canvas, allocates nothing
+// per tick, and a fixed run of ticks from construction is bit-reproducible,
+// which makes golden tests possible.
+//
+// The application owns one beside its graph data and re-declares the graph
+// component with it every paint. While Settled reports false, one Tick per
+// painted frame advances the layout and it cools to zero work on its own;
+// dragging a node or changing data calls Reheat to warm it back up. The
+// topology is fixed at construction: build a new simulation when notes and
+// links change, seeding nothing — a fresh spiral start keeps runs comparable.
+type GraphSim struct {
+ // LinkDistance is each edge's rest length in graph units.
+ LinkDistance float32
+ // RepelStrength is the charge every node carries; negative values push
+ // nodes apart.
+ RepelStrength float32
+ // CenterStrength is how hard nodes are pulled toward the origin.
+ CenterStrength float32
+
+ bodies []graphBody
+ links []GraphLink
+ degree []int
+ alpha float32
+}
+
+// NewGraphSim lays out nodeCount nodes joined by links, starting them on
+// d3's phyllotaxis spiral. Links naming a node outside the graph, or a node
+// joined to itself, are dropped.
+func NewGraphSim(nodeCount int, links []GraphLink) *GraphSim {
+ sim := &GraphSim{
+ LinkDistance: 30,
+ RepelStrength: -30,
+ CenterStrength: 0.1,
+ bodies: make([]graphBody, nodeCount),
+ degree: make([]int, nodeCount),
+ alpha: 1,
+ }
+ for index := range sim.bodies {
+ step := float32(index + 1)
+ radius := graphSpiralStep * sim.LinkDistance * float32(math.Sqrt(float64(step)))
+ angle := step * graphGoldenAngle
+ sim.bodies[index].x = radius * float32(math.Cos(float64(angle)))
+ sim.bodies[index].y = radius * float32(math.Sin(float64(angle)))
+ }
+ sim.links = make([]GraphLink, 0, len(links))
+ for _, link := range links {
+ if link.Source < 0 || link.Source >= nodeCount || link.Target < 0 || link.Target >= nodeCount || link.Source == link.Target {
+ continue
+ }
+ if link.Distance <= 0 {
+ link.Distance = sim.LinkDistance
+ }
+ sim.degree[link.Source]++
+ sim.degree[link.Target]++
+ sim.links = append(sim.links, link)
+ }
+ // The default spring strength is one over the smaller endpoint's final
+ // link count, d3's rule, so a hub's many springs are each weak enough to
+ // leave it in place while its spokes travel.
+ for at := range sim.links {
+ link := &sim.links[at]
+ if link.Strength <= 0 {
+ link.Strength = 1 / float32(min(sim.degree[link.Source], sim.degree[link.Target]))
+ }
+ }
+ return sim
+}
+
+// Len is the number of nodes the simulation lays out.
+func (sim *GraphSim) Len() int {
+ if sim == nil {
+ return 0
+ }
+ return len(sim.bodies)
+}
+
+// Degree is how many links node i carries.
+func (sim *GraphSim) Degree(i int) int {
+ if sim == nil || i < 0 || i >= len(sim.degree) {
+ return 0
+ }
+ return sim.degree[i]
+}
+
+// Position is node i's graph-space position.
+func (sim *GraphSim) Position(i int) (x, y float32) {
+ if sim == nil || i < 0 || i >= len(sim.bodies) {
+ return 0, 0
+ }
+ return sim.bodies[i].x, sim.bodies[i].y
+}
+
+// SetFixed pins node i at a graph-space position, as a drag does; the layout
+// moves everything else around it. Unpin with SetFree.
+func (sim *GraphSim) SetFixed(i int, x, y float32) {
+ if sim == nil || i < 0 || i >= len(sim.bodies) {
+ return
+ }
+ sim.bodies[i].fx, sim.bodies[i].fy, sim.bodies[i].fixed = x, y, true
+}
+
+// SetFree releases a pinned node and lets the layout move it again.
+func (sim *GraphSim) SetFree(i int) {
+ if sim == nil || i < 0 || i >= len(sim.bodies) {
+ return
+ }
+ sim.bodies[i].fixed = false
+}
+
+// Reheat warms the layout to at least alpha so it moves again, as a drag or a
+// changed graph should. The value d3 uses while dragging is 0.3.
+func (sim *GraphSim) Reheat(alpha float32) {
+ if sim == nil {
+ return
+ }
+ sim.alpha = max(sim.alpha, max(alpha, 0))
+}
+
+// Settled reports whether the layout has cooled below its minimum alpha and
+// Tick would do nothing.
+func (sim *GraphSim) Settled() bool {
+ return sim == nil || sim.alpha < graphAlphaMin
+}
+
+// Tick advances the simulation one step, in d3-force's order: anneal alpha,
+// apply the link, repulsion and centering forces to the velocities, damp
+// them, integrate the positions, and pin fixed bodies. It reports whether
+// the layout is still moving, so a caller can stop asking for frames.
+func (sim *GraphSim) Tick() bool {
+ if sim == nil || sim.Settled() {
+ return false
+ }
+ sim.tickLinks()
+ sim.tickRepel()
+ sim.tickCenter()
+ for index := range sim.bodies {
+ body := &sim.bodies[index]
+ body.vx *= 1 - graphVelocityDecay
+ body.vy *= 1 - graphVelocityDecay
+ if body.fixed {
+ body.x, body.y, body.vx, body.vy = body.fx, body.fy, 0, 0
+ continue
+ }
+ body.x += body.vx
+ body.y += body.vy
+ }
+ sim.alpha += (0 - sim.alpha) * graphAlphaDecay
+ return !sim.Settled()
+}
+
+// tickLinks springs each edge toward its rest length. d3 splits the
+// correction between the endpoints by their link counts, so a node joined to
+// many others moves less than its sparse neighbor.
+func (sim *GraphSim) tickLinks() {
+ strength := sim.alpha
+ for at := range sim.links {
+ link := &sim.links[at]
+ source, target := &sim.bodies[link.Source], &sim.bodies[link.Target]
+ dx, dy := target.x-source.x, target.y-source.y
+ length := float32(math.Hypot(float64(dx), float64(dy)))
+ if length < 0.01 {
+ // Coincident endpoints have no direction to spring along; part
+ // them a hair deterministically, as d3 does with a jiggle.
+ dx, dy, length = 0.01, -0.01, 0.0142
+ }
+ bias := float32(sim.degree[link.Source]) / float32(sim.degree[link.Source]+sim.degree[link.Target])
+ correction := (length - link.Distance) / length * strength * link.Strength
+ source.vx += dx * correction * (1 - bias)
+ source.vy += dy * correction * (1 - bias)
+ target.vx -= dx * correction * bias
+ target.vy -= dy * correction * bias
+ }
+}
+
+// tickRepel pushes every pair of nodes apart with a Coulomb force: a negative
+// RepelStrength repels, so the coefficient here is its negation. It is O(n²),
+// which a backlink graph of a few thousand notes does not notice.
+// ponytail: past ~2000 nodes swap in a Barnes-Hut quadtree (theta 0.9), as
+// d3-force's manyBody does, and reuse it across a few ticks.
+func (sim *GraphSim) tickRepel() {
+ strength := -sim.alpha * sim.RepelStrength
+ for i := 0; i < len(sim.bodies); i++ {
+ for j := i + 1; j < len(sim.bodies); j++ {
+ a, b := &sim.bodies[i], &sim.bodies[j]
+ dx, dy := a.x-b.x, a.y-b.y
+ distance := max(float32(math.Hypot(float64(dx), float64(dy))), 1)
+ force := strength / (distance * distance * distance)
+ a.vx += dx * force
+ a.vy += dy * force
+ b.vx -= dx * force
+ b.vy -= dy * force
+ }
+ }
+}
+
+// tickCenter pulls every node toward the origin, keeping disconnected pieces
+// on the canvas the way a forceX/forceY(0) pair does.
+func (sim *GraphSim) tickCenter() {
+ strength := sim.alpha * sim.CenterStrength
+ for index := range sim.bodies {
+ body := &sim.bodies[index]
+ body.vx -= body.x * strength
+ body.vy -= body.y * strength
+ }
+}
+
+// Neighbors lists the nodes node i is joined to, in link order. It allocates,
+// so a caller keeps the answer while it has the keyboard.
+func (sim *GraphSim) Neighbors(i int) []int {
+ if sim == nil || i < 0 || i >= len(sim.bodies) {
+ return nil
+ }
+ neighbors := make([]int, 0, sim.degree[i])
+ for _, link := range sim.links {
+ switch {
+ case link.Source == i:
+ neighbors = append(neighbors, link.Target)
+ case link.Target == i:
+ neighbors = append(neighbors, link.Source)
+ }
+ }
+ return neighbors
+}
+
+// Bounds is the graph-space rectangle the nodes occupy: the viewport a
+// fit-to-view transform computes from. A graph of no nodes, or of nodes piled
+// on one point, reports a unit box so a fit scale stays finite.
+func (sim *GraphSim) Bounds() (minX, minY, maxX, maxY float32) {
+ if sim == nil || len(sim.bodies) == 0 {
+ return -0.5, -0.5, 0.5, 0.5
+ }
+ minX, minY, maxX, maxY = math.MaxFloat32, math.MaxFloat32, -math.MaxFloat32, -math.MaxFloat32
+ for _, body := range sim.bodies {
+ minX, minY = min(minX, body.x), min(minY, body.y)
+ maxX, maxY = max(maxX, body.x), max(maxY, body.y)
+ }
+ maxX, maxY = max(maxX, minX+1), max(maxY, minY+1)
+ return minX, minY, maxX, maxY
+}
diff --git a/components/graph_sim_test.go b/components/graph_sim_test.go
new file mode 100644
index 000000000..d594498b5
--- /dev/null
+++ b/components/graph_sim_test.go
@@ -0,0 +1,132 @@
+package components
+
+import (
+ "math"
+ "testing"
+)
+
+func graphTestLinks() []GraphLink {
+ links := make([]GraphLink, 0, 20)
+ for index := 0; index < 11; index++ {
+ links = append(links, GraphLink{Source: index, Target: index + 1})
+ }
+ return append(links,
+ GraphLink{Source: 0, Target: 5},
+ GraphLink{Source: 2, Target: 9},
+ GraphLink{Source: 3, Target: 11},
+ GraphLink{Source: 12, Target: 0},
+ GraphLink{Source: 12, Target: 7},
+ GraphLink{Source: 1, Target: 8},
+ )
+}
+
+func TestGraphSimSettlesAndIsDeterministic(t *testing.T) {
+ first := NewGraphSim(13, graphTestLinks())
+ ticks := 0
+ for first.Tick() {
+ ticks++
+ if ticks > 1000 {
+ t.Fatal("simulation never settled")
+ }
+ }
+ if !first.Settled() {
+ t.Fatal("settled false after ticks ran out")
+ }
+ if ticks < 100 {
+ t.Fatalf("settled after %d ticks; alpha decay is far from d3's ~300", ticks)
+ }
+ second := NewGraphSim(13, graphTestLinks())
+ for second.Tick() {
+ }
+ for index := 0; index < first.Len(); index++ {
+ ax, ay := first.Position(index)
+ bx, by := second.Position(index)
+ if ax != bx || ay != by {
+ t.Fatalf("node %d differs between identical runs: (%v,%v) vs (%v,%v)", index, ax, ay, bx, by)
+ }
+ if math.IsNaN(float64(ax)) || math.IsNaN(float64(ay)) {
+ t.Fatalf("node %d left the plane", index)
+ }
+ }
+}
+
+func TestGraphSimGoldenLayout(t *testing.T) {
+ sim := NewGraphSim(13, graphTestLinks())
+ for sim.Tick() {
+ }
+ x, y := sim.Position(0)
+ goldenX, goldenY := float32(-15.272539), float32(-6.077562)
+ if diff := float32(math.Abs(float64(x - goldenX))); diff > 0.001 {
+ t.Fatalf("node 0 x = %v, want %v (diff %v); the force model changed", x, goldenX, diff)
+ }
+ if diff := float32(math.Abs(float64(y - goldenY))); diff > 0.001 {
+ t.Fatalf("node 0 y = %v, want %v (diff %v); the force model changed", y, goldenY, diff)
+ }
+}
+
+func TestGraphSimFixedNodeStaysPutAndReheats(t *testing.T) {
+ sim := NewGraphSim(13, graphTestLinks())
+ for sim.Tick() {
+ }
+ sim.SetFixed(4, 500, -300)
+ sim.Reheat(0.3)
+ if sim.Settled() {
+ t.Fatal("reheat left the simulation cold")
+ }
+ for ticks := 0; sim.Tick(); ticks++ {
+ if x, y := sim.Position(4); x != 500 || y != -300 {
+ t.Fatalf("fixed node moved to (%v,%v)", x, y)
+ }
+ if ticks > 1000 {
+ t.Fatal("simulation never settled around the fixed node")
+ }
+ }
+ sim.SetFree(4)
+ sim.Reheat(0.3)
+ x, y := sim.Position(4)
+ moved := false
+ for ticks := 0; sim.Tick(); ticks++ {
+ if nx, ny := sim.Position(4); nx != x || ny != y {
+ moved = true
+ break
+ }
+ if ticks > 50 {
+ break
+ }
+ }
+ if !moved {
+ t.Fatal("freed node stayed at the pinned position")
+ }
+}
+
+func TestGraphSimDropsInvalidLinksAndCountsDegrees(t *testing.T) {
+ sim := NewGraphSim(4, []GraphLink{
+ {Source: 0, Target: 1},
+ {Source: 1, Target: 2},
+ {Source: 2, Target: 2}, // self
+ {Source: 3, Target: 9}, // out of range
+ {Source: -1, Target: 0}, // out of range
+ })
+ if sim.Len() != 4 {
+ t.Fatalf("len = %d", sim.Len())
+ }
+ if got := sim.Degree(0) + sim.Degree(1) + sim.Degree(2) + sim.Degree(3); got != 4 {
+ t.Fatalf("degrees sum to %d, want 4", got)
+ }
+ if neighbors := sim.Neighbors(1); len(neighbors) != 2 {
+ t.Fatalf("node 1 neighbors = %v", neighbors)
+ }
+}
+
+func TestGraphSimBoundsCoverEveryNode(t *testing.T) {
+ sim := NewGraphSim(9, []GraphLink{{Source: 0, Target: 8}})
+ for sim.Tick() {
+ }
+ minX, minY, maxX, maxY := sim.Bounds()
+ for index := 0; index < sim.Len(); index++ {
+ x, y := sim.Position(index)
+ if x < minX || x > maxX || y < minY || y > maxY {
+ t.Fatalf("node %d at (%v,%v) outside bounds (%v,%v)-(%v,%v)", index, x, y, minX, minY, maxX, maxY)
+ }
+ }
+}
diff --git a/components/graph_test.go b/components/graph_test.go
new file mode 100644
index 000000000..6368fa967
--- /dev/null
+++ b/components/graph_test.go
@@ -0,0 +1,389 @@
+package components
+
+import (
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/vivaui/viva/gfx"
+)
+
+var graphTestTree gfx.Tree
+
+func graphTestScope() gfx.Scope {
+ return graphTestTree.Sub(0, graphTestTree.Name("nodes"))
+}
+
+func graphTestData() (*GraphSim, []GraphNode) {
+ sim := NewGraphSim(6, []GraphLink{
+ {Source: 0, Target: 1}, {Source: 1, Target: 2}, {Source: 2, Target: 0},
+ {Source: 1, Target: 3}, {Source: 3, Target: 4}, {Source: 1, Target: 5},
+ })
+ nodes := []GraphNode{
+ {Label: "Index", Group: 0, Resolved: true},
+ {Label: "Graph", Group: 0, Resolved: true},
+ {Label: "Links", Group: 1, Resolved: true},
+ {Label: "Tags", Group: 1, Resolved: true},
+ {Label: "Drafts", Group: 2, Resolved: true},
+ {Label: "Missing", Group: 2},
+ }
+ return sim, nodes
+}
+
+func graphTestPaint(canvas *gfx.Canvas, state *GraphState, options GraphOptions) GraphLayout {
+ if canvas != nil {
+ canvas.SetMeasurer(chartTestMeasure)
+ canvas.SetTree(&graphTestTree)
+ }
+ sim, nodes := graphTestData()
+ return PaintGraph(canvas, gfx.LightTheme(), gfx.Rect{X: 10, Y: 10, Width: 300, Height: 220}, sim, nodes, state, options)
+}
+
+func TestPaintGraphPaintsEdgesNodesAndHits(t *testing.T) {
+ var canvas gfx.Canvas
+ state := &GraphState{}
+ layout := graphTestPaint(&canvas, state, GraphOptions{Nodes: graphTestScope()})
+ if layout.Scale <= 0 {
+ t.Fatalf("scale = %v", layout.Scale)
+ }
+ if len(canvas.Triangles()) == 0 {
+ t.Fatal("no edge geometry painted")
+ }
+ // One circle per resolved-or-not node and one hit per node, plus none for
+ // a surface that was not named.
+ if len(canvas.Rectangles()) != 6 {
+ t.Fatalf("node circles = %d, want 6", len(canvas.Rectangles()))
+ }
+ if len(canvas.Hits()) != 6 {
+ t.Fatalf("node hits = %d, want 6", len(canvas.Hits()))
+ }
+ for index, hit := range canvas.Hits() {
+ if hit.ID != graphTestScope().At(index) || hit.Role != gfx.RoleLink {
+ t.Fatalf("hit %d = %+v", index, hit)
+ }
+ }
+}
+
+func TestPaintGraphHoverHighlightsAndLabelsNeighbors(t *testing.T) {
+ var canvas gfx.Canvas
+ state := &GraphState{}
+ graphTestPaint(&canvas, state, GraphOptions{Nodes: graphTestScope()})
+ quiet := len(canvas.Texts())
+ canvas.Reset()
+ canvas.SetInteraction(graphTestScope().At(1), gfx.ID{}, gfx.ID{}, false)
+ graphTestPaint(&canvas, state, GraphOptions{Nodes: graphTestScope()})
+ if len(canvas.Texts()) <= quiet {
+ t.Fatalf("hover painted %d labels, quiet graph %d", len(canvas.Texts()), quiet)
+ }
+ labels := ""
+ for _, text := range canvas.Texts() {
+ labels += text.Value + " "
+ }
+ for _, want := range []string{"Graph", "Index", "Links", "Tags", "Missing"} {
+ if !strings.Contains(labels, want) {
+ t.Fatalf("hover labels %q miss neighbor %q", labels, want)
+ }
+ }
+}
+
+func TestPaintGraphClickSelectsNode(t *testing.T) {
+ var canvas gfx.Canvas
+ state := &GraphState{}
+ graphTestPaint(&canvas, state, GraphOptions{Nodes: graphTestScope()})
+ canvas.Reset()
+ canvas.BeginEventPass(graphTestScope().At(3), gfx.ClickInfo{})
+ graphTestPaint(&canvas, state, GraphOptions{Nodes: graphTestScope()})
+ canvas.EndEventPass()
+ if clicked, ok := state.Selection(); !ok || clicked != 3 {
+ t.Fatalf("selection after click = %d, %v", clicked, ok)
+ }
+ // The selected node holds the tab stop; every other node stays reachable
+ // by pointer and arrows but out of Tab traversal.
+ tabStops := 0
+ for _, hit := range canvas.Hits() {
+ if !hit.SkipTab {
+ tabStops++
+ }
+ }
+ if tabStops != 1 {
+ t.Fatalf("graph declares %d tab stops, want the one selected node", tabStops)
+ }
+}
+
+func TestGraphLayoutMapsBetweenSpaces(t *testing.T) {
+ var canvas gfx.Canvas
+ layout := graphTestPaint(&canvas, nil, GraphOptions{})
+ x, y := layout.FromScreen(150, 200)
+ sx, sy := layout.ToScreen(x, y)
+ if abs32(sx-150) > 0.01 || abs32(sy-200) > 0.01 {
+ t.Fatalf("round trip moved the point: (%v,%v) -> (%v,%v) -> (%v,%v)", 150, 200, x, y, sx, sy)
+ }
+ if node, ok := layout.NodeAt(layout.points[2].X, layout.points[2].Y); !ok || node != 2 {
+ t.Fatalf("NodeAt over node 2 = %d, %v", node, ok)
+ }
+ if _, ok := layout.NodeAt(11, 11); ok {
+ t.Fatal("NodeAt found a node in the corner")
+ }
+}
+
+func TestPaintGraphHoverYieldsToPress(t *testing.T) {
+ var canvas gfx.Canvas
+ state := &GraphState{}
+ options := GraphOptions{Nodes: graphTestScope(), SurfaceID: gfx.Item(90)}
+ quiet := func() int {
+ canvas.Reset()
+ graphTestPaint(&canvas, state, options)
+ return len(canvas.Texts())
+ }
+ // A held node owns the highlight even while the pointer sweeps others:
+ // dragging through a crowd must not light up the nodes it passes. Node 5
+ // is a neighbor of the held node 1 but not of the swept node 2, so its
+ // label is what tells the two hovers apart.
+ quiet()
+ canvas.SetInteraction(graphTestScope().At(2), graphTestScope().At(1), gfx.ID{}, false)
+ graphTestPaint(&canvas, state, options)
+ labels := ""
+ for _, text := range canvas.Texts() {
+ labels += text.Value + " "
+ }
+ if !strings.Contains(labels, "Graph") || !strings.Contains(labels, "Missing") {
+ t.Fatalf("held node's labels missing: %q", labels)
+ }
+ // A held background — a pan — keeps the graph quiet entirely.
+ canvas.SetInteraction(graphTestScope().At(2), gfx.Item(90), gfx.ID{}, false)
+ if count := quiet(); count != 0 {
+ t.Fatalf("pan painted %d labels", count)
+ }
+}
+
+func TestPaintGraphFreezesViewportWhenSettled(t *testing.T) {
+ var canvas gfx.Canvas
+ canvas.SetReduceMotion(true)
+ canvas.SetMeasurer(chartTestMeasure)
+ canvas.SetTree(&graphTestTree)
+ sim, nodes := graphTestData()
+ state := &GraphState{}
+ options := GraphOptions{Nodes: graphTestScope()}
+ bounds := gfx.Rect{X: 10, Y: 10, Width: 300, Height: 220}
+ theme := gfx.LightTheme()
+ paint := func() GraphLayout {
+ canvas.Reset()
+ return PaintGraph(&canvas, theme, bounds, sim, nodes, state, options)
+ }
+ first := paint()
+ if state.Zoom <= 0 {
+ t.Fatal("a settled paint left the fit following instead of frozen into Zoom")
+ }
+ // A drag to a far corner reheats the layout and swings its bounds with
+ // it; the frozen view must not chase them back under the pointer, which
+ // is what made a long drag look pinned.
+ sim.SetFixed(4, 4000, -4000)
+ sim.Reheat(0.3)
+ for ticks := 0; ticks < 20 && sim.Tick(); ticks++ {
+ }
+ second := paint()
+ if second.Scale != first.Scale {
+ t.Fatalf("scale drifted from %v to %v while the layout reheated", first.Scale, second.Scale)
+ }
+ sx, sy := first.ToScreen(30, -30)
+ tx, ty := second.ToScreen(30, -30)
+ if sx != tx || sy != ty {
+ t.Fatalf("world point (30,-30) moved on screen from (%v,%v) to (%v,%v)", sx, sy, tx, ty)
+ }
+ // Writing Zoom back to zero refits once the layout is quiet again.
+ sim.SetFree(4)
+ for sim.Tick() {
+ }
+ state.Zoom = 0
+ refit := paint()
+ if refit.Scale == first.Scale {
+ t.Fatalf("refit scale %v equals the frozen one", refit.Scale)
+ }
+ if state.Zoom <= 0 {
+ t.Fatal("refit left Zoom following")
+ }
+}
+
+func TestPaintGraphSurvivesStaleSelectionAndNegativeGroup(t *testing.T) {
+ var canvas gfx.Canvas
+ canvas.SetMeasurer(chartTestMeasure)
+ canvas.SetTree(&graphTestTree)
+ sim, nodes := graphTestData()
+ nodes[2].Group = -3 // caller-owned data: Go's remainder keeps the sign
+ state := &GraphState{}
+ state.Select(11) // a state kept across a smaller rebuilt simulation
+ options := GraphOptions{Nodes: graphTestScope(), SurfaceID: gfx.Item(90)}
+ layout := PaintGraph(&canvas, gfx.LightTheme(), gfx.Rect{X: 10, Y: 10, Width: 300, Height: 220},
+ sim, nodes, state, options)
+ if _, ok := state.Selection(); ok {
+ t.Fatal("stale selection survived the paint")
+ }
+ if layout.Scale <= 0 {
+ t.Fatal("graph did not paint")
+ }
+ // A hover cache from a larger graph must not label past the nodes: the
+ // pointer is still over node 1, so the cache is kept, and its neighbor 3 is
+ // not in the smaller simulation.
+ small := NewGraphSim(3, nil)
+ smallNodes := []GraphNode{{Label: "Index", Resolved: true}, {Label: "Graph", Resolved: true}, {Label: "Links", Resolved: true}}
+ stale := &GraphState{sim: small, nodeCount: len(smallNodes), hover: 1, neighbors: []int{1, 3}}
+ scope := graphTestScope()
+ canvas.SetInteraction(scope.At(1), gfx.ID{}, gfx.ID{}, false)
+ PaintGraph(&canvas, gfx.LightTheme(), gfx.Rect{X: 10, Y: 10, Width: 300, Height: 220}, small, smallNodes, stale, GraphOptions{Nodes: scope})
+ if stale.hover != 1 {
+ t.Fatalf("hover over node 1 = %d, want it kept", stale.hover)
+ }
+ // The pan surface is not a control: it must not join the focus order.
+ for _, hit := range canvas.Hits() {
+ if hit.ID == gfx.Item(90) && hit.Focusable {
+ t.Fatalf("pan surface is focusable: %+v", hit)
+ }
+ }
+}
+
+func TestPaintGraphSettlesOnTheClock(t *testing.T) {
+ var canvas gfx.Canvas
+ canvas.SetMeasurer(chartTestMeasure)
+ canvas.SetTree(&graphTestTree)
+ sim, nodes := graphTestData()
+ state := &GraphState{}
+ options := GraphOptions{Nodes: graphTestScope()}
+ bounds := gfx.Rect{X: 10, Y: 10, Width: 300, Height: 220}
+ theme := gfx.LightTheme()
+ now := time.Duration(0)
+ canvas.SetClock(func() time.Duration { return now })
+ paint := func() bool {
+ canvas.Reset()
+ canvas.BeginFrame()
+ PaintGraph(&canvas, theme, bounds, sim, nodes, state, options)
+ canvas.EndFrame()
+ return canvas.Animating()
+ }
+ if !paint() {
+ t.Fatal("a fresh graph does not animate")
+ }
+ // Sparse frames still settle inside four seconds: the gallery harness
+ // paints nine frames in its window, half a second apart.
+ animating := false
+ for step := 0; step < 8; step++ {
+ now += 500 * time.Millisecond
+ animating = paint()
+ }
+ if animating {
+ t.Fatal("graph still asks for frames after four idle seconds")
+ }
+ if !sim.Settled() {
+ t.Fatal("clock-driven anneal left the simulation unsettled")
+ }
+}
+
+func TestPaintGraphStaticPreviewWithoutScope(t *testing.T) {
+ var canvas gfx.Canvas
+ graphTestPaint(&canvas, nil, GraphOptions{})
+ if len(canvas.Hits()) != 0 {
+ t.Fatalf("static preview declared %d hits", len(canvas.Hits()))
+ }
+ if len(canvas.Rectangles()) == 0 {
+ t.Fatal("static preview painted nothing")
+ }
+}
+
+func TestGraphStepForKeyStepsNeighbors(t *testing.T) {
+ neighbors := []int{4, 7, 9}
+ cases := [...]struct {
+ key gfx.Key
+ from int
+ want int
+ moving bool
+ }{
+ {gfx.KeyRight, 4, 7, true},
+ {gfx.KeyRight, 9, 4, true},
+ {gfx.KeyLeft, 4, 9, true},
+ {gfx.KeyLeft, 7, 4, true},
+ {gfx.KeyDown, 7, 9, true},
+ {gfx.KeyUp, 9, 7, true},
+ {gfx.KeyHome, 9, 4, true},
+ {gfx.KeyEnd, 4, 9, true},
+ {gfx.KeyEnter, 4, 4, false},
+ {gfx.KeyRight, 5, 4, true}, // not a neighbor: first neighbor
+ }
+ for _, test := range cases {
+ got, moved := GraphStepForKey(test.key, test.from, neighbors)
+ if moved != test.moving || got != test.want {
+ t.Fatalf("%v from %d = (%d,%v), want (%d,%v)", test.key, test.from, got, moved, test.want, test.moving)
+ }
+ }
+ if _, moved := GraphStepForKey(gfx.KeyRight, 1, nil); moved {
+ t.Fatal("step moved with no neighbors")
+ }
+}
+
+func TestPaintGraphSteadyStateAllocatesNothing(t *testing.T) {
+ var canvas gfx.Canvas
+ canvas.SetReduceMotion(true)
+ sim, nodes := graphTestData()
+ state := &GraphState{}
+ options := GraphOptions{Nodes: graphTestScope()}
+ bounds := gfx.Rect{X: 10, Y: 10, Width: 300, Height: 220}
+ theme := gfx.LightTheme()
+ paint := func() {
+ canvas.Reset()
+ canvas.SetMeasurer(chartTestMeasure)
+ canvas.SetTree(&graphTestTree)
+ canvas.SetInteraction(graphTestScope().At(1), gfx.ID{}, gfx.ID{}, false)
+ PaintGraph(&canvas, theme, bounds, sim, nodes, state, options)
+ }
+ paint()
+ allocations := testing.AllocsPerRun(10, paint)
+ if allocations > 0 {
+ t.Fatalf("steady graph paint allocated %v times", allocations)
+ }
+}
+
+// graphBenchmarkData builds a settled graph of nodes notes with a ring and a
+// hub-like second link each, the shape a vault's backlink graph has.
+func graphBenchmarkData(b *testing.B, count int) (*GraphSim, []GraphNode) {
+ b.Helper()
+ links := make([]GraphLink, 0, count*2)
+ for index := 0; index < count; index++ {
+ links = append(links, GraphLink{Source: index, Target: (index + 1) % count})
+ links = append(links, GraphLink{Source: index, Target: (index * 7) % count})
+ }
+ nodes := make([]GraphNode, count)
+ for index := range nodes {
+ nodes[index] = GraphNode{Label: "note", Group: index % 4, Resolved: true}
+ }
+ return NewGraphSim(count, links), nodes
+}
+
+// BenchmarkPaintGraph is the steady cost of a settled graph: a real vault's
+// few hundred notes, painted without hovering.
+func BenchmarkPaintGraph(b *testing.B) {
+ sim, nodes := graphBenchmarkData(b, 400)
+ for ticks := 0; ticks < 2000 && sim.Tick(); ticks++ {
+ }
+ var canvas gfx.Canvas
+ canvas.SetMeasurer(chartTestMeasure)
+ canvas.SetTree(&graphTestTree)
+ state := &GraphState{}
+ bounds := gfx.Rect{Width: 900, Height: 600}
+ b.ReportAllocs()
+ for b.Loop() {
+ PaintGraph(&canvas, gfx.LightTheme(), bounds, sim, nodes, state, GraphOptions{})
+ }
+}
+
+// BenchmarkGraphSettle is the first paint a reduced-motion session pays: the
+// whole anneal runs before the frame is drawn.
+func BenchmarkGraphSettle(b *testing.B) {
+ sim, nodes := graphBenchmarkData(b, 300)
+ var canvas gfx.Canvas
+ canvas.SetMeasurer(chartTestMeasure)
+ canvas.SetTree(&graphTestTree)
+ bounds := gfx.Rect{Width: 900, Height: 600}
+ b.ReportAllocs()
+ for b.Loop() {
+ sim.Reheat(1)
+ PaintGraph(&canvas, gfx.LightTheme(), bounds, sim, nodes, &GraphState{}, GraphOptions{})
+ }
+}
diff --git a/internal/componentdemo/catalog_a.go b/internal/componentdemo/catalog_a.go
index 8ddadaeb2..4f5337bbf 100644
--- a/internal/componentdemo/catalog_a.go
+++ b/internal/componentdemo/catalog_a.go
@@ -20,4 +20,5 @@ var groupAComponents = []Component{
chartDownsampleComponent,
collapsibleComponent,
comboboxComponent,
+ graphComponent,
}
diff --git a/internal/componentdemo/catalog_a_test.go b/internal/componentdemo/catalog_a_test.go
index 950eb61c4..1e46ad590 100644
--- a/internal/componentdemo/catalog_a_test.go
+++ b/internal/componentdemo/catalog_a_test.go
@@ -46,7 +46,7 @@ func TestGroupACatalogOrder(t *testing.T) {
want := []string{
"accordion", "alert", "alert-dialog", "aspect-ratio", "attachment",
"avatar", "avatar-editor", "breadcrumb", "bubble", "button-group", "calendar", "card",
- "carousel", "chart", "chart-area", "chart-bar", "chart-downsample", "collapsible", "combobox",
+ "carousel", "chart", "chart-area", "chart-bar", "chart-downsample", "collapsible", "combobox", "graph",
}
if len(groupAComponents) != len(want) {
t.Fatalf("group A has %d components, want %d", len(groupAComponents), len(want))
diff --git a/internal/componentdemo/graph.go b/internal/componentdemo/graph.go
new file mode 100644
index 000000000..9b02bc51a
--- /dev/null
+++ b/internal/componentdemo/graph.go
@@ -0,0 +1,329 @@
+package componentdemo
+
+import (
+ "math"
+
+ "github.com/vivaui/viva/components"
+ "github.com/vivaui/viva/gfx"
+ "github.com/vivaui/viva/ui"
+)
+
+var graphComponent = Component{
+ ID: "graph", Title: "Graph", Category: "Data Display",
+ Summary: "力导向双向链接图谱:调用方持有模拟与视口,悬停高亮邻居,拖动节点,滚轮缩放。",
+ paint: (*State).paintGraph,
+ pointer: (*State).pointerGraph,
+ key: (*State).keyGraph,
+ scroll: (*State).scrollGraph,
+ initialize: (*State).initializeGraph,
+ Examples: []Example{
+ {
+ ID: "vault", Title: "全局图谱",
+ Description: "整个库的笔记与链接;悬停高亮邻居,其余压暗。",
+ Height: 360,
+ Snippet: `graph.layout = components.PaintGraph(canvas, theme, bounds, graph.sim,
+ graph.nodes, graph.view, components.GraphOptions{
+ Nodes: graphNodeList, SurfaceID: graphSurface})
+if clicked, ok := graph.layout.Clicked(); ok {
+ openNote(clicked) // the application owns what a node opens
+}`,
+ PageSnippet: `// m.graph is the page's graph: the simulation, its nodes and
+// a GraphState the page keeps. m.graph.draw paints it on the page canvas.
+m.graph.sim.Step(1.0 / 120.0)
+ui.Box(c).Draw(m.graph.draw)`,
+ PageSnippetZh: `// m.graph 是本页的图谱:模拟、节点与页面持有的 GraphState。
+// m.graph.draw 在页面画布上绘制它。
+m.graph.sim.Step(1.0 / 120.0)
+ui.Box(c).Draw(m.graph.draw)`,
+ },
+ {
+ ID: "local", Title: "局部图谱",
+ Description: "当前笔记两跳邻域的子图,同样的组件与状态。",
+ Height: 360,
+ Snippet: `// A local graph is the same component over a smaller simulation: the
+// application extracts the two-hop neighborhood of the current note.
+local := graphNeighborhood(sim, links, currentNote, 2)
+components.PaintGraph(canvas, theme, bounds, local.sim, local.nodes,
+ local.view, components.GraphOptions{Nodes: graphNodeList})`,
+ PageSnippet: `// m.graph.local is the page's smaller simulation for the note it shows.
+m.graph.local.Step(1.0 / 120.0)
+ui.Box(c).Draw(m.graph.draw)`,
+ PageSnippetZh: `// m.graph.local 是页面为当前笔记保存的较小子图模拟。
+m.graph.local.Step(1.0 / 120.0)
+ui.Box(c).Draw(m.graph.draw)`,
+ },
+ },
+}
+
+var (
+ graphUI = tree.Feature("graph")
+ graphSurface = graphUI.ID(tree.Name("surface"))
+ graphNodeList = tree.Sub(graphUI, tree.Name("node"))
+)
+
+// graphDemoState is the caller-owned state of the graph examples: the
+// simulation, the display data, the viewport, and the pointer bookkeeping a
+// drag and a pan need between events.
+type graphDemoState struct {
+ sim *components.GraphSim
+ nodes []components.GraphNode
+ view *components.GraphState
+ layout components.GraphLayout
+ drag int
+ panning bool
+ lastX float32
+ lastY float32
+ opened string
+}
+
+// graphVaultLabels names the demo vault's notes in both preview languages.
+// The structure is a hub-and-spoke vault: an index note, three groups each
+// with its own head, chains inside a group, a few cross links, and two
+// unresolved links to notes that do not exist.
+var graphVaultGroups = [3]struct{ chinese, english string }{
+ {"概念", "Concepts"}, {"工具", "Tools"}, {"人物", "People"},
+}
+
+func graphVaultLabels(english bool) []string {
+ names := [...]string{"索引", "图谱", "链接", "卡片", "标签", "草稿", "归档", "日志",
+ "编辑器", "终端", "同步", "备份", "剪贴板", "窗口", "主题", "快捷键",
+ "高斯", "图灵", "香农", "维纳", "麦卡锡", "汉明", "未创建的引用", "待写的笔记"}
+ if english {
+ names = [...]string{"Index", "Graph", "Links", "Cards", "Tags", "Drafts", "Archive", "Journal",
+ "Editor", "Terminal", "Sync", "Backup", "Clipboard", "Windows", "Themes", "Shortcuts",
+ "Gauss", "Turing", "Shannon", "Wiener", "McCarthy", "Hamming", "Unresolved ref", "Note to write"}
+ }
+ return names[:]
+}
+
+func graphVaultLinks() []components.GraphLink {
+ heads := [3]int{1, 8, 16} // 概念/工具/人物 group heads
+ limits := [3]int{7, 15, 21} // last index of each group
+ links := make([]components.GraphLink, 0, 44)
+ for group, head := range heads {
+ links = append(links, components.GraphLink{Source: 0, Target: head})
+ for index := head; index < limits[group]; index++ {
+ links = append(links, components.GraphLink{Source: index, Target: index + 1})
+ }
+ }
+ return append(links,
+ components.GraphLink{Source: 2, Target: 9},
+ components.GraphLink{Source: 5, Target: 22},
+ components.GraphLink{Source: 11, Target: 17},
+ components.GraphLink{Source: 12, Target: 23},
+ components.GraphLink{Source: 19, Target: 4},
+ )
+}
+
+// initializeGraph builds the demo vault, whole for the vault example and as
+// the two-hop neighborhood of the 索引 note's 概念 head for the local one.
+func (state *State) initializeGraph() {
+ english := state.english
+ labels := graphVaultLabels(english)
+ links := graphVaultLinks()
+ demo := &graphDemoState{
+ nodes: make([]components.GraphNode, len(labels)),
+ view: &components.GraphState{},
+ drag: -1,
+ }
+ for index := range demo.nodes {
+ demo.nodes[index] = components.GraphNode{Label: labels[index], Group: graphVaultGroup(index), Resolved: index < 22}
+ }
+ if state.exampleID == "local" {
+ keep := graphNeighborhood(len(labels), links, 1, 2)
+ remap := make([]int, len(labels))
+ for index := range remap {
+ remap[index] = -1
+ }
+ nodes := make([]components.GraphNode, 0, len(keep))
+ for index := range demo.nodes {
+ if !keep[index] {
+ continue
+ }
+ remap[index] = len(nodes)
+ nodes = append(nodes, demo.nodes[index])
+ }
+ local := make([]components.GraphLink, 0, len(links))
+ for _, link := range links {
+ if keep[link.Source] && keep[link.Target] {
+ local = append(local, components.GraphLink{Source: remap[link.Source], Target: remap[link.Target]})
+ }
+ }
+ demo.nodes, links = nodes, local
+ }
+ demo.sim = components.NewGraphSim(len(demo.nodes), links)
+ state.graph = demo
+}
+
+// graphNeighborhood reports which of count nodes lie within depth hops of
+// from, by a breadth-first walk over links.
+func graphNeighborhood(count int, links []components.GraphLink, from, depth int) []bool {
+ keep := make([]bool, count)
+ if from < 0 || from >= count {
+ return keep
+ }
+ keep[from] = true
+ frontier := []int{from}
+ for step := 0; step < depth && len(frontier) > 0; step++ {
+ next := frontier[:0:0]
+ for _, node := range frontier {
+ for _, link := range links {
+ other, isLink := link.Source, link.Target == node
+ if link.Source == node {
+ other, isLink = link.Target, true
+ }
+ if isLink && other >= 0 && other < count && !keep[other] {
+ keep[other] = true
+ next = append(next, other)
+ }
+ }
+ }
+ frontier = next
+ }
+ return keep
+}
+
+// graphVaultGroup is the color group a note of the demo vault belongs to.
+func graphVaultGroup(index int) int {
+ switch {
+ case index == 0:
+ return 0
+ case index < 8:
+ return 0
+ case index < 16:
+ return 1
+ default:
+ return 2
+ }
+}
+
+func (state *State) paintGraph(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) {
+ graph := state.graph
+ var card ui.Box
+ var opened ui.Box
+ state.drawPage(canvas, theme, size, 680, state.Text("Graph · 双向链接图谱", "Graph · Backlink graph"), func(c ui.C) {
+ card = ui.Slot(c).FillWidth().Height(320)
+ caption(c, state.Text("悬停高亮邻居;拖动节点或背景;滚轮缩放;方向键在邻居间移动。",
+ "Hover highlights neighbors; drag a node or the background; scroll zooms; arrows step neighbors."))
+ opened = ui.Slot(c).FillWidth().Height(18)
+ })
+ bounds := card.Rect()
+ components.PaintCard(canvas, theme, bounds, components.CardOptions{})
+ inner := gfx.Rect{X: bounds.X + 8, Y: bounds.Y + 8, Width: bounds.Width - 16, Height: bounds.Height - 16}
+ graph.layout = components.PaintGraph(canvas, theme, inner, graph.sim, graph.nodes, graph.view, components.GraphOptions{
+ Nodes: graphNodeList,
+ SurfaceID: graphSurface,
+ })
+ if clicked, ok := graph.layout.Clicked(); ok {
+ graph.opened = graph.nodes[clicked].Label
+ }
+ if graph.opened != "" {
+ canvas.Label(state.Text("已打开:", "Opened: ")+graph.opened, opened.Rect(),
+ gfx.TextStyle{Size: theme.Metrics.FontSizeS, Color: theme.MutedForeground})
+ }
+}
+
+// pointerGraph drags a node (the simulation follows while it is held), pans
+// the viewport from the background, and keeps the node under the keyboard
+// focused while it is dragged.
+func (state *State) pointerGraph(event gfx.PointerEvent) gfx.EventResult {
+ graph := state.graph
+ if graph == nil {
+ return gfx.EventResult{}
+ }
+ switch event.Kind {
+ case gfx.PointerDown:
+ if event.Button != gfx.PointerButtonPrimary {
+ return gfx.EventResult{}
+ }
+ if node, ok := event.Target.In(graphNodeList); ok {
+ graph.drag = node
+ x, y := graph.layout.FromScreen(event.X, event.Y)
+ graph.sim.SetFixed(node, x, y)
+ // d3 keeps the layout warm for the whole drag, so the neighbors
+ // give way while the node travels instead of after the release.
+ graph.sim.Reheat(0.3)
+ graph.view.Select(node)
+ return gfx.EventResult{Focus: graphNodeList.At(node), Handled: true, Repaint: true}
+ }
+ if event.Target == graphSurface {
+ graph.panning = true
+ graph.lastX, graph.lastY = event.X, event.Y
+ return gfx.EventResult{Handled: true, Repaint: true}
+ }
+ return gfx.EventResult{}
+ case gfx.PointerMove:
+ if !event.Captured {
+ return gfx.EventResult{}
+ }
+ if graph.drag >= 0 {
+ x, y := graph.layout.FromScreen(event.X, event.Y)
+ graph.sim.SetFixed(graph.drag, x, y)
+ graph.sim.Reheat(0.3)
+ return gfx.EventResult{Handled: true, Repaint: true}
+ }
+ if graph.panning {
+ graph.view.Pan.X += event.X - graph.lastX
+ graph.view.Pan.Y += event.Y - graph.lastY
+ graph.lastX, graph.lastY = event.X, event.Y
+ return gfx.EventResult{Handled: true, Repaint: true}
+ }
+ return gfx.EventResult{}
+ case gfx.PointerUp, gfx.PointerExit:
+ if graph.drag >= 0 {
+ graph.sim.SetFree(graph.drag)
+ graph.sim.Reheat(0.3)
+ graph.drag = -1
+ return gfx.EventResult{Handled: true, Repaint: true}
+ }
+ if graph.panning {
+ graph.panning = false
+ return gfx.EventResult{Handled: true}
+ }
+ }
+ return gfx.EventResult{}
+}
+
+// scrollGraph zooms about the pointer, keeping the graph point under it in
+// place, from whatever the current zoom is — the fit zoom included.
+func (state *State) scrollGraph(event gfx.ScrollEvent) gfx.EventResult {
+ graph := state.graph
+ if graph == nil {
+ return gfx.EventResult{}
+ }
+ bounds := graph.layout.Bounds
+ if event.X < bounds.X || event.X > bounds.X+bounds.Width || event.Y < bounds.Y || event.Y > bounds.Y+bounds.Height {
+ return gfx.EventResult{}
+ }
+ current := graph.view.Zoom
+ if current <= 0 {
+ current = graph.layout.Scale
+ }
+ next := min(max(current*float32(math.Exp(float64(-event.DeltaY*0.0022))), 0.15), 4)
+ centerX, centerY := bounds.X+bounds.Width/2, bounds.Y+bounds.Height/2
+ underX := (event.X - centerX - graph.view.Pan.X) / current
+ underY := (event.Y - centerY - graph.view.Pan.Y) / current
+ graph.view.Zoom = next
+ graph.view.Pan.X = event.X - centerX - underX*next
+ graph.view.Pan.Y = event.Y - centerY - underY*next
+ return gfx.EventResult{Handled: true, Repaint: true}
+}
+
+// keyGraph moves the selection through the focused node's neighbors; the
+// runtime delivers Enter and Space as the node's click.
+func (state *State) keyGraph(event gfx.KeyEvent) gfx.EventResult {
+ graph := state.graph
+ if graph == nil || event.Release {
+ return gfx.EventResult{}
+ }
+ node, ok := event.Target.In(graphNodeList)
+ if !ok {
+ return gfx.EventResult{}
+ }
+ next, moved := components.GraphStepForKey(event.Key, node, graph.sim.Neighbors(node))
+ if !moved {
+ return gfx.EventResult{}
+ }
+ graph.view.Select(next)
+ return gfx.EventResult{Focus: graphNodeList.At(next), FocusVisible: true, Handled: true, Repaint: true}
+}
diff --git a/internal/componentdemo/state.go b/internal/componentdemo/state.go
index dbd5d64d8..f8bfa762e 100644
--- a/internal/componentdemo/state.go
+++ b/internal/componentdemo/state.go
@@ -133,6 +133,9 @@ type State struct {
picker *colorPickerDemoState
// chart keeps the hover and label caches of the chart examples.
chart *chartDemoState
+ // graph keeps the simulation, viewport and pointer bookkeeping of the
+ // graph examples.
+ graph *graphDemoState
// list is the page-layer List example: its rows, choice and page.
list *listDemo
// page keeps the memory and identities of the demo's Page (see drawPage).
diff --git a/tools/docs/catalog.go b/tools/docs/catalog.go
index ab6f1bc00..39d258c17 100644
--- a/tools/docs/catalog.go
+++ b/tools/docs/catalog.go
@@ -128,7 +128,7 @@ func loadPages(root string) ([]Page, Manifest, error) {
if file.Name() == "doc.go" || file.Name() == "direction.go" ||
file.Name() == "menu_typeahead.go" || file.Name() == "code_diff_model.go" || file.Name() == "code_diff_inline.go" ||
file.Name() == "code_editor_layout.go" || file.Name() == "code_editor_decorations.go" || file.Name() == "caret_blink.go" || file.Name() == "find_bar.go" || file.Name() == "go_to_line.go" || file.Name() == "hierarchy_menu.go" ||
- file.Name() == "markdown_anchor.go" || file.Name() == "text_selection.go" {
+ file.Name() == "graph_sim.go" || file.Name() == "markdown_anchor.go" || file.Name() == "text_selection.go" {
continue
}
id := strings.ReplaceAll(strings.TrimSuffix(file.Name(), ".go"), "_", "-")
From 15d4e38cb4f9d0b8d44d1e68e0524b2b7709bf3b Mon Sep 17 00:00:00 2001
From: t8y2 <1156263951@qq.com>
Date: Sat, 21 Nov 2026 22:55:40 +0800
Subject: [PATCH 16/47] fix(gfx): wrap long paragraphs in time linear in their
length
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Each wrapped line measured the whole rest of the paragraph to see whether
it fit, and bisected over all of it for the break, so a paragraph of L
lines cost O(L·N·log N): 16 KiB took 3.9 ms, 100 KiB about 335 ms, paid
again whenever the width changed. fitPrefix now gallops from the line's
start and bisects only the last doubling, which WrapLines and WrapRow
share. 16 KiB now takes 0.24 ms; short texts are unchanged.
Viva-only change; Motty picks it up through the existing wrapping API.
---
gfx/wrap.go | 46 +++++++++++++++++++++++++++++++++++-----------
gfx/wrap_rows.go | 5 +++--
gfx/wrap_test.go | 18 ++++++++++++++++++
3 files changed, 56 insertions(+), 13 deletions(-)
diff --git a/gfx/wrap.go b/gfx/wrap.go
index 8f838cf73..8db56f88e 100644
--- a/gfx/wrap.go
+++ b/gfx/wrap.go
@@ -115,7 +115,7 @@ func (canvas *Canvas) wrapLines(dst []string, value string, font lineFont, width
for {
line = trimSpaceRight(line)
last := len(dst)-first == maxLines-1
- fits := canvas.widthIn(line, font) <= width
+ fit, fits := canvas.fitPrefix(line, font, width)
if fits && !(last && more) {
dst = append(dst, line)
break
@@ -123,7 +123,7 @@ func (canvas *Canvas) wrapLines(dst []string, value string, font lineFont, width
if last {
return append(dst, canvas.ellipsizeCached(line, font, width, cache))
}
- cut := canvas.breakPoint(line, font, width)
+ cut := breakPoint(line, fit)
dst = append(dst, trimSpaceRight(line[:cut]))
if line = trimSpaceLeft(line[cut:]); line == "" {
break
@@ -267,15 +267,29 @@ func splitLine(value string) (line, rest string) {
return line, rest
}
-// breakPoint is where to cut line (wider than width) so the first part fits: at the
-// last UAX #14 break opportunity that fits; else, between Hangul syllables or, for a word
-// wider than the line, after the last path or hyphen separator that fits, whichever
-// fits more; else after the last whole grapheme cluster that fits, but never before the
-// first one.
-func (canvas *Canvas) breakPoint(line string, font lineFont, width float32) int {
- // The longest prefix that fits, found by bisection on rune boundaries: widths
- // grow with the text, so the answer is the largest boundary whose prefix fits.
- lo, hi := 0, len(line) // line[:lo] fits (the empty prefix does), line[:hi] does not
+// wrapProbe is the first prefix, in bytes, fitPrefix measures: a few words, so a
+// short line is measured once and a long one in a few doublings.
+const wrapProbe = 64
+
+// fitPrefix finds the longest prefix of line that fits width: fit is the largest
+// rune boundary whose prefix, its trailing spaces dropped, is no wider, and all
+// reports that this is the whole line. Widths grow with the text, so the answer
+// is found by galloping from the start, each probe twice as far as the last, and
+// then bisecting the last doubling: measuring a prefix costs its length, so a
+// line costs a few times its own length (times its logarithm), not the length
+// of the paragraph behind it.
+func (canvas *Canvas) fitPrefix(line string, font lineFont, width float32) (fit int, all bool) {
+ lo, hi := 0, len(line) // line[:lo] fits (the empty prefix does); line[:hi] does not once a probe failed
+ for step := wrapProbe; ; step *= 2 {
+ probe := runeFloor(line, lo+step)
+ if canvas.widthIn(trimSpaceRight(line[:probe]), font) > width {
+ hi = probe
+ break
+ }
+ if lo = probe; lo == len(line) {
+ return lo, true
+ }
+ }
for hi-lo > 1 {
mid := runeFloor(line, (lo+hi)/2)
if mid <= lo {
@@ -290,6 +304,16 @@ func (canvas *Canvas) breakPoint(line string, font lineFont, width float32) int
hi = mid
}
}
+ return lo, false
+}
+
+// breakPoint is where to cut line, whose longest prefix that fits ends at fit
+// (see fitPrefix), so the first part fits: at the last UAX #14 break opportunity
+// that fits; else, between Hangul syllables or, for a word wider than the line,
+// after the last path or hyphen separator that fits, whichever fits more; else
+// after the last whole grapheme cluster that fits, but never before the first one.
+func breakPoint(line string, fit int) int {
+ lo := fit
limit := clusterFloor(line, lo)
var strong, weak int
var scanner linebreak.Scanner
diff --git a/gfx/wrap_rows.go b/gfx/wrap_rows.go
index 0884cae2f..e05aff946 100644
--- a/gfx/wrap_rows.go
+++ b/gfx/wrap_rows.go
@@ -34,10 +34,11 @@ func (canvas *Canvas) WrapRow(value string, from int, size, weight, width float3
return TextRow{Start: from, End: end}, next
}
line := value[from:end]
- if canvas.TextWidthWeight(trimSpaceRight(line), size, weight) <= width {
+ fit, all := canvas.fitPrefix(line, lineFont{size: size, weight: weight}, width)
+ if all {
return TextRow{Start: from, End: end}, next
}
- cut := canvas.breakPoint(line, lineFont{size: size, weight: weight}, width)
+ cut := breakPoint(line, fit)
cut += len(line[cut:]) - len(trimSpaceLeft(line[cut:])) // the spaces after the break hang on this row
if from+cut >= end {
return TextRow{Start: from, End: end}, next
diff --git a/gfx/wrap_test.go b/gfx/wrap_test.go
index 63337d636..6fbceacdd 100644
--- a/gfx/wrap_test.go
+++ b/gfx/wrap_test.go
@@ -1,6 +1,8 @@
package gfx
import (
+ "math"
+ "strconv"
"strings"
"testing"
"unicode/utf8"
@@ -465,3 +467,19 @@ func TestFitLineReusesOneLabelAtDifferentControlWidths(t *testing.T) {
}
}
}
+
+// A long paragraph wrapped into many lines, as a log message or a pasted document
+// is: each line must cost its own length, not the length of the text behind it.
+func BenchmarkWrapLongParagraph(b *testing.B) {
+ for _, size := range []int{1 << 10, 1 << 14} {
+ b.Run(strconv.Itoa(size), func(b *testing.B) {
+ var canvas Canvas
+ text := strings.Repeat("the quick brown fox jumps over the lazy dog ", size/44+1)[:size]
+ lines := make([]string, 0, size/40)
+ b.ReportAllocs()
+ for b.Loop() {
+ lines = canvas.WrapLines(lines[:0], text, 14, WeightRegular, 400, math.MaxInt)
+ }
+ })
+ }
+}
From 21b6aca896f774558c85ada567d0bd6192e0c937 Mon Sep 17 00:00:00 2001
From: t8y2 <1156263951@qq.com>
Date: Sat, 21 Nov 2026 22:55:40 +0800
Subject: [PATCH 17/47] fix(gfx): keep a screen's working set of cell glyphs
cached
The cache of built cell glyphs held 64 entries and started over when
full, so a braille chart (which shows most of its 256 characters) rebuilt
and reallocated its glyphs on every line: 38 us and 254 allocations for a
line of 128 distinct characters. It is now two generations of a map in
front of which a direct-mapped table, indexed by character and cell width
parity, answers the glyphs a line repeats. The same line takes 17.8 us
with no allocation; a line of a few table characters costs about 5% more.
Viva-only change; it serves Motty's terminal through LabelRuns.
---
gfx/block_elements_test.go | 21 +++++++++
gfx/canvas.go | 2 +-
gfx/cell_glyphs.go | 96 +++++++++++++++++++++++++++++---------
3 files changed, 95 insertions(+), 24 deletions(-)
diff --git a/gfx/block_elements_test.go b/gfx/block_elements_test.go
index 0b5f0cd88..d68271c7a 100644
--- a/gfx/block_elements_test.go
+++ b/gfx/block_elements_test.go
@@ -195,3 +195,24 @@ func BenchmarkCellGlyphs(b *testing.B) {
scratch = canvas.CellGlyphGeometry(scratch, line)
}
}
+
+// A line of braille charts draw: more distinct characters than a table or a spinner, the
+// working set a cache of cell glyphs must hold without rebuilding them every line.
+func BenchmarkCellGlyphsBraille(b *testing.B) {
+ var canvas Canvas
+ canvas.SetPixelScale(2)
+ var value strings.Builder
+ for r := rune(0x2800); r < 0x2880; r++ {
+ value.WriteRune(r)
+ }
+ line := blockLine(&canvas, strings.Repeat(value.String(), 2), 9.6, Color{Red: 1, Alpha: 1})
+ scratch := CellGlyphShapes{
+ Rectangles: make([]Rectangle, 0, 4096),
+ Triangles: make([]Triangle, 0, 512),
+ }
+ b.ReportAllocs()
+ for b.Loop() {
+ scratch.Rectangles, scratch.Triangles = scratch.Rectangles[:0], scratch.Triangles[:0]
+ scratch = canvas.CellGlyphGeometry(scratch, line)
+ }
+}
diff --git a/gfx/canvas.go b/gfx/canvas.go
index 1b7ddd3ba..eb0eebb3c 100644
--- a/gfx/canvas.go
+++ b/gfx/canvas.go
@@ -749,7 +749,7 @@ type Canvas struct {
cell cellGlyph // scratch of CellGlyphGeometry
// cellCache holds the cell glyphs the last paints built, keyed by character
// and metrics; it survives Reset and is bounded by cellCacheLimit.
- cellCache []cellGlyphCacheEntry
+ cellCache cellGlyphCache
// fits remembers the lines FitLine cut; a different measurement empties it.
fits []fitEntry
hovered ID
diff --git a/gfx/cell_glyphs.go b/gfx/cell_glyphs.go
index 50b8d5a6b..8d2822627 100644
--- a/gfx/cell_glyphs.go
+++ b/gfx/cell_glyphs.go
@@ -295,18 +295,69 @@ func (canvas *Canvas) cellLine(text Text) cellLine {
}
}
-// cellGlyphCacheEntry is one built cell glyph, kept while the same character keeps being
-// drawn at the same metrics.
-type cellGlyphCacheEntry struct {
+// cellGlyphKey names one built cell glyph: the character and the metrics of its cell.
+type cellGlyphKey struct {
r rune
metrics cellMetrics
- shapes CellGlyphShapes
}
-// cellCacheLimit bounds the built cell glyphs a canvas keeps: box drawing, blocks,
-// braille and powerline together are a few hundred characters, and a screen shows
-// a few dozen of them at one or two metrics.
-const cellCacheLimit = 64
+// cellGlyphCache holds built cell glyphs in two generations: a lookup that
+// finds an entry in the previous one moves it to the current one, and a full
+// current generation becomes the previous one, so what the screens of the last
+// while showed stays and what they no longer show ages out. In front of them a
+// direct-mapped table answers the glyphs a line repeats without hashing.
+type cellGlyphCache struct {
+ front *[cellFrontSize]cellGlyphSlot
+ current, previous map[cellGlyphKey]CellGlyphShapes
+}
+
+type cellGlyphSlot struct {
+ key cellGlyphKey
+ shapes CellGlyphShapes
+ set bool
+}
+
+// cellCacheLimit bounds one generation of built cell glyphs: box drawing, blocks,
+// braille and powerline together are several hundred characters, and a chart of
+// braille dots alone can show most of its 256 on one screen, at one or two metrics.
+const cellCacheLimit = 512
+
+// cellFrontSize is the direct-mapped table's size: one block of 256 characters,
+// such as braille, at each of the two cell widths a fractional cell rounds to in
+// whole device pixels, without collisions.
+const cellFrontSize = 512
+
+func (key cellGlyphKey) frontIndex() int {
+ r := uint32(key.r)
+ return int((r^r>>7)&0xff | uint32(key.metrics.width&1)<<8)
+}
+
+// lookup finds a built glyph the direct-mapped table did not hold, in the maps.
+func (cache *cellGlyphCache) lookup(key cellGlyphKey) (CellGlyphShapes, bool) {
+ shapes, ok := cache.current[key]
+ if !ok {
+ if shapes, ok = cache.previous[key]; !ok {
+ return shapes, false
+ }
+ delete(cache.previous, key)
+ }
+ cache.put(key, shapes)
+ return shapes, true
+}
+
+func (cache *cellGlyphCache) put(key cellGlyphKey, shapes CellGlyphShapes) {
+ if len(cache.current) >= cellCacheLimit {
+ cache.previous, cache.current = cache.current, nil
+ }
+ if cache.current == nil {
+ cache.current = make(map[cellGlyphKey]CellGlyphShapes, 64)
+ }
+ cache.current[key] = shapes
+ if cache.front == nil {
+ cache.front = new([cellFrontSize]cellGlyphSlot)
+ }
+ cache.front[key.frontIndex()] = cellGlyphSlot{key: key, shapes: shapes, set: true}
+}
// glyphShapes is what r draws in a cell of these metrics, in device pixels from the cell's corner:
// the same for every cell of that size, whatever its place or colour. It draws into the canvas's
@@ -315,29 +366,28 @@ const cellCacheLimit = 64
// whole screen of the same table glyph rebuilds one of them — and the cache's entries are only
// read: place appends copies.
func (canvas *Canvas) glyphShapes(metrics cellMetrics, r rune) CellGlyphShapes {
- for i := range canvas.cellCache {
- if entry := &canvas.cellCache[i]; entry.r == r && entry.metrics == metrics {
- return entry.shapes
+ key := cellGlyphKey{r: r, metrics: metrics}
+ // The direct-mapped table is read here, inline: a line of repeated glyphs
+ // costs an index and a comparison per cell.
+ if front := canvas.cellCache.front; front != nil {
+ if slot := &front[key.frontIndex()]; slot.set && slot.key == key {
+ return slot.shapes
}
}
+ if shapes, ok := canvas.cellCache.lookup(key); ok {
+ return shapes
+ }
cell := &canvas.cell
cell.canvas, cell.cellMetrics = canvas, metrics
cell.shapes.Rectangles, cell.shapes.Triangles = cell.shapes.Rectangles[:0], cell.shapes.Triangles[:0]
if draw := cellGlyphDrawer(r); draw != nil {
draw(cell, r)
}
- var entry cellGlyphCacheEntry
- entry.r, entry.metrics = r, metrics
- entry.shapes.Rectangles = append(entry.shapes.Rectangles, cell.shapes.Rectangles...)
- entry.shapes.Triangles = append(entry.shapes.Triangles, cell.shapes.Triangles...)
- if len(canvas.cellCache) >= cellCacheLimit {
- // The working set of a screen is a few dozen characters at one or two
- // metrics; past the limit the whole cache starts over rather than
- // growing with every character a document ever showed.
- canvas.cellCache = canvas.cellCache[:0]
- }
- canvas.cellCache = append(canvas.cellCache, entry)
- return canvas.cellCache[len(canvas.cellCache)-1].shapes
+ var shapes CellGlyphShapes
+ shapes.Rectangles = append(shapes.Rectangles, cell.shapes.Rectangles...)
+ shapes.Triangles = append(shapes.Triangles, cell.shapes.Triangles...)
+ canvas.cellCache.put(key, shapes)
+ return shapes
}
// CellGlyphGeometry appends to dst the geometry that draws the cell glyphs of a text made by
From 99d61467cc159bd14cc71a5a779c2a8c17790aaa Mon Sep 17 00:00:00 2001
From: t8y2 <1156263951@qq.com>
Date: Sat, 21 Nov 2026 22:55:40 +0800
Subject: [PATCH 18/47] fix(framebuild): send layer and clip changes as a
range, not a rebuild
A frame where any instance's stamped layer or clip changed was sent as a
full rebuild, so scrolling a list whose rows clip themselves re-uploaded
the whole page every frame. stampState now returns the range it changed
and the update is widened to cover it, keeping the suffix form backends
require when the count grows or shrinks. Every backend regroups batches
from the full instance list on a partial update, so nothing else changes.
The painter tests now assert that a moved layer is covered by the update
rather than that the update is a rebuild.
---
app/painter_bitmap_test.go | 17 ++++++--
app/painter_test.go | 8 +++-
internal/framebuild/framebuild.go | 38 ++++++++++++-----
internal/framebuild/framebuild_test.go | 56 ++++++++++++++++++++++++++
4 files changed, 104 insertions(+), 15 deletions(-)
diff --git a/app/painter_bitmap_test.go b/app/painter_bitmap_test.go
index 407ccd409..1d3da252a 100644
--- a/app/painter_bitmap_test.go
+++ b/app/painter_bitmap_test.go
@@ -264,12 +264,15 @@ func TestBackdropIsBeneathEveryLayerAndShiftsThemOnlyWhilePresent(t *testing.T)
if err != nil {
t.Fatal(err)
}
+ before := rectangles
rectangles, labels = layers()
if !slices.Equal(rectangles, []uint16{0, 600, math.MaxUint16}) || !slices.Equal(labels, []uint16{0}) {
t.Fatalf("without: rectangles %v, labels %v", rectangles, labels)
}
- if !frame.Update.Rebuild {
- t.Fatalf("losing the backdrop moved every layer but the update is %+v", frame.Update)
+ for index := range rectangles {
+ if rectangles[index] != before[index] && !updateCovers(frame.Update, index) {
+ t.Fatalf("losing the backdrop moved layer %d but the update %+v leaves it behind", index, frame.Update)
+ }
}
if frame.TextLabels == nil {
t.Fatal("the labels were not sent again")
@@ -280,9 +283,15 @@ func TestBackdropIsBeneathEveryLayerAndShiftsThemOnlyWhilePresent(t *testing.T)
if err != nil {
t.Fatal(err)
}
+ before = rectangles
rectangles, _ = layers()
- if !frame.Update.Rebuild || !slices.Equal(rectangles, []uint16{1, 601, math.MaxUint16}) {
- t.Fatalf("gaining it again: %+v %v", frame.Update, rectangles)
+ if !slices.Equal(rectangles, []uint16{1, 601, math.MaxUint16}) {
+ t.Fatalf("gaining it again: %v", rectangles)
+ }
+ for index := range rectangles {
+ if rectangles[index] != before[index] && !updateCovers(frame.Update, index) {
+ t.Fatalf("gaining the backdrop moved layer %d but the update %+v leaves it behind", index, frame.Update)
+ }
}
}
diff --git a/app/painter_test.go b/app/painter_test.go
index ab71a5e0c..cbe959775 100644
--- a/app/painter_test.go
+++ b/app/painter_test.go
@@ -512,7 +512,8 @@ func TestRepaintLayerOnlyChangePublishesCompositingUpdate(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- if !frame.Update.Rebuild || frame.Update.Count != 1 || frame.Rectangles[0].Layer != 5 {
+ // The instance whose layer moved must travel, whether as a rebuild or in the range.
+ if !updateCovers(frame.Update, 0) || frame.Rectangles[0].Layer != 5 {
t.Fatalf("rectangle layer update = %+v, rectangles = %+v", frame.Update, frame.Rectangles)
}
if len(frame.TextLabels) != 1 || frame.TextLabels[0].Layer != 5 {
@@ -2719,3 +2720,8 @@ func TestRepaintShrinksWhenAShapeIsRemoved(t *testing.T) {
t.Fatalf("rectangles = %d, want 2", len(frame.Rectangles))
}
}
+
+// updateCovers reports whether update sends the instance at index to the renderer.
+func updateCovers(update render.Update, index int) bool {
+ return update.Rebuild || index >= update.First && index < update.First+update.Count
+}
diff --git a/internal/framebuild/framebuild.go b/internal/framebuild/framebuild.go
index 425b2d587..4219dfde2 100644
--- a/internal/framebuild/framebuild.go
+++ b/internal/framebuild/framebuild.go
@@ -97,8 +97,8 @@ func (builder *Builder) Build() (platform.Frame, error) {
return platform.Frame{}, err
}
}
- if builder.stampState() && !update.Rebuild {
- update = render.Update{Count: len(builder.renderer.Rectangles()), Rebuild: true}
+ if first, end := builder.stampState(); end > first && !update.Rebuild {
+ update = widenUpdate(update, first, end, len(builder.renderer.Rectangles()))
}
frame := platform.Frame{Update: update, Rectangles: builder.renderer.Rectangles()}
@@ -963,16 +963,17 @@ type instanceState struct {
}
// stampState copies each primitive's canvas layer and clip onto its render
-// instance and reports whether either changed anywhere, which a partial update
-// would not carry to the GPU. Instances are listed by the scene's tree order,
+// instance and returns the range [first, end) of instances where either changed
+// (empty when none did): Apply's update does not carry them, so the frame must. Instances are listed by the scene's tree order,
// which syncShapes keeps equal to paint order, so the shape at index i is the
// instance at index i; should the store ever disagree, the state travels with
// the node's storage slot instead.
-func (builder *Builder) stampState() (changed bool) {
+func (builder *Builder) stampState() (first, end int) {
instances := builder.renderer.Rectangles()
if len(instances) != len(builder.shapeIDs) {
return builder.stampBySlot()
}
+ first, end = len(instances), 0
for index, id := range builder.shapeIDs {
instance := &instances[index]
if instance.ID != id {
@@ -981,14 +982,14 @@ func (builder *Builder) stampState() (changed bool) {
state := builder.shapeState(builder.order[index])
if instance.Layer != state.layer || instance.Clipped != state.clipped || instance.Clip != state.clip {
instance.Layer, instance.Clipped, instance.Clip = state.layer, state.clipped, state.clip
- changed = true
+ first, end = min(first, index), index+1
}
}
- return changed
+ return first, end
}
// stampBySlot is stampState for a store whose order is not the paint order.
-func (builder *Builder) stampBySlot() (changed bool) {
+func (builder *Builder) stampBySlot() (first, end int) {
for index, id := range builder.shapeIDs {
slot, ok := id.Slot()
if !ok {
@@ -1000,15 +1001,32 @@ func (builder *Builder) stampBySlot() (changed bool) {
builder.stateBySlot[slot] = builder.shapeState(builder.order[index])
}
instances := builder.renderer.Rectangles()
+ first, end = len(instances), 0
for index := range instances {
slot, _ := instances[index].ID.Slot()
state := builder.stateBySlot[slot]
if instances[index].Layer != state.layer || instances[index].Clipped != state.clipped || instances[index].Clip != state.clip {
instances[index].Layer, instances[index].Clipped, instances[index].Clip = state.layer, state.clipped, state.clip
- changed = true
+ first, end = min(first, index), index+1
}
}
- return changed
+ return first, end
+}
+
+// widenUpdate makes update also carry the instances [first, end) whose layer or
+// clip was stamped. Apply's range already runs to the end of the store's total
+// instances whenever the count grew, and must when it shrank, so the union
+// keeps the suffix form a backend requires.
+func widenUpdate(update render.Update, first, end, total int) render.Update {
+ if update.Shrink {
+ end = total
+ }
+ if update.Count > 0 {
+ end = max(end, update.First+update.Count)
+ first = min(first, update.First)
+ }
+ update.First, update.Count = first, end-first
+ return update
}
// shapeState is the layer and clip the platform draws a shape with.
diff --git a/internal/framebuild/framebuild_test.go b/internal/framebuild/framebuild_test.go
index 3b2671838..9a61b5221 100644
--- a/internal/framebuild/framebuild_test.go
+++ b/internal/framebuild/framebuild_test.go
@@ -6,6 +6,7 @@ import (
"github.com/vivaui/viva/gfx"
"github.com/vivaui/viva/internal/platform"
+ "github.com/vivaui/viva/internal/render"
"github.com/vivaui/viva/internal/scene"
)
@@ -284,3 +285,58 @@ func TestReplaceCellGlyphsMemoFollowsItsInput(t *testing.T) {
t.Fatal("a line without cell glyphs was copied or remembered")
}
}
+
+// A scrolled list whose rows each clip themselves changes only where the clips
+// cut: the frame sends the instances whose clip moved, not the whole page, and
+// when a row leaves while the clips move the update still ends at the new total.
+func TestBuilderSendsOnlyTheInstancesWhoseClipMoved(t *testing.T) {
+ const page, rows = 50, 6
+ scroll, clipTop, shown := float32(0), float32(2), rows
+ paint := func(canvas *gfx.Canvas) {
+ for index := range page {
+ canvas.Fill(gfx.Rect{X: float32(index), Width: 1, Height: 1}, gfx.Color{Alpha: 1})
+ }
+ for index := range shown {
+ top := float32(index*10) - scroll
+ canvas.Clip(gfx.Rect{Y: clipTop, Width: 100, Height: 50})
+ canvas.Fill(gfx.Rect{Y: top, Width: 100, Height: 10}, gfx.Color{Red: 1, Alpha: 1})
+ canvas.Unclip()
+ }
+ }
+ var canvas gfx.Canvas
+ paint(&canvas)
+ builder := New(&canvas)
+ if _, err := builder.Build(); err != nil {
+ t.Fatal(err)
+ }
+ covers := func(update render.Update, index int) bool {
+ return update.Rebuild || index >= update.First && index < update.First+update.Count
+ }
+
+ scroll = 1
+ canvas.Reset()
+ paint(&canvas)
+ frame, err := builder.Build()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if frame.Update.Rebuild || frame.Update.First < page {
+ t.Fatalf("scrolling the clipped rows sent %+v, want only the rows after the %d still shapes", frame.Update, page)
+ }
+ for index := page; index < page+rows; index++ {
+ if !covers(frame.Update, index) {
+ t.Fatalf("row %d moved but the update %+v leaves it behind", index, frame.Update)
+ }
+ }
+
+ clipTop, shown = 3, rows-1
+ canvas.Reset()
+ paint(&canvas)
+ if frame, err = builder.Build(); err != nil {
+ t.Fatal(err)
+ }
+ total := len(frame.Rectangles)
+ if total != page+rows-1 || frame.Update.Rebuild || !frame.Update.Shrink || frame.Update.First+frame.Update.Count != total || !covers(frame.Update, page) {
+ t.Fatalf("a row left while the clips moved: total %d, update %+v, want a shrinking range from row %d to the total", total, frame.Update, page)
+ }
+}
From 8695305d0c10ab8b380076534d97549d8b6eb663 Mon Sep 17 00:00:00 2001
From: t8y2 <1156263951@qq.com>
Date: Sat, 21 Nov 2026 22:55:41 +0800
Subject: [PATCH 19/47] fix(app): compare published hit labels by text, not by
pointer
sameHits compared hit lists as raw bytes, so a label formatted anew every
frame with the same text counted as a structural change and every repaint
rebuilt the region and semantic mirrors (3.4x slower at 4000 hits). The
lists are now compared by value.
---
app/hit_gate_test.go | 16 ++++++++++++++++
app/painter.go | 22 +++++-----------------
2 files changed, 21 insertions(+), 17 deletions(-)
diff --git a/app/hit_gate_test.go b/app/hit_gate_test.go
index f8df45bd0..c02ce3405 100644
--- a/app/hit_gate_test.go
+++ b/app/hit_gate_test.go
@@ -182,3 +182,19 @@ func TestRepaintReleasesFocusWhenThePaintAsksWithoutChangingHits(t *testing.T) {
t.Fatalf("focused = %v, want the focus released", painter.focus.Focused())
}
}
+
+// A page that formats its labels every frame declares the same text in a new
+// allocation each time: that is an unchanged hit list, which keeps the repaint on
+// the path that skips the semantic mirror.
+func TestSameHitsComparesLabelsByText(t *testing.T) {
+ fresh := func(text string) string { return string([]byte(text)) }
+ published := []gfx.Hit{{ID: gfx.Item(1), Label: fresh("Clicked 3 times"), Value: fresh("3")}}
+ current := []gfx.Hit{{ID: gfx.Item(1), Label: fresh("Clicked 3 times"), Value: fresh("3")}}
+ if !sameHits(published, current) {
+ t.Fatal("the same labels in new allocations compared as a change")
+ }
+ current[0].Label = fresh("Clicked 4 times")
+ if sameHits(published, current) {
+ t.Fatal("a changed label compared as unchanged")
+ }
+}
diff --git a/app/painter.go b/app/painter.go
index 3f3b8b1af..c82ea056d 100644
--- a/app/painter.go
+++ b/app/painter.go
@@ -1,7 +1,6 @@
package app
import (
- "bytes"
"errors"
"fmt"
"math"
@@ -9,7 +8,6 @@ import (
"time"
"unicode"
"unicode/utf8"
- "unsafe"
"github.com/vivaui/viva/gfx"
"github.com/vivaui/viva/internal/framebuild"
@@ -1511,22 +1509,12 @@ func (painter *painter) structuresUnchanged() bool {
// sameHits reports whether two hit lists are identical in the fields the
// semantic tree and the accessibility payload read. The text-editor geometry
// lives beside the hits (Canvas.HitText) and feeds neither, so it is not part of
-// the comparison. The structs are compared as bytes: Go strings are immutable,
-// and the published list keeps the previous string allocations reachable, so a
-// matching pointer cannot name different bytes. Padding, and the index into the
-// text table, can only make the comparison stricter (an unnecessary publish),
-// never more permissive.
+// the comparison. Strings compare by content: a page that formats a label every
+// frame makes a new allocation of the same text, and that is an unchanged hit.
+// The index into the text table can only make the comparison stricter (an
+// unnecessary publish), never more permissive.
func sameHits(published, current []gfx.Hit) bool {
- if len(published) != len(current) {
- return false
- }
- if len(published) == 0 {
- return true
- }
- size := int(unsafe.Sizeof(gfx.Hit{}))
- left := unsafe.Slice((*byte)(unsafe.Pointer(unsafe.SliceData(published))), len(published)*size)
- right := unsafe.Slice((*byte)(unsafe.Pointer(unsafe.SliceData(current))), len(current)*size)
- return bytes.Equal(left, right)
+ return slices.Equal(published, current)
}
// recordHitStructures keeps the state that lets the next repaint skip the
From f53eddc1a361d1de4aa5b7625d9cb8799bf3b745 Mon Sep 17 00:00:00 2001
From: t8y2 <1156263951@qq.com>
Date: Sat, 21 Nov 2026 22:55:41 +0800
Subject: [PATCH 20/47] fix(base): hand out released slots in constant time and
stable order
slotPool popped its free list by moving the whole rest of it, so swapping
a 10k-row data set spent most of its time in memmove (5.6 ms for the
turnover alone, now 45 us). The free list is a queue with a head index,
compacted as it is reused, and the slots one sweep releases are taken in
number order, so the names a later paint hands out no longer depend on
map iteration.
---
base/accessors.go | 2 +-
base/names.go | 43 ++++++++++++++++++++++++++++++++++++++-----
base/names_test.go | 46 ++++++++++++++++++++++++++++++++++++++++++++++
3 files changed, 85 insertions(+), 6 deletions(-)
create mode 100644 base/names_test.go
diff --git a/base/accessors.go b/base/accessors.go
index 9a63d4948..4c7494557 100644
--- a/base/accessors.go
+++ b/base/accessors.go
@@ -1893,7 +1893,7 @@ func (x *shortcutEntry) GetRows() gfx.Scope { return x.rows }
func (x *shortcutEntry) GetScope() gfx.Scope { return x.scope }
// GetFree reads the free of slotPool for the styled painting layer.
-func (x *slotPool) GetFree() []freeSlot { return x.free }
+func (x *slotPool) GetFree() []freeSlot { return x.free[x.head:] }
// GetAnimated reads the animated of stateLooks for the styled painting layer.
func (x *stateLooks) GetAnimated() bool { return x.animated }
diff --git a/base/names.go b/base/names.go
index a53e21ce3..c507157ad 100644
--- a/base/names.go
+++ b/base/names.go
@@ -1,6 +1,8 @@
package base
import (
+ "cmp"
+ "slices"
"strings"
"unsafe"
@@ -14,19 +16,39 @@ import (
const slotQuarantine = 2
// slotPool hands out numbers, and takes them back to give again after the quarantine.
+// The free list is a queue: free[head:] waits in release order, and take pops
+// its front without moving the rest, so a paint that releases and claims
+// thousands of rows stays linear.
type slotPool struct {
Next uint32
free []freeSlot
+ head int
+ // unsorted marks a release of this paint that came after a higher number of
+ // the same paint: a sweep releases in map order, and the numbers a paint
+ // hands out should not depend on it.
+ unsorted bool
}
type freeSlot struct{ slot, at uint32 }
func (pool *slotPool) take(epoch uint32) uint32 {
- if len(pool.free) > 0 && epoch-pool.free[0].at >= slotQuarantine {
- slot := pool.free[0].slot
- copy(pool.free, pool.free[1:])
- pool.free = pool.free[:len(pool.free)-1]
- return slot
+ if pool.head < len(pool.free) {
+ if pool.unsorted {
+ slices.SortFunc(pool.free[pool.head:], func(a, b freeSlot) int {
+ if c := cmp.Compare(a.at, b.at); c != 0 {
+ return c
+ }
+ return cmp.Compare(a.slot, b.slot)
+ })
+ pool.unsorted = false
+ }
+ if front := pool.free[pool.head]; epoch-front.at >= slotQuarantine {
+ pool.head++
+ if pool.head == len(pool.free) {
+ pool.free, pool.head = pool.free[:0], 0
+ }
+ return front.slot
+ }
}
slot := pool.Next
pool.Next++
@@ -34,6 +56,17 @@ func (pool *slotPool) take(epoch uint32) uint32 {
}
func (pool *slotPool) give(slot, epoch uint32) {
+ if pool.head > 0 && pool.head >= len(pool.free)-pool.head {
+ // More taken than waiting: move the waiting ones down so the queue
+ // reuses its array, at a cost the takes already paid for.
+ n := copy(pool.free, pool.free[pool.head:])
+ pool.free, pool.head = pool.free[:n], 0
+ }
+ if last := len(pool.free) - 1; last >= pool.head {
+ if prev := pool.free[last]; prev.at == epoch && prev.slot > slot {
+ pool.unsorted = true
+ }
+ }
pool.free = append(pool.free, freeSlot{slot: slot, at: epoch})
}
diff --git a/base/names_test.go b/base/names_test.go
new file mode 100644
index 000000000..e5a6eb4e3
--- /dev/null
+++ b/base/names_test.go
@@ -0,0 +1,46 @@
+package base
+
+import "testing"
+
+// Numbers one paint releases come back after the quarantine in the order of the
+// numbers, whatever order the sweep found them in, so the names a later paint
+// hands out do not depend on map iteration.
+func TestSlotPoolGivesReleasedNumbersBackInOrder(t *testing.T) {
+ var pool slotPool
+ for range 6 {
+ pool.take(1)
+ }
+ for _, slot := range []uint32{4, 1, 5, 0} {
+ pool.give(slot, 2)
+ }
+ if got := pool.take(3); got != 6 {
+ t.Fatalf("a number still in quarantine was handed out: %d", got)
+ }
+ for _, want := range []uint32{0, 1, 4, 5, 7} {
+ if got := pool.take(2 + slotQuarantine); got != want {
+ t.Fatalf("take = %d, want %d", got, want)
+ }
+ }
+}
+
+// Releasing and claiming a whole page of keys at once stays linear: the queue
+// pops its front without moving the rest.
+func BenchmarkSlotPoolTurnover(b *testing.B) {
+ const rows = 10000
+ var pool slotPool
+ epoch := uint32(0)
+ for range rows {
+ pool.take(epoch)
+ }
+ b.ReportAllocs()
+ for b.Loop() {
+ epoch++
+ for slot := range uint32(rows) {
+ pool.give(slot, epoch)
+ }
+ epoch += slotQuarantine
+ for range rows {
+ pool.take(epoch)
+ }
+ }
+}
From 3a8af08cb1ce203ca6589084683a4bc047fd1502 Mon Sep 17 00:00:00 2001
From: t8y2 <1156263951@qq.com>
Date: Sat, 21 Nov 2026 22:55:41 +0800
Subject: [PATCH 21/47] fix(platform): stop idle wakeups in background windows
and prompts
- macOS polls the pasteboard only while the application is active and
compares the change count once when it becomes active again; a
background or status-area application no longer wakes 4 times a second.
- macOS and Linux hide the native caret and stop its blink timer while
the window does not have the keyboard, as a native field does, and show
it again at once when the keyboard returns.
- The Linux Secret Service prompt waits on the bus instead of sleeping
25 ms between non-blocking reads.
Motty registers OnClipboardChange to forward the clipboard to desktop
sessions; the change reaches them when the user returns to the window,
which is when they can use it. No Motty change is needed.
---
app/system.go | 8 ++-
internal/platform/darwin/native.m | 23 +++++-
internal/platform/darwin/system_darwin.m | 71 +++++++++++++++----
internal/platform/linux/secret_linux.go | 10 ++-
internal/platform/linux/text_input_linux.go | 41 +++++++++--
.../platform/linux/text_input_linux_test.go | 48 +++++++++++++
internal/platform/linux/window_linux.go | 34 +++++++--
7 files changed, 204 insertions(+), 31 deletions(-)
diff --git a/app/system.go b/app/system.go
index 621bdbb7e..68b72c2a6 100644
--- a/app/system.go
+++ b/app/system.go
@@ -131,9 +131,11 @@ func ClipboardText() (string, error) {
// stops watching. An error wrapping ErrUnsupported means this target cannot
// watch the clipboard (the Linux and web targets today): the clipboard keeps
// working, only the news is missing, and a caller may fall back to reading it
-// when the user acts. macOS has no change notification, so it polls the
-// pasteboard's change count on a 250 ms timer for as long as a registration is
-// held.
+// when the user acts. macOS has no change notification, so while a
+// registration is held it polls the pasteboard's change count on a 250 ms
+// timer, and only while the application is active: a change made while another
+// application is in front is reported the moment this one becomes active again,
+// and a background application wakes for nothing.
func OnClipboardChange(notify func()) error { return nativeOnClipboardChange(notify) }
func SetClipboardText(value string) error {
diff --git a/internal/platform/darwin/native.m b/internal/platform/darwin/native.m
index 29c04f6d2..f1edebb21 100644
--- a/internal/platform/darwin/native.m
+++ b/internal/platform/darwin/native.m
@@ -5115,6 +5115,13 @@ - (void)keyWindowChanged:(NSNotification *)notification {
notification.object == self.window && _textInputEnabled && _tentativeComposition) {
[self endOwnedNativeComposition];
}
+ if (notification.object == self.window && _textInputEnabled) {
+ BOOL visible = _caretVisible;
+ [self restartCaretBlink];
+ if (_caretVisible != visible && [self rebuildTextTexture]) {
+ [self render];
+ }
+ }
}
- (viva_editor_line)newTextLine {
@@ -5137,8 +5144,16 @@ - (BOOL)rebuildTextTexture {
return YES;
}
+// caretHasKeyboard reports whether the caret belongs on screen at all: as a native
+// text view's insertion point, only while its window is key. A view not yet in a
+// window has nothing to lose it to.
+- (BOOL)caretHasKeyboard {
+ NSWindow *window = self.window;
+ return window == nil || window.isKeyWindow;
+}
+
- (void)caretBlinkTimerFired:(NSTimer *)timer {
- if (timer != _caretTimer || !viva_text_input_caret_should_blink(
+ if (timer != _caretTimer || ![self caretHasKeyboard] || !viva_text_input_caret_should_blink(
_textInputEnabled, _selectedRange.length, _hasMarkedText, _textTerminal, _textHideNativeOverlays)) {
[self stopCaretBlink];
return;
@@ -5160,8 +5175,10 @@ - (void)stopCaretBlink {
- (void)restartCaretBlink {
[self stopCaretBlink];
- _caretVisible = YES;
- if (!viva_text_input_caret_should_blink(
+ // A window in the background shows no caret and keeps no timer, so it wakes
+ // for nothing; becoming key restarts the blink from the visible phase.
+ _caretVisible = [self caretHasKeyboard];
+ if (!_caretVisible || !viva_text_input_caret_should_blink(
_textInputEnabled, _selectedRange.length, _hasMarkedText, _textTerminal, _textHideNativeOverlays)) {
return;
}
diff --git a/internal/platform/darwin/system_darwin.m b/internal/platform/darwin/system_darwin.m
index 0bf9a839f..fbecc0ec7 100644
--- a/internal/platform/darwin/system_darwin.m
+++ b/internal/platform/darwin/system_darwin.m
@@ -37,13 +37,19 @@ static void viva_set_error(char **error_message, NSString *message) {
}
// The pasteboard has no change notification on macOS: what a clipboard viewer watches is its
-// change count, so this polls it on the main queue for as long as a caller wants the news.
-// The timer exists only between viva_system_watch_clipboard(1) and (0); an application that
-// never asks pays nothing.
+// change count, so this polls it on the main queue for as long as a caller wants the news, and
+// only while the application is active. Another application's copy while this one is in the
+// background is found by the comparison made the moment it becomes active again, which is when
+// the news can first matter to the user; a background application, or one that sits in the
+// status area, wakes for nothing. The timer and the observers exist only between
+// viva_system_watch_clipboard(1) and (0); an application that never asks pays nothing.
extern void vivaSystemClipboardChanged(void);
static dispatch_source_t viva_clipboard_timer = NULL;
static NSInteger viva_clipboard_count = 0;
+static BOOL viva_clipboard_watching = NO;
+static id viva_clipboard_became_active = nil;
+static id viva_clipboard_resigned_active = nil;
static void viva_clipboard_poll(void *unused) {
(void)unused;
@@ -75,27 +81,68 @@ static void viva_on_main_async(dispatch_block_t operation) {
dispatch_async(dispatch_get_main_queue(), operation);
}
+static void viva_clipboard_start_timer(void) {
+ if (viva_clipboard_timer != NULL) {
+ return;
+ }
+ viva_clipboard_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
+ dispatch_source_set_timer(viva_clipboard_timer, dispatch_time(DISPATCH_TIME_NOW, 250 * NSEC_PER_MSEC), 250 * NSEC_PER_MSEC, 50 * NSEC_PER_MSEC);
+ dispatch_source_set_event_handler_f(viva_clipboard_timer, viva_clipboard_poll);
+ dispatch_resume(viva_clipboard_timer);
+}
+
+static void viva_clipboard_stop_timer(void) {
+ if (viva_clipboard_timer != NULL) {
+ dispatch_source_cancel(viva_clipboard_timer);
+ viva_clipboard_timer = NULL;
+ }
+}
+
// viva_system_watch_clipboard starts (enable 1) or stops (0) reporting changes of the
-// pasteboard. Starting twice does nothing. The timer changes on the main queue in the order
+// pasteboard. Starting twice does nothing. The watch changes on the main queue in the order
// the calls were made; a notification after a stop is dropped on the Go side, which clears its
// callback before this runs.
void viva_system_watch_clipboard(int enable) {
viva_on_main_async(^{
+ NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
if (!enable) {
- if (viva_clipboard_timer != NULL) {
- dispatch_source_cancel(viva_clipboard_timer);
- viva_clipboard_timer = NULL;
+ if (!viva_clipboard_watching) {
+ return;
}
+ viva_clipboard_watching = NO;
+ viva_clipboard_stop_timer();
+ [center removeObserver:viva_clipboard_became_active];
+ [center removeObserver:viva_clipboard_resigned_active];
+ [viva_clipboard_became_active release];
+ [viva_clipboard_resigned_active release];
+ viva_clipboard_became_active = nil;
+ viva_clipboard_resigned_active = nil;
return;
}
- if (viva_clipboard_timer != NULL) {
+ if (viva_clipboard_watching) {
return;
}
+ viva_clipboard_watching = YES;
viva_clipboard_count = [NSPasteboard generalPasteboard].changeCount;
- viva_clipboard_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
- dispatch_source_set_timer(viva_clipboard_timer, dispatch_time(DISPATCH_TIME_NOW, 250 * NSEC_PER_MSEC), 250 * NSEC_PER_MSEC, 50 * NSEC_PER_MSEC);
- dispatch_source_set_event_handler_f(viva_clipboard_timer, viva_clipboard_poll);
- dispatch_resume(viva_clipboard_timer);
+ NSOperationQueue *main = [NSOperationQueue mainQueue];
+ viva_clipboard_became_active = [[center addObserverForName:NSApplicationDidBecomeActiveNotification
+ object:nil
+ queue:main
+ usingBlock:^(NSNotification *note) {
+ (void)note;
+ viva_clipboard_poll(NULL);
+ viva_clipboard_start_timer();
+ }] retain];
+ viva_clipboard_resigned_active = [[center addObserverForName:NSApplicationDidResignActiveNotification
+ object:nil
+ queue:main
+ usingBlock:^(NSNotification *note) {
+ (void)note;
+ viva_clipboard_stop_timer();
+ }] retain];
+ if (NSApp == nil || NSApp.active) {
+ viva_clipboard_start_timer();
+ }
});
}
diff --git a/internal/platform/linux/secret_linux.go b/internal/platform/linux/secret_linux.go
index 7a8b5b1ef..277acd434 100644
--- a/internal/platform/linux/secret_linux.go
+++ b/internal/platform/linux/secret_linux.go
@@ -124,8 +124,13 @@ func (store *secretStore) waitPrompt(prompt string) error {
return secretCallError("show a prompt", err)
}
deadline := time.Now().Add(promptTimeout)
- for time.Now().Before(deadline) {
- messages, err := store.conn.Receive()
+ for {
+ remaining := time.Until(deadline)
+ if remaining <= 0 {
+ break
+ }
+ // Block on the bus until something arrives: the user may take minutes.
+ messages, err := store.conn.Wait(remaining)
if err != nil {
return fmt.Errorf("linux: secret service prompt: %w", err)
}
@@ -138,7 +143,6 @@ func (store *secretStore) waitPrompt(prompt string) error {
return nil
}
}
- time.Sleep(25 * time.Millisecond)
}
return fmt.Errorf("%w: the prompt was not answered", platform.ErrSecretDenied)
}
diff --git a/internal/platform/linux/text_input_linux.go b/internal/platform/linux/text_input_linux.go
index 2fec649eb..e98ca94bc 100644
--- a/internal/platform/linux/text_input_linux.go
+++ b/internal/platform/linux/text_input_linux.go
@@ -32,7 +32,10 @@ type linuxTextInput struct {
stateRevision uint64
inputRevision uint64
- caretVisible bool
+ caretVisible bool
+ // unfocused is a window that lost the keyboard: its field shows no caret and
+ // nothing blinks until the keyboard comes back, as a native field does.
+ unfocused bool
caretGeneration uint32
caretTimer *time.Timer
postCaret func(uint32)
@@ -709,11 +712,39 @@ func (state *linuxTextInput) currentTextFrame() platform.Frame {
return platform.Frame{TextInput: platform.TextInputUpdate{Changed: true, Input: current}}
}
-// caretShown says whether the field has a native caret to draw: not a terminal,
-// not while a component paints its own caret, not while composing, and not
-// over a selection.
+// caretShown says whether the field has a native caret to draw: not in a window
+// without the keyboard, not a terminal, not while a component paints its own
+// caret, not while composing, and not over a selection.
func (state *linuxTextInput) caretShown() bool {
- return state.enabled && !state.input.Terminal && !state.input.HideNativeOverlays && !state.state.Composing && state.state.Selection.Start == state.state.Selection.End
+ return state.enabled && !state.unfocused && !state.input.Terminal && !state.input.HideNativeOverlays && !state.state.Composing && state.state.Selection.Start == state.state.Selection.End
+}
+
+// setWindowFocused follows the window gaining or losing the keyboard: the caret
+// shows again and blinks from its visible phase, or hides and its timer stops, so
+// a window in the background wakes for nothing. The frame redraws the caret's one
+// rectangle.
+func (state *linuxTextInput) setWindowFocused(focused bool) (platform.Frame, bool) {
+ if state.unfocused == !focused {
+ return platform.Frame{}, false
+ }
+ state.unfocused = !focused
+ state.restartCaretBlink()
+ index := len(state.baseRectangles) + 1
+ if !state.enabled || state.input.Terminal || index >= len(state.rectangles) {
+ return platform.Frame{}, false
+ }
+ caret := render.Rectangle{}
+ if state.caretShown() {
+ caret = state.caret
+ }
+ if state.rectangles[index] == caret {
+ return platform.Frame{}, false
+ }
+ state.rectangles[index] = caret
+ return platform.Frame{
+ Update: render.Update{First: index, Count: 1},
+ Rectangles: state.rectangles,
+ }, true
}
func (state *linuxTextInput) caretShouldBlink() bool {
diff --git a/internal/platform/linux/text_input_linux_test.go b/internal/platform/linux/text_input_linux_test.go
index 09b4c42c0..315363d96 100644
--- a/internal/platform/linux/text_input_linux_test.go
+++ b/internal/platform/linux/text_input_linux_test.go
@@ -141,6 +141,54 @@ func TestLinuxCaretBlinkUpdatesOnlyCaretAndRejectsStaleTicks(t *testing.T) {
}
}
+// A window in the background shows no caret and arms no blink timer, so it wakes
+// for nothing; the keyboard coming back shows the caret at once and blinks again.
+func TestLinuxCaretStopsWhileTheWindowHasNoKeyboard(t *testing.T) {
+ config := platform.Config{DynamicTextInput: true}
+ state := &linuxTextInput{
+ config: &config,
+ engine: fixedAdvanceEngine{},
+ postCaret: func(uint32) {},
+ }
+ inputState := platform.TextInput{
+ Width: 120, Height: 28, FontSize: 16,
+ Color: platform.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1},
+ State: platform.TextState{Value: "A", Selection: text.Range{Start: 1, End: 1}},
+ OnEvent: func(platform.TextEvent) (platform.TextState, error) { return platform.TextState{}, nil },
+ }
+ if _, _, err := state.prepare(platform.Frame{TextInput: platform.TextInputUpdate{Changed: true, Input: &inputState}}); err != nil {
+ t.Fatal(err)
+ }
+ defer state.stopCaretBlink()
+ caretIndex := len(state.baseRectangles) + 1
+ if state.caretTimer == nil || state.rectangles[caretIndex] == (render.Rectangle{}) {
+ t.Fatalf("focused field: timer=%v caret=%+v, want a blinking caret", state.caretTimer != nil, state.rectangles[caretIndex])
+ }
+ generation := state.caretGeneration
+
+ frame, changed := state.setWindowFocused(false)
+ if !changed || frame.Update != (render.Update{First: caretIndex, Count: 1}) || frame.Rectangles[caretIndex] != (render.Rectangle{}) {
+ t.Fatalf("focus lost = changed:%v update:%+v caret:%+v, want the caret hidden", changed, frame.Update, frame.Rectangles[caretIndex])
+ }
+ if state.caretTimer != nil {
+ t.Fatal("a window without the keyboard still arms the blink timer")
+ }
+ if _, changed := state.blinkCaret(generation); changed {
+ t.Fatal("a tick from before the focus left still blinks the caret")
+ }
+ if err := state.rebuild(); err != nil || state.rectangles[caretIndex] != (render.Rectangle{}) {
+ t.Fatalf("rebuild without the keyboard: caret=%+v err=%v, want none", state.rectangles[caretIndex], err)
+ }
+
+ frame, changed = state.setWindowFocused(true)
+ if !changed || frame.Rectangles[caretIndex] == (render.Rectangle{}) || state.caretTimer == nil {
+ t.Fatalf("focus back = changed:%v caret:%+v timer:%v, want the caret shown and blinking", changed, frame.Rectangles[caretIndex], state.caretTimer != nil)
+ }
+ if _, changed := state.setWindowFocused(true); changed {
+ t.Fatal("a repeated focus-in changed the frame")
+ }
+}
+
func TestLinuxTextPointerPlacesCaretAtNearestCharacter(t *testing.T) {
editor := text.NewEditor("abcd")
inputState := platform.TextInput{
diff --git a/internal/platform/linux/window_linux.go b/internal/platform/linux/window_linux.go
index 7e529a29f..0603bd7b7 100644
--- a/internal/platform/linux/window_linux.go
+++ b/internal/platform/linux/window_linux.go
@@ -870,6 +870,24 @@ func (state *linuxWindowState) refreshReadOnlyTextInput() error {
return state.router.presentFrame(config.OnRedraw())
}
+// presentCaret draws a frame that changed only the native caret.
+func presentCaret(renderer windowRenderer, frame platform.Frame) error {
+ dirty, err := renderer.apply(frame)
+ if err == nil && dirty {
+ err = renderer.present()
+ }
+ return err
+}
+
+// followFocus shows or hides the native caret as the window gains or loses the
+// keyboard.
+func followFocus(renderer windowRenderer, textInput *linuxTextInput, focused bool) error {
+ if frame, changed := textInput.setWindowFocused(focused); changed {
+ return presentCaret(renderer, frame)
+ }
+ return nil
+}
+
func (state *linuxWindowState) handleEvent(event unsafe.Pointer) (bool, error) {
win, config, textInput, renderer, router := state.win, state.config, state.text, state.renderer, state.router
if !win.preview {
@@ -921,11 +939,7 @@ func (state *linuxWindowState) handleEvent(event unsafe.Pointer) (bool, error) {
case message.Format == 32 && message.Window == win.id && message.Type == win.caretAtom:
generation := binary.LittleEndian.Uint32(message.Data[:4])
if frame, changed := textInput.blinkCaret(generation); changed {
- dirty, err := renderer.apply(frame)
- if err == nil && dirty {
- err = renderer.present()
- }
- return false, err
+ return false, presentCaret(renderer, frame)
}
case message.Format == 32 && message.Window == win.id && message.Type == win.redrawAtom && config.OnRedraw != nil:
frame, err := config.OnRedraw()
@@ -1148,6 +1162,11 @@ func (state *linuxWindowState) handleEvent(event unsafe.Pointer) (bool, error) {
if router.ime != nil && realFocus {
router.ime.setFocused(true)
}
+ if realFocus {
+ if err := followFocus(renderer, textInput, true); err != nil {
+ return false, err
+ }
+ }
case xcbFocusOut:
state.application.atspiActive(state, false)
focus := (*xcbFocusEvent)(event)
@@ -1164,6 +1183,11 @@ func (state *linuxWindowState) handleEvent(event unsafe.Pointer) (bool, error) {
if router.ime != nil && realFocusLoss {
router.ime.setFocused(false)
}
+ if realFocusLoss {
+ if err := followFocus(renderer, textInput, false); err != nil {
+ return false, err
+ }
+ }
if realFocusLoss {
if err := state.releaseHeldKeys(); err != nil {
return false, err
From 76824aadc06c96fde18a406673154ca39a68bf73 Mon Sep 17 00:00:00 2001
From: t8y2
Date: Sat, 21 Nov 2026 23:12:14 +0800
Subject: [PATCH 22/47] fix(website): name the graph component in the sidebar
The catalog gained a Graph component, and the site test requires a Chinese
name for every page.
---
website/src/lib/i18n.ts | 1 +
1 file changed, 1 insertion(+)
diff --git a/website/src/lib/i18n.ts b/website/src/lib/i18n.ts
index 83a41458b..722945e04 100644
--- a/website/src/lib/i18n.ts
+++ b/website/src/lib/i18n.ts
@@ -158,6 +158,7 @@ const chineseComponentNames: Record = {
'single-select': '单选',
'avatar-editor': '头像编辑器',
'image-view': '图片视图',
+ graph: '关系图谱',
'column-resize': '列宽调整',
'reorder-grid': '排序网格',
'reorder-list': '排序列表',
From 0ab9054c132501d948410b1bc09a33575162bf4d Mon Sep 17 00:00:00 2001
From: t8y2
Date: Sat, 21 Nov 2026 23:12:14 +0800
Subject: [PATCH 23/47] fix(web): give the clipboard test a PNG its check can
read
CheckClipboardPNG now reads the header, so the stand-in bytes stopped
decoding; the test carries a real 1x1 PNG instead.
---
internal/platform/web/clipboard_image_js_test.go | 8 +++++---
1 file changed, 5 insertions(+), 3 deletions(-)
diff --git a/internal/platform/web/clipboard_image_js_test.go b/internal/platform/web/clipboard_image_js_test.go
index 21cf200a2..742d05d6a 100644
--- a/internal/platform/web/clipboard_image_js_test.go
+++ b/internal/platform/web/clipboard_image_js_test.go
@@ -39,15 +39,17 @@ func readImage(t *testing.T) ([]byte, error) {
}
}
-const pngHeader = "new Uint8Array([0x89,0x50,0x4e,0x47,0x0d,0x0a,0x1a,0x0a,1,2,3])"
+// pngPicture is a 1x1 PNG: the clipboard check reads its header, so the bytes
+// must decode as one.
+const pngPicture = "new Uint8Array([0x89,0x50,0x4e,0x47,0x0d,0x0a,0x1a,0x0a,0x00,0x00,0x00,0x0d,0x49,0x48,0x44,0x52,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x08,0x06,0x00,0x00,0x00,0x1f,0x15,0xc4,0x89,0x00,0x00,0x00,0x0b,0x49,0x44,0x41,0x54,0x78,0x9c,0x63,0x60,0x00,0x02,0x00,0x00,0x05,0x00,0x01,0x7a,0x5e,0xab,0x3f,0x00,0x00,0x00,0x00,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82])"
func TestReadClipboardImagePNG(t *testing.T) {
installClipboard(t, `return { read: () => Promise.resolve([
{ types: ["text/plain"], getType: () => Promise.reject(new Error("text")) },
- { types: ["image/png"], getType: () => Promise.resolve(new Blob([`+pngHeader+`])) },
+ { types: ["image/png"], getType: () => Promise.resolve(new Blob([`+pngPicture+`])) },
]) }`)
png, err := readImage(t)
- if err != nil || len(png) != 11 || png[1] != 'P' {
+ if err != nil || len(png) != 68 || png[1] != 'P' {
t.Fatalf("png = %d bytes, %v", len(png), err)
}
}
From 5da48b6f0c46d1689dc4c83a0c20f65706623e11 Mon Sep 17 00:00:00 2001
From: Lichenkang <2188718831@qq.com>
Date: Sat, 21 Nov 2026 07:30:56 -0800
Subject: [PATCH 24/47] feat(ui): fill the control gaps in fields, splitter,
tooltip and tree
---
base/elements.go | 5 +-
base/input_disabled_test.go | 26 ++++++
base/leaves_test.go | 71 ++++++++++++++++-
base/page.go | 9 +++
base/page_bases.go | 2 +-
base/splitter.go | 133 +++++++++++++++++++++++++++----
base/tree.go | 3 +
cmd/viva/initfiles/AGENTS.md.txt | 8 +-
cmd/viva/templates/input.go.txt | 2 +-
cmd/viva/templates/tree.go.txt | 12 +++
components/input.go | 2 +-
components/tree.go | 12 +++
components/tree_test.go | 34 ++++++++
examples/guides/input/main.go | 6 +-
gfx/theme.go | 6 ++
ui/controls_paint.go | 14 ++++
ui/radio_disabled_test.go | 26 ++++++
ui/splitter_page_test.go | 60 ++++++++++++++
ui/tooltip_paint.go | 2 +-
ui/tooltip_test.go | 26 ++++++
ui/tree_paint.go | 2 +-
21 files changed, 428 insertions(+), 33 deletions(-)
create mode 100644 base/input_disabled_test.go
create mode 100644 ui/radio_disabled_test.go
create mode 100644 ui/splitter_page_test.go
diff --git a/base/elements.go b/base/elements.go
index 7bba3d6b0..19846c536 100644
--- a/base/elements.go
+++ b/base/elements.go
@@ -246,8 +246,11 @@ func Slider(c C, state *SliderState) Box {
return c.f.Slider(c.page.boundID(pkSlider, unsafe.Pointer(state)), state)
}
-// Splitter is a draggable divider between the panes around it, at state.Pos.
+// Splitter is a draggable divider between the panes around it, at state.Pos. The
+// page routes the arrow keys of the focused divider to SplitterState.Key, so they
+// work without giving it to the window's key callback.
func Splitter(c C, state *SplitterState) Box {
+ c.page.splits(state)
return c.f.Splitter(c.page.boundID(pkSplitter, unsafe.Pointer(state)), state)
}
diff --git a/base/input_disabled_test.go b/base/input_disabled_test.go
new file mode 100644
index 000000000..03b79930e
--- /dev/null
+++ b/base/input_disabled_test.go
@@ -0,0 +1,26 @@
+package base
+
+import (
+ "testing"
+
+ "github.com/vivaui/viva/gfx"
+)
+
+// Disabled is the declaration's as well as the snapshot's: a field disabled by a
+// condition after it was declared is not a tab stop and takes no press, as the other
+// controls do.
+func TestDisabledFieldMarksItsHitDisabled(t *testing.T) {
+ var view View
+ canvas := testCanvas()
+ id := gfx.Item(5)
+ view.Draw(canvas, gfx.LightTheme(), gfx.Rect{Width: 240, Height: 80}, func(f *Frame) {
+ f.Input(InputSnapshot{ID: id, Label: "Name", Value: "Gopher"}).Disabled(true)
+ })
+ hits := canvas.Hits()
+ if len(hits) != 1 || hits[0].ID != id {
+ t.Fatalf("hits = %+v", hits)
+ }
+ if !hits[0].Disabled || hits[0].Focusable {
+ t.Fatalf("a disabled field's hit = %+v, want disabled and not focusable", hits[0])
+ }
+}
diff --git a/base/leaves_test.go b/base/leaves_test.go
index 49d70dc4e..b80931300 100644
--- a/base/leaves_test.go
+++ b/base/leaves_test.go
@@ -185,9 +185,6 @@ func TestSplitterKeepsItsPositionInRangeWhenTheWindowShrinksAndTakesArrowKeys(t
if want := float32(400 - splitterThickness - 150); state.Pos != want {
t.Errorf("after the window shrank the first pane is %v, want %v", state.Pos, want)
}
- if _, asked := canvas.NextFrame(); !asked {
- t.Error("moving the position asked for no frame, so the panes would lag behind it")
- }
if got := state.Key(gfx.KeyEvent{Key: gfx.KeyLeft, Target: omit}); got.Handled {
t.Error("an arrow key for another control moved the splitter")
}
@@ -406,3 +403,71 @@ func TestSplitterThicknessKeepsTheLineThinAndTheGrabWide(t *testing.T) {
t.Fatalf("the strip %v does not cover the line at 200", bar)
}
}
+
+// A width the user chose comes back when a window that was too narrow for it grows
+// again, and Maxs bounds the panes from either side.
+func TestSplitterKeepsItsPreferredWidthAndHonoursMaxs(t *testing.T) {
+ var view View
+ state := SplitterState{Pos: 300}
+ canvas := testCanvas()
+ draw := func(width float32) {
+ canvas.Reset()
+ view.Draw(canvas, gfx.LightTheme(), gfx.Rect{Width: width, 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).Maxs(360, 0)
+ f.Column().Grow(1).Children(func() { f.Text("right") })
+ })
+ })
+ }
+ draw(500)
+ if state.Pos != 300 {
+ t.Fatalf("the first pane is %v, want 300", state.Pos)
+ }
+ draw(400)
+ if want := float32(400 - splitterThickness - 150); state.Pos != want {
+ t.Fatalf("after the window shrank the first pane is %v, want %v", state.Pos, want)
+ }
+ draw(500)
+ if state.Pos != 300 {
+ t.Fatalf("after the window grew the first pane is %v, want its preferred 300", state.Pos)
+ }
+
+ // The greatest size of the second pane is the least size of the first.
+ state = SplitterState{Pos: 100}
+ draw = func(width float32) {
+ canvas.Reset()
+ view.Draw(canvas, gfx.LightTheme(), gfx.Rect{Width: width, 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, 50).Maxs(0, 120)
+ f.Column().Grow(1).Children(func() { f.Text("right") })
+ })
+ })
+ }
+ draw(500)
+ if want := float32(500 - splitterThickness - 120); state.Pos != want {
+ t.Fatalf("a second pane capped at 120 put the first at %v, want %v", state.Pos, want)
+ }
+}
+
+// Maxs caps the first pane from above, and End takes a focused splitter to that cap.
+func TestSplitterMaxsCapsTheFirstPane(t *testing.T) {
+ var view View
+ state := SplitterState{Pos: 300}
+ canvas := testCanvas()
+ view.Draw(canvas, gfx.LightTheme(), gfx.Rect{Width: 500, 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, 100).Maxs(180, 0)
+ f.Column().Grow(1).Children(func() { f.Text("right") })
+ })
+ })
+ if state.Pos != 180 {
+ t.Fatalf("the first pane is %v, want Maxs' 180", state.Pos)
+ }
+ state.Key(gfx.KeyEvent{Key: gfx.KeyEnd, Target: splitID})
+ if state.Pos != 180 {
+ t.Fatalf("End put the first pane at %v, want Maxs' 180", state.Pos)
+ }
+}
diff --git a/base/page.go b/base/page.go
index 4e829b168..fe9f75d43 100644
--- a/base/page.go
+++ b/base/page.go
@@ -279,6 +279,7 @@ type Page struct {
drags []*DragState // the DragStates of the last paint
drag *DragState // the one following a press, if any
listStates []*ListState // the Lists of the last paint
+ splitters []*SplitterState // the Splitters of the last paint
tables []tableRoute // the Tables of the last paint, for the wheel and keys under the pointer
pointer gfx.Point // where the pointer was at the last pointer event
pointerIn bool // a pointer event put it there, and no exit has taken it away
@@ -311,6 +312,7 @@ type Page struct {
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
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)
@@ -447,6 +449,11 @@ func (p *Page) RouteKey(event gfx.KeyEvent) (gfx.EventResult, bool) {
return result, true
}
}
+ if p.splitRoute != nil {
+ if result, ok := p.splitRoute(p, event); ok {
+ return result, true
+ }
+ }
if p.sliderRoute != nil {
if result, ok := p.sliderRoute(p, event); ok {
return result, true
@@ -760,6 +767,8 @@ func (p *Page) paintOnce(Surface *gfx.Canvas, bounds Rect, View func(C)) {
p.rovers = p.rovers[:0]
clear(p.sliders)
p.sliders = p.sliders[:0]
+ clear(p.splitters)
+ p.splitters = p.splitters[:0]
p.groups, p.groupIDs = p.groups[:0], p.groupIDs[:0]
clear(p.contexts)
p.contexts = p.contexts[:0]
diff --git a/base/page_bases.go b/base/page_bases.go
index bb7f14bb1..d41ebb5f7 100644
--- a/base/page_bases.go
+++ b/base/page_bases.go
@@ -104,7 +104,7 @@ func TabBase[T comparable](c C, Value *T, tab T, Label string) Box {
// choose writes option into *value when b is clicked, and records whether it changed.
func choose[T comparable](c C, b Box, Value *T, option T) {
- changed := c.f.Surface != nil && b.N().Flags&flagVeto == 0 && c.f.Surface.Clicked(b.N().ID) && *Value != option
+ changed := c.f.Surface != nil && b.N().Flags&(flagVeto|flagDisabled) == 0 && c.f.Surface.Clicked(b.N().ID) && *Value != option
if changed {
*Value = option
}
diff --git a/base/splitter.go b/base/splitter.go
index 66273f87a..bb07c7f1f 100644
--- a/base/splitter.go
+++ b/base/splitter.go
@@ -14,7 +14,9 @@ const (
// Pos is the size in pixels of the pane before the splitter (its width in a Row, its
// height in a Column); set it before the first frame (a zero Pos is the pane's
// minimum), give the pane that size, and a drag, an arrow key or a window resize
-// keeps it inside the limits. The rest is bookkeeping.
+// keeps it inside the limits. A width the user chose is remembered even while the
+// window is too narrow for it, and comes back when the window grows; assign Pos
+// between paints to choose a new one. The rest is bookkeeping.
type SplitterState struct {
// StepFraction, when positive, makes an arrow key move the splitter that
// share of the room it has (the component's 5% step) instead of 16 pixels.
@@ -25,8 +27,14 @@ type SplitterState struct {
// two thirds" without knowing the window's size, and a resize keeps the
// proportion. A drag or an arrow key updates Ratio from the new position;
// set Ratio to zero to hold Pos as pixels instead.
- Ratio float32
- ID gfx.ID
+ Ratio float32
+ ID gfx.ID
+ // preferred is the width the user chose, which Pos is clamped from when the
+ // window is temporarily too narrow; applied is the Pos the last layout left, so
+ // a Pos the program assigned between paints is taken as the new preference.
+ preferred float32
+ applied float32
+ hasPreferred bool
dragging bool
startPointer float32
startPos float32
@@ -39,8 +47,9 @@ type SplitterState struct {
func (s *SplitterState) Dragging() bool { return s.dragging }
// Key moves a focused splitter: Left and Up shrink the first pane, Right and Down
-// grow it by 16 pixels, Home and End take it to its smallest and largest. Give it to
-// Config.OnKey (or call it from yours); it ignores every other key and every other
+// grow it by 16 pixels, Home and End take it to its smallest and largest. A Splitter
+// declared in a Page gives it to the page's key routing; a Splitter declared on a
+// Frame is given it through Config.OnKey. It ignores every other key and every other
// focus.
func (s *SplitterState) Key(event gfx.KeyEvent) gfx.EventResult {
if s.ID.IsZero() || event.Target != s.ID {
@@ -68,10 +77,33 @@ func (s *SplitterState) Key(event gfx.KeyEvent) gfx.EventResult {
return gfx.EventResult{}
}
s.Pos = s.limit(pos)
+ s.preferred, s.applied = s.Pos, s.Pos
s.keepRatio()
return gfx.EventResult{Handled: true, Repaint: true}
}
+// splits records that state, a Splitter declared in this paint, takes the keys that
+// move its divider while it has the focus.
+func (p *Page) splits(state *SplitterState) {
+ p.splitters = append(p.splitters, state)
+ if p.splitRoute == nil {
+ p.keyRoute, p.splitRoute = (*Page).RouteKey, (*Page).splitKey
+ }
+}
+
+// splitKey gives a key to the Splitter that has the focus.
+func (p *Page) splitKey(event gfx.KeyEvent) (gfx.EventResult, bool) {
+ if event.Release {
+ return gfx.EventResult{}, false
+ }
+ for _, state := range p.splitters {
+ if result := state.Key(event); result.Handled {
+ return result, true
+ }
+ }
+ return gfx.EventResult{}, false
+}
+
// keepRatio stores the pane's current share after a drag or a key, so a window
// resize keeps the proportion the user chose. A state that holds Pos in pixels
// (Ratio zero) is left alone.
@@ -94,9 +126,10 @@ func (s *SplitterState) limit(pos float32) float32 {
}
type SplitDecl struct {
- state *SplitterState
- First int32 // the pane before the splitter, or -1
- minFirst, minSecond float32
+ state *SplitterState
+ First int32 // the pane before the splitter, or -1
+ minFirst, maxFirst float32
+ minSecond, maxSecond float32
// thickness is the room the divider takes in the layout; zero is the
// default strip. The pointer's strip is never narrower than that default.
thickness float32
@@ -115,8 +148,10 @@ type SplitDecl struct {
//
// The pointer is captured for the drag, so it may leave the strip, and the cursor
// shows the resize shape over it; with the keyboard, SplitterState.Key moves it. Mins
-// sets the least size of the first and the second pane (48 each by default). The
-// divider is 8 pixels thick, as long as the container is across.
+// sets the least size of the first and the second pane (48 each by default), Maxs the
+// greatest. A window too narrow for the width the user chose clamps the panes without
+// forgetting it, so they return to it when the window grows. The divider is 8 pixels
+// thick, as long as the container is across.
func (f *Frame) Splitter(ID gfx.ID, state *SplitterState) Box {
first := int32(-1)
if f.Parent >= 0 {
@@ -127,10 +162,26 @@ func (f *Frame) Splitter(ID gfx.ID, state *SplitterState) Box {
n.ID = ID
n.Aux = int32(len(WidgetsOf(f).splits))
WidgetsOf(f).splits = append(WidgetsOf(f).splits, SplitDecl{state: state, First: first, minFirst: splitterMin, minSecond: splitterMin})
+ state.adopt()
state.ID = ID
return b
}
+// adopt keeps the width the state holds as the preferred one: the width first
+// declared, or one the program assigned between paints. reportSplitters only
+// clamps Pos, so a window that is briefly too narrow does not replace it.
+//
+// A splitter that named no size keeps sizing its first pane as the pane asks, as it
+// did before: Pos starts at zero, which is "unset" there rather than the minimum it
+// means once the splitter owns the pane, so a zero is only taken as a choice after a
+// width was chosen. That also keeps a Pos the page clamped, which reportSplitters
+// records in applied, from becoming a preferred width of its own.
+func (s *SplitterState) adopt() {
+ if s.Pos != s.applied && (s.hasPreferred || s.Pos > 0) {
+ s.preferred, s.applied, s.hasPreferred = s.Pos, s.Pos, true
+ }
+}
+
// SplitterThickness sets how much room the divider takes in the layout, for a
// split whose panes should meet with a hairline between them. The pointer's strip
// stays at least as wide as the default (8), centred on the line, so a one-pixel
@@ -151,6 +202,20 @@ func (b Box) Mins(First, second float32) Box {
return b
}
+// Maxs sets the greatest size of the panes either side of a Splitter, along its
+// container; it combines with the room there is. A max of zero is no greatest size,
+// and the pane's minimum wins over it when the two are said to be smaller than each
+// other.
+//
+// ui.Splitter(c, &m.split).Mins(120, 200).Maxs(400, 0)
+func (b Box) Maxs(first, second float32) Box {
+ if n := b.N(); n.Kind == kindSplitter {
+ d := &WidgetsOf(b.f).splits[n.Aux]
+ d.maxFirst, d.maxSecond = max(first, 0), max(second, 0)
+ }
+ return b
+}
+
// splitsRow reports whether the splitter's container lays out left to right, so its
// bar is vertical and its pointer coordinate is x.
func (f *Frame) splitsRow(n *Node) bool { return n.Parent < 0 || f.Nodes[n.Parent].Dir != column }
@@ -183,8 +248,22 @@ func (f *Frame) splitLimits(n *Node) (lo, hi, Span float32) {
first, second := &f.Nodes[d.First], &f.Nodes[n.Next]
Span = *origin(&second.Rect, axis) + *extent(&second.Rect, axis) - *origin(&first.Rect, axis)
gaps := Span - *extent(&first.Rect, axis) - *extent(&n.Rect, axis) - *extent(&second.Rect, axis)
- hi = Span - *extent(&n.Rect, axis) - gaps - d.minSecond
- return lo, max(hi, lo), Span
+ lo, hi = splitBounds(d.minFirst, d.maxFirst, d.minSecond, d.maxSecond, Span, gaps, *extent(&n.Rect, axis))
+ return lo, hi, Span
+}
+
+// splitBounds is the least and greatest size of the first pane for a span the two
+// panes and the splitter share, with the gaps between them: what Mins and Maxs say,
+// bounded by the room.
+func splitBounds(minFirst, maxFirst, minSecond, maxSecond, span, gaps, thickness float32) (lo, hi float32) {
+ lo, hi = max(minFirst, 0), span-gaps-thickness-max(minSecond, 0)
+ if maxSecond > 0 {
+ lo = max(lo, span-gaps-thickness-maxSecond)
+ }
+ if maxFirst > 0 {
+ hi = min(hi, maxFirst)
+ }
+ return lo, max(hi, lo)
}
// placeSplitRatios gives every splitter with a Ratio its first pane's size on
@@ -207,19 +286,35 @@ func (f *Frame) placeSplitRatios(n *Node, axis int, avail float32) {
}
d := &WidgetsOf(f).splits[bar.Aux]
state := d.state
- if state.Ratio <= 0 || d.First < 0 {
+ if d.First < 0 {
continue
}
thickness := bar.Pref[axis]
if thickness <= 0 {
thickness = splitterThickness
}
- lo := d.minFirst
- hi := max(avail-gaps-thickness-d.minSecond, lo)
- pos := min(max(state.Ratio*(avail-gaps-thickness), lo), hi)
+ lo, hi := splitBounds(d.minFirst, d.maxFirst, d.minSecond, d.maxSecond, avail, gaps, thickness)
+ var pos float32
+ switch {
+ case state.Ratio > 0:
+ pos = state.Ratio * (avail - gaps - thickness)
+ case state.hasPreferred:
+ // The width the user chose is what the pane goes back to when the room
+ // allows it again; Pos itself may have been clamped last frame.
+ pos = state.preferred
+ default:
+ continue
+ }
+ // As limit does: the upper bound only applies when there is room to move
+ // within, so a pane the application sized past a too-small room keeps its
+ // size, as it did before the splitter remembered one.
+ if hi > lo {
+ pos = min(pos, hi)
+ }
+ pos = max(pos, lo)
first := &f.Nodes[d.First]
first.Raw[axis], first.Pref[axis] = pos, pos
- state.Pos = pos
+ state.Pos, state.applied = pos, pos
state.thickness = thickness
state.lo, state.hi, state.Span = lo, hi, avail
}
@@ -243,11 +338,14 @@ func (f *Frame) reportSplitters() {
}
s.thickness = *extent(&n.Rect, axis)
if pos := s.limit(s.Pos); pos != s.Pos {
+ // Pos follows the room the layout found; preferred stays as the user left
+ // it, so placeSplitRatios gives the pane that width when there is room.
s.Pos = pos
if f.Surface != nil {
f.Surface.RequestFrame()
}
}
+ s.applied = s.Pos
}
}
@@ -271,6 +369,7 @@ func (f *Frame) PaintSplitter(n *Node) {
case event.Kind == gfx.PointerMove && s.dragging:
s.lo, s.hi, s.Span = f.splitLimits(n)
s.Pos = s.limit(s.startPos + pointer - s.startPointer)
+ s.preferred, s.applied = s.Pos, s.Pos
s.keepRatio()
canvas.Consume()
case event.Kind == gfx.PointerUp && s.dragging:
diff --git a/base/tree.go b/base/tree.go
index 42840cc5a..5c7c56570 100644
--- a/base/tree.go
+++ b/base/tree.go
@@ -39,6 +39,9 @@ type TreeState struct {
Node func(i int) TreeNode
RowHeight float32
Indent float32
+ // SelectedColor paints the selected row's background instead of the theme's
+ // Accent. Zero keeps the theme's.
+ SelectedColor gfx.Color
// DisplayDepth maps a row's Depth to the level the tree indents it by, when
// the application compresses deep rows to keep their names in view. Depth
// stays the tree's structure, which keyboard movement, typeahead and drops
diff --git a/cmd/viva/initfiles/AGENTS.md.txt b/cmd/viva/initfiles/AGENTS.md.txt
index e8f2da591..7f90e27bf 100644
--- a/cmd/viva/initfiles/AGENTS.md.txt
+++ b/cmd/viva/initfiles/AGENTS.md.txt
@@ -595,8 +595,9 @@ asks for a repaint, `Handled: true` stops the default handling; it is a struct,
`gfx.PointerDown`, `PointerMove`, `PointerUp` or `PointerExit`, `e.X`/`e.Y` are window pixels, `e.Target` is the identity
pressed (it stays the pressed one while a drag runs). Two panes with a draggable divider need none of it: keep a
`ui.SplitterState` in the model, give the first pane its `Pos` and declare `ui.Splitter(c, &m.split)` between them (the
-pointer is captured, the resize cursor shows, `Mins` bounds both panes, and `SplitterState.Key` given to the config's
-`OnKey` adds the arrow keys; `m.split.Dragging()` says a drag is running):
+pointer is captured, the resize cursor shows, `Mins` and `Maxs` bound both panes, and the page routes the focused
+divider's arrow keys (or give `SplitterState.Key` to the config's `OnKey`); a width the user chose comes back after a
+window that was too narrow for it grows, and `m.split.Dragging()` says a drag is running):
```go
m.split = ui.SplitterState{Pos: 240} // once, in newModel
@@ -683,7 +684,8 @@ of `gfx.LightTheme()`: keep the theme in the model (`m.theme`) and give it to th
value is the next paint's theme. `PageConfig.Background` fills the window with a color other than the theme's
`Background`.
`theme.Metrics` has `ControlHeight`, `RadiusControl`, `RadiusSurface`, `FontSizeS`, `FontSizeM`, `FontSizeL`,
-`PadControlX`, `PadSurface`, `GapItem`. Take colors and sizes from the theme rather than writing literals.
+`PadControlX`, `PadSurface`, `GapItem`. The theme's `TooltipDelay` (a `time.Duration`) is how long the pointer rests before a
+hover tooltip appears; zero shows it with the pointer. Take colors and sizes from the theme rather than writing literals.
## Components (package github.com/vivaui/viva/components)
diff --git a/cmd/viva/templates/input.go.txt b/cmd/viva/templates/input.go.txt
index c616daef2..c40795a45 100644
--- a/cmd/viva/templates/input.go.txt
+++ b/cmd/viva/templates/input.go.txt
@@ -85,7 +85,7 @@ func paintInputContent(canvas *gfx.Canvas, theme gfx.Theme, bounds, content gfx.
}
if snapshot.Text.Mono {
snapshot.PlatformEditing = false
- snapshot.ShowCaret = focused
+ snapshot.ShowCaret = focused && !snapshot.ReadOnly && !snapshot.Disabled
}
// A caret the component paints keeps its own blink phase, whether the field is fixed
// pitch or asked to hide the editor's text; the platform's caret is not drawn, so its
diff --git a/cmd/viva/templates/tree.go.txt b/cmd/viva/templates/tree.go.txt
index 7312ecd1d..cd3929d10 100644
--- a/cmd/viva/templates/tree.go.txt
+++ b/cmd/viva/templates/tree.go.txt
@@ -15,6 +15,7 @@ type Tree struct {
cursorY float32
rowHeight float32
indent float32
+ selected gfx.Color // zero is the theme's Accent
}
// TreeRow is the geometry reserved for caller-owned row content.
@@ -54,6 +55,14 @@ func (tree Tree) Indent(width float32) Tree {
return tree
}
+// SelectedColor paints the selected row's background in color instead of the theme's
+// Accent. A zero color keeps the theme's, so a theme that is faded or tinted still
+// reads as its own.
+func (tree Tree) SelectedColor(color gfx.Color) Tree {
+ tree.selected = color
+ return tree
+}
+
// Item paints one visible row and returns its caller-owned content area. The
// component never walks children or allocates a backing model.
func (tree *Tree) Item(item TreeItem) TreeRow {
@@ -72,6 +81,9 @@ func (tree *Tree) Item(item TreeItem) TreeRow {
background := tree.theme.Muted
if item.Selected {
background = tree.theme.Accent
+ if tree.selected != (gfx.Color{}) {
+ background = tree.selected
+ }
}
tree.canvas.Rounded(row, radius, background)
}
diff --git a/components/input.go b/components/input.go
index b68270574..cadd6490d 100644
--- a/components/input.go
+++ b/components/input.go
@@ -85,7 +85,7 @@ func paintInputContent(canvas *gfx.Canvas, theme gfx.Theme, bounds, content gfx.
}
if snapshot.Text.Mono {
snapshot.PlatformEditing = false
- snapshot.ShowCaret = focused
+ snapshot.ShowCaret = focused && !snapshot.ReadOnly && !snapshot.Disabled
}
// A caret the component paints keeps its own blink phase, whether the field is fixed
// pitch or asked to hide the editor's text; the platform's caret is not drawn, so its
diff --git a/components/tree.go b/components/tree.go
index 13dab2e30..1f0f837df 100644
--- a/components/tree.go
+++ b/components/tree.go
@@ -15,6 +15,7 @@ type Tree struct {
cursorY float32
rowHeight float32
indent float32
+ selected gfx.Color // zero is the theme's Accent
}
// TreeRow is the geometry reserved for caller-owned row content.
@@ -54,6 +55,14 @@ func (tree Tree) Indent(width float32) Tree {
return tree
}
+// SelectedColor paints the selected row's background in color instead of the theme's
+// Accent. A zero color keeps the theme's, so a theme that is faded or tinted still
+// reads as its own.
+func (tree Tree) SelectedColor(color gfx.Color) Tree {
+ tree.selected = color
+ return tree
+}
+
// Item paints one visible row and returns its caller-owned content area. The
// component never walks children or allocates a backing model.
func (tree *Tree) Item(item TreeItem) TreeRow {
@@ -72,6 +81,9 @@ func (tree *Tree) Item(item TreeItem) TreeRow {
background := tree.theme.Muted
if item.Selected {
background = tree.theme.Accent
+ if tree.selected != (gfx.Color{}) {
+ background = tree.selected
+ }
}
tree.canvas.Rounded(row, radius, background)
}
diff --git a/components/tree_test.go b/components/tree_test.go
index 8d6408326..a41507754 100644
--- a/components/tree_test.go
+++ b/components/tree_test.go
@@ -86,3 +86,37 @@ func TestTreeDraggingRowDropsTheFocusRing(t *testing.T) {
t.Fatal("a focused row that is not dragged painted no focus ring")
}
}
+
+// SelectedColor replaces the theme's Accent for the selected row; a zero color
+// leaves the theme's, so a theme's own fade or tint still applies.
+func TestTreeSelectedRowColourIsTheTrees(t *testing.T) {
+ theme := gfx.LightTheme()
+ selected := gfx.Color{Red: 0.2, Green: 0.5, Blue: 0.4, Alpha: 1}
+ paint := func(color gfx.Color) []gfx.Rectangle {
+ var canvas gfx.Canvas
+ tree := BeginTree(&canvas, theme, gfx.Rect{Width: 200, Height: 32}).SelectedColor(color)
+ tree.Item(TreeItem{ID: gfx.Item(1), Label: "Selected", Selected: true})
+ return canvas.Rectangles()
+ }
+ found := false
+ for _, rectangle := range paint(selected) {
+ if rectangle.Color == selected {
+ found = true
+ }
+ if rectangle.Color == theme.Accent {
+ t.Fatal("the selected row painted the theme's Accent instead of the tree's colour")
+ }
+ }
+ if !found {
+ t.Fatal("the selected row painted no background in the tree's colour")
+ }
+ found = false
+ for _, rectangle := range paint(gfx.Color{}) {
+ if rectangle.Color == theme.Accent {
+ found = true
+ }
+ }
+ if !found {
+ t.Fatal("a zero SelectedColor did not keep the theme's Accent")
+ }
+}
diff --git a/examples/guides/input/main.go b/examples/guides/input/main.go
index a68772ca2..9bdac7dd0 100644
--- a/examples/guides/input/main.go
+++ b/examples/guides/input/main.go
@@ -85,10 +85,8 @@ func newConfig(m *model) app.Config {
page := ui.NewPage(ui.PageConfig{View: m.page, Theme: &theme})
return ui.Configure(page, app.Config{
Title: "Input", Width: 640, Height: 360,
- // The page routes pointer, wheel, shortcut and text input to the controls
- // it declares. A splitter keeps its arrow keys in its own state, so give
- // them to the window's key callback.
- OnKey: m.split.Key,
+ // The page routes pointer, wheel, keys and text input to the controls it
+ // declares; the focused splitter gets its arrow keys from the page.
})
}
diff --git a/gfx/theme.go b/gfx/theme.go
index 6664bb5bb..8a2ed7991 100644
--- a/gfx/theme.go
+++ b/gfx/theme.go
@@ -1,5 +1,7 @@
package gfx
+import "time"
+
const (
WeightRegular float32 = 0
WeightMedium float32 = 0.15
@@ -118,6 +120,10 @@ type Theme struct {
// Transition is the default state-change motion for controls. A zero
// value disables animation for hand-built themes.
Transition Motion
+ // TooltipDelay is how long the pointer rests on a control before a hover
+ // tooltip appears. Zero shows it with the pointer, which is Viva's pinned
+ // behaviour; a desktop feel is closer to half a second.
+ TooltipDelay time.Duration
}
// WithRadius is the theme with another corner radius for its controls
diff --git a/ui/controls_paint.go b/ui/controls_paint.go
index 4c917cf38..5eda8b44e 100644
--- a/ui/controls_paint.go
+++ b/ui/controls_paint.go
@@ -452,6 +452,14 @@ func paintInput(f *Frame, n *Node) {
// otherwise, so the snapshot's own declaration is left alone only by an alignment it
// declares. What the snapshot leaves at AlignLeft the element's TextEnd() takes.
snapshot := base.WidgetsOf(f).GetInputs()[n.Aux]
+ // Disabled and read-only are the declaration's as well as the field's: Disabled
+ // comes from the Box, so a condition written after the field is still obeyed.
+ if n.Flags&FlagDisabled != 0 {
+ snapshot.Disabled = true
+ }
+ if snapshot.Disabled || snapshot.ReadOnly {
+ snapshot.ShowCaret = false
+ }
if n.TextEnd {
if snapshot.Alignment == gfx.AlignLeft || snapshot.Alignment == gfx.AlignStart {
snapshot.Alignment = gfx.AlignEnd
@@ -480,6 +488,12 @@ func paintInput(f *Frame, n *Node) {
// Border, as paintInput does for a line.
func paintTextarea(f *Frame, n *Node) {
snapshot := base.WidgetsOf(f).GetTextareas()[n.Aux]
+ if n.Flags&FlagDisabled != 0 {
+ snapshot.Disabled = true
+ }
+ if snapshot.Disabled || snapshot.ReadOnly {
+ snapshot.ShowCaret = false
+ }
if n.FontSize > 0 {
snapshot.TextSize = n.FontSize
}
diff --git a/ui/radio_disabled_test.go b/ui/radio_disabled_test.go
new file mode 100644
index 000000000..d912de968
--- /dev/null
+++ b/ui/radio_disabled_test.go
@@ -0,0 +1,26 @@
+package ui_test
+
+import (
+ "testing"
+
+ "github.com/vivaui/viva/ui"
+)
+
+// A click on a disabled RadioBase is not a choice: Box.Disabled is the option's, not
+// only its look.
+func TestRadioBaseHonoursDisabled(t *testing.T) {
+ value := "one"
+ d := openPage(t, func(c ui.C) {
+ ui.Column(c).Pad(16).Gap(8).Children(func() {
+ ui.RadioBase(c, &value, "one", "one").Pad(6).Children(func() { ui.Text(c, "one") })
+ ui.RadioBase(c, &value, "two", "two").Pad(6).Children(func() { ui.Text(c, "two") }).Disabled(true)
+ })
+ })
+ d.click("two")
+ if value != "one" {
+ t.Fatalf("a disabled RadioBase chose %q", value)
+ }
+ if hit := d.hit("two"); !hit.Disabled {
+ t.Fatalf("a disabled RadioBase's hit = %+v", hit)
+ }
+}
diff --git a/ui/splitter_page_test.go b/ui/splitter_page_test.go
new file mode 100644
index 000000000..fb9ffd33d
--- /dev/null
+++ b/ui/splitter_page_test.go
@@ -0,0 +1,60 @@
+package ui_test
+
+import (
+ "testing"
+
+ "github.com/vivaui/viva/gfx"
+ "github.com/vivaui/viva/ui"
+)
+
+func splitPageWith(split *ui.SplitterState) func(ui.C) {
+ return func(c ui.C) {
+ ui.Row(c).Fill().Children(func() {
+ ui.Column(c).Width(split.Pos).Children(func() { ui.Text(c, "left") })
+ ui.Splitter(c, split).Mins(80, 80).Label("Resize panes")
+ ui.Column(c).Grow(1).Children(func() { ui.Text(c, "right") })
+ })
+ }
+}
+
+// The page routes the keys of the focused divider, so a Splitter in a page needs no
+// OnKey wiring to move with the arrows.
+func TestSplitterKeysAreRoutedByThePage(t *testing.T) {
+ split := ui.SplitterState{Pos: 200}
+ d := openPage(t, splitPageWith(&split))
+ d.click("Resize panes")
+ d.key(gfx.KeyRight)
+ if split.Pos != 200+16 {
+ t.Fatalf("Right moved the splitter to %v, want 216", split.Pos)
+ }
+ d.key(gfx.KeyEnd)
+ if want := float32(480 - 8 - 80); split.Pos != want {
+ t.Fatalf("End moved the splitter to %v, want %v", split.Pos, want)
+ }
+ d.key(gfx.KeyHome)
+ if split.Pos != 80 {
+ t.Fatalf("Home moved the splitter to %v, want the minimum 80", split.Pos)
+ }
+}
+
+// A window that is too narrow for the width the user chose clamps the pane, and the
+// width they chose comes back when the window grows again.
+func TestSplitterPreferredWidthSurvivesANarrowWindow(t *testing.T) {
+ split := ui.SplitterState{Pos: 300}
+ d := openPage(t, splitPageWith(&split))
+ if split.Pos != 300 {
+ t.Fatalf("the first pane is %v, want 300", split.Pos)
+ }
+ if err := d.driver.Resize(340, 480); err != nil {
+ t.Fatal(err)
+ }
+ if want := float32(340 - 8 - 80); split.Pos != want {
+ t.Fatalf("in a narrow window the first pane is %v, want %v", split.Pos, want)
+ }
+ if err := d.driver.Resize(480, 480); err != nil {
+ t.Fatal(err)
+ }
+ if split.Pos != 300 {
+ t.Fatalf("after the window grew the first pane is %v, want its preferred 300", split.Pos)
+ }
+}
diff --git a/ui/tooltip_paint.go b/ui/tooltip_paint.go
index 5482c97e6..0f82abf51 100644
--- a/ui/tooltip_paint.go
+++ b/ui/tooltip_paint.go
@@ -17,7 +17,7 @@ func paintTooltip(f *Frame) {
return
}
frameTooltipState(f).Paint(f.Surface, f.Palette, f.GetBounds(), components.TooltipOptions{Layer: TooltipLayer, SideOf: f.TooltipSideOf},
- components.HoverTooltipDelay)
+ f.Palette.TooltipDelay)
}
// tooltipState is the tooltip state the layer above owns; the engine only keeps
diff --git a/ui/tooltip_test.go b/ui/tooltip_test.go
index a2384b072..d4678a203 100644
--- a/ui/tooltip_test.go
+++ b/ui/tooltip_test.go
@@ -2,7 +2,9 @@ package ui_test
import (
"testing"
+ "time"
+ "github.com/vivaui/viva/app"
"github.com/vivaui/viva/gfx"
"github.com/vivaui/viva/ui"
)
@@ -103,3 +105,27 @@ func TestTooltipOn(t *testing.T) {
}
}
}
+
+// The page's theme sets how long the pointer rests before a tip appears; zero, the
+// default, still shows it with the pointer.
+func TestTooltipDelayComesFromTheTheme(t *testing.T) {
+ theme := ui.LightTheme()
+ theme.TooltipDelay = 500 * time.Millisecond
+ d := openPageWith(t, ui.PageConfig{Theme: &theme, View: func(c ui.C) {
+ ui.Column(c).Pad(40).Children(func() {
+ ui.Button(c, "Delete").Tooltip("Delete the host")
+ })
+ }}, app.Config{})
+ if err := d.driver.Move(center(d.hit("Delete").Bounds)); err != nil {
+ t.Fatal(err)
+ }
+ if tooltipShown(d, "Delete the host") {
+ t.Fatal("the tip appeared before the theme's delay")
+ }
+ if err := d.driver.Advance(600 * time.Millisecond); err != nil {
+ t.Fatal(err)
+ }
+ if !tooltipShown(d, "Delete the host") {
+ t.Fatal("the tip did not appear after the theme's delay")
+ }
+}
diff --git a/ui/tree_paint.go b/ui/tree_paint.go
index 5e317eddf..331cb4368 100644
--- a/ui/tree_paint.go
+++ b/ui/tree_paint.go
@@ -57,7 +57,7 @@ func treeStateDraw(s *TreeState, d *DrawContext) {
if row.GetGen() != d.Frame.GetGen() || &d.Frame.Nodes[row.Node] != d.Node {
continue
}
- tree := components.BeginTree(d.Canvas, *d.Theme, d.Rect).RowHeight(d.Rect.Height).Indent(s.IndentValue(d.Theme))
+ tree := components.BeginTree(d.Canvas, *d.Theme, d.Rect).RowHeight(d.Rect.Height).Indent(s.IndentValue(d.Theme)).SelectedColor(s.SelectedColor)
tree.Item(row.GetItem())
if s.DragPtr().GetActive() {
s.DragOver(row, d)
From 69aa61963499b4b1b8bfacdf861bcd073fa53484 Mon Sep 17 00:00:00 2001
From: t8y2
Date: Sat, 21 Nov 2026 23:36:29 +0800
Subject: [PATCH 25/47] docs(website): resync the input guide from its example
The page now routes a splitter's keys, so the example no longer wires
OnKey; the guides embed that example.
---
website/content/guides/en/handling-input.md | 6 ++----
website/content/guides/zh/handling-input.md | 6 ++----
2 files changed, 4 insertions(+), 8 deletions(-)
diff --git a/website/content/guides/en/handling-input.md b/website/content/guides/en/handling-input.md
index 3a685e265..b51a62937 100644
--- a/website/content/guides/en/handling-input.md
+++ b/website/content/guides/en/handling-input.md
@@ -96,10 +96,8 @@ func newConfig(m *model) app.Config {
page := ui.NewPage(ui.PageConfig{View: m.page, Theme: &theme})
return ui.Configure(page, app.Config{
Title: "Input", Width: 640, Height: 360,
- // The page routes pointer, wheel, shortcut and text input to the controls
- // it declares. A splitter keeps its arrow keys in its own state, so give
- // them to the window's key callback.
- OnKey: m.split.Key,
+ // The page routes pointer, wheel, keys and text input to the controls it
+ // declares; the focused splitter gets its arrow keys from the page.
})
}
diff --git a/website/content/guides/zh/handling-input.md b/website/content/guides/zh/handling-input.md
index 44fae6c66..81581c68b 100644
--- a/website/content/guides/zh/handling-input.md
+++ b/website/content/guides/zh/handling-input.md
@@ -96,10 +96,8 @@ func newConfig(m *model) app.Config {
page := ui.NewPage(ui.PageConfig{View: m.page, Theme: &theme})
return ui.Configure(page, app.Config{
Title: "Input", Width: 640, Height: 360,
- // The page routes pointer, wheel, shortcut and text input to the controls
- // it declares. A splitter keeps its arrow keys in its own state, so give
- // them to the window's key callback.
- OnKey: m.split.Key,
+ // The page routes pointer, wheel, keys and text input to the controls it
+ // declares; the focused splitter gets its arrow keys from the page.
})
}
From c59e92da1ef4f267e87fd8ee3900e5d266be3065 Mon Sep 17 00:00:00 2001
From: t8y2 <1156263951@qq.com>
Date: Sat, 21 Nov 2026 23:41:08 +0800
Subject: [PATCH 26/47] fix(focus): support explicit one-shot focus requests
Keep repeatable user actions distinct from persistent autofocus claims, including event passes and embedded views. This reusable focus boundary supports t8y2/motty#1033 without application-level input workarounds.
---
app/painter.go | 4 +-
base/style.go | 17 ++++++
gfx/canvas.go | 18 ++++++
gfx/embed.go | 3 +
gfx/embed_test.go | 15 +++++
internal/interaction/focus.go | 18 +++++-
ui/page_focus_test.go | 103 ++++++++++++++++++++++++++++++++++
7 files changed, 173 insertions(+), 5 deletions(-)
diff --git a/app/painter.go b/app/painter.go
index c82ea056d..97c1adda6 100644
--- a/app/painter.go
+++ b/app/painter.go
@@ -859,7 +859,7 @@ func (painter *painter) repaint() (platform.Frame, error) {
painter.noteFrameStart()
}
painter.paintCanvas()
- if !painter.focus.PendingFocus().IsZero() || painter.focus.Carries() {
+ if !painter.focus.PendingFocus().IsZero() || painter.focus.Carries() || !painter.canvas.FocusOnce().IsZero() {
before, beforeVisible := painter.focus.Focused(), painter.focus.KeyboardFocus()
painter.focus.Sync(painter.canvas)
if painter.focus.Focused() != before || painter.focus.KeyboardFocus() != beforeVisible {
@@ -950,7 +950,7 @@ func (painter *painter) publish() (platform.Frame, error) {
// as it was, so it must not rebuild them.
hitStructuresUnchanged := painter.hitStructuresUnchanged()
regionsUnchanged := (hitStructuresUnchanged || painter.regionStructuresUnchanged()) &&
- painter.canvas.FocusRelease().IsZero() && !painter.focus.Carries()
+ painter.canvas.FocusRelease().IsZero() && painter.canvas.FocusOnce().IsZero() && !painter.focus.Carries()
if regionsUnchanged {
painter.reusedHits++
} else {
diff --git a/base/style.go b/base/style.go
index c119e5932..183a0bb9d 100644
--- a/base/style.go
+++ b/base/style.go
@@ -178,6 +178,23 @@ func (b Box) AutoFocus() Box {
return b
}
+// RequestFocus asks to focus this element for the current action, even if its
+// AutoFocus declaration was already honored. Call it only in an event handler
+// or when consuming state set by one, not on every paint.
+func (b Box) RequestFocus() Box {
+ if b.f.memoDepth > 0 {
+ panic("ui: RequestFocus in a Memo: a copied part cannot request focus")
+ }
+ id := b.N().ID
+ if id.IsZero() {
+ panic("ui: RequestFocus needs an element with an identity")
+ }
+ if b.f.Surface != nil {
+ b.f.Surface.RequestFocusOnce(id)
+ }
+ return b
+}
+
// Focused is how the element looks while the keyboard has it, however it got there: a click
// on a text field focuses it without making the focus visible, and a field that is being typed
// into still reads as the one with the keyboard (CSS's :focus, where Focus is :focus-visible).
diff --git a/gfx/canvas.go b/gfx/canvas.go
index eb0eebb3c..a5b7db416 100644
--- a/gfx/canvas.go
+++ b/gfx/canvas.go
@@ -793,6 +793,7 @@ type Canvas struct {
// non-modal popover does. The runtime honors a given request once, so
// painting it every frame never pulls focus back after the user leaves.
focusRequest ID
+ focusOnce ID
// focusRelease takes the focus away from one hit if it still has it, and
// focusReturns are the non-modal scopes that give the focus back on closing.
focusRelease ID
@@ -1037,6 +1038,7 @@ func (canvas *Canvas) Reset() {
canvas.escapeTarget = ID{}
canvas.initialFocus = ID{}
canvas.focusRequest = ID{}
+ canvas.focusOnce = ID{}
canvas.focusRelease = ID{}
canvas.focusReturns = canvas.focusReturns[:0]
canvas.trapDepth, canvas.escapeDepth, canvas.initialDepth = -1, -1, -1
@@ -1884,6 +1886,22 @@ func (canvas *Canvas) RequestFocus(id ID) {
// FocusRequest returns the non-modal focus request, or zero.
func (canvas *Canvas) FocusRequest() ID { return canvas.focusRequest }
+// RequestFocusOnce requests an explicit focus change, even if id has already
+// been claimed by a persistent RequestFocus or AutoFocus declaration. Call it
+// only in response to an action, or from state consumed by the next paint.
+// The request is carried across an event pass and applied at most once.
+func (canvas *Canvas) RequestFocusOnce(id ID) { canvas.focusOnce = id }
+
+// FocusOnce returns the explicit focus request, or zero.
+func (canvas *Canvas) FocusOnce() ID { return canvas.focusOnce }
+
+// TakeFocusOnce consumes the explicit focus request.
+func (canvas *Canvas) TakeFocusOnce() ID {
+ id := canvas.focusOnce
+ canvas.focusOnce = ID{}
+ return id
+}
+
// ReleaseFocus asks the runtime to take the keyboard focus away from id if id
// still has it when this paint ends, and does nothing otherwise. A control that
// finds its identity now names something else than what the user focused (a row
diff --git a/gfx/embed.go b/gfx/embed.go
index 3e462fcf7..347bee4c8 100644
--- a/gfx/embed.go
+++ b/gfx/embed.go
@@ -201,6 +201,9 @@ func (canvas *Canvas) AdoptEmbedded(child *Canvas, mount Scope) {
if request := child.FocusRequest(); !request.IsZero() {
canvas.RequestFocus(tree.MountID(mount, request))
}
+ if request := child.TakeFocusOnce(); !request.IsZero() {
+ canvas.RequestFocusOnce(tree.MountID(mount, request))
+ }
if release := child.FocusRelease(); !release.IsZero() {
canvas.ReleaseFocus(tree.MountID(mount, release))
}
diff --git a/gfx/embed_test.go b/gfx/embed_test.go
index e6612eec5..038af6498 100644
--- a/gfx/embed_test.go
+++ b/gfx/embed_test.go
@@ -360,6 +360,21 @@ func TestAdoptEmbeddedTakesTheViewsFocusAndModalState(t *testing.T) {
}
}
+func TestAdoptEmbeddedConsumesExplicitFocusOnce(t *testing.T) {
+ var child, page Canvas
+ mount := testMount(&page, 1)
+ child.RequestFocusOnce(Item(4))
+ page.AdoptEmbedded(&child, mount)
+ want := page.Tree().MountID(mount, Item(4))
+ if got := page.TakeFocusOnce(); got != want {
+ t.Fatalf("adopted focus = %v, want %v", got, want)
+ }
+ page.AdoptEmbedded(&child, mount)
+ if got := page.FocusOnce(); !got.IsZero() {
+ t.Fatalf("repeated adoption requested focus %v", got)
+ }
+}
+
func TestEmbedTranslatesShadowsAndTheirPaintOrder(t *testing.T) {
var child, page Canvas
page.Fill(Rect{Width: 10, Height: 10}, Color{Alpha: 1})
diff --git a/internal/interaction/focus.go b/internal/interaction/focus.go
index 1444360fb..0daab6a09 100644
--- a/internal/interaction/focus.go
+++ b/internal/interaction/focus.go
@@ -24,8 +24,9 @@ type Focus struct {
// carried is a request made while handling a click or a shortcut. The event
// pass paints with it, but the repaint that follows begins with a new frame
// and would clear it before Sync reads the published paint.
- carried gfx.ID
- escape gfx.ID
+ carried gfx.ID
+ carriedOnce gfx.ID
+ escape gfx.ID
// painted is the hit list of the previous paint, so a newly appearing
// Autofocus hit takes the keyboard once. scratch is the next list.
painted []gfx.ID
@@ -61,6 +62,9 @@ func (f *Focus) SetKeyboardFocus(visible bool) { f.keyboardFocus = visible }
// paints, and Sync reads only the paint it publishes. A request the repaint
// makes itself replaces this one.
func (f *Focus) Carry(canvas *gfx.Canvas) {
+ if request := canvas.TakeFocusOnce(); !request.IsZero() {
+ f.carriedOnce = request
+ }
// A channel that carries no request leaves the one a channel before it in
// the same event made: deliverPointer then deliverClick, each carrying.
if request := canvas.FocusRequest(); !request.IsZero() {
@@ -69,7 +73,7 @@ func (f *Focus) Carry(canvas *gfx.Canvas) {
}
// Carries reports whether an event-pass focus request waits for the next Sync.
-func (f *Focus) Carries() bool { return !f.carried.IsZero() }
+func (f *Focus) Carries() bool { return !f.carried.IsZero() || !f.carriedOnce.IsZero() }
// PendingFocus returns a target whose paint-time reveal is not resolved yet.
func (f *Focus) PendingFocus() gfx.ID { return f.pendingFocus }
@@ -139,6 +143,11 @@ func (f *Focus) Sync(canvas *gfx.Canvas) {
f.router.SetActiveScope(canvas.TrappedFocusScope(), input.Target(canvas.InitialFocus()))
f.applyAutofocus(hits)
request := canvas.FocusRequest()
+ once := canvas.TakeFocusOnce()
+ if once.IsZero() && (request.IsZero() || request == f.focusClaim) {
+ once = f.carriedOnce
+ }
+ f.carriedOnce = gfx.ID{}
carried := false
if request.IsZero() && !f.carried.IsZero() {
request, carried = f.carried, true
@@ -157,6 +166,9 @@ func (f *Focus) Sync(canvas *gfx.Canvas) {
} else {
f.focusClaim = gfx.ID{}
}
+ if !once.IsZero() {
+ f.router.Focus(input.Target(once))
+ }
if !f.pendingFocus.IsZero() {
target := input.Target(f.pendingFocus)
f.router.Focus(target)
diff --git a/ui/page_focus_test.go b/ui/page_focus_test.go
index 02eb7e0e7..5ee7ee19d 100644
--- a/ui/page_focus_test.go
+++ b/ui/page_focus_test.go
@@ -6,6 +6,109 @@ import (
"github.com/vivaui/viva/ui"
)
+func TestPageRepeatedAutoFocusDoesNotStealPointerFocus(t *testing.T) {
+ var search ui.Field
+ d := openPage(t, func(c ui.C) {
+ ui.Column(c).Pad(16).Gap(8).Children(func() {
+ ui.TextField(c, &search, "Search", "").AutoFocus()
+ ui.Button(c, "Other")
+ })
+ })
+ d.click("Other")
+ if got := d.Focused(); got != "Other" {
+ t.Fatalf("focus after clicking Other = %q", got)
+ }
+}
+
+func TestPageClickCanRenewTheSameAutoFocus(t *testing.T) {
+ var search ui.Field
+ d := openPage(t, func(c ui.C) {
+ ui.Column(c).Pad(16).Gap(8).Children(func() {
+ field := ui.TextField(c, &search, "Search", "").AutoFocus()
+ if ui.Button(c, "Focus search").Clicked() {
+ field.RequestFocus()
+ }
+ ui.Button(c, "Other")
+ })
+ })
+ d.click("Focus search")
+ if got := d.Focused(); got != "Search" {
+ t.Fatalf("focus after the click = %q, want Search", got)
+ }
+ d.click("Other")
+ if got := d.Focused(); got != "Other" {
+ t.Fatalf("focus after a later click = %q, want Other", got)
+ }
+}
+
+func TestPageDeferredFocusRequestOverridesAnExistingAutoFocus(t *testing.T) {
+ var search ui.Field
+ pending := false
+ d := openPage(t, func(c ui.C) {
+ ui.Column(c).Pad(16).Gap(8).Children(func() {
+ field := ui.TextField(c, &search, "Search", "").AutoFocus()
+ if pending {
+ field.RequestFocus()
+ pending = false
+ }
+ if ui.Button(c, "Focus search").Clicked() {
+ c.After(func() { pending = true })
+ }
+ ui.Button(c, "Other")
+ })
+ })
+ d.click("Focus search")
+ if got := d.Focused(); got != "Search" {
+ t.Fatalf("focus after deferred request = %q, want Search", got)
+ }
+ d.click("Other")
+ if got := d.Focused(); got != "Other" {
+ t.Fatalf("focus after later click = %q, want Other", got)
+ }
+}
+
+func TestPageNewAutoFocusOutranksAnExplicitEventRequest(t *testing.T) {
+ var first, second ui.Field
+ wantSecond := false
+ d := openPage(t, func(c ui.C) {
+ ui.Column(c).Pad(16).Gap(8).Children(func() {
+ secondField := ui.TextField(c, &second, "Second", "")
+ firstField := ui.TextField(c, &first, "First", "")
+ if wantSecond {
+ secondField.AutoFocus()
+ }
+ if ui.Button(c, "Focus first").Clicked() {
+ wantSecond = true
+ firstField.RequestFocus()
+ }
+ })
+ })
+ d.click("Focus first")
+ if got := d.Focused(); got != "Second" {
+ t.Fatalf("focus = %q, want the new autofocus", got)
+ }
+}
+
+func TestPageShortcutCanRenewTheSameAutoFocus(t *testing.T) {
+ var search ui.Field
+ d := openPage(t, func(c ui.C) {
+ ui.Column(c).Pad(16).Gap(8).Children(func() {
+ field := ui.TextField(c, &search, "Search", "").AutoFocus()
+ ui.Button(c, "Other")
+ if ui.Shortcut(c, ui.Primary, "f") {
+ field.RequestFocus()
+ }
+ })
+ })
+ d.click("Other")
+ if _, err := d.driver.ShortcutChord(ui.Primary, 'f'); err != nil {
+ t.Fatal(err)
+ }
+ if got := d.Focused(); got != "Search" {
+ t.Fatalf("focus after shortcut = %q, want Search", got)
+ }
+}
+
// A focus request made while handling a click is carried into the repaint that
// follows, the one that shows the result of the click.
func TestPageFocusRequestInAClickHandlerTakesEffect(t *testing.T) {
From e94ad0403eb70556dfdfad5df71a1ee82280aaaa Mon Sep 17 00:00:00 2001
From: t8y2 <1156263951@qq.com>
Date: Sat, 21 Nov 2026 23:49:29 +0800
Subject: [PATCH 27/47] feat(app): report a window losing the activation
---
app/app.go | 7 ++
app/deactivate_test.go | 105 ++++++++++++++++++
app/driver.go | 14 +++
app/painter.go | 31 +++++-
app/run_canvas.go | 1 +
docs/system-integrations.md | 1 +
docs/web-deployment.md | 1 +
internal/platform/contract.go | 11 +-
internal/platform/darwin/callback.go | 18 +++
internal/platform/darwin/native.m | 5 +
internal/platform/darwin/platform.go | 2 +
.../platform/darwin/testdata/dock_reopen.m | 1 +
internal/platform/darwin/testdata/file_drop.m | 1 +
.../platform/darwin/testdata/live_resize.m | 1 +
.../platform/darwin/testdata/modifier_taps.m | 1 +
.../platform/darwin/testdata/text_selection.m | 1 +
.../platform/darwin/testdata/traffic_lights.m | 1 +
.../platform/darwin/testdata/window_close.m | 1 +
.../platform/darwin/testdata/window_size.m | 1 +
internal/platform/linux/gtk_input_linux.go | 4 +
internal/platform/linux/window_linux.go | 6 +
internal/platform/windows/window_windows.go | 4 +
22 files changed, 215 insertions(+), 3 deletions(-)
create mode 100644 app/deactivate_test.go
diff --git a/app/app.go b/app/app.go
index 6e04008d8..f01f10e43 100644
--- a/app/app.go
+++ b/app/app.go
@@ -202,6 +202,13 @@ type Config struct {
// call it. It lets an application refresh data that may have gone stale
// while the window was in the background, without polling.
OnActivate func()
+ // OnDeactivate runs on the window thread when the top-level window stops
+ // being the active window, after the keys that were down are released. It
+ // is how an application saves or hides what only makes sense while it has
+ // the user's attention. Its Repaint asks for a new frame. Moving focus
+ // between editors inside the window does not call it, and the Web target
+ // does not report it.
+ OnDeactivate func() gfx.EventResult
// OnMaximize runs on the window thread when the window is maximized or
// restored on Windows and Linux, including by the system (the window
// manager, the taskbar, or a keyboard shortcut), not only by Viva's own
diff --git a/app/deactivate_test.go b/app/deactivate_test.go
new file mode 100644
index 000000000..cbad555f5
--- /dev/null
+++ b/app/deactivate_test.go
@@ -0,0 +1,105 @@
+//go:build darwin || windows || linux
+
+package app
+
+import (
+ "testing"
+
+ "github.com/vivaui/viva/gfx"
+)
+
+// Deactivate is the window's, not the keyboard's: the keys that were down are
+// released before the application hears about it, so what it saves or hides sees
+// no key still held.
+func TestDeactivateReleasesKeysBeforeItsCallback(t *testing.T) {
+ var order []string
+ probe := &keyProbe{releases: true}
+ config := probe.config()
+ key := config.OnKey
+ config.OnKey = func(event gfx.KeyEvent) gfx.EventResult {
+ if event.Release {
+ order = append(order, "release")
+ }
+ return key(event)
+ }
+ calls := 0
+ config.OnDeactivate = func() gfx.EventResult {
+ calls++
+ order = append(order, "deactivate")
+ return gfx.EventResult{Repaint: true}
+ }
+ driver, err := NewDriver(config, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(driver.Close)
+ if err := driver.Click(100, 100); err != nil {
+ t.Fatal(err)
+ }
+ probe.keys = nil
+ if err := driver.KeyDown(gfx.KeyUnknown, "a"); err != nil {
+ t.Fatal(err)
+ }
+ order = nil
+ if err := driver.DeactivateWindow(); err != nil {
+ t.Fatal(err)
+ }
+ if calls != 1 {
+ t.Fatalf("OnDeactivate ran %d times, want 1", calls)
+ }
+ if len(order) != 2 || order[0] != "release" || order[1] != "deactivate" {
+ t.Fatalf("the order was %v, want the held key released, then the callback", order)
+ }
+}
+
+// Losing the keyboard inside the window is not a deactivation: a page or a view
+// taking the keys releases them without telling the application the window is gone.
+func TestLosingTheKeyboardInsideTheWindowDoesNotDeactivate(t *testing.T) {
+ probe := &keyProbe{releases: true}
+ config := probe.config()
+ calls := 0
+ config.OnDeactivate = func() gfx.EventResult {
+ calls++
+ return gfx.EventResult{}
+ }
+ driver, err := NewDriver(config, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(driver.Close)
+ if err := driver.Click(100, 100); err != nil {
+ t.Fatal(err)
+ }
+ if err := driver.KeyDown(gfx.KeyUnknown, "a"); err != nil {
+ t.Fatal(err)
+ }
+ if err := driver.LoseFocus(); err != nil {
+ t.Fatal(err)
+ }
+ if calls != 0 {
+ t.Fatalf("losing the keyboard called OnDeactivate %d times, want none", calls)
+ }
+}
+
+// A window with no key handling still reports its deactivation.
+func TestDeactivateRunsWithoutKeys(t *testing.T) {
+ calls := 0
+ driver, err := NewDriver(Config{
+ Width: 200, Height: 120,
+ Paint: func(canvas *gfx.Canvas, size gfx.Size) {},
+ OnDeactivate: func() gfx.EventResult {
+ calls++
+ return gfx.EventResult{}
+ },
+ }, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(driver.Close)
+ if err := driver.DeactivateWindow(); err != nil {
+ t.Fatal(err)
+ }
+ if calls != 1 {
+ t.Fatalf("OnDeactivate ran %d times, want 1", calls)
+ }
+}
diff --git a/app/driver.go b/app/driver.go
index 0f5ab35bc..c66838d82 100644
--- a/app/driver.go
+++ b/app/driver.go
@@ -620,6 +620,20 @@ func (driver *Driver) KeyUp(key gfx.Key, character string) error {
return err
}
+// DeactivateWindow reports the window as deactivated, as the window manager
+// would when the user switches away, and calls OnDeactivate after the keys
+// that were down are released. A closed driver reports nothing.
+func (driver *Driver) DeactivateWindow() error {
+ if err := driver.Pump(); err != nil {
+ return err
+ }
+ driver.modifierKeys = 0
+ if _, err := driver.painter.deactivate(); err != nil {
+ return err
+ }
+ return driver.Pump()
+}
+
// LoseFocus makes the window lose the keyboard, as switching to another
// application does: keys held down are released first. Modifiers held by
// KeyDown are forgotten with them.
diff --git a/app/painter.go b/app/painter.go
index 97c1adda6..2d9641714 100644
--- a/app/painter.go
+++ b/app/painter.go
@@ -26,8 +26,11 @@ type painter struct {
paint func(canvas *gfx.Canvas, size gfx.Size)
onPointer func(gfx.PointerEvent) gfx.EventResult
onKey func(gfx.KeyEvent) gfx.EventResult
- onShortcut func(gfx.KeyEvent) gfx.EventResult
- onScroll func(gfx.ScrollEvent) gfx.EventResult
+ // onDeactivate is the application's, called after a window loses the
+ // activation and the keys that were down are released.
+ onDeactivate func() gfx.EventResult
+ onShortcut func(gfx.KeyEvent) gfx.EventResult
+ onScroll func(gfx.ScrollEvent) gfx.EventResult
// onModifierTap and tap recognize a modifier pressed and released on its own.
onModifierTap func(gfx.ModifierTapEvent) gfx.EventResult
tap input.ModifierTap
@@ -142,6 +145,7 @@ func newPainterWithClock(canvas *gfx.Canvas, config *Config, clock func() time.D
paint: config.Paint,
onPointer: config.OnPointer,
onKey: config.OnKey,
+ onDeactivate: config.OnDeactivate,
onShortcut: config.OnShortcut,
onScroll: config.OnScroll,
onModifierTap: config.OnModifierTap,
@@ -699,6 +703,29 @@ func (painter *painter) focusLostHandler() platform.FocusLostHandler {
return painter.focusLost
}
+// deactivateHandler is what a window hands the platform for the loss of the
+// activation: it releases the keys that were down and then tells the
+// application, so the callback sees no key still held.
+func (painter *painter) deactivateHandler() platform.DeactivateHandler {
+ if painter.onDeactivate == nil && painter.onKey == nil && painter.onModifierTap == nil {
+ return nil
+ }
+ return painter.deactivate
+}
+
+func (painter *painter) deactivate() (platform.Frame, error) {
+ painter.tap.Cancel()
+ repaint := painter.releaseKeys()
+ if painter.onDeactivate != nil {
+ response := painter.onDeactivate()
+ repaint = painter.applyEventResult(response) || response.Repaint || repaint
+ }
+ if !repaint {
+ return platform.Frame{}, nil
+ }
+ return painter.repaint()
+}
+
func (painter *painter) focusLost() (platform.Frame, error) {
painter.tap.Cancel()
if !painter.releaseKeys() {
diff --git a/app/run_canvas.go b/app/run_canvas.go
index 385c6e2e9..c17d820ef 100644
--- a/app/run_canvas.go
+++ b/app/run_canvas.go
@@ -193,6 +193,7 @@ func nativeWindowConfig(normalized *Config, painter *painter) (platform.Config,
OnAccessibility: painter.accessibilityHandler(normalized),
OnFocusLost: painter.focusLostHandler(),
OnActivate: normalized.OnActivate,
+ OnDeactivate: painter.deactivateHandler(),
OnScroll: scrollHandler,
OnFileDrop: dropHandler,
OnRedraw: redrawHandler,
diff --git a/docs/system-integrations.md b/docs/system-integrations.md
index 580fefff6..3eaf4fb8b 100644
--- a/docs/system-integrations.md
+++ b/docs/system-integrations.md
@@ -41,6 +41,7 @@ synchronous forms report `ErrAsyncRequired`, `ErrSecretStoreUnavailable` or
| Window title (`SetTitle`) | `NSWindow.title`, the text the window list and Mission Control show | `SetWindowTextW`, applied on the window thread | `WM_NAME` and `_NET_WM_NAME` on X11; `gtk_window_set_title` on the GTK shell | `ErrUnsupported`: the page keeps its own title |
| Page visibility (`OnMinimize`) | window minimized/restored | window minimized/restored | window minimized/restored | `visibilitychange`; a hidden tab counts as minimized |
| Window activation (`OnActivate`) | `NSWindowDidBecomeKeyNotification` | `WM_ACTIVATE`, when not `WA_INACTIVE` | an X11 `FocusIn` whose detail is `Ancestor` or `Nonlinear` outside a grab, or GTK's `focus-in-event` | the window `focus` event |
+| Window deactivation (`OnDeactivate`) | `NSWindowDidResignKeyNotification` | `WM_ACTIVATE`, when `WA_INACTIVE` | an X11 `FocusOut` outside a grab, or GTK's `focus-out-event`; the keys that were down are released first | not reported |
## Opening registered documents
diff --git a/docs/web-deployment.md b/docs/web-deployment.md
index 170923e0c..761f80fdd 100644
--- a/docs/web-deployment.md
+++ b/docs/web-deployment.md
@@ -235,6 +235,7 @@ The page is the window, so the lifecycle callbacks map onto document events:
| `OnMinimize` | `visibilitychange` | The tab became hidden or visible; a hidden tab is not necessarily minimized |
| `OnFullscreen` | `fullscreenchange` | Entered or left the browser's fullscreen mode |
| `OnActivate` | `focus` on the window | The browser window gained focus; focus moving inside the page does not call it |
+| `OnDeactivate` | not reported | The page is the window and the browser keeps activation to itself |
| `OnCloseRequest` | `beforeunload` | Ask before the page unloads; `allow` must be called synchronously |
| `OnClosed` | `pagehide` (not persisted) and `unload` | The page is being torn down |
| `OnFileDrop` | `dragenter`, `dragover`, `dragleave`, `drop` | Files dragged from outside the page |
diff --git a/internal/platform/contract.go b/internal/platform/contract.go
index 5b706c453..3757f7744 100644
--- a/internal/platform/contract.go
+++ b/internal/platform/contract.go
@@ -106,7 +106,12 @@ type Config struct {
// the runtime can release the keys that were down: their releases will go
// to the other window.
OnFocusLost FocusLostHandler
- OnScroll ScrollHandler
+ // OnDeactivate, when set, runs on the window thread when the top-level
+ // window stops being the active window, after OnFocusLost released the
+ // keys that were down. Focus moving between views inside the window does
+ // not call it.
+ OnDeactivate DeactivateHandler
+ OnScroll ScrollHandler
// OnFileDrop, when set, makes the window a target for files dragged from the
// system. The adapter reports hover and leave where the system does and
// always the drop.
@@ -628,6 +633,10 @@ type KeyHandler func(KeyEvent) (Frame, error)
// optional repaint.
type FocusLostHandler func() (Frame, error)
+// DeactivateHandler reports that the window stopped being the active window,
+// after the keys that were down were released, and returns the frame to paint.
+type DeactivateHandler func() (Frame, error)
+
// ShortcutHandler offers one printable chord with any modifiers, or
// Control or Meta with Enter, before native text handling and reports whether the
// application consumed it.
diff --git a/internal/platform/darwin/callback.go b/internal/platform/darwin/callback.go
index a2f0836e9..dcce9f129 100644
--- a/internal/platform/darwin/callback.go
+++ b/internal/platform/darwin/callback.go
@@ -307,6 +307,24 @@ func vivaWindowActivated(handle C.uintptr_t) {
}
}
+// vivaWindowDeactivated reports that the window stopped being the active window.
+//
+//export vivaWindowDeactivated
+func vivaWindowDeactivated(handle C.uintptr_t, view unsafe.Pointer) {
+ state, ok := runStateFor(handle)
+ if !ok || state.closed || state.deactivateHandler == nil {
+ return
+ }
+ frame, err := state.deactivateHandler()
+ if err == nil {
+ err = presentFrame(state, view, frame, false)
+ }
+ if err != nil {
+ state.err = err
+ C.viva_view_close(view)
+ }
+}
+
// vivaFocusLost reports that the window stopped being the keyboard window.
//
//export vivaFocusLost
diff --git a/internal/platform/darwin/native.m b/internal/platform/darwin/native.m
index f1edebb21..528535b2d 100644
--- a/internal/platform/darwin/native.m
+++ b/internal/platform/darwin/native.m
@@ -523,6 +523,7 @@ extern void vivaRawKeyEvent(
// terminal's own table in Go.
extern int vivaTerminalCells(uint32_t character);
extern void vivaWindowActivated(uintptr_t callbackHandle);
+extern void vivaWindowDeactivated(uintptr_t callbackHandle, void *view);
extern void vivaFocusLost(
uintptr_t callbackHandle,
void *view
@@ -5111,6 +5112,10 @@ - (void)keyWindowChanged:(NSNotification *)notification {
notification.object == self.window && _callbackHandle != 0 && _keyEventsEnabled) {
vivaFocusLost(_callbackHandle, self);
}
+ if ([notification.name isEqualToString:NSWindowDidResignKeyNotification] &&
+ notification.object == self.window && _callbackHandle != 0) {
+ vivaWindowDeactivated(_callbackHandle, self);
+ }
if (_textInputGeneration == generation && [notification.name isEqualToString:NSWindowDidResignKeyNotification] &&
notification.object == self.window && _textInputEnabled && _tentativeComposition) {
[self endOwnedNativeComposition];
diff --git a/internal/platform/darwin/platform.go b/internal/platform/darwin/platform.go
index 4eed2f46a..ca4cab14b 100644
--- a/internal/platform/darwin/platform.go
+++ b/internal/platform/darwin/platform.go
@@ -163,6 +163,7 @@ type runState struct {
onActivate func()
keyHandler KeyHandler
focusLostHandler platform.FocusLostHandler
+ deactivateHandler platform.DeactivateHandler
accessibility platform.AccessibilityHandler
// nodes is the accessibility tree last presented, for turning the UTF-16
// ranges AppKit sends back into code points. It is the application's slice,
@@ -398,6 +399,7 @@ func (application *nativeApplication) OpenWindow(config Config) (platform.Window
state.resizeHandler = config.OnResize
state.keyHandler = config.OnKey
state.focusLostHandler = config.OnFocusLost
+ state.deactivateHandler = config.OnDeactivate
state.accessibility, state.nodes = config.OnAccessibility, config.Accessibility
state.shortcutHandler = config.OnShortcut
state.scrollHandler = config.OnScroll
diff --git a/internal/platform/darwin/testdata/dock_reopen.m b/internal/platform/darwin/testdata/dock_reopen.m
index 45a84f734..ca1efffc0 100644
--- a/internal/platform/darwin/testdata/dock_reopen.m
+++ b/internal/platform/darwin/testdata/dock_reopen.m
@@ -8,6 +8,7 @@ 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; }
diff --git a/internal/platform/darwin/testdata/file_drop.m b/internal/platform/darwin/testdata/file_drop.m
index bb3652505..a5fd45781 100644
--- a/internal/platform/darwin/testdata/file_drop.m
+++ b/internal/platform/darwin/testdata/file_drop.m
@@ -31,6 +31,7 @@ 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; }
diff --git a/internal/platform/darwin/testdata/live_resize.m b/internal/platform/darwin/testdata/live_resize.m
index bcef9abb4..4ff6bd95e 100644
--- a/internal/platform/darwin/testdata/live_resize.m
+++ b/internal/platform/darwin/testdata/live_resize.m
@@ -10,6 +10,7 @@ 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; }
diff --git a/internal/platform/darwin/testdata/modifier_taps.m b/internal/platform/darwin/testdata/modifier_taps.m
index 298f97bca..4746f4c9b 100644
--- a/internal/platform/darwin/testdata/modifier_taps.m
+++ b/internal/platform/darwin/testdata/modifier_taps.m
@@ -24,6 +24,7 @@ void vivaRawKeyEvent(uintptr_t handle, void *view, int key, int modifiers, int f
raw_code = code;
}
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; }
diff --git a/internal/platform/darwin/testdata/text_selection.m b/internal/platform/darwin/testdata/text_selection.m
index a5f9961c0..8a558eada 100644
--- a/internal/platform/darwin/testdata/text_selection.m
+++ b/internal/platform/darwin/testdata/text_selection.m
@@ -60,6 +60,7 @@ void vivaRawKeyEvent(uintptr_t handle, void *view, int key, int modifiers, int f
}
}
void vivaWindowActivated(uintptr_t handle) {}
+void vivaWindowDeactivated(uintptr_t handle, void *view) {}
void vivaFocusLost(uintptr_t handle, void *view) {}
// The terminal's table, reduced to what these tests use: CJK ideographs take two cells,
// combining marks none.
diff --git a/internal/platform/darwin/testdata/traffic_lights.m b/internal/platform/darwin/testdata/traffic_lights.m
index 6b95fb841..e3c22c283 100644
--- a/internal/platform/darwin/testdata/traffic_lights.m
+++ b/internal/platform/darwin/testdata/traffic_lights.m
@@ -9,6 +9,7 @@ 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; }
diff --git a/internal/platform/darwin/testdata/window_close.m b/internal/platform/darwin/testdata/window_close.m
index b55067003..3dcfeb4a2 100644
--- a/internal/platform/darwin/testdata/window_close.m
+++ b/internal/platform/darwin/testdata/window_close.m
@@ -18,6 +18,7 @@ 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; }
diff --git a/internal/platform/darwin/testdata/window_size.m b/internal/platform/darwin/testdata/window_size.m
index 89e42ea56..d8498e6d0 100644
--- a/internal/platform/darwin/testdata/window_size.m
+++ b/internal/platform/darwin/testdata/window_size.m
@@ -10,6 +10,7 @@ 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; }
diff --git a/internal/platform/linux/gtk_input_linux.go b/internal/platform/linux/gtk_input_linux.go
index b34630c7a..dd50a539f 100644
--- a/internal/platform/linux/gtk_input_linux.go
+++ b/internal/platform/linux/gtk_input_linux.go
@@ -419,6 +419,10 @@ func (w *gtkWindow) setKeyboard(focused bool) {
frame, err := w.config.OnFocusLost()
w.present(frame, err)
}
+ if w.config.OnDeactivate != nil {
+ frame, err := w.config.OnDeactivate()
+ w.present(frame, err)
+ }
}
// stateChanged follows the window being minimized and maximized.
diff --git a/internal/platform/linux/window_linux.go b/internal/platform/linux/window_linux.go
index 0603bd7b7..bb4308f2c 100644
--- a/internal/platform/linux/window_linux.go
+++ b/internal/platform/linux/window_linux.go
@@ -1180,6 +1180,12 @@ func (state *linuxWindowState) handleEvent(event unsafe.Pointer) (bool, error) {
return false, err
}
}
+ if realFocusLoss && config.OnDeactivate != nil {
+ frame, err := config.OnDeactivate()
+ if err := router.presentFrame(frame, err); err != nil {
+ return false, err
+ }
+ }
if router.ime != nil && realFocusLoss {
router.ime.setFocused(false)
}
diff --git a/internal/platform/windows/window_windows.go b/internal/platform/windows/window_windows.go
index 4ce043a2c..cfecee918 100644
--- a/internal/platform/windows/window_windows.go
+++ b/internal/platform/windows/window_windows.go
@@ -646,6 +646,10 @@ func windowProc(window, kind, first, second uintptr) (result uintptr) {
case wmActivate:
if uint16(first) == waInactive {
state.panelDeactivated()
+ if state.config.OnDeactivate != nil {
+ frame, err := state.config.OnDeactivate()
+ state.frame(frame, err)
+ }
} else if state.config.OnActivate != nil {
state.config.OnActivate()
}
From 73515edf014267b8936e7c45fd0418363020505c Mon Sep 17 00:00:00 2001
From: ezreal <71426102+Ezreal-byte@users.noreply.github.com>
Date: Sun, 22 Nov 2026 00:17:02 +0800
Subject: [PATCH 28/47] fix(text): draw nothing for fully transparent text
---
.github/workflows/ci.yml | 9 +++-
internal/platform/darwin/text_engine_test.go | 1 +
.../platform/linux/text_engine_linux_test.go | 1 +
internal/platform/linux/text_linux.go | 5 +++
internal/platform/windows/direct_windows.go | 3 ++
internal/platform/windows/text_windows.go | 5 +++
.../windows/textengine_windows_test.go | 41 +++++++++++++++++++
internal/textenginetest/raster.go | 29 +++++++++++++
8 files changed, 92 insertions(+), 2 deletions(-)
create mode 100644 internal/textenginetest/raster.go
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 5eead527c..2ce86e9f8 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -154,6 +154,11 @@ jobs:
wait "$pid" || status=1
done
exit "$status"
+ - name: Native Linux text rasterization
+ run: |
+ sudo apt-get install -y libpangocairo-1.0-0 fonts-noto-color-emoji ||
+ { sudo apt-get update && sudo apt-get install -y libpangocairo-1.0-0 fonts-noto-color-emoji; }
+ go test ./internal/platform/linux -run '^TestTextEngineRasterizesProportionalText$' -count=1 -v
- name: GTK optional capability contracts
run: |
go vet -tags vivagtk ./app ./internal/platform/linux
@@ -355,8 +360,8 @@ jobs:
env:
VIVA_NATIVE_GLOBAL_SHORTCUT_TEST: '1'
run: go test ./internal/platform/windows -run '^TestNativeGlobalShortcutRegistration$' -count=1 -v
- - name: Native Direct2D text origins
- run: go test ./internal/platform/windows -run '^TestDirectTextLayoutOriginByValue$' -count=1 -v
+ - name: Native Direct2D text origins and hidden labels
+ run: go test ./internal/platform/windows -run '^Test(DirectTextLayoutOriginByValue|HiddenNativeEditorDoesNotDrawColorEmoji|TextEngineRasterizesProportionalText)$' -count=1 -v
# The installer contracts, including WinVerifyTrust's struct layout, only
# compile and run on Windows.
- name: Update installer contracts
diff --git a/internal/platform/darwin/text_engine_test.go b/internal/platform/darwin/text_engine_test.go
index 5d16d9c8d..10f7ec68d 100644
--- a/internal/platform/darwin/text_engine_test.go
+++ b/internal/platform/darwin/text_engine_test.go
@@ -15,6 +15,7 @@ func TestTextEnginePassesTheContract(t *testing.T) {
func TestTextEngineRasterizesProportionalText(t *testing.T) {
engine := SharedTextEngine()
+ textenginetest.TransparentColorGlyphs(t, engine)
bitmap, err := engine.RasterizeText("Privacy 中文", gfx.TextStyle{
Size: 14, Weight: gfx.WeightSemibold, Color: gfx.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1},
}, 2, 240, 56)
diff --git a/internal/platform/linux/text_engine_linux_test.go b/internal/platform/linux/text_engine_linux_test.go
index 8aea9360d..e1129d963 100644
--- a/internal/platform/linux/text_engine_linux_test.go
+++ b/internal/platform/linux/text_engine_linux_test.go
@@ -40,6 +40,7 @@ func TestEnginePassesTheTextEngineContract(t *testing.T) {
func TestTextEngineRasterizesProportionalText(t *testing.T) {
engine := newTestEngine(t)
+ textenginetest.TransparentColorGlyphs(t, engine)
bitmap, err := engine.RasterizeText("Privacy 中文", gfx.TextStyle{
Size: 14, Weight: gfx.WeightSemibold, Color: gfx.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1},
}, 2, 240, 56)
diff --git a/internal/platform/linux/text_linux.go b/internal/platform/linux/text_linux.go
index a1b481ac1..12f260df9 100644
--- a/internal/platform/linux/text_linux.go
+++ b/internal/platform/linux/text_linux.go
@@ -517,6 +517,11 @@ func (services *textServices) draw(label platform.TextLabel, scale float32, skip
return nil, fmt.Errorf("linux: invalid label font size or scale")
}
pixels := make([]byte, width*height*4)
+ // Color glyphs can carry ink even when Pango's foreground is transparent.
+ // A run can supply its own color independently of this foreground.
+ if label.Color.Alpha <= 0 && len(label.Runs) == 0 {
+ return pixels, nil
+ }
format := int32(0) // CAIRO_FORMAT_ARGB32
if lcd {
format = 1 // CAIRO_FORMAT_RGB24: the only content Cairo antialiases per channel
diff --git a/internal/platform/windows/direct_windows.go b/internal/platform/windows/direct_windows.go
index c5a5ef4c9..d415d93e7 100644
--- a/internal/platform/windows/direct_windows.go
+++ b/internal/platform/windows/direct_windows.go
@@ -294,6 +294,9 @@ func (rasterizer *directRasterizer) rasterize(label platform.TextLabel, scale fl
return nil, false, fmt.Errorf("windows: invalid label font size")
}
rasterizer.spans = rasterizer.spans[:0]
+ if label.Color.Alpha <= 0 && len(label.Runs) == 0 {
+ return pixels, false, nil
+ }
if label.Mono || len(label.Runs) > 0 {
if allowLCD && !platform.ColorGlyphs(label.Value) {
return pixels, true, rasterizer.gridLCD(pixels, label, scale, width, height, skip)
diff --git a/internal/platform/windows/text_windows.go b/internal/platform/windows/text_windows.go
index d6d57046b..df70b8414 100644
--- a/internal/platform/windows/text_windows.go
+++ b/internal/platform/windows/text_windows.go
@@ -262,6 +262,11 @@ func (label *labelTexture) pixelOrigin(scale float32) (x, y int) {
// false when nothing is drawn: none of the label can be seen, or it is too tall for
// any texture.
func (label *labelTexture) window(scale float32, viewport int) (skip, width int, ok bool) {
+ // DirectWrite color glyphs carry their own ink. A hidden plain label must
+ // skip them as well; bitmaps and grid runs have independent colors.
+ if label.label.Color.Alpha <= 0 && len(label.label.Bitmap) == 0 && len(label.label.Runs) == 0 {
+ return 0, 0, false
+ }
full := int(math.Ceil(float64(label.label.Width * scale)))
if label.label.Mono && len(label.label.Runs) > 0 {
full = min(full, gridInkWidth(label.label.Runs, label.label.CellWidth, scale))
diff --git a/internal/platform/windows/textengine_windows_test.go b/internal/platform/windows/textengine_windows_test.go
index 372090cd8..64072c7dc 100644
--- a/internal/platform/windows/textengine_windows_test.go
+++ b/internal/platform/windows/textengine_windows_test.go
@@ -55,6 +55,7 @@ func TestTextEngineRasterizesProportionalText(t *testing.T) {
if err != nil {
t.Skipf("DirectWrite unavailable: %v", err)
}
+ textenginetest.TransparentColorGlyphs(t, engine)
bitmap, err := engine.RasterizeText("Privacy 中文", gfx.TextStyle{
Size: 14, Weight: gfx.WeightSemibold, Color: gfx.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1},
}, 2, 240, 56)
@@ -328,3 +329,43 @@ func TestTextInputOfAVeryLongDocumentIsLaidOutByTheLine(t *testing.T) {
t.Fatal("the line was not drawn")
}
}
+
+func TestHiddenNativeEditorDoesNotDrawColorEmoji(t *testing.T) {
+ runtime.LockOSThread()
+ defer runtime.UnlockOSThread()
+ input := platform.TextInput{
+ X: 12, Y: 12, Width: 280, Height: 170, FontSize: 20,
+ Multiline: true, Placed: true, HideNativeOverlays: true,
+ State: platform.TextState{Value: "哈😷🥺哈哈", Selection: text.Range{Start: 3, End: 3}},
+ }
+ state := windowState{
+ textEngine: newTestEngine(t), textInput: input, textState: input.State, textEnabled: true,
+ textLabels: make([]platform.TextLabel, 1), textRectangles: make([]render.Rectangle, textRectangleCount),
+ }
+ if err := state.updateTextVisuals(); err != nil {
+ t.Fatal(err)
+ }
+ visible := platform.TextLabel{
+ Value: input.State.Value, X: input.X, Y: input.Y,
+ Width: input.Width, Height: 28, FontSize: input.FontSize,
+ Color: platform.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1},
+ }
+ background := platform.Color{Red: 0.13, Green: 0.15, Blue: 0.18, Alpha: 1}
+ for _, test := range []struct {
+ name string
+ batch bool
+ }{{"per label", false}, {"batched", true}} {
+ t.Run(test.name, func(t *testing.T) {
+ offscreen, want := renderPage(t, 640, 400, background, test.batch, []platform.TextLabel{visible})
+ defer offscreen.Close()
+ if err := offscreen.Set(nil, []platform.TextLabel{visible, state.textLabels[0]}); err != nil {
+ t.Fatal(err)
+ }
+ got, err := offscreen.Image()
+ if err != nil {
+ t.Fatal(err)
+ }
+ comparePixels(t, want, got)
+ })
+ }
+}
diff --git a/internal/textenginetest/raster.go b/internal/textenginetest/raster.go
new file mode 100644
index 000000000..383a8f360
--- /dev/null
+++ b/internal/textenginetest/raster.go
@@ -0,0 +1,29 @@
+package textenginetest
+
+import (
+ "testing"
+
+ "github.com/vivaui/viva/gfx"
+)
+
+// TransparentColorGlyphs checks that a color font obeys the same zero opacity
+// as the ordinary glyph next to it.
+func TransparentColorGlyphs(t *testing.T, engine gfx.TextRasterizer) {
+ t.Helper()
+ for _, alpha := range []float32{1, 0} {
+ style := gfx.TextStyle{Size: 24, Color: gfx.Color{Alpha: alpha}}
+ bitmap, err := engine.RasterizeText("A😷🥺", style, 1, 160, 48)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ink := 0
+ for i := 3; i < len(bitmap.Pix); i += 4 {
+ if bitmap.Pix[i] != 0 {
+ ink++
+ }
+ }
+ if (alpha == 0) != (ink == 0) {
+ t.Errorf("foreground alpha %g produced %d painted pixels", alpha, ink)
+ }
+ }
+}
From 3a7d45185223360c0d2dbba21e7f05046a50c956 Mon Sep 17 00:00:00 2001
From: ezreal <71426102+Ezreal-byte@users.noreply.github.com>
Date: Sun, 22 Nov 2026 00:17:17 +0800
Subject: [PATCH 29/47] feat(theme): scale text size and line height by a
preference
---
base/text_scale_test.go | 34 ++++++++++++++++++++++++
gfx/text_scale_test.go | 44 ++++++++++++++++++++++++++++++
gfx/theme.go | 59 ++++++++++++++++++++++++++++++++++++++---
3 files changed, 134 insertions(+), 3 deletions(-)
create mode 100644 base/text_scale_test.go
create mode 100644 gfx/text_scale_test.go
diff --git a/base/text_scale_test.go b/base/text_scale_test.go
new file mode 100644
index 000000000..d1b171d7c
--- /dev/null
+++ b/base/text_scale_test.go
@@ -0,0 +1,34 @@
+package base
+
+import (
+ "testing"
+
+ "github.com/vivaui/viva/gfx"
+)
+
+func TestScaledAndAbsoluteTextShareOneLayout(t *testing.T) {
+ theme := gfx.LightTheme().WithTextScale(1.5)
+ canvas := testCanvas()
+ var view View
+ var heading Box
+ view.Draw(canvas, theme, gfx.Rect{Width: 300, Height: 180}, func(f *Frame) {
+ f.Column().Children(func() {
+ heading = f.Text("Heading").FontSize(theme.Metrics.ScaledText(20)).LineHeight(theme.Metrics.ScaledText(28))
+ f.Text("Token").FontSize(theme.Metrics.FontSizeM)
+ f.Text("Fixed").FontSize(12)
+ })
+ })
+ if got := heading.Rect().Height; got != 42 {
+ t.Fatalf("heading line height = %v, want 42", got)
+ }
+ labels := canvas.Texts()
+ want := []float32{30, 21, 12}
+ if len(labels) != len(want) {
+ t.Fatalf("drew %d labels, want %d", len(labels), len(want))
+ }
+ for i, l := range labels {
+ if l.Style.Size != want[i] {
+ t.Errorf("%s font size = %v, want %v", l.Value, l.Style.Size, want[i])
+ }
+ }
+}
diff --git a/gfx/text_scale_test.go b/gfx/text_scale_test.go
new file mode 100644
index 000000000..1ea1dfa6a
--- /dev/null
+++ b/gfx/text_scale_test.go
@@ -0,0 +1,44 @@
+package gfx
+
+import (
+ "math"
+ "testing"
+)
+
+func TestThemeTextScale(t *testing.T) {
+ base := LightTheme().WithFontSize(16)
+ scaled := base.WithTextScale(1.5)
+ want := base.WithFontSize(24).Metrics
+ want.textScale = 1.5
+ if scaled.Metrics != want || scaled.Metrics.ScaledText(20) != 30 || scaled.Metrics.ScaledText(28) != 42 {
+ t.Fatalf("scaled metrics = %+v", scaled.Metrics)
+ }
+ if scaled.WithTextScale(1.5) != scaled || scaled.WithTextScale(1) != base {
+ t.Fatal("reapplying or resetting the preference changed the base theme")
+ }
+ for _, invalid := range []float32{0, -1, float32(math.Inf(1)), float32(math.NaN())} {
+ if scaled.WithTextScale(invalid) != scaled {
+ t.Errorf("invalid scale %v changed the theme", invalid)
+ }
+ }
+ if got := base.WithTextScale(math.MaxFloat32); got != base {
+ t.Fatal("a scale that overflows a font size changed the theme")
+ }
+ defaultTheme := LightTheme()
+ tiny := defaultTheme.WithTextScale(math.SmallestNonzeroFloat32)
+ if tiny.Metrics.ScaledText(1) != math.SmallestNonzeroFloat32 || tiny.WithTextScale(1) != defaultTheme {
+ t.Fatal("a representable tiny font scale could not be reset")
+ }
+ custom := defaultTheme
+ custom.Metrics.FontSizeS = 0.25
+ if got := custom.WithTextScale(math.SmallestNonzeroFloat32); got != custom {
+ t.Fatal("a scale that rounds a nonzero font size to zero changed the theme")
+ }
+ for _, density := range []Density{DensityCompact, DensityLarge} {
+ first := base
+ first.Metrics = first.Metrics.WithDensity(density)
+ if got := scaled.Metrics.WithDensity(density); got != first.WithTextScale(1.5).Metrics {
+ t.Errorf("scale and density applied in a different order: %+v", got)
+ }
+ }
+}
diff --git a/gfx/theme.go b/gfx/theme.go
index 8a2ed7991..85c32aa30 100644
--- a/gfx/theme.go
+++ b/gfx/theme.go
@@ -1,6 +1,9 @@
package gfx
-import "time"
+import (
+ "math"
+ "time"
+)
const (
WeightRegular float32 = 0
@@ -30,6 +33,17 @@ type Metrics struct {
PadControlX float32 // horizontal control padding
PadSurface float32 // card interior padding
GapItem float32 // row-to-row spacing inside lists
+ textScale float32 // zero is the default multiplier of one
+}
+
+// ScaledText converts a design size or line height to logical pixels at the
+// application's text scale. FontSizeS, FontSizeM and FontSizeL are already
+// scaled and can be passed directly to controls.
+func (m Metrics) ScaledText(size float32) float32 {
+ if m.textScale == 0 {
+ return size
+ }
+ return size * m.textScale
}
// RadiusItem is the corner radius of a row inside a menu, list or popup: two
@@ -68,15 +82,16 @@ func DefaultMetrics() Metrics {
// WithDensity derives a metrics set at another density.
func (m Metrics) WithDensity(density Density) Metrics {
+ var preset Metrics
switch density {
case DensityCompact:
- return Metrics{
+ preset = Metrics{
ControlHeight: 26, RadiusControl: 5.5, RadiusSurface: 9,
FontSizeS: 11, FontSizeM: 13, FontSizeL: 22,
PadControlX: 10, PadSurface: 14, GapItem: 6,
}
case DensityLarge:
- return Metrics{
+ preset = Metrics{
ControlHeight: 40, RadiusControl: 9, RadiusSurface: 13,
FontSizeS: 14, FontSizeM: 16, FontSizeL: 30,
PadControlX: 18, PadSurface: 24, GapItem: 10,
@@ -84,6 +99,7 @@ func (m Metrics) WithDensity(density Density) Metrics {
default:
return m
}
+ return preset.withTextScale(m.textScale)
}
// Theme contains semantic design tokens rather than runtime CSS.
@@ -166,6 +182,43 @@ func (theme Theme) WithFontSize(size float32) Theme {
return theme
}
+// WithTextScale sets an absolute text multiplier on a copy of the theme.
+// It scales the small, body and title tokens while leaving control geometry
+// alone. Use Metrics.ScaledText for explicit sizes, including line heights:
+//
+// look := gfx.LightTheme().WithTextScale(1.5)
+// ui.Text(c, title).FontSize(look.Metrics.ScaledText(20)).LineHeight(look.Metrics.ScaledText(28))
+//
+// Passing one restores the original scale. It ignores non-positive or
+// non-finite scales and scales that would overflow a font size or round a
+// nonzero font size to zero.
+func (theme Theme) WithTextScale(scale float32) Theme {
+ theme.Metrics = theme.Metrics.withTextScale(scale)
+ return theme
+}
+
+func (m Metrics) withTextScale(scale float32) Metrics {
+ if !(scale > 0) || scale > math.MaxFloat32 || scale == m.ScaledText(1) {
+ return m
+ }
+ // The ratio of two float32 scales can overflow even when all three final
+ // font sizes fit, for example when returning from a very small scale.
+ ratio := float64(scale) / float64(m.ScaledText(1))
+ next := m
+ for _, token := range [...]*float32{&next.FontSizeS, &next.FontSizeM, &next.FontSizeL} {
+ size := float32(float64(*token) * ratio)
+ if math.IsInf(float64(size), 0) || (size == 0 && *token != 0) {
+ return m
+ }
+ *token = size
+ }
+ next.textScale = scale
+ if scale == 1 {
+ next.textScale = 0
+ }
+ return next
+}
+
// WithOpacity is the theme with the opacity of every color multiplied by opacity,
// 0 to 1, for a control painted faded: what it draws with the copy is as
// transparent as the copy's colors, so a faded Button, Input or Card needs no
From 8f69ffecc7bc1ae81e7f9738cdb2de47642bbd78 Mon Sep 17 00:00:00 2001
From: ezreal <71426102+Ezreal-byte@users.noreply.github.com>
Date: Sun, 22 Nov 2026 00:30:34 +0800
Subject: [PATCH 30/47] feat(app): add a clickable notification popup
---
.github/workflows/ci.yml | 20 ++++-
README.md | 2 +
app/app.go | 7 ++
app/panel.go | 11 +--
headless/application.go | 26 +++---
headless/application_test.go | 30 +++++++
internal/platform/contract.go | 2 +
internal/platform/darwin/native.m | 40 ++++++---
.../darwin/testdata/window_notification.m | 89 +++++++++++++++++++
.../platform/darwin/testdata/window_size.m | 36 +-------
.../darwin/testdata/window_test_callbacks.h | 36 ++++++++
.../platform/linux/always_on_top_linux.go | 3 +-
internal/platform/linux/gtk_icon_linux.go | 2 +-
internal/platform/linux/gtk_library_linux.go | 8 ++
.../linux/gtk_notification_linux_test.go | 36 ++++++++
internal/platform/linux/gtk_window_linux.go | 41 ++++++++-
internal/platform/linux/status_item_linux.go | 43 +++++++--
internal/platform/linux/window_linux.go | 6 +-
.../linux/window_notification_linux_test.go | 79 ++++++++++++++++
internal/platform/status_item.go | 6 ++
internal/platform/status_item_test.go | 10 +++
.../platform/windows/always_on_top_windows.go | 3 +-
.../platform/windows/status_item_windows.go | 8 +-
.../window_notification_windows_test.go | 84 +++++++++++++++++
internal/platform/windows/window_windows.go | 22 ++++-
website/content/guides/en/windows.md | 1 +
website/content/guides/zh/windows.md | 1 +
27 files changed, 567 insertions(+), 85 deletions(-)
create mode 100644 internal/platform/darwin/testdata/window_notification.m
create mode 100644 internal/platform/darwin/testdata/window_test_callbacks.h
create mode 100644 internal/platform/linux/gtk_notification_linux_test.go
create mode 100644 internal/platform/linux/window_notification_linux_test.go
create mode 100644 internal/platform/windows/window_notification_windows_test.go
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 2ce86e9f8..8ef49427b 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -167,13 +167,15 @@ jobs:
# titlebar contracts that do not need a server name their tests here.
- name: Titlebar and window contracts
run: go test ./internal/platform/linux -run '^Test(MaximizeButtonSetsBothDirections|PreviewMovePreservesSizeAndFocus|AClipboardImageIsOfferedAsPNGAndNoText|SetClipboardImageClaimsTheClipboardAndDropsOtherFlavours)$' -count=1 -v
- - name: Native X11 drag preview
+ - name: Native X11 drag preview and notification
env:
VIVA_TEST_PREVIEW_XVFB: '1'
+ VIVA_TEST_NOTIFICATION_XVFB: '1'
run: |
- sudo apt-get install -y xvfb libxcb-shape0 ||
- { sudo apt-get update && sudo apt-get install -y xvfb libxcb-shape0; }
- xvfb-run -a go test ./internal/platform/linux -run '^TestPreviewNativeX11Contract$' -count=1 -v
+ sudo apt-get install -y xvfb libxcb-shape0 libgtk-3-0 ||
+ { sudo apt-get update && sudo apt-get install -y xvfb libxcb-shape0 libgtk-3-0; }
+ xvfb-run -a go test ./internal/platform/linux -run '^Test(PreviewNativeX11Contract|NotificationNativeX11)$' -count=1 -v
+ GDK_BACKEND=x11 VIVA_TEST_GTK_NOTIFICATION=1 xvfb-run -a go test -tags vivagtk ./internal/platform/linux -run '^TestGTKNotificationFocusHints$' -count=1 -v
- name: Native X11 global shortcut
env:
VIVA_NATIVE_GLOBAL_SHORTCUT_TEST: '1'
@@ -310,6 +312,11 @@ jobs:
with:
go-version-file: go.mod
cache: true
+ - name: Native AppKit notification focus and click
+ working-directory: internal/platform/darwin
+ run: |
+ xcrun clang -fno-objc-arc -Werror -Wno-deprecated-declarations testdata/window_notification.m -o "$RUNNER_TEMP/window-notification" -framework Cocoa -framework CoreText -framework Metal -framework QuartzCore
+ "$RUNNER_TEMP/window-notification"
# A package with no darwin file compiles to the same source on every
# operating system, so the lint job's `go vet ./...` already covers it;
# what is left here is the darwin build of the packages that have one. The
@@ -333,6 +340,7 @@ jobs:
VIVA_NATIVE_GLOBAL_SHORTCUT_TEST: '1'
run: go test ./internal/platform/darwin -run '^TestNativeCarbonGlobalShortcut$' -count=1 -v
+
windows-materials:
needs: changes
if: needs.changes.outputs.code == 'true'
@@ -356,6 +364,10 @@ jobs:
run: go test ./internal/platform/windows -run '^TestATerminalGetsEditingKeysAndChordsAsRawKeys$' -count=1 -v
- name: Native window and grouped taskbar icons
run: go test ./internal/platform/windows -run '^TestWindowIconUpdatesOnTheWindowThread$' -count=1 -v
+ - name: Non-activating desktop notification
+ env:
+ VIVA_TEST_NOTIFICATION_DESKTOP: '1'
+ run: go test ./internal/platform/windows -run '^TestNotificationNativeWindows$' -count=1 -v
- name: Native Windows global shortcut
env:
VIVA_NATIVE_GLOBAL_SHORTCUT_TEST: '1'
diff --git a/README.md b/README.md
index 679172bcd..13d83512d 100644
--- a/README.md
+++ b/README.md
@@ -112,6 +112,8 @@ WebView and no bundled rendering runtime.
StatusNotifier host; `StatusItemConfig.Menu` makes it open the system's own
menu (NSMenu, a Win32 popup menu, `com.canonical.dbusmenu`); `WindowPanel` is
the borderless popup that opens beside it and closes when it loses focus;
+ `WindowNotification` is a clickable popup that does not take the keyboard and
+ stays open when focus moves away;
`Window.Hide`/`Show` keep an application running without a visible window.
- `Application.SetDockBadge` puts a label in the red badge macOS draws at the
corner of the application's Dock tile, and an empty label removes it.
diff --git a/app/app.go b/app/app.go
index f01f10e43..62de4ecac 100644
--- a/app/app.go
+++ b/app/app.go
@@ -5,6 +5,7 @@ import (
"fmt"
"github.com/vivaui/viva/gfx"
+ "github.com/vivaui/viva/internal/platform"
)
const (
@@ -40,6 +41,12 @@ const (
// closes itself when it loses focus; OnClosed reports that, and OnCloseRequest
// is not asked.
WindowPanel
+ // WindowNotification opens a desktop popup that accepts pointer input and
+ // stays open when focus changes. On Windows, macOS and X11 it requests the
+ // bottom-right of the pointer monitor's work area without taking keyboard
+ // focus. On native Wayland, the compositor decides placement, stacking and
+ // keyboard focus. Use SendNotification for a system-managed notification.
+ WindowNotification WindowMode = WindowMode(platform.WindowNotification)
)
// Config describes the initial native window.
diff --git a/app/panel.go b/app/panel.go
index 1fe0c3f3f..99bd29643 100644
--- a/app/panel.go
+++ b/app/panel.go
@@ -3,15 +3,16 @@ package app
import "runtime"
// panelCornerRadius is the radius, in logical pixels, to which macOS rounds a
-// WindowPanel. It matches VIVA_PANEL_CORNER_RADIUS in
+// WindowPanel and a WindowNotification. It matches VIVA_PANEL_CORNER_RADIUS in
// internal/platform/darwin/native.m; panel_test.go keeps the two equal.
const panelCornerRadius = 14
// PanelCornerRadius is the radius, in logical pixels, at which the system cuts
-// the corners of a WindowPanel: whatever the panel paints beyond it is not
-// shown. Draw the panel's edge as a gfx.Canvas.RoundedBorder of this radius so
-// the outline follows the corner instead of being clipped by it. It is zero
-// where panels have square corners.
+// the corners of a WindowPanel or a WindowNotification: whatever the popup
+// paints beyond it is not shown. Draw its edge as a gfx.Canvas.RoundedBorder of
+// this radius so the outline follows the corner instead of being clipped by it.
+// It is zero where popups have square corners (Linux), and on Windows the
+// system's own window rounding applies.
func PanelCornerRadius() float32 {
if runtime.GOOS == "darwin" {
return panelCornerRadius
diff --git a/headless/application.go b/headless/application.go
index eb6786654..aa9e89f9d 100644
--- a/headless/application.go
+++ b/headless/application.go
@@ -21,15 +21,16 @@ type applicationWindow struct {
fullscreen atomic.Bool
fullscreenRequest atomic.Int32
// sizeRequest is the content size SetSize queued for the loop, or nil.
- sizeRequest atomic.Pointer[[2]int32]
- invalidator *app.Invalidator
- id uint64
- title string
- icon app.WindowIcon
- panel bool
- hidden bool
- session *Session
- closed func()
+ sizeRequest atomic.Pointer[[2]int32]
+ invalidator *app.Invalidator
+ id uint64
+ title string
+ icon app.WindowIcon
+ panel bool
+ notification bool
+ hidden bool
+ session *Session
+ closed func()
// closeRequest is the application's OnCloseRequest, if it set one.
closeRequest func(allow func())
}
@@ -121,8 +122,11 @@ func (application *applicationSession) OpenWindow(config app.Config, canvas *gfx
id := application.nextID
application.nextID++
entry.id, entry.title, entry.panel, entry.session, entry.closed, entry.closeRequest = id, config.Title, config.WindowMode == app.WindowPanel, session, closed, config.OnCloseRequest
+ entry.notification = config.WindowMode == app.WindowNotification
application.windows[id] = entry
- application.active = id
+ if !entry.notification || application.active == 0 {
+ application.active = id
+ }
application.mu.Unlock()
return &headlessWindow{application: application, id: id}, nil
}
@@ -215,7 +219,7 @@ func (application *applicationSession) setHidden(id uint64, hidden bool) {
defer application.mu.Unlock()
if window := application.windows[id]; window != nil {
window.hidden = hidden
- if !hidden {
+ if !hidden && !window.notification {
application.active = id
}
}
diff --git a/headless/application_test.go b/headless/application_test.go
index 004206f14..1c7b83f30 100644
--- a/headless/application_test.go
+++ b/headless/application_test.go
@@ -45,6 +45,36 @@ func TestApplicationSessionRoutesStateFocusAndClosePerWindow(t *testing.T) {
}
}
+func TestNotificationKeepsCurrentWindow(t *testing.T) {
+ session := newApplicationSession(Options{Scale: 1})
+ t.Cleanup(session.closeAll)
+ _, err := session.OpenWindow(app.Config{Width: 200, Height: 100}, nil, func() {})
+ if err != nil {
+ t.Fatal(err)
+ }
+ owner := session.activeID()
+ popup, err := session.OpenWindow(app.Config{Width: 160, Height: 80, WindowMode: app.WindowNotification}, nil, func() {})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if session.activeID() != owner {
+ t.Fatal("opening the notification moved the headless command target")
+ }
+ notification := popup.(*headlessWindow)
+ notification.Hide()
+ notification.Show()
+ if err := session.blurWindow(notification.id); err != nil {
+ t.Fatal(err)
+ }
+ if _, windows := session.describe(); len(windows) != 2 || session.activeID() != owner {
+ t.Fatal("show or blur changed the current window or dismissed the notification")
+ }
+ notification.Close()
+ if _, windows := session.describe(); len(windows) != 1 || session.activeID() != owner {
+ t.Fatal("closing the notification disturbed the previous window")
+ }
+}
+
func editingWindow(title string, hit uint32, editor *text.Editor) app.Config {
return app.Config{
Title: title, Width: 240, Height: 100,
diff --git a/internal/platform/contract.go b/internal/platform/contract.go
index 3757f7744..7ecbf8780 100644
--- a/internal/platform/contract.go
+++ b/internal/platform/contract.go
@@ -849,6 +849,8 @@ const (
// whatever is under it still gets every event. Adapters that cannot make
// one refuse it. WindowMover moves it.
WindowPreview
+ // WindowNotification is an interactive, non-activating desktop popup.
+ WindowNotification
)
// DefaultTitlebarHeight is the custom titlebar strip, in logical pixels, of a
diff --git a/internal/platform/darwin/native.m b/internal/platform/darwin/native.m
index 528535b2d..7272d016b 100644
--- a/internal/platform/darwin/native.m
+++ b/internal/platform/darwin/native.m
@@ -67,6 +67,7 @@ static int viva_remember_shader_library(const unsigned char *bytes, size_t lengt
VIVA_WINDOW_CUSTOM_TITLEBAR = 2,
VIVA_WINDOW_PANEL = 3,
VIVA_WINDOW_PREVIEW = 4,
+ VIVA_WINDOW_NOTIFICATION = 5,
};
/* How far from the status item a panel opens, the margin it keeps from the edge
@@ -4216,14 +4217,14 @@ - (instancetype)initWithFrame:(NSRect)frame
self.wantsLayer = YES;
self.layer = _metalLayer;
- if (windowMode == VIVA_WINDOW_PANEL) {
+ 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
* rows still react to the pointer. */
- NSTrackingAreaOptions activeness = windowMode == VIVA_WINDOW_PANEL ? NSTrackingActiveAlways : NSTrackingActiveInActiveApp;
+ NSTrackingAreaOptions activeness = (windowMode == VIVA_WINDOW_PANEL || windowMode == VIVA_WINDOW_NOTIFICATION) ? NSTrackingActiveAlways : NSTrackingActiveInActiveApp;
NSTrackingArea *tracking = [[NSTrackingArea alloc]
initWithRect:self.bounds
options:NSTrackingMouseMoved |
@@ -4362,7 +4363,7 @@ - (BOOL)replaceCompositePlanForRectangles:(const viva_rectangle *)rectangles
}
- (BOOL)isOpaque {
- return _windowMode != VIVA_WINDOW_PANEL && _windowMode != VIVA_WINDOW_PREVIEW;
+ return _windowMode != VIVA_WINDOW_PANEL && _windowMode != VIVA_WINDOW_PREVIEW && _windowMode != VIVA_WINDOW_NOTIFICATION;
}
- (BOOL)acceptsFirstResponder {
@@ -6572,14 +6573,14 @@ - (void)applicationDidFinishLaunching:(NSNotification *)notification {
NSWindowStyleMaskResizable;
if (_windowMode == VIVA_WINDOW_FRAMELESS) {
style = NSWindowStyleMaskBorderless;
- } else if (_windowMode == VIVA_WINDOW_PANEL || _windowMode == VIVA_WINDOW_PREVIEW) {
+ } else if (_windowMode == VIVA_WINDOW_PANEL || _windowMode == VIVA_WINDOW_PREVIEW || _windowMode == VIVA_WINDOW_NOTIFICATION) {
style = NSWindowStyleMaskBorderless | NSWindowStyleMaskNonactivatingPanel;
} else if (_windowMode == VIVA_WINDOW_CUSTOM_TITLEBAR) {
style |= NSWindowStyleMaskFullSizeContentView;
}
Class windowClass = _windowMode == VIVA_WINDOW_PANEL ? [VivaPanel class] : [NSWindow class];
- if (_windowMode == VIVA_WINDOW_PREVIEW) {
+ if (_windowMode == VIVA_WINDOW_PREVIEW || _windowMode == VIVA_WINDOW_NOTIFICATION) {
windowClass = [VivaPreview class];
}
if (_windowMode == VIVA_WINDOW_FRAMELESS) {
@@ -6594,7 +6595,7 @@ - (void)applicationDidFinishLaunching:(NSNotification *)notification {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(screenParametersChanged:)
name:NSApplicationDidChangeScreenParametersNotification object:nil];
_window.releasedWhenClosed = NO;
- if (_windowMode != VIVA_WINDOW_PANEL && _windowMode != VIVA_WINDOW_PREVIEW) {
+ if (_windowMode != VIVA_WINDOW_PANEL && _windowMode != VIVA_WINDOW_PREVIEW && _windowMode != VIVA_WINDOW_NOTIFICATION) {
_window.collectionBehavior |= NSWindowCollectionBehaviorFullScreenPrimary;
}
if (_windowMode == VIVA_WINDOW_PREVIEW) {
@@ -6612,7 +6613,7 @@ - (void)applicationDidFinishLaunching:(NSNotification *)notification {
NSWindowCollectionBehaviorTransient |
NSWindowCollectionBehaviorIgnoresCycle;
((NSPanel *)_window).hidesOnDeactivate = NO;
- } else if (_windowMode == VIVA_WINDOW_PANEL) {
+ } else if (_windowMode == VIVA_WINDOW_PANEL || _windowMode == VIVA_WINDOW_NOTIFICATION) {
_window.minSize = NSMakeSize(1, 1);
_window.backgroundColor = [NSColor clearColor];
_window.opaque = NO;
@@ -6681,7 +6682,7 @@ - (void)applicationDidFinishLaunching:(NSNotification *)notification {
[self keepTrafficLightsCentered];
}
- if (_windowMode == VIVA_WINDOW_PANEL) {
+ if (_windowMode == VIVA_WINDOW_PANEL || _windowMode == VIVA_WINDOW_NOTIFICATION) {
[self placePanel];
} else if (_hasOrigin) {
[self placeAtOrigin];
@@ -6698,7 +6699,7 @@ - (void)applicationDidFinishLaunching:(NSNotification *)notification {
[_window setFrame:[_window constrainFrameRect:fitted toScreen:screen] display:NO];
}
}
- if (_windowMode == VIVA_WINDOW_PREVIEW) {
+ if (_windowMode == VIVA_WINDOW_PREVIEW || _windowMode == VIVA_WINDOW_NOTIFICATION) {
/* It appears without taking the key or bringing the application forward. */
[_window orderFrontRegardless];
} else {
@@ -7123,7 +7124,7 @@ - (void)confirmClose {
/* Whether this window is one the application's ordinary window handling
* leaves alone: no Dock reopen, no full screen. */
- (BOOL)isPanel {
- return _windowMode == VIVA_WINDOW_PANEL || _windowMode == VIVA_WINDOW_PREVIEW;
+ return _windowMode == VIVA_WINDOW_PANEL || _windowMode == VIVA_WINDOW_PREVIEW || _windowMode == VIVA_WINDOW_NOTIFICATION;
}
- (BOOL)isHidden {
@@ -7142,6 +7143,10 @@ - (void)showWindow {
if (_window == nil || !_running) {
return;
}
+ if (_windowMode == VIVA_WINDOW_NOTIFICATION) {
+ [_window orderFrontRegardless];
+ return;
+ }
if (_window.isMiniaturized) {
[_window deminiaturize:nil];
}
@@ -7246,6 +7251,21 @@ - (BOOL)contentFrame:(double *)out {
* the menu bar at the top of the screen, and kept inside the visible part of the
* screen the anchor is on. Without an anchor it is centered on the screen. */
- (void)placePanel {
+ if (_windowMode == VIVA_WINDOW_NOTIFICATION) {
+ NSPoint point = NSEvent.mouseLocation;
+ NSScreen *screen = NSScreen.mainScreen ?: NSScreen.screens.firstObject;
+ for (NSScreen *candidate in NSScreen.screens) {
+ if (NSPointInRect(point, candidate.frame)) {
+ screen = candidate;
+ break;
+ }
+ }
+ NSRect area = screen.visibleFrame;
+ NSSize size = _window.frame.size;
+ [_window setFrameOrigin:NSMakePoint(MAX(NSMinX(area), NSMaxX(area) - size.width - 12),
+ MIN(NSMaxY(area) - size.height, NSMinY(area) + 12))];
+ return;
+ }
if (!_hasAnchor) {
[_window center];
return;
diff --git a/internal/platform/darwin/testdata/window_notification.m b/internal/platform/darwin/testdata/window_notification.m
new file mode 100644
index 000000000..d1d5e6a2e
--- /dev/null
+++ b/internal/platform/darwin/testdata/window_notification.m
@@ -0,0 +1,89 @@
+#include "../native.m"
+#include "../main_menu_darwin.m"
+#include "window_test_callbacks.h"
+#include
+
+static unsigned downs, ups;
+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++;
+ if (kind == VIVA_POINTER_UP) ups++;
+}
+
+static void dispatchEvents(NSTimeInterval seconds) {
+ NSDate *deadline = [NSDate dateWithTimeIntervalSinceNow:seconds];
+ while (deadline.timeIntervalSinceNow > 0) {
+ NSEvent *event = [NSApp nextEventMatchingMask:NSEventMaskAny untilDate:deadline
+ inMode:NSDefaultRunLoopMode dequeue:YES];
+ if (event != nil) [NSApp sendEvent:event];
+ }
+}
+
+// This runs on a private CI desktop. The native window and event dispatch are
+// real. No accessibility permission or system-wide mouse injection is needed.
+int main(void) {
+ @autoreleasepool {
+ [NSApplication sharedApplication];
+ [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
+ [NSApp finishLaunching];
+ NSWindow *owner = [[NSWindow alloc] initWithContentRect:NSMakeRect(100, 100, 240, 120)
+ styleMask:NSWindowStyleMaskTitled
+ backing:NSBackingStoreBuffered defer:NO];
+ [NSApp activateIgnoringOtherApps:YES];
+ [owner makeKeyAndOrderFront:nil];
+ NSDate *deadline = [NSDate dateWithTimeIntervalSinceNow:3];
+ while (NSApp.keyWindow != owner && deadline.timeIntervalSinceNow > 0) {
+ dispatchEvents(0.05);
+ }
+ NSWindow *key = NSApp.keyWindow;
+ pid_t foreground = NSWorkspace.sharedWorkspace.frontmostApplication.processIdentifier;
+ // WindowServer may keep a different application in front of a test
+ // executable. In that case verify that application's focus as well.
+ assert(key == owner || (foreground > 0 && foreground != NSProcessInfo.processInfo.processIdentifier));
+
+ viva_window_config config = {.title = "Viva notification", .width = 180, .height = 80};
+ id device = MTLCreateSystemDefaultDevice();
+ id queue = [device newCommandQueue];
+ VivaAppDelegate *popup = [[VivaAppDelegate alloc] initWithConfig:config device:device
+ commandQueue:queue 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:YES
+ resizeEventsEnabled:NO keyEventsEnabled:NO scrollEventsEnabled:NO windowMode:VIVA_WINDOW_NOTIFICATION
+ closeInterceptEnabled:NO callbackHandle:1];
+ [popup applicationDidFinishLaunching:[NSNotification notificationWithName:NSApplicationDidFinishLaunchingNotification object:NSApp]];
+ NSWindow *window = [popup valueForKey:@"window"];
+ dispatchEvents(0.1);
+ assert(window.isVisible && NSApp.keyWindow == key);
+ assert(NSWorkspace.sharedWorkspace.frontmostApplication.processIdentifier == foreground);
+ assert(!window.canBecomeKeyWindow && !window.canBecomeMainWindow && !window.ignoresMouseEvents);
+ // The popup is cut like a panel, so its content aligns with the system's rounding.
+ assert(window.contentView.layer.cornerRadius == VIVA_PANEL_CORNER_RADIUS);
+ assert(window.level > NSNormalWindowLevel);
+
+ for (NSNumber *type in @[@(NSEventTypeLeftMouseDown), @(NSEventTypeLeftMouseUp)]) {
+ NSEvent *event = [NSEvent mouseEventWithType:(NSEventType)type.unsignedIntegerValue
+ location:NSMakePoint(30, 20) modifierFlags:0 timestamp:NSProcessInfo.processInfo.systemUptime
+ windowNumber:window.windowNumber context:nil eventNumber:1 clickCount:1 pressure:1];
+ assert([window.contentView acceptsFirstMouse:event]);
+ [window sendEvent:event];
+ }
+ dispatchEvents(0.1);
+ assert(downs == 1 && ups == 1 && NSApp.keyWindow == key);
+ assert(NSWorkspace.sharedWorkspace.frontmostApplication.processIdentifier == foreground);
+ [popup hideWindow];
+ assert(!window.isVisible);
+ [popup showWindow];
+ dispatchEvents(0.1);
+ assert(window.isVisible && NSApp.keyWindow == key);
+ assert(NSWorkspace.sharedWorkspace.frontmostApplication.processIdentifier == foreground);
+ [popup hideWindow];
+ [owner orderOut:nil];
+ [popup release];
+ [queue release];
+ [device release];
+ [owner release];
+ printf("AppKit notification received the click and preserved the %s focus on open and show\n",
+ key == owner ? "owner window's" : "other application's");
+ }
+ return 0;
+}
diff --git a/internal/platform/darwin/testdata/window_size.m b/internal/platform/darwin/testdata/window_size.m
index d8498e6d0..a7998ca54 100644
--- a/internal/platform/darwin/testdata/window_size.m
+++ b/internal/platform/darwin/testdata/window_size.m
@@ -5,41 +5,7 @@
// The callbacks native.m reports to Go; this test listens to none of them.
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 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; }
+#include "window_test_callbacks.h"
static BOOL near(CGFloat a, CGFloat b) { return fabs(a - b) < 0.5; }
diff --git a/internal/platform/darwin/testdata/window_test_callbacks.h b/internal/platform/darwin/testdata/window_test_callbacks.h
new file mode 100644
index 000000000..a659f6740
--- /dev/null
+++ b/internal/platform/darwin/testdata/window_test_callbacks.h
@@ -0,0 +1,36 @@
+// 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 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; }
diff --git a/internal/platform/linux/always_on_top_linux.go b/internal/platform/linux/always_on_top_linux.go
index bbcf85117..549a99c97 100644
--- a/internal/platform/linux/always_on_top_linux.go
+++ b/internal/platform/linux/always_on_top_linux.go
@@ -13,7 +13,8 @@ func (window *nativeWindow) SetAlwaysOnTop(enabled bool) error {
return fmt.Errorf("linux: window is closed")
}
state := window.state
- if state.config.WindowMode == platform.WindowPanel || state.config.WindowMode == platform.WindowPreview {
+ switch state.config.WindowMode {
+ case platform.WindowPanel, platform.WindowPreview, platform.WindowNotification:
return platform.ErrAlwaysOnTopUnsupported
}
win := state.win
diff --git a/internal/platform/linux/gtk_icon_linux.go b/internal/platform/linux/gtk_icon_linux.go
index 9f6996466..4839897f1 100644
--- a/internal/platform/linux/gtk_icon_linux.go
+++ b/internal/platform/linux/gtk_icon_linux.go
@@ -84,7 +84,7 @@ func (w *gtkWindow) setIcon() {
// the difference between the content and the asked-for origin is corrected once.
func (w *gtkWindow) placeAtOrigin() {
config := w.config
- if !config.HasOrigin || w.app.wayland || config.WindowMode == platform.WindowPanel {
+ if !config.HasOrigin || w.app.wayland || (config.WindowMode == platform.WindowPanel || config.WindowMode == platform.WindowNotification) {
return
}
x, y := int32(math.Round(float64(config.Origin.X*w.ratio))), int32(math.Round(float64(config.Origin.Y*w.ratio)))
diff --git a/internal/platform/linux/gtk_library_linux.go b/internal/platform/linux/gtk_library_linux.go
index 5872ba19b..c3ab18a44 100644
--- a/internal/platform/linux/gtk_library_linux.go
+++ b/internal/platform/linux/gtk_library_linux.go
@@ -54,6 +54,7 @@ type gtkLibrary struct {
windowSkipTaskbar func(window uintptr, skip int32)
windowKeepAbove func(window uintptr, keep int32)
windowAcceptFocus func(window uintptr, accept int32)
+ windowFocusOnMap func(window uintptr, focus int32)
windowSetWMClass func(window uintptr, name, class *byte)
windowSetIconList func(window, list uintptr)
windowIconify func(window uintptr)
@@ -158,7 +159,10 @@ type gtkLibrary struct {
gdkScreenDefault func() uintptr
gdkDisplayName func(display uintptr) uintptr
gdkDisplaySeat func(display uintptr) uintptr
+ gdkMonitorAtPoint func(display uintptr, x, y int32) uintptr
+ gdkMonitorAtIndex func(display uintptr, index int32) uintptr
gdkDisplayMonitorAt func(display, window uintptr) uintptr
+ gdkMonitorWorkarea func(monitor uintptr, rect *[4]int32)
gdkMonitorGeometry func(monitor uintptr, rect *[4]int32)
gdkWindowSetCursor func(window, cursor uintptr)
gdkWindowNew func(parent uintptr, attrs *gdkWindowAttr, mask int32) uintptr
@@ -356,6 +360,7 @@ func (g *gtkLibrary) bindAll() {
b(&g.windowSkipTaskbar, "gtk_window_set_skip_taskbar_hint")
b(&g.windowKeepAbove, "gtk_window_set_keep_above")
b(&g.windowAcceptFocus, "gtk_window_set_accept_focus")
+ b(&g.windowFocusOnMap, "gtk_window_set_focus_on_map")
b(&g.windowSetWMClass, "gtk_window_set_wmclass")
b(&g.windowSetIconList, "gtk_window_set_icon_list")
b(&g.windowIconify, "gtk_window_iconify")
@@ -454,6 +459,9 @@ func (g *gtkLibrary) bindAll() {
b(&g.gdkDisplayName, "gdk_display_get_name")
b(&g.gdkDisplaySeat, "gdk_display_get_default_seat")
b(&g.gdkDisplayMonitorAt, "gdk_display_get_monitor_at_window")
+ b(&g.gdkMonitorAtPoint, "gdk_display_get_monitor_at_point")
+ b(&g.gdkMonitorAtIndex, "gdk_display_get_monitor")
+ b(&g.gdkMonitorWorkarea, "gdk_monitor_get_workarea")
b(&g.gdkMonitorGeometry, "gdk_monitor_get_geometry")
b(&g.gdkWindowSetCursor, "gdk_window_set_cursor")
b(&g.gdkWindowNew, "gdk_window_new")
diff --git a/internal/platform/linux/gtk_notification_linux_test.go b/internal/platform/linux/gtk_notification_linux_test.go
new file mode 100644
index 000000000..adc995c7f
--- /dev/null
+++ b/internal/platform/linux/gtk_notification_linux_test.go
@@ -0,0 +1,36 @@
+//go:build linux && vivagtk
+
+package linux
+
+import (
+ "fmt"
+ "os"
+ "testing"
+
+ "github.com/vivaui/viva/internal/platform"
+)
+
+// Run against a private display. The hints are GTK's request, observable even
+// on Wayland, where the compositor decides whether to grant it.
+func TestGTKNotificationFocusHints(t *testing.T) {
+ if os.Getenv("VIVA_TEST_GTK_NOTIFICATION") != "1" {
+ t.Skip("requires a private GTK display")
+ }
+ err := RunGTKApplication(func(app platform.Application) error {
+ popup, err := app.OpenWindow(platform.Config{Width: 160, Height: 80, WindowMode: platform.WindowNotification})
+ if err != nil {
+ return err
+ }
+ w := popup.(*gtkWindow)
+ for _, property := range []string{"accept-focus", "focus-on-map"} {
+ if w.app.boolProperty(w.toplevel, property) != 0 {
+ return fmt.Errorf("GTK notification requested %s", property)
+ }
+ }
+ app.Quit()
+ return nil
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+}
diff --git a/internal/platform/linux/gtk_window_linux.go b/internal/platform/linux/gtk_window_linux.go
index 1d927b829..45432b538 100644
--- a/internal/platform/linux/gtk_window_linux.go
+++ b/internal/platform/linux/gtk_window_linux.go
@@ -144,6 +144,20 @@ func (a *gtkApplication) OpenWindow(config platform.Config) (platform.Window, er
switch config.WindowMode {
case platform.WindowFrameless, platform.WindowCustomTitlebar:
g.windowSetDecorated(w.toplevel, 0)
+ case platform.WindowNotification:
+ g.windowSetDecorated(w.toplevel, 0)
+ g.windowSetTypeHint(w.toplevel, 11) // GDK_WINDOW_TYPE_HINT_NOTIFICATION
+ g.windowSkipTaskbar(w.toplevel, 1)
+ g.windowKeepAbove(w.toplevel, 1)
+ g.windowAcceptFocus(w.toplevel, 0)
+ g.windowFocusOnMap(w.toplevel, 0)
+ if monitor := w.notificationMonitor(display); monitor != 0 {
+ var rect [4]int32
+ g.gdkMonitorWorkarea(monitor, &rect)
+ area := platform.ScreenRect{X: float32(rect[0]), Y: float32(rect[1]), Width: float32(rect[2]), Height: float32(rect[3])}
+ x, y := platform.PlaceNotification(float32(config.Width)*w.ratio, float32(config.Height)*w.ratio, 12*w.ratio, area)
+ g.windowMove(w.toplevel, int32(x), int32(y))
+ }
case platform.WindowPanel:
g.windowSetDecorated(w.toplevel, 0)
g.windowSetTypeHint(w.toplevel, 8) // GDK_WINDOW_TYPE_HINT_POPUP_MENU
@@ -243,6 +257,28 @@ func (a *gtkApplication) OpenWindow(config platform.Config) (platform.Window, er
return w, nil
}
+// On X11 the popup follows the pointer's monitor and respects its work area.
+// Native Wayland clients leave placement to the compositor.
+func (w *gtkWindow) notificationMonitor(display uintptr) uintptr {
+ if w.app.wayland {
+ return 0
+ }
+ g := w.g
+ if seat := g.gdkDisplaySeat(display); seat != 0 {
+ if pointer := g.gdkSeatPointer(seat); pointer != 0 {
+ var x, y int32
+ g.gdkDevicePosition(pointer, nil, &x, &y)
+ if m := g.gdkMonitorAtPoint(display, x, y); m != 0 {
+ return m
+ }
+ }
+ }
+ if monitor := g.gdkDisplayPrimary(display); monitor != 0 {
+ return monitor
+ }
+ return g.gdkMonitorAtIndex(display, 0)
+}
+
// x11Scale decides the unit and the scale on X11 from the desktop's settings, in the order
// display_scale.go gives.
func (w *gtkWindow) x11Scale(display uintptr) (unit int32, scale float32) {
@@ -317,7 +353,8 @@ func (w *gtkWindow) SetAlwaysOnTop(enabled bool) error {
if w == nil || w.app == nil {
return fmt.Errorf("linux: window is closed")
}
- if w.config.WindowMode == platform.WindowPanel || w.config.WindowMode == platform.WindowPreview {
+ switch w.config.WindowMode {
+ case platform.WindowPanel, platform.WindowPreview, platform.WindowNotification:
return platform.ErrAlwaysOnTopUnsupported
}
if w.app.wayland {
@@ -343,7 +380,7 @@ func (w *gtkWindow) Show() {
w.g.widgetShowAll(w.toplevel)
case w.minimized:
w.g.windowDeiconify(w.toplevel)
- case !w.app.wayland:
+ case !w.app.wayland && w.config.WindowMode != platform.WindowNotification:
w.g.windowPresent(w.toplevel)
}
// A Wayland client cannot raise its window: gtk_window_present on a window that is
diff --git a/internal/platform/linux/status_item_linux.go b/internal/platform/linux/status_item_linux.go
index cc920eae7..3fb66c36c 100644
--- a/internal/platform/linux/status_item_linux.go
+++ b/internal/platform/linux/status_item_linux.go
@@ -64,7 +64,7 @@ func (win *window) panelOrigin(config platform.Config) (x, y int16) {
return clampInt16(int(config.Origin.X * scale)), clampInt16(int(config.Origin.Y * scale))
}
monitors := win.placementMonitors()
- if config.WindowMode != platform.WindowPanel {
+ if config.WindowMode != platform.WindowPanel && config.WindowMode != platform.WindowNotification {
if config.HasOrigin {
// The origin is in logical screen coordinates, like Frame's result.
scale := win.displayScale()
@@ -83,7 +83,7 @@ func (win *window) panelOrigin(config platform.Config) (x, y int16) {
width, height := float32(win.width), float32(win.height)
area := platform.ScreenRect{Width: float32(win.screen.WidthPixels), Height: float32(win.screen.HeightPixels)}
focusX, focusY := int(area.Width)/2, int(area.Height)/2
- if config.HasAnchor {
+ if config.WindowMode == platform.WindowPanel && config.HasAnchor {
focusX, focusY = int(config.Anchor.X+config.Anchor.Width/2), int(config.Anchor.Y+config.Anchor.Height/2)
} else if pointerX, pointerY, ok := win.pointerPosition(); ok {
focusX, focusY = pointerX, pointerY
@@ -94,7 +94,9 @@ func (win *window) panelOrigin(config platform.Config) (x, y int16) {
area = platform.ScreenRect{X: float32(usable.x), Y: float32(usable.y), Width: float32(usable.width), Height: float32(usable.height)}
}
var fx, fy float32
- if config.HasAnchor {
+ if config.WindowMode == platform.WindowNotification {
+ fx, fy = platform.PlaceNotification(width, height, 12*win.displayScale(), area)
+ } else if config.HasAnchor {
fx, fy = platform.PlacePanel(config.Anchor, width, height, area)
} else {
fx, fy = area.X+(area.Width-width)/2, area.Y+(area.Height-height)/2
@@ -129,7 +131,23 @@ func (win *window) markPanel(config platform.Config, x, y int16) error {
api.changeProperty(connection, xcbPropertyReplace, win.id, name, xcbAtomAtom, 32, uint32(len(atoms)), unsafe.Pointer(&atoms[0]))
return nil
}
- if err := setAtoms("_NET_WM_WINDOW_TYPE", "_NET_WM_WINDOW_TYPE_DIALOG"); err != nil {
+ windowType := "_NET_WM_WINDOW_TYPE_DIALOG"
+ if config.WindowMode == platform.WindowNotification {
+ windowType = "_NET_WM_WINDOW_TYPE_NOTIFICATION"
+ atom, err := api.atom(connection, "_NET_WM_USER_TIME")
+ if err != nil {
+ return err
+ }
+ input, err := api.atom(connection, "WM_HINTS")
+ if err != nil {
+ return err
+ }
+ hints := [9]uint32{1, 0} // ICCCM input hint: clicks act without moving keyboard focus.
+ api.changeProperty(connection, xcbPropertyReplace, win.id, input, input, 32, uint32(len(hints)), unsafe.Pointer(&hints[0]))
+ var timestamp uint32 // EWMH: mapping this window should not acquire focus.
+ api.changeProperty(connection, xcbPropertyReplace, win.id, atom, xcbAtomCardinal, 32, 1, unsafe.Pointer(×tamp))
+ }
+ if err := setAtoms("_NET_WM_WINDOW_TYPE", windowType); err != nil {
return err
}
if err := setAtoms("_NET_WM_STATE", "_NET_WM_STATE_ABOVE", "_NET_WM_STATE_SKIP_TASKBAR", "_NET_WM_STATE_SKIP_PAGER"); err != nil {
@@ -195,17 +213,28 @@ func (state *linuxWindowState) command(command uint32, data []byte) error {
state.config.OnVisibility(false)
}
case commandShow:
+ if state.config.WindowMode == platform.WindowNotification {
+ if state.hidden {
+ x, y := win.panelOrigin(state.config)
+ if err := win.markPanel(state.config, x, y); err != nil {
+ return err
+ }
+ }
+ } else {
+ win.setUserTime(state.application.lastUserTime)
+ }
state.hidden = false
- win.setUserTime(state.application.lastUserTime)
win.api.mapWindow(win.connection, win.id)
- if win.topmostConfigured.Load() {
+ if state.config.WindowMode == platform.WindowNotification {
+ win.sendToRoot(win.frame.stateAtom, [5]uint32{1, win.frame.above, 0, sourceApp})
+ } else if win.topmostConfigured.Load() {
action := uint32(0)
if win.topmost.Load() {
action = 1
}
win.sendToRoot(win.frame.stateAtom, [5]uint32{action, win.frame.above, 0, sourceApp})
}
- if state.config.WindowMode != platform.WindowPanel {
+ if state.config.WindowMode != platform.WindowPanel && state.config.WindowMode != platform.WindowNotification {
if err := state.requestActivation(); err != nil {
return err
}
diff --git a/internal/platform/linux/window_linux.go b/internal/platform/linux/window_linux.go
index bb4308f2c..f8f1f21c5 100644
--- a/internal/platform/linux/window_linux.go
+++ b/internal/platform/linux/window_linux.go
@@ -1340,7 +1340,7 @@ func validateConfig(config platform.Config) error {
if config.Width < 1 || config.Height < 1 || config.Width > math.MaxUint16 || config.Height > math.MaxUint16 {
return fmt.Errorf("linux: X11 window dimensions must be between 1 and %d, got %dx%d", uint32(math.MaxUint16), config.Width, config.Height)
}
- if config.WindowMode > platform.WindowPreview {
+ if config.WindowMode > platform.WindowNotification {
return fmt.Errorf("linux: invalid window mode %d", config.WindowMode)
}
if err := validateRectangles(config.Rectangles); err != nil {
@@ -1484,7 +1484,7 @@ func (application *linuxApplication) openWindow(config platform.Config) (*window
}
win.minimizeHandler = config.OnMinimize
}
- if config.HasOrigin && config.WindowMode != platform.WindowPanel {
+ if config.HasOrigin && config.WindowMode != platform.WindowPanel && config.WindowMode != platform.WindowNotification {
// The user-specified position hint: without it a window manager places the
// window as it likes and ignores where it was created.
const usPosition = 1
@@ -1532,7 +1532,7 @@ func (application *linuxApplication) openWindow(config platform.Config) (*window
win.close()
return nil, err
}
- if config.WindowMode == platform.WindowPanel {
+ if config.WindowMode == platform.WindowPanel || config.WindowMode == platform.WindowNotification {
if err := win.markPanel(config, x, y); err != nil {
win.close()
return nil, err
diff --git a/internal/platform/linux/window_notification_linux_test.go b/internal/platform/linux/window_notification_linux_test.go
new file mode 100644
index 000000000..b6c8ad522
--- /dev/null
+++ b/internal/platform/linux/window_notification_linux_test.go
@@ -0,0 +1,79 @@
+package linux
+
+import (
+ "encoding/binary"
+ "os"
+ "testing"
+ "unsafe"
+
+ "github.com/ebitengine/purego"
+ "github.com/vivaui/viva/internal/platform"
+)
+
+// The fixture uses a private X server: changing keyboard focus is part of this test.
+func TestNotificationNativeX11(t *testing.T) {
+ if os.Getenv("VIVA_TEST_NOTIFICATION_XVFB") != "1" {
+ t.Skip("requires a private Xvfb server")
+ }
+ owner, err := openWindow(platform.Config{Width: 160, Height: 100})
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer owner.close()
+ var setFocus func(uintptr, uint8, uint32, uint32) xcbVoidCookie
+ var getFocus func(uintptr) xcbVoidCookie
+ var focusReply func(uintptr, xcbVoidCookie, *unsafe.Pointer) unsafe.Pointer
+ purego.RegisterLibFunc(&setFocus, owner.api.library, "xcb_set_input_focus")
+ purego.RegisterLibFunc(&getFocus, owner.api.library, "xcb_get_input_focus")
+ purego.RegisterLibFunc(&focusReply, owner.api.library, "xcb_get_input_focus_reply")
+ setFocus(owner.connection, 0, owner.id, 0)
+ focused := func() uint32 {
+ reply := focusReply(owner.connection, getFocus(owner.connection), nil)
+ if reply == nil {
+ t.Fatal("missing focus reply")
+ }
+ defer owner.api.free(reply)
+ return *(*uint32)(unsafe.Add(reply, 8))
+ }
+ if focused() != owner.id {
+ t.Fatal("owner did not acquire keyboard focus")
+ }
+ config := platform.Config{Width: 336, Height: 136, WindowMode: platform.WindowNotification}
+ win, err := openWindow(config)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer win.close()
+ x, y := win.rootOrigin()
+ wantX, wantY := win.panelOrigin(config)
+ if x != int32(wantX) || y != int32(wantY) {
+ t.Fatalf("origin %d,%d want %d,%d", x, y, wantX, wantY)
+ }
+ getProperty := func(name string, kind uint32) uint32 {
+ t.Helper()
+ atom, err := win.api.atom(win.connection, name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ buf, ok := win.tracker.property(win.id, atom, kind)
+ if !ok || len(buf) != 4 {
+ t.Fatalf("property %s: %x", name, buf)
+ }
+ return binary.LittleEndian.Uint32(buf)
+ }
+ notification, err := win.api.atom(win.connection, "_NET_WM_WINDOW_TYPE_NOTIFICATION")
+ if err != nil || getProperty("_NET_WM_WINDOW_TYPE", xcbAtomAtom) != notification {
+ t.Fatal("desktop notification type missing")
+ }
+ if getProperty("_NET_WM_USER_TIME", xcbAtomCardinal) != 0 || focused() != owner.id {
+ t.Fatal("opening the desktop popup took the keyboard")
+ }
+ wmHints, err := win.api.atom(win.connection, "WM_HINTS")
+ if err != nil {
+ t.Fatal(err)
+ }
+ hints, ok := win.tracker.property(win.id, wmHints, wmHints)
+ if !ok || len(hints) < 8 || binary.LittleEndian.Uint32(hints)&1 == 0 || binary.LittleEndian.Uint32(hints[4:]) != 0 {
+ t.Fatal("notification did not opt out of keyboard focus in WM_HINTS")
+ }
+}
diff --git a/internal/platform/status_item.go b/internal/platform/status_item.go
index 8ee35c718..a68d4010b 100644
--- a/internal/platform/status_item.go
+++ b/internal/platform/status_item.go
@@ -33,6 +33,12 @@ func PlacePanel(anchor ScreenRect, width, height float32, area ScreenRect) (x, y
return x, y
}
+// PlaceNotification returns the bottom-right origin inside a screen's working
+// area. All coordinates and the margin use the same units.
+func PlaceNotification(width, height, margin float32, area ScreenRect) (float32, float32) {
+ return max(area.X, area.X+area.Width-width-margin), max(area.Y, area.Y+area.Height-height-margin)
+}
+
// Scaled returns the icon at size x size pixels, each result pixel the average
// of the source pixels it covers, weighted by their alpha so that a transparent
// edge does not bleed its hidden color into the shape. Platforms that draw a
diff --git a/internal/platform/status_item_test.go b/internal/platform/status_item_test.go
index e68e3b0f7..2df69bc71 100644
--- a/internal/platform/status_item_test.go
+++ b/internal/platform/status_item_test.go
@@ -2,6 +2,16 @@ package platform
import "testing"
+func TestNotificationPlacementRespectsWorkAreaAndNegativeScreenOrigins(t *testing.T) {
+ area := ScreenRect{X: -1920, Y: 36, Width: 1920, Height: 1000}
+ if x, y := PlaceNotification(320, 128, 12, area); x != -332 || y != 896 {
+ t.Fatalf("notification at %g,%g", x, y)
+ }
+ if x, y := PlaceNotification(2000, 1200, 12, area); x != area.X || y != area.Y {
+ t.Fatalf("oversize notification at %g,%g", x, y)
+ }
+}
+
func TestPlacePanelOpensTowardTheMiddleOfTheScreen(t *testing.T) {
work := ScreenRect{Width: 1920, Height: 1040} // a 40 pixel taskbar at the bottom
// An icon in the bottom-right corner of a bottom taskbar: the panel is above
diff --git a/internal/platform/windows/always_on_top_windows.go b/internal/platform/windows/always_on_top_windows.go
index 865578dd2..9e0273d2f 100644
--- a/internal/platform/windows/always_on_top_windows.go
+++ b/internal/platform/windows/always_on_top_windows.go
@@ -12,7 +12,8 @@ func (window *nativeWindow) SetAlwaysOnTop(enabled bool) error {
if window == nil || window.closed.Load() {
return fmt.Errorf("windows: window is closed")
}
- if window.state.config.WindowMode == platform.WindowPanel || window.state.config.WindowMode == platform.WindowPreview {
+ switch window.state.config.WindowMode {
+ case platform.WindowPanel, platform.WindowPreview, platform.WindowNotification:
return platform.ErrAlwaysOnTopUnsupported
}
value := uintptr(0)
diff --git a/internal/platform/windows/status_item_windows.go b/internal/platform/windows/status_item_windows.go
index bff4f5342..62224896a 100644
--- a/internal/platform/windows/status_item_windows.go
+++ b/internal/platform/windows/status_item_windows.go
@@ -480,7 +480,7 @@ func (state *windowState) placePanel() {
getWindowRect.Call(state.window, uintptr(unsafe.Pointer(&bounds)))
width, height := float32(bounds.Right-bounds.Left), float32(bounds.Bottom-bounds.Top)
config := state.config
- if !config.HasAnchor {
+ if !config.HasAnchor || config.WindowMode == platform.WindowNotification {
// Centered on the monitor the cursor is on.
var info monitorInfo
info.Size = uint32(unsafe.Sizeof(info))
@@ -488,7 +488,11 @@ func (state *windowState) placePanel() {
getMonitorInfo.Call(monitor, uintptr(unsafe.Pointer(&info)))
x := float32(info.Work.Left) + (float32(info.Work.Right-info.Work.Left)-width)/2
y := float32(info.Work.Top) + (float32(info.Work.Bottom-info.Work.Top)-height)/2
- setWindowPosition.Call(state.window, hwndTopmost, uintptr(int32(x)), uintptr(int32(y)), 0, 0, 0x1)
+ if config.WindowMode == platform.WindowNotification {
+ area := platform.ScreenRect{X: float32(info.Work.Left), Y: float32(info.Work.Top), Width: float32(info.Work.Right - info.Work.Left), Height: float32(info.Work.Bottom - info.Work.Top)}
+ x, y = platform.PlaceNotification(width, height, 12*state.scale, area)
+ }
+ setWindowPosition.Call(state.window, hwndTopmost, uintptr(int32(x)), uintptr(int32(y)), 0, 0, 0x11) // NOSIZE | NOACTIVATE
return
}
anchor := config.Anchor
diff --git a/internal/platform/windows/window_notification_windows_test.go b/internal/platform/windows/window_notification_windows_test.go
new file mode 100644
index 000000000..b9f8197c3
--- /dev/null
+++ b/internal/platform/windows/window_notification_windows_test.go
@@ -0,0 +1,84 @@
+package windows
+
+import (
+ "os"
+ "runtime"
+ "strconv"
+ "syscall"
+ "testing"
+ "unsafe"
+
+ "github.com/vivaui/viva/internal/platform"
+)
+
+// Window focus belongs to a desktop. The test thread creates its own hidden
+// one so an interactive user's editor is never raised, hidden or unfocused.
+func TestNotificationNativeWindows(t *testing.T) {
+ if os.Getenv("VIVA_TEST_NOTIFICATION_DESKTOP") != "1" {
+ t.Skip("requires private Win32 desktop creation rights")
+ }
+ runtime.LockOSThread()
+ threadID, _, _ := syscall.NewLazyDLL("kernel32.dll").NewProc("GetCurrentThreadId").Call()
+ previous, _, _ := user.NewProc("GetThreadDesktop").Call(threadID)
+ desktopName, _ := syscall.UTF16PtrFromString("VivaNotificationTest-" + strconv.Itoa(os.Getpid()))
+ desktop, _, err := user.NewProc("CreateDesktopW").Call(uintptr(unsafe.Pointer(desktopName)), 0, 0, 0, 0x01ff, 0)
+ if desktop == 0 {
+ runtime.UnlockOSThread()
+ t.Fatal(err)
+ }
+ // Return the original desktop before releasing the thread. If a system
+ // library retains a hidden window, the runtime discards this locked thread.
+ defer func() {
+ if ok, _, _ := user.NewProc("SetThreadDesktop").Call(previous); ok != 0 {
+ runtime.UnlockOSThread()
+ }
+ user.NewProc("CloseDesktop").Call(desktop)
+ }()
+ if ok, _, err := user.NewProc("SetThreadDesktop").Call(desktop); ok == 0 {
+ t.Fatal(err)
+ }
+ send := user.NewProc("SendMessageW")
+ focus := user.NewProc("GetFocus")
+ err = RunApplication(func(app platform.Application) error {
+ owner, err := app.OpenWindow(platform.Config{Title: "Typing", Width: 200, Height: 100})
+ if err != nil {
+ return err
+ }
+ defer owner.Close()
+ handle := owner.(*nativeWindow).state.window
+ setFocus.Call(handle)
+ if before, _, _ := focus.Call(); before != handle {
+ t.Fatalf("expected original keyboard focus %x, got %x", handle, before)
+ }
+ clicks := 0
+ popup, err := app.OpenWindow(platform.Config{Title: "Incoming", Width: 336, Height: 136, WindowMode: platform.WindowNotification, OnPointer: func(e platform.PointerEvent) (platform.Frame, error) {
+ if e.Kind == platform.PointerDown {
+ clicks++
+ }
+ return platform.Frame{}, nil
+ }})
+ if err != nil {
+ return err
+ }
+ defer popup.Close()
+ hwnd := popup.(*nativeWindow).state.window
+ if after, _, _ := focus.Call(); after != handle {
+ t.Fatal("opening the popup stole focus")
+ }
+ if activate, _, _ := send.Call(hwnd, 0x0021, handle, 0); activate != 3 {
+ t.Fatalf("mouse activation response %d", activate)
+ }
+ send.Call(hwnd, wmLeftDown, mkLButton, 10<<16|10)
+ send.Call(hwnd, wmLeftUp, 0, 10<<16|10)
+ if clicks != 1 {
+ t.Fatalf("notification received %d click(s)", clicks)
+ }
+ if after, _, _ := focus.Call(); after != handle {
+ t.Fatal("interacting with notification stole focus")
+ }
+ return nil
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+}
diff --git a/internal/platform/windows/window_windows.go b/internal/platform/windows/window_windows.go
index cfecee918..294943567 100644
--- a/internal/platform/windows/window_windows.go
+++ b/internal/platform/windows/window_windows.go
@@ -331,6 +331,9 @@ func (application *windowsApplication) OpenWindow(config platform.Config) (platf
switch config.WindowMode {
case platform.WindowFrameless:
style = wsPopup
+ case platform.WindowNotification:
+ style = wsPopup
+ extendedStyle = wsExToolWindow | wsExTopmost | wsExNoActivate
case platform.WindowPanel:
// A popup that has no taskbar button and stays above other windows.
style = wsPopup
@@ -395,7 +398,7 @@ func (application *windowsApplication) OpenWindow(config platform.Config) (platf
}
setWindowPosition.Call(state.window, 0, 0, 0, uintptr(bounds.Right-bounds.Left), uintptr(bounds.Bottom-bounds.Top), 0x16)
}
- if config.WindowMode != platform.WindowPanel {
+ if config.WindowMode != platform.WindowPanel && config.WindowMode != platform.WindowNotification {
if config.HasOrigin {
state.placeAtOrigin(config.Origin)
} else {
@@ -432,7 +435,10 @@ func (application *windowsApplication) OpenWindow(config platform.Config) (platf
if state.activeBackdrop() {
postMessage.Call(state.window, wmRedraw, 0, 0)
}
- if config.WindowMode == platform.WindowPanel {
+ if config.WindowMode == platform.WindowNotification {
+ state.placePanel()
+ showWindow.Call(state.window, swShowNoActivate)
+ } else if config.WindowMode == platform.WindowPanel {
state.placePanel()
showWindow.Call(state.window, swShow)
setForegroundWindow.Call(state.window)
@@ -561,7 +567,15 @@ func windowProc(window, kind, first, second uintptr) (result uintptr) {
case wmHideWindow:
showWindow.Call(window, swHide)
return 0
+ case 0x0021: // WM_MOUSEACTIVATE
+ if state.config.WindowMode == platform.WindowNotification {
+ return 3 // MA_NOACTIVATE: deliver the click, keep the previous keyboard focus.
+ }
case wmShowWindow:
+ if state.config.WindowMode == platform.WindowNotification {
+ showWindow.Call(window, swShowNoActivate)
+ return 0
+ }
showOrRaise(window)
return 0
case wmClose:
@@ -883,7 +897,9 @@ func windowProc(window, kind, first, second uintptr) (result uintptr) {
}
}
if kind == wmLeftDown || kind == wmRightDown || kind == wmMiddleDown || kind == wmXButtonDown {
- setFocus.Call(window)
+ if state.config.WindowMode != platform.WindowNotification {
+ setFocus.Call(window)
+ }
setCapture.Call(window)
}
if !state.tracking {
diff --git a/website/content/guides/en/windows.md b/website/content/guides/en/windows.md
index 0915db645..543183198 100644
--- a/website/content/guides/en/windows.md
+++ b/website/content/guides/en/windows.md
@@ -21,6 +21,7 @@ Every window has its own canvas, paint callback, focus, input state and close ha
| `WindowFrameless` | No chrome at all, traffic lights included. |
| `WindowCustomTitlebar` | Content runs full height behind a transparent title bar. The window moves from the regions you declare with `MovesWindow` (or `Canvas.MoveRegion`), and from nowhere else. |
| `WindowPanel` | A transient popup with no chrome, above other windows, meant to open beside a status icon. |
+| `WindowNotification` | A desktop popup that accepts pointer input without taking keyboard focus, meant for the outcome of background work. On Wayland the compositor decides its placement, stacking and focus. |
With a custom title bar the window buttons are the system's on macOS and are drawn by Viva on Windows and Linux. Either way they cover part of the strip, so ask `app.TitlebarInsets` how much and keep your own content clear of it. `Config.TitlebarHeight` sets the strip's height (where Viva puts its buttons and the traffic lights); the window moves from the row you mark `MovesWindow`, controls inside it keep their own clicks, and a menu or dialog open over it is dismissed by a click there, with the window moving once the pointer drags. `Config.WindowControls` styles the buttons Viva draws so they follow your theme.
diff --git a/website/content/guides/zh/windows.md b/website/content/guides/zh/windows.md
index 56157aa84..1a24c8f91 100644
--- a/website/content/guides/zh/windows.md
+++ b/website/content/guides/zh/windows.md
@@ -21,6 +21,7 @@ group: guides
| `WindowFrameless` | 没有任何外框,包括红绿灯按钮。 |
| `WindowCustomTitlebar` | 内容延伸到透明标题栏之后,占满整个高度,窗口从你用 `MovesWindow`(或 `Canvas.MoveRegion`)声明的区域移动,别处不能。 |
| `WindowPanel` | 无外框的临时弹出窗口,位于其他窗口之上,用来在状态栏图标旁边打开。 |
+| `WindowNotification` | 接受鼠标操作但不抢键盘焦点的桌面浮窗,用于后台任务的结果提示;Wayland 下位置、层级与焦点由合成器决定。 |
使用自定义标题栏时,窗口按钮在 macOS 上由系统绘制,在 Windows 和 Linux 上由 Viva 绘制。无论哪种,它们都会盖住条带的一部分,所以用 `app.TitlebarInsets` 询问盖住多少,让自己的内容避开。`Config.TitlebarHeight` 设置条带高度(Viva 放置自绘按钮和 macOS 红绿灯的位置);窗口从你标记了 `MovesWindow` 的那一行移动,行内的控件仍然接收自己的点击,行上方打开的菜单或对话框会被那里的点击关闭,指针拖动后窗口才移动。`Config.WindowControls` 给 Viva 绘制的按钮定样式,使它们跟随你的主题。
From c23aa44c7c5a7a5e8355e37ca1f986063b751c64 Mon Sep 17 00:00:00 2001
From: MYCF711 <1451895195@qq.com>
Date: Sun, 22 Nov 2026 00:33:52 +0800
Subject: [PATCH 31/47] feat(app): report when a web view's process dies
---
app/web.go | 58 +++++++
app/web_test.go | 53 +++++-
docs/web-views.md | 33 +++-
internal/platform/darwin/web_darwin.go | 26 +++
internal/platform/darwin/web_darwin.m | 10 ++
internal/platform/linux/gtk_app_linux.go | 9 +-
internal/platform/linux/gtk_web_linux.go | 66 ++++++++
internal/platform/web_host.go | 9 +
internal/platform/web_process_failure.go | 155 ++++++++++++++++++
internal/platform/web_process_failure_test.go | 99 +++++++++++
internal/platform/windows/web_windows.go | 43 +++++
internal/platform/windows/webview2_windows.go | 16 ++
12 files changed, 572 insertions(+), 5 deletions(-)
create mode 100644 internal/platform/web_process_failure.go
create mode 100644 internal/platform/web_process_failure_test.go
diff --git a/app/web.go b/app/web.go
index d80b42669..eb02c2f5c 100644
--- a/app/web.go
+++ b/app/web.go
@@ -106,6 +106,16 @@ type WebViewConfig struct {
TopCornerRadius float32
// OnLoad reports the page's navigation.
OnLoad func(WebLoad)
+ // OnProcessFailed reports the page's process gone: it crashed, the system or the engine stopped
+ // it, or it never started. That is not a navigation that failed: the page was there, and its
+ // process is gone, so what the user typed into it may be lost and it cannot draw again until it
+ // is loaded again, which WebView.Reload does. The WebProcessFailure says which of those it was,
+ // because a crash is worth warning about before a reload and a page the system reclaimed under
+ // memory pressure is not. WebProcessHostGone is the exception: the engine's own process went,
+ // taking the control with it, so the application closes the page and opens a new one instead of
+ // reloading it. WebView.IsCrashed answers the same question afterwards, and a navigation that
+ // starts again clears it.
+ OnProcessFailed func(WebProcessFailure)
// Navigate decides a navigation before it starts; nil allows every navigation.
Navigate func(WebNavigation) bool
// NewWindow decides a window.open or target=_blank before it opens; nil refuses it. That is a
@@ -254,6 +264,34 @@ type WebLoad struct {
Description string
}
+// WebProcessFailure is why a page's process is gone, in the terms every engine can be held to: the
+// engines name the same failures differently, so a page whose process was lost reads the same way
+// on every platform. WebProcessNoFailure is a page whose process is there.
+//
+// This is not a navigation that failed: a page that did not load has its process, and reports
+// through WebLoad. A page that lost its process was there, and cannot draw again until it is
+// loaded again.
+type WebProcessFailure = platform.WebProcessFailure
+
+const (
+ // WebProcessNoFailure is a page whose process is there.
+ WebProcessNoFailure = platform.WebProcessNoFailure
+ // WebProcessCrashed is a process that stopped without being asked to: a fault in the page or
+ // in the engine, which may have lost what the user typed into it that was not saved.
+ WebProcessCrashed = platform.WebProcessCrashed
+ // WebProcessKilled is a process the system or the engine stopped: memory pressure, an
+ // out-of-memory kill, or the engine ending it itself. The page is gone with it, but nothing
+ // the page did made it happen.
+ WebProcessKilled = platform.WebProcessKilled
+ // WebProcessUnresponsive is a process that stopped answering, which the engine ended.
+ WebProcessUnresponsive = platform.WebProcessUnresponsive
+ // WebProcessLaunchFailed is a process that never started, so the page never ran at all.
+ WebProcessLaunchFailed = platform.WebProcessLaunchFailed
+ // WebProcessUnknown is a process the engine reports as gone without a reason Viva classifies,
+ // including macOS, whose delegate names no reason at all.
+ WebProcessUnknown = platform.WebProcessUnknown
+)
+
// WebView is one open page.
type WebView struct {
id gfx.NativeViewID
@@ -370,6 +408,12 @@ func (host *WebHost) Open(config WebViewConfig) (*WebView, error) {
return config.Navigate(WebNavigation(navigation))
}
}
+ if config.OnProcessFailed != nil {
+ platformConfig.OnProcessFailed = func(failure platform.WebProcessFailure) {
+ config.OnProcessFailed(WebProcessFailure(failure))
+ host.requestPaint()
+ }
+ }
platformConfig.NewWindow = config.NewWindow
platformConfig.Download = config.Download
platformConfig.BridgeMainFrameOnly = config.BridgeMainFrameOnly
@@ -414,6 +458,20 @@ func (view *WebView) CanGoForward() bool { return view.native.CanGoForward() }
// one until it finishes or fails, which is when WebLoad reports WebLoadStarted and WebLoadFinished.
func (view *WebView) IsLoading() bool { return view.native.IsLoading() }
+// ProcessFailure is why the page's process is gone, WebProcessNoFailure while it is there: the value
+// OnProcessFailed was given, until the page starts a navigation again, which is what clears it. The
+// engines have no way to ask, so it is kept from what they reported.
+func (view *WebView) ProcessFailure() WebProcessFailure { return view.native.ProcessFailure() }
+
+// IsCrashed reports whether the page's process is gone: it crashed, the system or the engine stopped
+// it, or it never started. Such a page cannot draw and its input is lost, so an application that
+// hosts one shows its own notice and Reload loads it again rather than leaving the engine's blank
+// view. A page whose ProcessFailure is WebProcessHostGone is the exception: its control is gone with
+// the engine's process, so close it and open a new one rather than reloading. It says the page is
+// gone, not that the reason was a crash: ProcessFailure names the reason, which is what a notice that
+// tells the user whether their input is lost needs.
+func (view *WebView) IsCrashed() bool { return view.native.ProcessFailure() != WebProcessNoFailure }
+
// Eval runs a script in the page. The result is not read back: have the script post a message.
func (view *WebView) Eval(script string) { view.native.Eval(script) }
diff --git a/app/web_test.go b/app/web_test.go
index b5cb00ab9..6eb57bed4 100644
--- a/app/web_test.go
+++ b/app/web_test.go
@@ -244,6 +244,7 @@ type testWebView struct {
canGoBack bool
canGoForward bool
loading bool
+ failure platform.WebProcessFailure
loaded []string
}
@@ -265,7 +266,10 @@ func (view *testWebView) Title() string { return view.title }
func (view *testWebView) CanGoBack() bool { return view.canGoBack }
func (view *testWebView) CanGoForward() bool { return view.canGoForward }
func (view *testWebView) IsLoading() bool { return view.loading }
-func (view *testWebView) Close() {}
+func (view *testWebView) ProcessFailure() platform.WebProcessFailure {
+ return view.failure
+}
+func (view *testWebView) Close() {}
func TestAPageReportsItsOwnState(t *testing.T) {
page := &testWebView{title: "Settings", canGoBack: true, loading: true}
@@ -411,3 +415,50 @@ func TestARefusedPartitionNameNeverReachesThePlatform(t *testing.T) {
t.Fatal("the platform was asked to open a page whose partition name was refused")
}
}
+
+func TestAPageWhoseProcessIsGoneReachesTheApplication(t *testing.T) {
+ var report func(platform.WebProcessFailure)
+ page := &testWebView{}
+ host := &WebHost{native: &platform.WebHost{Open: func(config platform.WebViewConfig) (platform.WebView, error) {
+ report = config.OnProcessFailed
+ return page, nil
+ }}}
+ var failures []WebProcessFailure
+ view, err := host.Open(WebViewConfig{OnProcessFailed: func(failure WebProcessFailure) {
+ failures = append(failures, failure)
+ }})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if report == nil {
+ t.Fatal("the platform got no process failure callback")
+ }
+ report(platform.WebProcessKilled)
+ if len(failures) != 1 || failures[0] != WebProcessKilled {
+ t.Fatalf("a page the system stopped reported %v, want it named", failures)
+ }
+ // The page answers the same question afterwards, read from the page each time.
+ page.failure = platform.WebProcessKilled
+ if !view.IsCrashed() || view.ProcessFailure() != WebProcessKilled {
+ t.Fatalf("crashed=%v failure=%v, want the page's own state", view.IsCrashed(), view.ProcessFailure())
+ }
+ // The process a page has again is not the one it lost.
+ page.failure = platform.WebProcessNoFailure
+ if view.IsCrashed() || view.ProcessFailure() != WebProcessNoFailure {
+ t.Fatalf("crashed=%v failure=%v, want a page with its process", view.IsCrashed(), view.ProcessFailure())
+ }
+}
+
+func TestAPageNobodyWatchesForFailureGivesThePlatformNone(t *testing.T) {
+ var got platform.WebViewConfig
+ host := &WebHost{native: &platform.WebHost{Open: func(config platform.WebViewConfig) (platform.WebView, error) {
+ got = config
+ return &testWebView{}, nil
+ }}}
+ if _, err := host.Open(WebViewConfig{}); err != nil {
+ t.Fatal(err)
+ }
+ if got.OnProcessFailed != nil {
+ t.Fatal("an application that set no OnProcessFailed got one")
+ }
+}
diff --git a/docs/web-views.md b/docs/web-views.md
index f3edd7925..3f6c0430e 100644
--- a/docs/web-views.md
+++ b/docs/web-views.md
@@ -56,6 +56,19 @@ scheme, a message in each direction and a menu that stands over the page.
that failed carries `Code`, a `WebLoadError` that names the same failures on every engine, and
`Description`, the engine's own words for it. A navigation your `Navigate` refused is not reported:
that is the answer you gave, and the engine's interruption of it would be the same thing twice.
+- `OnProcessFailed` reports the page's process gone: it crashed, the system or the engine stopped it, or
+ it never started. That is not a navigation that failed — the page was there, and its process is gone —
+ so it cannot draw again until it is loaded again with `Reload`, and what the user typed into it may be
+ lost. The `WebProcessFailure` says which of those it was, in the terms every engine can be held to:
+ `WebProcessCrashed` (a fault, whose unsaved input is probably gone), `WebProcessKilled` (memory
+ pressure, an out-of-memory kill, or the engine ending it itself, which the page did nothing to cause),
+ `WebProcessUnresponsive`, `WebProcessLaunchFailed`, or `WebProcessUnknown` (including macOS, which
+ names no reason at all). `WebProcessHostGone` is the engine's own process gone: the control is
+ unusable, so close the page and open a new one instead of reloading. A notice that tells the user
+ whether their input is lost, or just offers a reload, is written from that value rather than from the
+ engine's own enum. `IsCrashed` answers whether the page is gone and `ProcessFailure` why, until the
+ page starts a navigation again, which clears it:
+ no engine offers a way to ask, so both are kept from what the engine reported.
- The page and the application talk through `window.viva.postMessage(text)` / `window.viva.onmessage` and
`OnMessage` / `WebView.PostMessage`. A page sees nothing else of the application.
- `Navigate` decides a navigation before it starts, the application's own `Load` included: the
@@ -181,7 +194,10 @@ The decisions are the engine's own, and each one has a limit worth knowing:
A form submitted by a script therefore reads as a gesture, and a redirect keeps the gesture that started
it. Downloads need macOS 11.3 (`WKDownload`); on an older system a download response is refused rather
than saved, and `Download` is not asked. A failed load arrives as an `NSError`: `WebLoad.Code` is mapped
- from its domain and code, and `WebLoad.Description` is the system's own message, which is localized.
+ from its domain and code, and `WebLoad.Description` is the system's own message, which is localized. A
+ page whose content process is gone arrives as `webViewWebContentProcessDidTerminate:`, which names no
+ reason at all: `ProcessFailure` is `WebProcessUnknown` there, so a notice may say the page was lost but
+ not whether it crashed or the system reclaimed it, and the page draws nothing until it is loaded again.
- **Linux**: WebKitGTK's navigation action names no target frame (there is no way from the action to
the frame), so `WebNavigation.MainFrame` is always true here and a subframe cannot be told apart from
the main frame. The decision still cancels the right request. The redirect flag needs WebKitGTK 2.20;
@@ -190,7 +206,11 @@ The decisions are the engine's own, and each one has a limit worth knowing:
application decides it in `decide-destination`, before the body is written. A failed load arrives as a
`GError` from `load-failed`: `WebLoad.Code` is mapped from its code and `WebLoad.Description` is the
engine's message. A certificate the engine refuses reaches the load as a cancellation rather than
- `WebLoadBadCertificate`, because the TLS error signal is the engine's own to answer.
+ `WebLoadBadCertificate`, because the TLS error signal is the engine's own to answer. A page whose web
+ process is gone arrives as `web-process-terminated`, which needs WebKitGTK 2.20: an older engine opens
+ the page and never calls `OnProcessFailed`, and a warning through `diag` says so once, when the page
+ opens, rather than leaving the callback silently unset. The signal's reason maps to `WebProcessCrashed`,
+ or `WebProcessKilled` for a process that exceeded the memory limit or was terminated by API.
- **Windows**: `DownloadStarting` needs `ICoreWebView2_4`. A runtime older than that (2021) cannot report a
download before it starts, so `Download` is not asked and the engine saves the file its own way in the
user's downloads folder; a warning through `diag` says so once, when the page opens. `NewWindow` and
@@ -198,4 +218,11 @@ The decisions are the engine's own, and each one has a limit worth knowing:
`WebErrorStatus`, which carries no text: `WebLoad.Description` is empty here, so show `Code`. The base
interface has no property for `IsLoading`, so the page follows `NavigationStarting` and
`NavigationCompleted` instead: it becomes true on the turn of the window's thread that reports the
- navigation's start, not inside the call to `Load` itself.
+ navigation's start, not inside the call to `Load` itself. `ProcessFailed` is on the base interface too,
+ and its kind decides whether the page hears of it: the browser process, which every renderer is a child
+ of, and the renderer that draws the main frame end the page, while a frame's own renderer (the runtime
+ puts its error page in that frame) and a GPU, utility, sandbox helper or plugin process are the
+ runtime's to start again and are not reported, which is what the other engines' signals do as well. The
+ reason needs `ICoreWebView2ProcessFailedEventArgs2` (Runtime 94, inside what an ephemeral page already
+ asks for): a runtime without it gives the kind alone, and an exit with no reason reads
+ `WebProcessUnknown`.
diff --git a/internal/platform/darwin/web_darwin.go b/internal/platform/darwin/web_darwin.go
index 7e7806c1f..656b0c9a8 100644
--- a/internal/platform/darwin/web_darwin.go
+++ b/internal/platform/darwin/web_darwin.go
@@ -52,6 +52,10 @@ type darwinWeb struct {
// refused is a navigation the application's Navigate cancelled. The engine may report the
// cancellation as the navigation's end, which the application already answered.
refused bool
+ // failure is why the page's content process is gone, WebProcessNoFailure while it is there:
+ // the delegate reports the termination without a reason, and a navigation that starts again
+ // clears it.
+ failure platform.WebProcessFailure
// placed is where the page was last put, to leave AppKit alone when nothing changed.
placed platform.NativeView
cutsSet []gfx.Rect
@@ -215,6 +219,9 @@ func (page *darwinWeb) IsLoading() bool {
return page.usable() && C.viva_web_is_loading(page.native) != 0
}
+// ProcessFailure is why the page's process is gone, WebProcessNoFailure while it is there.
+func (page *darwinWeb) ProcessFailure() platform.WebProcessFailure { return page.failure }
+
func (page *darwinWeb) Eval(script string) {
if page.usable() {
text := C.CString(script)
@@ -351,6 +358,9 @@ func vivaWebLoad(handle C.uintptr_t, id C.uint32_t, phase C.int, url, domain *C.
}
if loadPhase == platform.WebLoadStarted {
page.refused = false
+ // A page that loads again has a content process again, so the one it lost is no longer
+ // what it is.
+ page.failure = platform.WebProcessNoFailure
}
if page.config.OnLoad == nil {
return
@@ -365,6 +375,22 @@ func vivaWebLoad(handle C.uintptr_t, id C.uint32_t, phase C.int, url, domain *C.
})
}
+// vivaWebProcessTerminated reports a page whose content process is gone: the delegate's
+// webViewWebContentProcessDidTerminate: names no reason at all, so the page is WebProcessUnknown in
+// the terms of internal/platform, and it draws nothing until it is loaded again.
+//
+//export vivaWebProcessTerminated
+func vivaWebProcessTerminated(handle C.uintptr_t, id C.uint32_t) {
+ page := pageOf(handle, id)
+ if page == nil || !page.usable() {
+ return
+ }
+ page.failure = platform.WebProcessFailureDarwinTermination
+ if page.config.OnProcessFailed != nil {
+ page.config.OnProcessFailed(page.failure)
+ }
+}
+
// vivaWebNavigate asks the application about a navigation before WebKit makes it. It answers 1 to
// allow, which is what an application that set no Navigate wants.
//
diff --git a/internal/platform/darwin/web_darwin.m b/internal/platform/darwin/web_darwin.m
index 9ed7dd4ab..1ebeb914e 100644
--- a/internal/platform/darwin/web_darwin.m
+++ b/internal/platform/darwin/web_darwin.m
@@ -12,6 +12,7 @@
// What the page does reaches Go through these (web_darwin.go).
extern void vivaWebMessage(uintptr_t handle, uint32_t id, char *utf8);
extern void vivaWebLoad(uintptr_t handle, uint32_t id, int phase, char *url, char *domain, int code, char *description);
+extern void vivaWebProcessTerminated(uintptr_t handle, uint32_t id);
extern int vivaWebNavigate(uintptr_t handle, uint32_t id, char *url, int mainFrame, int userGesture);
extern int vivaWebNewWindow(uintptr_t handle, uint32_t id, char *url);
extern int vivaWebDownload(uintptr_t handle, uint32_t id, char *url);
@@ -230,6 +231,15 @@ - (void)webView:(WKWebView *)web didFailProvisionalNavigation:(WKNavigation *)na
[self reportFailure:web error:error];
}
+// The page's content process is gone: it crashed, or the system reclaimed it. That is not a
+// navigation that failed (WebKit reports those through the two methods above), and the delegate
+// names no reason: Go reports the page as WebProcessUnknown and the page draws nothing until it is
+// loaded again.
+- (void)webViewWebContentProcessDidTerminate:(WKWebView *)web {
+ (void)web;
+ vivaWebProcessTerminated(_handle, _id);
+}
+
// finishTask answers task and lets it go. headers is the header block Go resolved: one "Name: value"
// line each.
- (void)finishTask:(id)task status:(int)status headers:(char *)headers data:(unsigned char *)data length:(size_t)length {
diff --git a/internal/platform/linux/gtk_app_linux.go b/internal/platform/linux/gtk_app_linux.go
index 68a555e88..fa9d7f713 100644
--- a/internal/platform/linux/gtk_app_linux.go
+++ b/internal/platform/linux/gtk_app_linux.go
@@ -326,7 +326,7 @@ func typeNameOf(g *gtkLibrary, object uintptr) string {
// frees a callback and allows a fixed number, so a window must not make its own. The window a call
// is for travels in the data pointer, as its id.
type gtkCallbacks struct {
- task, descriptor, settings, dragMotion, dragLeave, dragDrop, dragData, event, capturePress, draw, allocate, destroy, deleteEvent, mapped, unmapped, commit, preeditStart, preedit, preeditEnd, surrounding, deleteSurrounding, retireIME, releaseIME, redraw, webMessage, webLoad, webFailed, webScheme, webDecide, webCreate, webDownload, webDestination uintptr
+ task, descriptor, settings, dragMotion, dragLeave, dragDrop, dragData, event, capturePress, draw, allocate, destroy, deleteEvent, mapped, unmapped, commit, preeditStart, preedit, preeditEnd, surrounding, deleteSurrounding, retireIME, releaseIME, redraw, webMessage, webLoad, webFailed, webProcessTerminated, webScheme, webDecide, webCreate, webDownload, webDestination uintptr
}
var (
@@ -468,6 +468,13 @@ func callbacks() *gtkCallbacks {
}
return 0
}),
+ // void web-process-terminated(view, WebKitWebProcessTerminationReason, handle).
+ webProcessTerminated: purego.NewCallback(func(view, reason, handle uintptr) uintptr {
+ if v := webViews[handle]; v != nil {
+ v.processTerminated(int32(reason))
+ }
+ return 0
+ }),
// void (*WebKitURISchemeRequestCallback)(request, user_data).
webScheme: purego.NewCallback(func(request, data uintptr) uintptr {
if a := gtkRunning.Load(); a != nil {
diff --git a/internal/platform/linux/gtk_web_linux.go b/internal/platform/linux/gtk_web_linux.go
index bd4b24738..cdccdcc89 100644
--- a/internal/platform/linux/gtk_web_linux.go
+++ b/internal/platform/linux/gtk_web_linux.go
@@ -16,6 +16,7 @@ import (
"github.com/ebitengine/purego"
"github.com/vivaui/viva/gfx"
+ "github.com/vivaui/viva/internal/diag"
"github.com/vivaui/viva/internal/platform"
)
@@ -108,12 +109,19 @@ type webKit struct {
// downloadDestinationPath says set_destination takes a path (2.40 and later) rather than a URI,
// decided from the library's own major and minor version at load time.
downloadDestinationPath bool
+ // processTerminated tells whether the engine has the web-process-terminated signal, which names
+ // a page whose web process is gone: WebKitGTK has it from 2.20, and an engine without it is not
+ // handed a signal to connect.
+ processTerminated bool
}
var (
webOnce sync.Once
webAPI *webKit
webErr error
+ // webProcessTerminatedUnsupported says once, rather than at every page, that this engine cannot
+ // report a page whose process is gone.
+ webProcessTerminatedUnsupported sync.Once
)
func loadWebKit(g *gtkLibrary) (*webKit, error) {
@@ -230,11 +238,35 @@ func loadWebKit(g *gtkLibrary) (*webKit, error) {
k.schemeResponse = true
}
g.lookup(&k.schemeWebView, "webkit_uri_scheme_request_get_web_view")
+ k.processTerminated = webProcessTerminatedSignal(g)
webAPI = k
})
return webAPI, webErr
}
+// webProcessTerminatedSignal reports whether the engine has WebKitWebView's web-process-terminated
+// signal, which says the page's web process is gone: WebKitGTK added it in 2.20, and an older engine
+// would only warn about a signal it does not have.
+func webProcessTerminatedSignal(g *gtkLibrary) bool {
+ var viewType func() uintptr
+ var signalLookup func(name *byte, itype uintptr) uint32
+ var classRef func(itype uintptr) uintptr
+ var classUnref func(class uintptr)
+ if !g.lookup(&viewType, "webkit_web_view_get_type") || !g.lookup(&signalLookup, "g_signal_lookup") ||
+ !g.lookup(&classRef, "g_type_class_ref") || !g.lookup(&classUnref, "g_type_class_unref") {
+ return false
+ }
+ // Signals are installed in the type's class_init, so a type that no instance has
+ // initialized yet has none to look up: take the class first, then give it back.
+ class := classRef(viewType())
+ if class == 0 {
+ return false
+ }
+ defer classUnref(class)
+ name := cString("web-process-terminated")
+ return signalLookup(&name[0], viewType()) != 0
+}
+
// webQuirks keeps a virtual machine or a container from breaking the engine: without a GPU render
// node its buffer sharing between processes fails and pages stay blank.
func webQuirks() {
@@ -283,6 +315,9 @@ type gtkWebView struct {
// too: only the interruption of that same request is the answer the application gave.
failed bool
refused string
+ // failure is why the page's web process is gone, WebProcessNoFailure while it is there: the
+ // engine reports the termination and why, and a navigation that starts again clears it.
+ failure platform.WebProcessFailure
}
// viewPlace is a rectangle in the overlay's units.
@@ -606,6 +641,18 @@ func (w *gtkWindow) openWebView(c platform.WebViewConfig) (platform.WebView, err
g.overlayAdd(w.overlay, v.widget)
g.connect(v.widget, "load-changed", cb.webLoad, v.handle)
g.connect(v.widget, "load-failed", cb.webFailed, v.handle)
+ if k.processTerminated {
+ g.connect(v.widget, "web-process-terminated", cb.webProcessTerminated, v.handle)
+ } else if c.OnProcessFailed != nil {
+ // The page is opened: only the report of a process it loses is missing, and that is said
+ // once rather than left as a callback that never runs.
+ webProcessTerminatedUnsupported.Do(func() {
+ if diag.Enabled(diag.Warn) {
+ diag.Report(diag.Warn, "web", "process-failed",
+ "this WebKitGTK predates 2.20 and cannot report a page whose process is gone; OnProcessFailed is never called")
+ }
+ })
+ }
g.connect(v.widget, "focus-in-event", cb.event, w.id)
g.connect(v.widget, "focus-out-event", cb.event, w.id)
g.connect(v.widget, "decide-policy", cb.webDecide, v.handle)
@@ -725,6 +772,9 @@ func (v *gtkWebView) IsLoading() bool {
return !v.closed && v.k.isLoading(v.widget) != 0
}
+// ProcessFailure is why the page's process is gone, WebProcessNoFailure while it is there.
+func (v *gtkWebView) ProcessFailure() platform.WebProcessFailure { return v.failure }
+
func (v *gtkWebView) Eval(script string) {
if v.closed {
return
@@ -852,6 +902,9 @@ func (v *gtkWebView) loadChanged(event int32) {
switch event {
case webLoadStarted:
v.failed, v.refused = false, ""
+ // A page that loads again has a web process again, so the one it lost is no longer what
+ // it is.
+ v.failure = platform.WebProcessNoFailure
v.report(platform.WebLoadStarted, address, platform.WebLoadNoError, "")
case webLoadCommitted:
v.report(platform.WebLoadCommitted, address, platform.WebLoadNoError, "")
@@ -895,6 +948,19 @@ func (v *gtkWebView) loadFailed(uri, failure uintptr) {
v.report(platform.WebLoadFinished, goString(uri), code, description)
}
+// processTerminated reports the page's web process gone, with the engine's reason for it: the page
+// cannot draw again until it is loaded again, and the reason decides what an application says, so it
+// is reported in the terms every engine can be held to rather than the engine's own.
+func (v *gtkWebView) processTerminated(reason int32) {
+ if v.closed {
+ return
+ }
+ v.failure = platform.WebProcessFailureFromWebKitTerminationReason(reason)
+ if v.config.OnProcessFailed != nil {
+ v.config.OnProcessFailed(v.failure)
+ }
+}
+
// navigationAllowed asks the application whether the view may make a navigation. An application
// that set no Navigate allows every one.
func (v *gtkWebView) navigationAllowed(address string, mainFrame, userGesture bool) bool {
diff --git a/internal/platform/web_host.go b/internal/platform/web_host.go
index 80565f32f..4d12ad861 100644
--- a/internal/platform/web_host.go
+++ b/internal/platform/web_host.go
@@ -82,6 +82,12 @@ type WebViewConfig struct {
TopCornerRadius float32
// OnLoad reports the page's navigation.
OnLoad func(WebLoad)
+ // OnProcessFailed reports the page's process gone: it crashed, the system or the engine
+ // stopped it, or it never started. The page cannot draw again until it is loaded again, so an
+ // application says so and loads it, and the failure names which of those it was. Every engine
+ // here reports it; WebKitGTK before 2.20 has no signal for it, and says so once rather than
+ // leaving the callback silently unset.
+ OnProcessFailed func(WebProcessFailure)
// Navigate decides a navigation before it starts; nil allows every navigation.
Navigate func(WebNavigation) bool
// NewWindow decides a window.open or target=_blank before it opens; nil refuses it. That is a
@@ -207,5 +213,8 @@ type WebView interface {
// until it finishes or fails. WebView2 has no property for it, so Windows follows the
// navigation's events.
IsLoading() bool
+ // ProcessFailure is why the page's process is gone, WebProcessNoFailure while it is there: the
+ // value OnProcessFailed was given, until the page starts a navigation again.
+ ProcessFailure() WebProcessFailure
Close()
}
diff --git a/internal/platform/web_process_failure.go b/internal/platform/web_process_failure.go
new file mode 100644
index 000000000..e482b5f00
--- /dev/null
+++ b/internal/platform/web_process_failure.go
@@ -0,0 +1,155 @@
+package platform
+
+import "strconv"
+
+// WebProcessFailure is why a page's process is gone, in terms each engine can be held to: the
+// engines name the same failures differently, and what an application should say about a page that
+// lost its process depends on which it was. A page whose renderer crashed may have lost input the
+// user typed into it and is worth warning about before it is loaded again; a page whose renderer
+// the system reclaimed under memory pressure did nothing wrong, and a reload is all it needs.
+// Zero is a page whose process is there.
+type WebProcessFailure uint8
+
+const (
+ // WebProcessNoFailure is a page whose process is there: the page can draw, and nothing is
+ // wrong with it that this value would name.
+ WebProcessNoFailure WebProcessFailure = iota
+ // WebProcessCrashed is a process that stopped without being asked to: a fault in the page or
+ // in the engine, which loses whatever the page held that was not saved.
+ WebProcessCrashed
+ // WebProcessKilled is a process that the system or the engine stopped: memory pressure, an
+ // out-of-memory kill, or the engine ending it itself. The page is gone with it, but nothing
+ // the page did made it happen, so a reload usually brings it back.
+ WebProcessKilled
+ // WebProcessUnresponsive is a process that stopped answering, which the engine ended.
+ WebProcessUnresponsive
+ // WebProcessLaunchFailed is a process that never started, so the page never ran at all.
+ WebProcessLaunchFailed
+ // WebProcessHostGone is the engine's own process gone, taking every page it hosted with it.
+ // Unlike the failures above, this page cannot be loaded again in place: Reload has no
+ // process to bring back, so the application closes it and opens a new one. Only WebView2
+ // has such a process; the other engines lose one page's process at a time.
+ WebProcessHostGone
+ // WebProcessUnknown is a process the engine reports as gone without a reason this package
+ // classifies, including an engine that names no reason at all.
+ WebProcessUnknown
+)
+
+// String names the failure, for a status line or a log.
+func (f WebProcessFailure) String() string {
+ switch f {
+ case WebProcessNoFailure:
+ return "no failure"
+ case WebProcessCrashed:
+ return "crashed"
+ case WebProcessKilled:
+ return "killed"
+ case WebProcessUnresponsive:
+ return "unresponsive"
+ case WebProcessLaunchFailed:
+ return "launch failed"
+ case WebProcessHostGone:
+ return "host process gone"
+ case WebProcessUnknown:
+ return "unknown failure"
+ }
+ return "web process failure " + strconv.FormatUint(uint64(f), 10)
+}
+
+// COREWEBVIEW2_PROCESS_FAILED_KIND values, which ICoreWebView2ProcessFailedEventArgs.get_
+// ProcessFailedKind reports for the process the runtime lost. Only the three that end the page are
+// here: a frame's own renderer (3), a utility (4), a sandbox helper (5), a GPU (6) and a plugin (7,
+// 8) process are the engine's to restart, and the page draws again without the application being
+// told; the value this package does not know (9) is treated the same way, because a failure the
+// runtime cannot name is not one it believes ended the page.
+const (
+ webView2FailedBrowserProcessExited = 0
+ webView2FailedRenderProcessExited = 1
+ webView2FailedRenderProcessUnresponsive = 2
+)
+
+// COREWEBVIEW2_PROCESS_FAILED_REASON values, which ICoreWebView2ProcessFailedEventArgs2.get_Reason
+// reports for why the process exited. -1 is this package's own value for a runtime too old to say
+// (see WebProcessFailureFromWebView2), not one the runtime reports.
+const (
+ webView2ReasonUnexpected = 0
+ webView2ReasonUnresponsive = 1
+ webView2ReasonTerminated = 2
+ webView2ReasonCrashed = 3
+ webView2ReasonLaunchFailed = 4
+ webView2ReasonOutOfMemory = 5
+ webView2ReasonProfileDelete = 6
+
+ webView2ReasonUnsaid = -1
+)
+
+// WebProcessFailureFromWebView2 maps what the runtime reports about a process that failed: kind is
+// COREWEBVIEW2_PROCESS_FAILED_KIND and reason is COREWEBVIEW2_PROCESS_FAILED_REASON, which is
+// webView2ReasonUnsaid when the runtime predates ICoreWebView2ProcessFailedEventArgs2 (WebView2
+// SDK 1.0.818.41) and says only the kind.
+//
+// ok is false for a process whose loss the page survives: the engine starts the others again by
+// itself, and an application is told about the one that draws the page it hosts.
+func WebProcessFailureFromWebView2(kind, reason int32) (WebProcessFailure, bool) {
+ switch kind {
+ case webView2FailedBrowserProcessExited:
+ // The browser process draws no page of its own, but every renderer is its child: when it
+ // goes, every page goes and the control itself is unusable, whatever reason it gives.
+ // Reload has nothing to load into, so the application reopens the page.
+ return WebProcessHostGone, true
+ case webView2FailedRenderProcessExited:
+ return webProcessFailureFromWebView2Reason(reason), true
+ case webView2FailedRenderProcessUnresponsive:
+ return WebProcessUnresponsive, true
+ }
+ return WebProcessNoFailure, false
+}
+
+func webProcessFailureFromWebView2Reason(reason int32) WebProcessFailure {
+ switch reason {
+ case webView2ReasonUnresponsive:
+ return WebProcessUnresponsive
+ case webView2ReasonTerminated, webView2ReasonOutOfMemory:
+ // The runtime calls a process it ended itself terminated, and one the system reclaimed
+ // out of memory: both are a page that did nothing wrong, the second by the system rather
+ // than by the engine.
+ return WebProcessKilled
+ case webView2ReasonCrashed, webView2ReasonUnexpected:
+ // Unexpected is the exit the runtime has no name for, which is a process that stopped
+ // without being asked in the terms an application acts on: the page lost what it held.
+ return WebProcessCrashed
+ case webView2ReasonLaunchFailed:
+ return WebProcessLaunchFailed
+ }
+ // A reason this package does not know, the deprecated one, and a runtime that says only the
+ // kind.
+ return WebProcessUnknown
+}
+
+// WebKitWebProcessTerminationReason values, which the web-process-terminated signal carries from
+// WebKitGTK 2.20.
+const (
+ webKitProcessCrashed = 0
+ webKitProcessExceededMemoryLimit = 1
+ webKitProcessTerminatedByAPI = 2
+)
+
+// WebProcessFailureFromWebKitTerminationReason maps the reason of WebKitGTK's web-process-terminated
+// signal: the engine ended the web process, and says why. The reason a reason this package does not
+// know is reported as such rather than guessed at.
+func WebProcessFailureFromWebKitTerminationReason(reason int32) WebProcessFailure {
+ switch reason {
+ case webKitProcessCrashed:
+ return WebProcessCrashed
+ case webKitProcessExceededMemoryLimit, webKitProcessTerminatedByAPI:
+ // Above the limit the system or the engine stopped it; by API the application asked
+ // WebKitGTK to, which is the engine's own termination as well.
+ return WebProcessKilled
+ }
+ return WebProcessUnknown
+}
+
+// WebProcessFailureDarwinTermination is what a WKWebView reports when its content process is gone:
+// webViewWebContentProcessDidTerminate: carries no reason at all, so a page that lost its process on
+// macOS is WebProcessUnknown in this package's terms rather than a guess at a crash.
+const WebProcessFailureDarwinTermination = WebProcessUnknown
diff --git a/internal/platform/web_process_failure_test.go b/internal/platform/web_process_failure_test.go
new file mode 100644
index 000000000..347483125
--- /dev/null
+++ b/internal/platform/web_process_failure_test.go
@@ -0,0 +1,99 @@
+package platform
+
+import "testing"
+
+func TestEachWebView2ProcessFailureNamesItsReason(t *testing.T) {
+ for _, c := range []struct {
+ kind, reason int32
+ want WebProcessFailure
+ }{
+ {0, 0, WebProcessHostGone}, // BROWSER_PROCESS_EXITED, UNEXPECTED
+ {0, 2, WebProcessHostGone}, // BROWSER_PROCESS_EXITED, TERMINATED: the kind decides
+ {1, 3, WebProcessCrashed}, // RENDER_PROCESS_EXITED, CRASHED
+ {1, 0, WebProcessCrashed}, // RENDER_PROCESS_EXITED, UNEXPECTED
+ {1, 2, WebProcessKilled}, // RENDER_PROCESS_EXITED, TERMINATED
+ {1, 5, WebProcessKilled}, // RENDER_PROCESS_EXITED, OUT_OF_MEMORY
+ {1, 4, WebProcessLaunchFailed}, // RENDER_PROCESS_EXITED, LAUNCH_FAILED
+ {1, 1, WebProcessUnresponsive}, // RENDER_PROCESS_EXITED, UNRESPONSIVE
+ {1, 6, WebProcessUnknown}, // 6 is the deprecated PROFILE_DELETED, never reported now
+ {1, 7, WebProcessUnknown}, // a reason newer than this package
+ {1, -1, WebProcessUnknown}, // a runtime too old to say why
+ {2, 1, WebProcessUnresponsive}, // RENDER_PROCESS_UNRESPONSIVE, UNRESPONSIVE
+ {2, 3, WebProcessUnresponsive}, // the kind decides: an unresponsive process is not crashed
+ {2, -1, WebProcessUnresponsive}, // a runtime too old to say why
+ {0, -1, WebProcessHostGone}, // a browser process gone with no reason given
+ } {
+ got, ok := WebProcessFailureFromWebView2(c.kind, c.reason)
+ if !ok || got != c.want {
+ t.Errorf("kind %d reason %d = %v, %v, want %v, true", c.kind, c.reason, got, ok, c.want)
+ }
+ }
+}
+
+func TestAWebView2ProcessThePageSurvivesIsNotReported(t *testing.T) {
+ for _, kind := range []int32{
+ 3, // FRAME_RENDER_PROCESS_EXITED: a frame's own renderer, replaced by an error page
+ 4, // UTILITY_PROCESS_EXITED
+ 5, // SANDBOX_HELPER_PROCESS_EXITED
+ 6, // GPU_PROCESS_EXITED
+ 7, // PPAPI_PLUGIN_PROCESS_EXITED
+ 8, // PPAPI_BROKER_PROCESS_EXITED
+ 9, // UNKNOWN_PROCESS_EXITED
+ 10, // a kind newer than this package
+ -1, // never reported, but not a page's process either
+ } {
+ if got, ok := WebProcessFailureFromWebView2(kind, 3); ok || got != WebProcessNoFailure {
+ t.Errorf("kind %d = %v, %v, want the page not to hear of it", kind, got, ok)
+ }
+ }
+}
+
+func TestEachWebKitTerminationReasonNamesItsFailure(t *testing.T) {
+ for _, c := range []struct {
+ reason int32
+ want WebProcessFailure
+ }{
+ {0, WebProcessCrashed}, // WEBKIT_WEB_PROCESS_CRASHED
+ {1, WebProcessKilled}, // WEBKIT_WEB_PROCESS_EXCEEDED_MEMORY_LIMIT
+ {2, WebProcessKilled}, // WEBKIT_WEB_PROCESS_TERMINATED_BY_API
+ {3, WebProcessUnknown}, // a reason newer than this package
+ {-1, WebProcessUnknown},
+ } {
+ if got := WebProcessFailureFromWebKitTerminationReason(c.reason); got != c.want {
+ t.Errorf("reason %d = %v, want %v", c.reason, got, c.want)
+ }
+ }
+}
+
+func TestDarwinTerminationNamesNoReason(t *testing.T) {
+ if WebProcessFailureDarwinTermination != WebProcessUnknown {
+ t.Fatalf("a WKWebView's termination = %v, want the reason it does not give", WebProcessFailureDarwinTermination)
+ }
+}
+
+func TestEachProcessFailureNamesItself(t *testing.T) {
+ for _, c := range []struct {
+ failure WebProcessFailure
+ want string
+ }{
+ {WebProcessNoFailure, "no failure"},
+ {WebProcessCrashed, "crashed"},
+ {WebProcessKilled, "killed"},
+ {WebProcessUnresponsive, "unresponsive"},
+ {WebProcessLaunchFailed, "launch failed"},
+ {WebProcessHostGone, "host process gone"},
+ {WebProcessUnknown, "unknown failure"},
+ {WebProcessFailure(200), "web process failure 200"},
+ } {
+ if got := c.failure.String(); got != c.want {
+ t.Errorf("%d = %q, want %q", c.failure, got, c.want)
+ }
+ }
+}
+
+func TestAPageWhoseProcessIsThereNamesNoFailure(t *testing.T) {
+ var failure WebProcessFailure
+ if failure != WebProcessNoFailure {
+ t.Fatalf("a zero WebProcessFailure = %v, want a page that has its process", failure)
+ }
+}
diff --git a/internal/platform/windows/web_windows.go b/internal/platform/windows/web_windows.go
index 358256bf8..2b483f343 100644
--- a/internal/platform/windows/web_windows.go
+++ b/internal/platform/windows/web_windows.go
@@ -117,6 +117,9 @@ type windowsWeb struct {
// loading is a navigation the page is in the middle of. WebView2 has no property for it, so it
// follows the events: a main frame navigation that started, until its NavigationCompleted.
loading bool
+ // processFailure is why the page's process is gone, WebProcessNoFailure while it is there,
+ // which the runtime reports through ProcessFailed and a navigation that starts again clears.
+ processFailure platform.WebProcessFailure
// refused is a main frame navigation the application's Navigate cancelled. The runtime reports
// the cancellation as the navigation's end, which the application already answered.
refused bool
@@ -342,6 +345,10 @@ func (page *windowsWeb) attach(environment uintptr) {
page.navigationCompleted(args)
return 0
}), uintptr(unsafe.Pointer(&token)))
+ comCall(view, viewAddProcessFailed, newHandler(func(_, args uintptr) uintptr {
+ page.processFailed(args)
+ return 0
+ }), uintptr(unsafe.Pointer(&token)))
script := platform.WebBridgeScript
if page.config.BridgeMainFrameOnly {
script = platform.WebBridgeMainFrameOnlyScript
@@ -414,6 +421,36 @@ func (page *windowsWeb) navigationCompleted(args uintptr) {
page.loaded(platform.WebLoadFinished, page.sourceAddress(), code, "")
}
+// processFailed reports a process the runtime lost. Only the page's own processes end the page: the
+// browser's, which every renderer is a child of, and the renderer that draws the main frame. A
+// frame's own renderer shows the runtime's error page inside that frame and the page keeps going, and
+// a GPU, utility, sandbox helper or plugin process is the runtime's to start again: neither is
+// reported, which is what the other engines do as well, their signals naming the web content process
+// alone.
+func (page *windowsWeb) processFailed(args uintptr) {
+ if page.closed || args == 0 {
+ return
+ }
+ var kind int32
+ comCall(args, processFailedKind, uintptr(unsafe.Pointer(&kind)))
+ // A runtime older than ICoreWebView2ProcessFailedEventArgs2 says only the kind: -1 is the
+ // platform's way of hearing that nothing was said about why.
+ reason := int32(-1)
+ var detailed uintptr
+ if status := comCall(args, 0, uintptr(unsafe.Pointer(&iidProcessFailedArgs2)), uintptr(unsafe.Pointer(&detailed))); status == 0 && detailed != 0 {
+ comCall(detailed, processFailedReason, uintptr(unsafe.Pointer(&reason)))
+ comCall(detailed, 2)
+ }
+ failure, pageProcess := platform.WebProcessFailureFromWebView2(kind, reason)
+ if !pageProcess {
+ return
+ }
+ page.processFailure, page.loading = failure, false
+ if page.config.OnProcessFailed != nil {
+ page.config.OnProcessFailed(failure)
+ }
+}
+
// sourceAddress is the address of the document the page has, as the runtime names it.
func (page *windowsWeb) sourceAddress() string {
if page.view == 0 {
@@ -475,6 +512,9 @@ func (page *windowsWeb) navigationStarting(args uintptr, mainFrame bool) {
// Committed or Finished. loaded names the address as the application knows it there too.
if mainFrame {
page.refused, page.loading = false, true
+ // A page that loads again has a process again, so the failure of the one it lost is no
+ // longer what it is.
+ page.processFailure = platform.WebProcessNoFailure
page.loaded(platform.WebLoadStarted, url, platform.WebLoadNoError, "")
}
}
@@ -720,6 +760,9 @@ func (page *windowsWeb) canGo(slot int) bool {
// events: WebView2 has no property that answers it.
func (page *windowsWeb) IsLoading() bool { return page.loading }
+// ProcessFailure is why the page's process is gone, WebProcessNoFailure while it is there.
+func (page *windowsWeb) ProcessFailure() platform.WebProcessFailure { return page.processFailure }
+
func (page *windowsWeb) Eval(script string) {
page.do(func() { comCall(page.view, viewExecuteScript, uintptr(unsafe.Pointer(wide(script))), 0) })
}
diff --git a/internal/platform/windows/webview2_windows.go b/internal/platform/windows/webview2_windows.go
index ee59aef5f..0d84119b7 100644
--- a/internal/platform/windows/webview2_windows.go
+++ b/internal/platform/windows/webview2_windows.go
@@ -444,7 +444,23 @@ const (
resourceContextAll = 0
)
+// ICoreWebView2's ProcessFailed event and what its arguments report: add_ProcessFailed is 25, before
+// AddScriptToExecuteOnDocumentCreated 27, and get_ProcessFailedKind is 3, which says which process
+// the runtime lost. ICoreWebView2ProcessFailedEventArgs2 (WebView2 SDK 1.0.818.41, Runtime 94) adds
+// get_Reason 4, which says why: the kind alone cannot tell a crash from a process the system
+// reclaimed under memory pressure.
+const (
+ viewAddProcessFailed = 25
+ processFailedKind = 3
+ processFailedReason = 4
+)
+
// iidEnvironment10 is ICoreWebView2Environment10, which offers the controller options an InPrivate
// page is made with. It comes from the WebView2 SDK 1.0.1210.39 and Runtime 101 (Edge 101); a
// runtime older than that does not answer for it.
var iidEnvironment10 = guid{0xee0eb9df, 0x6f12, 0x46ce, [8]byte{0xb5, 0x3f, 0x3f, 0x47, 0xb9, 0xc9, 0x28, 0xe0}}
+
+// iidProcessFailedArgs2 is ICoreWebView2ProcessFailedEventArgs2, the arguments of ProcessFailed that
+// say why the process went (WebView2 SDK 1.0.818.41, Runtime 94 and newer, which is older than the
+// runtime 101 that an ephemeral page already needs); a runtime without it gives the kind alone.
+var iidProcessFailedArgs2 = guid{0x4dab9422, 0x46fa, 0x4c3e, [8]byte{0xa5, 0xd2, 0x41, 0xd2, 0x07, 0x1d, 0x36, 0x80}}
From 3be62de2063e1ad7c1ebfe9dac77eae5530eb720 Mon Sep 17 00:00:00 2001
From: t8y2 <1156263951@qq.com>
Date: Sun, 22 Nov 2026 00:20:29 +0800
Subject: [PATCH 32/47] fix(ui): keep element identities stable across
conditional declarations
- A Key or Part given to an element without identity (a Text, an Icon)
no longer passes on to the next element, where it renamed a container
and reset its State whenever a list's length changed. A dev build stops
with a message saying where the Key belongs.
- A button that appears before the focused one takes the focused one's
number among its kind; the page now tells that from a relabel once the
whole scope is declared, and the focus follows the button it was on, so
Enter no longer presses the newcomer.
- Two States of one name and different types in a container are two
states, instead of one reset to the other's type every paint.
The paired Motty commit drops two Keys its RadioID calls never used.
---
base/attrcheck_dev.go | 21 ++++++++++++
base/attrcheck_release.go | 4 +++
base/frame.go | 6 ++++
base/names.go | 5 +++
base/page.go | 68 ++++++++++++++++++++++++++++++++++-----
ui/identity_shift_test.go | 50 ++++++++++++++++++++++++++++
ui/key_names_dev_test.go | 26 +++++++++++++++
ui/key_names_test.go | 34 ++++++++++++++++++++
ui/radio_test.go | 4 +--
ui/state_type_test.go | 29 +++++++++++++++++
10 files changed, 237 insertions(+), 10 deletions(-)
create mode 100644 ui/identity_shift_test.go
create mode 100644 ui/key_names_dev_test.go
create mode 100644 ui/key_names_test.go
create mode 100644 ui/state_type_test.go
diff --git a/base/attrcheck_dev.go b/base/attrcheck_dev.go
index 78942cfc9..53892933d 100644
--- a/base/attrcheck_dev.go
+++ b/base/attrcheck_dev.go
@@ -4,6 +4,7 @@ package base
import (
"os"
+ "strconv"
"github.com/vivaui/viva/gfx"
"github.com/vivaui/viva/style"
@@ -505,3 +506,23 @@ func kindAttributeName(n *Node) string {
}
return controlName(n.Kind)
}
+
+// unusedName reports a Key or Part given to an element that takes no name (a
+// Text, an Icon, a Spacer): it names nothing, and it would have passed to the
+// next element and taken that element's identity.
+func (f *Frame) unusedName(at int32, next protoName) {
+ given := "Part " + strconv.Quote(next.part)
+ if next.kindOf == 1 {
+ given = "Key " + next.key.describe()
+ }
+ name := "element"
+ if int(at) < len(f.Nodes) {
+ name = kindAttributeName(&f.Nodes[at])
+ }
+ message := "ui: " + given + " was given to a " + name + ", which has no identity: give it to the container or control it names"
+ if attrCheckWarn {
+ println("VIVA_ATTR_CHECK: " + message)
+ return
+ }
+ panic(message)
+}
diff --git a/base/attrcheck_release.go b/base/attrcheck_release.go
index 7cfa6ea3d..82e55e667 100644
--- a/base/attrcheck_release.go
+++ b/base/attrcheck_release.go
@@ -8,3 +8,7 @@ func (f *Frame) checkAttributes() {}
// markAttr is empty in release builds: no attribute set is recorded.
func (n *Node) markAttr(uint8) {}
+
+// unusedName is empty in release builds: a Key or Part given to an element
+// without identity is dropped, not reported.
+func (f *Frame) unusedName(int32, protoName) {}
diff --git a/base/frame.go b/base/frame.go
index af095b597..a4348c8a8 100644
--- a/base/frame.go
+++ b/base/frame.go
@@ -467,6 +467,12 @@ func (f *Frame) Add(k Kind) int32 {
panic("ui: an element was declared after the page was laid out (in a Draw callback, or after End): declare elements in the build function")
}
index := int32(len(f.Nodes))
+ if p := f.page; p != nil && p.ctx.nextSet && p.ctx.f == f && index > p.ctx.nextAt {
+ // The element Key or Part was given to took no name: it must not pass
+ // on to this one, which would take another element's identity.
+ p.ctx.nextSet = false
+ f.unusedName(p.ctx.nextAt, p.ctx.Next)
+ }
f.Nodes = append(f.Nodes, Node{Kind: k, Parent: f.Parent, First: -1, Last: -1, Next: -1, Items: Auto})
if f.Parent >= 0 {
parent := &f.Nodes[f.Parent]
diff --git a/base/names.go b/base/names.go
index c507157ad..af207dee1 100644
--- a/base/names.go
+++ b/base/names.go
@@ -93,6 +93,11 @@ type armedButton struct {
ID gfx.ID
Label string
moved bool // the number moved to another button: nothing it holds is delivered
+ // relabel is the label the button's place showed this paint when it differed
+ // from Label: a new label, or the place now naming another button. Which one
+ // is known only once the paint has declared the whole scope (settleHeld).
+ relabel string
+ relabeling bool
}
func (key keyKey) describe() string {
diff --git a/base/page.go b/base/page.go
index fe9f75d43..deaa86563 100644
--- a/base/page.go
+++ b/base/page.go
@@ -54,8 +54,12 @@ type Ctx struct {
page *Page
f *Frame
// next names the next element instead of its place: a Key, an index or a part.
- Next protoName
- nextSet bool
+ Next protoName
+ nextSet bool
+ // nextAt is how many elements the frame held when Next was set: the element
+ // added at that index is the one Next names, and one added after it while
+ // Next is still unused means the named element had no identity to take it.
+ nextAt int32
stateSeq map[stateName]uint32 // reset each paint: the States of each name asked for in each scope
}
@@ -71,12 +75,14 @@ type protoName struct {
// their siblings in a paint.
func (c *Ctx) Key(key string) C {
c.Next, c.nextSet = protoName{key: keyKey{Text: key, isText: true}, kindOf: 1}, true
+ c.nextAt = int32(len(c.f.Nodes))
return c
}
// KeyInt is Key for a number, a record's ID.
func (c *Ctx) KeyInt(key int) C {
c.Next, c.nextSet = protoName{key: keyKey{number: key}, kindOf: 1}, true
+ c.nextAt = int32(len(c.f.Nodes))
return c
}
@@ -85,6 +91,7 @@ func (c *Ctx) KeyInt(key int) C {
func (c *Ctx) Part(Name string) C {
checkName("Part", Name)
c.Next, c.nextSet = protoName{part: Name, kindOf: 2}, true
+ c.nextAt = int32(len(c.f.Nodes))
return c
}
@@ -165,6 +172,7 @@ type protoScope struct {
keySub gfx.Scope
keys slotPool
labels []string
+ ids []gfx.ID // the identity of each of labels, in the same order
prev []string
prevEpoch uint32
}
@@ -353,6 +361,9 @@ type intKey struct {
type stateName struct {
scope gfx.Scope
Name string
+ // typ is a nil *T: two States of one name and different types are two
+ // states, not one that each paint would reset to the other's type.
+ typ any
}
type protoStateKey struct {
@@ -745,6 +756,7 @@ func (p *Page) Draw(Surface *gfx.Canvas, bounds Rect, View func(C)) {
}
}
p.retry = false
+ p.settleHeld()
p.settleFocus()
p.settleEffects()
if len(p.memos) > 0 {
@@ -874,6 +886,7 @@ func (p *Page) record(scope gfx.Scope) *protoScope {
if s.epoch != p.epoch {
clear(s.prev)
s.prev, s.labels, s.prevEpoch = s.labels, s.prev[:0], s.epoch
+ s.ids = s.ids[:0]
s.epoch = p.epoch
}
return s
@@ -1036,6 +1049,7 @@ func (p *Page) Guard(b Box, ID gfx.ID, Label string) {
s := p.record(ID.Scope())
number := len(s.labels)
s.labels = append(s.labels, Label)
+ s.ids = append(s.ids, ID)
focused := canvas.Focused() == ID
if !focused && canvas.Pressed() != ID {
return
@@ -1065,7 +1079,44 @@ func (p *Page) Guard(b Box, ID gfx.ID, Label string) {
canvas.ReleaseFocus(ID)
}
default:
- held.Label = Label
+ held.relabel, held.relabeling = Label, true
+ }
+}
+
+// settleHeld decides, once the paint has declared every button, what a held
+// button's new label meant. When its old label is now another button's in the
+// same scope, a button appeared before it and its number moved on (a banner's
+// Dismiss above Save): the focus follows the button it was on, and a press is
+// not delivered to the one that took its place. Otherwise the button was only
+// relabeled ("Connect" becoming "Connecting…") and keeps what it holds.
+func (p *Page) settleHeld() {
+ canvas := p.ctx.f.Surface
+ for i := range p.held {
+ held := &p.held[i]
+ if !held.relabeling {
+ continue
+ }
+ held.relabeling = false
+ moved := gfx.ID{}
+ if scope := held.ID.Scope(); int(scope) < len(p.scopes) && p.scopes[scope] != nil {
+ s := p.scopes[scope]
+ for j, label := range s.labels {
+ if label == held.Label && s.ids[j] != held.ID {
+ moved = s.ids[j]
+ break
+ }
+ }
+ }
+ if moved.IsZero() {
+ held.Label = held.relabel
+ continue
+ }
+ if canvas != nil && canvas.Focused() == held.ID {
+ canvas.RequestFocus(moved)
+ *held = armedButton{ID: moved, Label: held.Label}
+ continue
+ }
+ held.moved = true
}
}
@@ -1196,8 +1247,9 @@ func (p *Page) RouteWheel(event gfx.ScrollEvent) gfx.EventResult {
//
// open := ui.State[bool](c, "open")
//
-// The name is the state's in its container, so a State asked for only in some paints
-// (behind an if) does not take another's value. A component declared twice in one
+// The name and the type are the state's in its container, so a State asked for only
+// in some paints (behind an if) does not take another's value, and two States of one
+// name and different types are two states. A component declared twice in one
// container asks for the same name twice: those are told apart by their order, as
// two Buttons are, so give each its own container or a Key when one of them comes
// and goes.
@@ -1209,13 +1261,13 @@ func State[T any](c C, Name string) *T {
// value it is bound to rather than its place.
func stateIn[T any](p *Page, scope gfx.Scope, Name string) *T {
c := &p.ctx
- at := stateName{scope: scope, Name: Name}
+ at := stateName{scope: scope, Name: Name, typ: (*T)(nil)}
n := c.stateSeq[at]
c.stateSeq[at] = n + 1
key := protoStateKey{stateName: at, n: n}
entry, ok := p.States[key]
- value, typed := entry.Value.(*T)
- if !ok || !typed {
+ value, _ := entry.Value.(*T)
+ if !ok {
value = new(T)
entry.Value = value
}
diff --git a/ui/identity_shift_test.go b/ui/identity_shift_test.go
new file mode 100644
index 000000000..4497314e2
--- /dev/null
+++ b/ui/identity_shift_test.go
@@ -0,0 +1,50 @@
+package ui_test
+
+import (
+ "testing"
+
+ "github.com/vivaui/viva/gfx"
+ "github.com/vivaui/viva/ui"
+)
+
+// A button that appears before the focused one takes its number among its kind,
+// and with it its identity: the focus follows the button it was on, so Enter
+// presses Save, not the banner's Dismiss that now holds Save's old name.
+func TestFocusFollowsAButtonWhoseNumberMoved(t *testing.T) {
+ show, got := false, ""
+ d := openPage(t, func(c ui.C) {
+ if show {
+ if ui.Button(c, "Dismiss banner").Clicked() {
+ got = "dismiss"
+ }
+ }
+ if ui.Button(c, "Save").Clicked() {
+ got = "save"
+ }
+ })
+ d.key(gfx.KeyTab)
+ show = true
+ d.repaint()
+ if d.Focused() != "Save" {
+ t.Fatalf("a button appearing before Save took the focus: %q", d.Focused())
+ }
+ d.key(gfx.KeyEnter)
+ if got != "save" {
+ t.Fatalf("Enter pressed %q", got)
+ }
+}
+
+// A focused button whose own label changes is the same button: it keeps the focus.
+func TestARelabeledButtonKeepsTheFocus(t *testing.T) {
+ label := "Connect"
+ d := openPage(t, func(c ui.C) {
+ ui.Button(c, label)
+ ui.Button(c, "Cancel")
+ })
+ d.key(gfx.KeyTab)
+ label = "Connecting…"
+ d.repaint()
+ if d.Focused() != "Connecting…" {
+ t.Fatalf("the relabeled button lost the focus to %q", d.Focused())
+ }
+}
diff --git a/ui/key_names_dev_test.go b/ui/key_names_dev_test.go
new file mode 100644
index 000000000..ef85b5181
--- /dev/null
+++ b/ui/key_names_dev_test.go
@@ -0,0 +1,26 @@
+//go:build dev || vivadev
+
+package ui_test
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/vivaui/viva/ui"
+)
+
+// In a dev build a Key given to an element without identity stops the page and
+// says where the Key belongs.
+func TestAKeyGivenToATextIsReported(t *testing.T) {
+ defer func() {
+ message, _ := recover().(string)
+ if !strings.Contains(message, `Key "row"`) || !strings.Contains(message, "Text") {
+ t.Fatalf("recovered %q, want the Key and the Text named", message)
+ }
+ }()
+ openPage(t, func(c ui.C) {
+ ui.Text(c.Key("row"), "row")
+ ui.Row(c)
+ })
+ t.Fatal("a Key on a Text was not reported")
+}
diff --git a/ui/key_names_test.go b/ui/key_names_test.go
new file mode 100644
index 000000000..276441e0b
--- /dev/null
+++ b/ui/key_names_test.go
@@ -0,0 +1,34 @@
+//go:build !dev && !vivadev
+
+package ui_test
+
+import (
+ "testing"
+
+ "github.com/vivaui/viva/ui"
+)
+
+// A Key given to an element without identity (a Text) names nothing, and must
+// not pass on to the container declared after it: that container would take a
+// name that moves with the list, and lose its State whenever the list's length
+// changes.
+func TestAKeyGivenToATextDoesNotRenameTheNextElement(t *testing.T) {
+ rows, painted := 2, 0
+ d := openPage(t, func(c ui.C) {
+ for i := range rows {
+ ui.Text(c.KeyInt(i), "row")
+ }
+ ui.Row(c).Children(func() {
+ count := ui.State[int](c, "paints")
+ *count++
+ painted = *count
+ })
+ })
+ d.repaint()
+ before := painted
+ rows = 3
+ d.repaint()
+ if painted != before+1 {
+ t.Fatalf("the row after the list lost its state when the list grew: %d paints after %d", painted, before)
+ }
+}
diff --git a/ui/radio_test.go b/ui/radio_test.go
index d593da4de..99d71b76d 100644
--- a/ui/radio_test.go
+++ b/ui/radio_test.go
@@ -35,8 +35,8 @@ func TestRadioIDKeepsTheApplicationsIdentity(t *testing.T) {
ungroup := false
d := openPage(t, func(c ui.C) {
ui.RadioGroup(c).Children(func() {
- ui.RadioID(c.Key("keep"), gfx.Item(40), &ungroup, false, "Keep")
- ui.RadioID(c.Key("ungroup"), id, &ungroup, true, "Ungroup")
+ ui.RadioID(c, gfx.Item(40), &ungroup, false, "Keep")
+ ui.RadioID(c, id, &ungroup, true, "Ungroup")
})
})
d.click("Ungroup")
diff --git a/ui/state_type_test.go b/ui/state_type_test.go
new file mode 100644
index 000000000..eea608993
--- /dev/null
+++ b/ui/state_type_test.go
@@ -0,0 +1,29 @@
+package ui_test
+
+import (
+ "testing"
+
+ "github.com/vivaui/viva/ui"
+)
+
+// Two States of one name and different types in one container are two states:
+// each keeps its value, instead of one resetting the other every paint, and
+// asking for them again allocates nothing.
+func TestStatesOfOneNameAndTwoTypesAreTwoStates(t *testing.T) {
+ var count *int
+ var open *bool
+ d := openPage(t, func(c ui.C) {
+ count = ui.State[int](c, "x")
+ open = ui.State[bool](c, "x")
+ *count++
+ *open = true
+ })
+ d.repaint()
+ d.repaint()
+ if *count != 3 || !*open {
+ t.Fatalf("after three paints: count %d, open %v", *count, *open)
+ }
+ if allocations := testing.AllocsPerRun(20, d.repaint); allocations != 0 {
+ t.Fatalf("a repaint asking for the States allocated %v times", allocations)
+ }
+}
From c6e7aae91193a43d974075cc2228a01389c3cf16 Mon Sep 17 00:00:00 2001
From: t8y2 <1156263951@qq.com>
Date: Sun, 22 Nov 2026 00:20:30 +0800
Subject: [PATCH 33/47] feat(app): let a goroutine hand its result to a window
with Post
Invalidator.Post queues an update that runs on the window thread before
OnWake and the repaint it asks for. It accepts updates only while the
window is open, drops the waiting ones when it closes, and refuses past
256, so a slow or closed window holds no backlog. Every entry point that
opens a window (RunCanvas, Application.OpenWindow, the headless Driver,
the web target) attaches it, and ContentWindow.Post now delegates to it
instead of keeping its own queue.
The background guide used OnWake to move a pending result into state,
which cleared the status on every animation frame's wake; it now uses
Post, and the guide's prose says what OnWake is for.
Viva-only; Motty's many hand-written result pumps can move to it next.
---
app/app.go | 12 +-
app/application.go | 2 +
app/content_window.go | 70 ++--------
app/content_window_test.go | 6 +-
app/driver.go | 1 +
app/invalidator.go | 123 +++++++++++++++++-
app/invalidator_post_test.go | 76 +++++++++++
app/run_canvas.go | 4 +
app/run_canvas_js.go | 2 +
examples/guides/background/main.go | 21 +--
examples/guides/background/main_test.go | 11 ++
ui/doc.go | 5 +-
.../content/guides/en/programming-model.md | 29 ++---
.../content/guides/zh/programming-model.md | 29 ++---
14 files changed, 255 insertions(+), 136 deletions(-)
create mode 100644 app/invalidator_post_test.go
diff --git a/app/app.go b/app/app.go
index 62de4ecac..df91cad41 100644
--- a/app/app.go
+++ b/app/app.go
@@ -238,13 +238,15 @@ type Config struct {
// OnClosed runs exactly once on the window thread after native resources
// stop receiving events. Release window-owned application resources here.
OnClosed func()
- // Invalidator, when set, lets other goroutines request a repaint with
- // Invalidate. Pair it with OnWake to apply what they produced. Unset, no
- // wake-up machinery exists. A development reload worker ignores it.
+ // Invalidator, when set, lets other goroutines hand results to the window
+ // with Post, or request a repaint with Invalidate. Unset, no wake-up
+ // machinery exists. A development reload worker ignores it.
Invalidator *Invalidator
// OnWake runs on the window thread right before each repaint that
- // Invalidate or a running transition requested. Move the results of
- // background work into application state here, so Paint only reads state.
+ // Invalidate, Post or a running transition requested, after the updates
+ // Post queued. It runs on every such wake, a transition's frames included,
+ // so it is for state the window thread advances itself; a result of
+ // background work is handed over with Invalidator.Post, which applies it once.
// It runs for a window nobody can see too (hidden, minimized, or covered, where
// the platform says so), which is not painted: the frame it missed is painted
// once the window shows again, so a status icon can be refreshed from here.
diff --git a/app/application.go b/app/application.go
index 86a3c92f0..e1b5a177b 100644
--- a/app/application.go
+++ b/app/application.go
@@ -223,6 +223,7 @@ func (application *Application) OpenWindow(config Config, canvas *gfx.Canvas) (*
return nil, errors.New("app: application is not running")
}
window := &Window{}
+ config.attachPosts()
application.mu.Lock()
if application.windows == nil {
application.windows = make(map[*Window]struct{})
@@ -275,6 +276,7 @@ func (application *Application) OpenWindow(config Config, canvas *gfx.Canvas) (*
}
control, err := application.host.OpenWindow(config, canvas, closed)
if err != nil {
+ config.Invalidator.closePosts()
forget()
return nil, err
}
diff --git a/app/content_window.go b/app/content_window.go
index 217762422..4801f49f9 100644
--- a/app/content_window.go
+++ b/app/content_window.go
@@ -2,13 +2,10 @@ package app
import (
"fmt"
- "sync"
"github.com/vivaui/viva/gfx"
)
-const contentWindowPostLimit = 256
-
// ContentWindow is an independent native window for application-owned content.
// It uses normal system chrome on Windows, macOS and Linux. Config supplies the
// content and close policy; the helper owns UI-thread delivery and lifetime.
@@ -16,15 +13,13 @@ const contentWindowPostLimit = 256
type ContentWindow struct {
window *Window
invalidator Invalidator
- mu sync.Mutex
- pending []func()
- closed bool
closeRequest func(func())
}
// OpenContentWindow opens a resizable system window. Call it on the application
-// thread, like OpenWindow. The helper owns Invalidator and drains Post updates
-// before the supplied OnWake. Background workers never touch UI state directly.
+// thread, like OpenWindow. The helper owns the window's Invalidator, whose Post
+// updates run before the supplied OnWake. Background workers never touch UI
+// state directly.
func (application *Application) OpenContentWindow(config Config, canvas *gfx.Canvas) (*ContentWindow, error) {
content := &ContentWindow{closeRequest: config.OnCloseRequest}
if config.Width <= 0 {
@@ -33,72 +28,23 @@ func (application *Application) OpenContentWindow(config Config, canvas *gfx.Can
if config.Height <= 0 {
config.Height = 720
}
- onWake, onClosed := config.OnWake, config.OnClosed
config.Invalidator = &content.invalidator
- config.OnWake = func() {
- content.mu.Lock()
- pending := content.pending
- content.pending = nil
- closed := content.closed
- content.mu.Unlock()
- if closed {
- return
- }
- for _, update := range pending {
- content.mu.Lock()
- closed = content.closed
- content.mu.Unlock()
- if closed {
- return
- }
- update()
- }
- content.mu.Lock()
- closed = content.closed
- content.mu.Unlock()
- if closed {
- return
- }
- if onWake != nil {
- onWake()
- }
- }
- config.OnClosed = func() {
- content.mu.Lock()
- content.closed = true
- content.pending = nil
- content.mu.Unlock()
- if onClosed != nil {
- onClosed()
- }
- }
window, err := application.OpenWindow(config, canvas)
if err != nil {
- content.mu.Lock()
- content.closed = true
- content.mu.Unlock()
return nil, err
}
content.window = window
return content, nil
}
-// Post queues an update for the window thread. It rejects updates after native
-// teardown or while the bounded queue is full, so a slow window cannot retain
-// unbounded background results or resurrect closed content.
+// Post queues an update for the window thread, as Invalidator.Post does: it is
+// refused after the window closes or while the bounded queue is full, so a slow
+// window cannot retain unbounded background results or resurrect closed content.
func (content *ContentWindow) Post(update func()) bool {
- if content == nil || update == nil {
- return false
- }
- content.mu.Lock()
- if content.closed || len(content.pending) >= contentWindowPostLimit {
- content.mu.Unlock()
+ if content == nil {
return false
}
- content.pending = append(content.pending, update)
- content.mu.Unlock()
- content.invalidator.Invalidate()
- return true
+ return content.invalidator.Post(update)
}
func (content *ContentWindow) Invalidate() {
diff --git a/app/content_window_test.go b/app/content_window_test.go
index b3c516666..42fa3ba8f 100644
--- a/app/content_window_test.go
+++ b/app/content_window_test.go
@@ -134,7 +134,7 @@ func TestContentWindowPostQueueIsBoundedAndReusable(t *testing.T) {
return err
}
delivered := 0
- for range contentWindowPostLimit {
+ for range postLimit {
if !content.Post(func() { delivered++ }) {
t.Fatal("rejected update before queue reached its limit")
}
@@ -143,14 +143,14 @@ func TestContentWindowPostQueueIsBoundedAndReusable(t *testing.T) {
t.Fatal("accepted update beyond queue limit")
}
host.windows[0].config.OnWake()
- if delivered != contentWindowPostLimit {
+ if delivered != postLimit {
t.Fatalf("delivered %d queued updates", delivered)
}
if !content.Post(func() { delivered++ }) {
t.Fatal("drained queue did not accept another update")
}
host.windows[0].config.OnWake()
- if delivered != contentWindowPostLimit+1 {
+ if delivered != postLimit+1 {
t.Fatal("reused queue did not deliver its update")
}
content.Close()
diff --git a/app/driver.go b/app/driver.go
index c66838d82..99d95b5be 100644
--- a/app/driver.go
+++ b/app/driver.go
@@ -112,6 +112,7 @@ func NewDriver(config Config, canvas *gfx.Canvas) (*Driver, error) {
if err != nil {
return nil, err
}
+ normalized.attachPosts()
if canvas == nil {
canvas = &gfx.Canvas{}
}
diff --git a/app/invalidator.go b/app/invalidator.go
index dfa30659d..390f5df95 100644
--- a/app/invalidator.go
+++ b/app/invalidator.go
@@ -1,20 +1,32 @@
package app
import (
+ "sync"
+
"github.com/vivaui/viva/internal/platform"
"github.com/vivaui/viva/window"
)
-// Invalidator lets background goroutines ask the window to repaint. Create one,
-// pass it as Config.Invalidator, and call Invalidate from anywhere after the
-// goroutine has published its result. It owns no goroutine, timer, or channel:
-// an application that never calls Invalidate pays nothing, and the window
-// thread is woken exactly once per call batch.
+// Invalidator lets background goroutines hand results to a window and ask it
+// to repaint. Create one, pass it as Config.Invalidator, and call Post with the
+// update a goroutine's result makes, or Invalidate when the goroutine published
+// under its own synchronization. It owns no goroutine, timer, or channel: an
+// application that never calls it pays nothing, and the window thread is woken
+// exactly once per call batch.
//
// Calls made before RunCanvas starts or after the window closes do nothing.
// The zero value is ready to use.
type Invalidator struct {
waker platform.Waker
+
+ mu sync.Mutex
+ posts []func()
+ // open is set while the window that wakes through this Invalidator is open:
+ // Post queues only then.
+ open bool
+ // running is the window thread's scratch for the updates it takes from the
+ // queue, kept so applying them allocates nothing in the steady state.
+ running []func()
}
var _ window.Invalidator = (*Invalidator)(nil)
@@ -25,6 +37,107 @@ func (invalidator *Invalidator) Invalidate() {
invalidator.waker.Wake()
}
+// postLimit bounds the updates waiting for one window.
+const postLimit = 256
+
+// Post queues update to run on the window thread, then repaints: the way a
+// background goroutine hands its result to the model the page reads.
+//
+// go func() {
+// hosts, err := load()
+// invalidator.Post(func() { m.hosts, m.err = hosts, err })
+// }()
+//
+// Updates run in the order they were posted, before OnWake and before the
+// repaint they asked for, and only while the window is open: Post returns false
+// before the window opens, after it closes (updates still waiting are dropped
+// then), and when the window already has 256 updates waiting, so a window that
+// cannot keep up holds no unbounded backlog. update runs on the window thread
+// and may change anything the page reads; it must not block. Post is safe to
+// call from any goroutine.
+func (invalidator *Invalidator) Post(update func()) bool {
+ if update == nil {
+ return false
+ }
+ invalidator.mu.Lock()
+ if !invalidator.open || len(invalidator.posts) >= postLimit {
+ invalidator.mu.Unlock()
+ return false
+ }
+ invalidator.posts = append(invalidator.posts, update)
+ invalidator.mu.Unlock()
+ invalidator.Invalidate()
+ return true
+}
+
+func (invalidator *Invalidator) isOpen() bool {
+ invalidator.mu.Lock()
+ defer invalidator.mu.Unlock()
+ return invalidator.open
+}
+
+// runPosted applies the queued updates on the window thread and reports whether
+// the window is still open. An update that closes the window ends the run: the
+// ones after it are dropped with the window.
+func (invalidator *Invalidator) runPosted() bool {
+ invalidator.mu.Lock()
+ if !invalidator.open {
+ invalidator.mu.Unlock()
+ return false
+ }
+ invalidator.running = append(invalidator.running[:0], invalidator.posts...)
+ clear(invalidator.posts)
+ invalidator.posts = invalidator.posts[:0]
+ invalidator.mu.Unlock()
+ for _, update := range invalidator.running {
+ if !invalidator.isOpen() {
+ break
+ }
+ update()
+ }
+ clear(invalidator.running)
+ return invalidator.isOpen()
+}
+
+// attachPosts makes the window config describes deliver its Invalidator's posts:
+// the Invalidator accepts them from now until the window closes, and every wake
+// applies them before OnWake. A window that has closed runs no OnWake. Each entry
+// point that opens a window calls it once.
+func (config *Config) attachPosts() {
+ invalidator := config.Invalidator
+ if invalidator == nil {
+ return
+ }
+ invalidator.mu.Lock()
+ invalidator.open = true
+ invalidator.mu.Unlock()
+ onWake, onClosed := config.OnWake, config.OnClosed
+ config.OnWake = func() {
+ if invalidator.runPosted() && onWake != nil {
+ onWake()
+ }
+ }
+ config.OnClosed = func() {
+ invalidator.closePosts()
+ if onClosed != nil {
+ onClosed()
+ }
+ }
+}
+
+// closePosts refuses posts from now on and drops the ones waiting: the window
+// closed, or never opened.
+func (invalidator *Invalidator) closePosts() {
+ if invalidator == nil {
+ return
+ }
+ invalidator.mu.Lock()
+ invalidator.open = false
+ clear(invalidator.posts)
+ invalidator.posts = nil
+ invalidator.mu.Unlock()
+}
+
// wakeHandler runs the application's OnWake hook, then repaints, so results
// that background work published are applied before the next paint reads them.
//
diff --git a/app/invalidator_post_test.go b/app/invalidator_post_test.go
new file mode 100644
index 000000000..d824761e5
--- /dev/null
+++ b/app/invalidator_post_test.go
@@ -0,0 +1,76 @@
+package app
+
+import (
+ "sync"
+ "testing"
+
+ "github.com/vivaui/viva/gfx"
+)
+
+// A background goroutine's result reaches the model through Post: the update
+// runs on the window thread, before OnWake and the repaint it asked for, and not
+// on the goroutine. A window that has closed takes no more updates.
+func TestInvalidatorPostRunsUpdatesOnTheWindowThreadUntilItCloses(t *testing.T) {
+ invalidator := new(Invalidator)
+ if invalidator.Post(func() { t.Error("an update posted before the window opened ran") }) {
+ t.Fatal("Post accepted an update before the window opened")
+ }
+ status, painted, order := "", "", []string{}
+ driver, err := NewDriver(Config{
+ Invalidator: invalidator,
+ OnWake: func() { order = append(order, "wake:"+status) },
+ Paint: func(*gfx.Canvas, gfx.Size) { painted = status },
+ }, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var wg sync.WaitGroup
+ for range 8 {
+ wg.Go(func() {
+ if !invalidator.Post(func() { status += "x" }) {
+ t.Error("a live window refused an update")
+ }
+ })
+ }
+ wg.Wait()
+ if status != "" {
+ t.Fatal("an update ran on the posting goroutine")
+ }
+ if err := driver.Pump(); err != nil {
+ t.Fatal(err)
+ }
+ if status != "xxxxxxxx" || painted != status || len(order) != 1 || order[0] != "wake:"+status {
+ t.Fatalf("status %q painted %q wakes %v: want every update applied before OnWake and the paint", status, painted, order)
+ }
+
+ driver.Close()
+ if invalidator.Post(func() { t.Error("an update ran after the window closed") }) {
+ t.Fatal("Post accepted an update after the window closed")
+ }
+}
+
+// A window that cannot keep up refuses updates past the limit instead of
+// holding an unbounded backlog.
+func TestInvalidatorPostIsBounded(t *testing.T) {
+ invalidator := new(Invalidator)
+ driver, err := NewDriver(Config{Invalidator: invalidator}, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer driver.Close()
+ ran := 0
+ for range postLimit {
+ if !invalidator.Post(func() { ran++ }) {
+ t.Fatal("an update under the limit was refused")
+ }
+ }
+ if invalidator.Post(func() { ran++ }) {
+ t.Fatal("an update past the limit was accepted")
+ }
+ if err := driver.Pump(); err != nil {
+ t.Fatal(err)
+ }
+ if ran != postLimit || !invalidator.Post(func() {}) {
+ t.Fatalf("ran %d of %d, and the drained queue must take updates again", ran, postLimit)
+ }
+}
diff --git a/app/run_canvas.go b/app/run_canvas.go
index c17d820ef..25610d553 100644
--- a/app/run_canvas.go
+++ b/app/run_canvas.go
@@ -25,6 +25,10 @@ func RunCanvas(config Config, canvas *gfx.Canvas) error {
if normalized.TextInput != nil && !nativeTextInputSupported {
return fmt.Errorf("%w: native text input", ErrUnsupported)
}
+ normalized.attachPosts()
+ // RunCanvas returns when the window has closed or could not open: either way
+ // it takes no more posts.
+ defer normalized.Invalidator.closePosts()
if runner != nil {
return runner(normalized, canvas)
}
diff --git a/app/run_canvas_js.go b/app/run_canvas_js.go
index 36f24254e..9af443490 100644
--- a/app/run_canvas_js.go
+++ b/app/run_canvas_js.go
@@ -28,6 +28,8 @@ func RunCanvas(config Config, canvas *gfx.Canvas) error {
if err != nil {
return err
}
+ normalized.attachPosts()
+ defer normalized.Invalidator.closePosts()
if canvas == nil {
canvas = &gfx.Canvas{}
}
diff --git a/examples/guides/background/main.go b/examples/guides/background/main.go
index e84e7db01..a103c7af5 100644
--- a/examples/guides/background/main.go
+++ b/examples/guides/background/main.go
@@ -2,7 +2,6 @@ package main
import (
"log"
- "sync"
"time"
"github.com/vivaui/viva/app"
@@ -17,8 +16,6 @@ var slowWork = func() string {
}
type model struct {
- mu sync.Mutex
- pending string // written by the worker goroutine, under mu
status string // read by the page, written only on the window thread
invalidator *app.Invalidator
}
@@ -29,10 +26,9 @@ func (m *model) page(c ui.C) {
m.status = "working"
go func() {
result := slowWork()
- m.mu.Lock()
- m.pending = result
- m.mu.Unlock()
- m.invalidator.Invalidate() // wakes the window thread once
+ // Post runs the update on the window thread, then repaints: the
+ // goroutine never touches what the page reads.
+ m.invalidator.Post(func() { m.status = result })
}()
}
ui.Text(c, m.status)
@@ -43,16 +39,7 @@ func newConfig(m *model, invalidator *app.Invalidator) app.Config {
theme := gfx.LightTheme()
m.invalidator = invalidator
page := ui.NewPage(ui.PageConfig{View: m.page, Theme: &theme})
- config := ui.Configure(page, app.Config{Title: "Background", Width: 480, Height: 240, Invalidator: invalidator})
-
- // OnWake runs on the window thread right before the repaint Invalidate asked
- // for: move what the goroutine published into state that the page reads.
- config.OnWake = func() {
- m.mu.Lock()
- m.status, m.pending = m.pending, ""
- m.mu.Unlock()
- }
- return config
+ return ui.Configure(page, app.Config{Title: "Background", Width: 480, Height: 240, Invalidator: invalidator})
}
func main() {
diff --git a/examples/guides/background/main_test.go b/examples/guides/background/main_test.go
index 0d135ebe7..ec6bdcb28 100644
--- a/examples/guides/background/main_test.go
+++ b/examples/guides/background/main_test.go
@@ -42,4 +42,15 @@ func TestBackgroundResultReachesTheWindow(t *testing.T) {
if !found {
t.Fatal("the result did not reach the page")
}
+ // A wake that only animates applies no update: the status stays.
+ if err := driver.Advance(time.Second); err != nil {
+ t.Fatal(err)
+ }
+ found = false
+ for _, label := range driver.Snapshot().Labels {
+ found = found || strings.Contains(label.Value, "done")
+ }
+ if !found {
+ t.Fatal("a later wake cleared the result")
+ }
}
diff --git a/ui/doc.go b/ui/doc.go
index 6158a96f4..1cffdbbbf 100644
--- a/ui/doc.go
+++ b/ui/doc.go
@@ -23,8 +23,9 @@
// The page and its model, including Field and text.Editor getters, belong to the
// window thread. Capture immutable values there before background work starts.
// Use NewEffectKeyed to give a worker a value snapshot and EffectState.Take to
-// consume its result in the page; other workers publish under synchronization
-// and use app.Config.Invalidator with app.Config.OnWake to deliver results.
+// consume its result in the page; another goroutine hands its result to the
+// window's app.Invalidator with Post, which runs it on the window thread and
+// repaints.
//
// The engine underneath is not part of the public model. A component is a
// function of the page (func(c ui.C) ui.Box); a custom control uses Control
diff --git a/website/content/guides/en/programming-model.md b/website/content/guides/en/programming-model.md
index 2692ca6fa..5ca6a103f 100644
--- a/website/content/guides/en/programming-model.md
+++ b/website/content/guides/en/programming-model.md
@@ -48,9 +48,9 @@ Three tools hand work back to the window thread; pick by what the work belongs t
| --- | --- |
| Belongs to a page and should stop when its key changes or the page stops declaring it | `ui.Effect` |
| Is a function a goroutine finished that must run on the window thread (the application's loop, any window) | `Application.Post` |
-| Is yours alone, with no page key: you publish under your own lock | `Invalidator.Invalidate` with `Config.OnWake` |
+| Is yours alone, with no page key: a goroutine hands its result to one window | `Invalidator.Post` |
-Other goroutines never touch the window. A goroutine publishes its result under your own synchronization, then calls `Invalidator.Invalidate`. The window thread wakes once, runs `OnWake`, and repaints.
+Other goroutines never touch the window. A goroutine hands its result to `Invalidator.Post` as a function; the window thread runs it, then `OnWake`, then repaints, so the page only ever reads state the window thread wrote. `Post` refuses updates once the window has closed and when 256 are already waiting.
This ownership includes the model and text editors, not just native window methods. Read `ui.Field.Text()` or `text.Editor.String()` on the window thread **before** launching a worker, and pass the returned immutable string to it. A getter is not necessarily a pure read: these methods populate caches, and a field can initialize its editor on first use. A lock used only by your worker does not synchronize with native editing or painting. Apply results on the window thread; for page-scoped work, use a snapshot as a keyed effect's key, as shown in [Text input and forms](text-input).
@@ -60,7 +60,6 @@ package main
import (
"log"
- "sync"
"time"
"github.com/vivaui/viva/app"
@@ -75,8 +74,6 @@ var slowWork = func() string {
}
type model struct {
- mu sync.Mutex
- pending string // written by the worker goroutine, under mu
status string // read by the page, written only on the window thread
invalidator *app.Invalidator
}
@@ -87,10 +84,9 @@ func (m *model) page(c ui.C) {
m.status = "working"
go func() {
result := slowWork()
- m.mu.Lock()
- m.pending = result
- m.mu.Unlock()
- m.invalidator.Invalidate() // wakes the window thread once
+ // Post runs the update on the window thread, then repaints: the
+ // goroutine never touches what the page reads.
+ m.invalidator.Post(func() { m.status = result })
}()
}
ui.Text(c, m.status)
@@ -101,16 +97,7 @@ func newConfig(m *model, invalidator *app.Invalidator) app.Config {
theme := gfx.LightTheme()
m.invalidator = invalidator
page := ui.NewPage(ui.PageConfig{View: m.page, Theme: &theme})
- config := ui.Configure(page, app.Config{Title: "Background", Width: 480, Height: 240, Invalidator: invalidator})
-
- // OnWake runs on the window thread right before the repaint Invalidate asked
- // for: move what the goroutine published into state that the page reads.
- config.OnWake = func() {
- m.mu.Lock()
- m.status, m.pending = m.pending, ""
- m.mu.Unlock()
- }
- return config
+ return ui.Configure(page, app.Config{Title: "Background", Width: 480, Height: 240, Invalidator: invalidator})
}
func main() {
@@ -122,7 +109,7 @@ func main() {
}
```
-`Invalidator` owns no goroutine, timer or channel. An application that never calls it pays nothing for it, and the page only ever reads state that `OnWake` already moved onto the window thread.
+`Invalidator` owns no goroutine, timer or channel. An application that never calls it pays nothing for it. `OnWake` runs on every wake, a running transition's frames included, so it is for state the window thread advances itself (a status icon); a result handed over with `Post` is applied exactly once.
### Scoped effects
@@ -146,7 +133,7 @@ The key names one run. The same key does not start the work again; a different k
The run function receives a context and must return when it is done; the framework does not kill goroutines or poll. A new key starts its run at once by default, so a cancelled run that is slow to return can overlap the next one; `.Sequential()` on the state waits for the previous run to return, and a key declared while it waits replaces the one that will run. A page that only draws into a canvas of your own gives `PageConfig.Invalidator` the invalidator of that window, and calls `Page.Close` when the page goes away; a page given no invalidator keeps the result for the next paint but cannot wake the window by itself.
-A goroutine of your own, for something with no page key to cancel it, still publishes under its own lock and calls `Invalidator.Invalidate`.
+A goroutine of your own, for something with no page key to cancel it, hands its result to `Invalidator.Post`.
## Text input
diff --git a/website/content/guides/zh/programming-model.md b/website/content/guides/zh/programming-model.md
index 025cfccdd..21693fada 100644
--- a/website/content/guides/zh/programming-model.md
+++ b/website/content/guides/zh/programming-model.md
@@ -48,9 +48,9 @@ config.OnKey = func(event gfx.KeyEvent) gfx.EventResult {
| --- | --- |
| 属于某个页面,键变化或页面不再声明时应当停止 | `ui.Effect` |
| 是后台 goroutine 完成后必须在窗口线程上执行的函数(应用的事件循环,任意窗口) | `Application.Post` |
-| 只归你自己所有,没有页面键:你用自己的锁发布结果 | `Invalidator.Invalidate` 加 `Config.OnWake` |
+| 只归你自己所有,没有页面键:goroutine 把结果交给一个窗口 | `Invalidator.Post` |
-其他 goroutine 从不直接操作窗口。goroutine 在你自己的同步保护下发布结果,然后调用 `Invalidator.Invalidate`。窗口线程被唤醒一次,运行 `OnWake`,再重绘。
+其他 goroutine 从不直接操作窗口。goroutine 把结果包成函数交给 `Invalidator.Post`;窗口线程先运行它,再运行 `OnWake`,然后重绘,所以页面读到的始终是窗口线程写下的状态。窗口关闭后,或已有 256 个更新在排队时,`Post` 会拒绝新的更新。
这个所有权也覆盖模型和文本编辑器,不只是原生窗口方法。必须在启动 worker **之前**,在窗口线程上调用 `ui.Field.Text()` 或 `text.Editor.String()`,再把返回的不可变字符串传给 worker。getter 不一定是纯读:这些方法会填充缓存,字段还可能在首次使用时初始化编辑器。只有 worker 使用的锁无法与原生编辑、绘制同步。结果在窗口线程上应用;页面作用域的任务可以把快照作为 keyed effect 的 key,见[文本输入与表单](text-input)。
@@ -60,7 +60,6 @@ package main
import (
"log"
- "sync"
"time"
"github.com/vivaui/viva/app"
@@ -75,8 +74,6 @@ var slowWork = func() string {
}
type model struct {
- mu sync.Mutex
- pending string // written by the worker goroutine, under mu
status string // read by the page, written only on the window thread
invalidator *app.Invalidator
}
@@ -87,10 +84,9 @@ func (m *model) page(c ui.C) {
m.status = "working"
go func() {
result := slowWork()
- m.mu.Lock()
- m.pending = result
- m.mu.Unlock()
- m.invalidator.Invalidate() // wakes the window thread once
+ // Post runs the update on the window thread, then repaints: the
+ // goroutine never touches what the page reads.
+ m.invalidator.Post(func() { m.status = result })
}()
}
ui.Text(c, m.status)
@@ -101,16 +97,7 @@ func newConfig(m *model, invalidator *app.Invalidator) app.Config {
theme := gfx.LightTheme()
m.invalidator = invalidator
page := ui.NewPage(ui.PageConfig{View: m.page, Theme: &theme})
- config := ui.Configure(page, app.Config{Title: "Background", Width: 480, Height: 240, Invalidator: invalidator})
-
- // OnWake runs on the window thread right before the repaint Invalidate asked
- // for: move what the goroutine published into state that the page reads.
- config.OnWake = func() {
- m.mu.Lock()
- m.status, m.pending = m.pending, ""
- m.mu.Unlock()
- }
- return config
+ return ui.Configure(page, app.Config{Title: "Background", Width: 480, Height: 240, Invalidator: invalidator})
}
func main() {
@@ -122,7 +109,7 @@ func main() {
}
```
-`Invalidator` 不拥有 goroutine、定时器或 channel。从不调用它的应用不为它付出任何代价,而页面读到的始终是 `OnWake` 已经搬到窗口线程上的状态。
+`Invalidator` 不拥有 goroutine、定时器或 channel。从不调用它的应用不为它付出任何代价。`OnWake` 在每次唤醒时都会运行,包括过渡动画的每一帧,所以它适合窗口线程自己推进的状态(例如状态栏图标);用 `Post` 交来的结果只会应用一次。
### 页面作用域的 effect
@@ -146,7 +133,7 @@ key 命名一次 run。同一个 key 不会再次启动;key 改变会取消旧
run 函数收到的 context 是取消信号,它必须在该 context 结束时返回;框架不杀 goroutine、不轮询。key 改变时新 run 默认立刻启动,所以返回得慢的旧 run 可能与它重叠;在 state 上调用 `.Sequential()` 会等上一个 run 返回后再启动下一个,等待期间声明的 key 只有最新的那个会运行。只把页面绘制到自己 canvas 里的应用,把该窗口的 invalidator 交给 `PageConfig.Invalidator`,并在页面消失时调用 `Page.Close`;没有给 invalidator 的页面保留结果到下一次绘制,但无法主动唤醒窗口。
-没有页面 key 可取消的长时间 watcher 仍然用自己的锁发布结果并调用 `Invalidator.Invalidate`。
+没有页面 key 可取消的长时间 watcher 把结果交给 `Invalidator.Post`。
## 文本输入
From 3f8845b40c6601fbc3a40b7f23caa2f3d8063519 Mon Sep 17 00:00:00 2001
From: t8y2 <1156263951@qq.com>
Date: Sun, 22 Nov 2026 00:20:30 +0800
Subject: [PATCH 34/47] fix(ui): correct the List, Slider, Select and command
examples
The List example used one field as both the ListState and the data; the
Slider and Select Key docs still said to wire them to Config.OnKey, which
a page does itself; and the command example made a new State every paint
against its own rule not to copy one.
---
base/list.go | 4 ++--
base/select.go | 3 ++-
base/slider.go | 5 +++--
ui/command/command.go | 7 +++++--
4 files changed, 12 insertions(+), 7 deletions(-)
diff --git a/base/list.go b/base/list.go
index a6a999f94..f555f639c 100644
--- a/base/list.go
+++ b/base/list.go
@@ -823,13 +823,13 @@ func (r ListRow) Focused() bool {
// The rows are one stop of Tab, on the row chosen last or the first shown. Give the
// list a name for assistive technology with Box.Label after it:
//
-// files := ui.List(c, &m.files, len(m.files), func(row ui.ListRow) {
+// ui.List(c, &m.fileList, len(m.files), func(row ui.ListRow) {
// row.Element.PadX(8).Gap(8).Items(ui.Center).Children(func() {
// ui.Icon(row.C, iconOf(m.files[row.Index]))
// ui.Text(row.C, m.files[row.Index].Name)
// })
// }).Label("Files").Grow(1)
-// if row, ok := m.files.Submitted(); ok { m.open(row) }
+// if row, ok := m.fileList.Submitted(); ok { m.open(row) }
func List(c C, state *ListState, n int, row func(ListRow)) Box {
p := c.page
p.ForbidInMemo("List")
diff --git a/base/select.go b/base/select.go
index 9e5744000..30777fb45 100644
--- a/base/select.go
+++ b/base/select.go
@@ -120,7 +120,8 @@ func (s *SelectState) Wheel(event gfx.ScrollEvent) gfx.EventResult {
// without regard to case; a pause of a second starts a new word, and the same letter
// repeated cycles through the options that start with it). In an open list the match is
// scrolled into view and takes the focus, so Enter picks it; on a closed select the list
-// opens on it. Give it to Config.OnKey, ahead of your own handling. It reacts to the
+// opens on it. A page routes a declared Select its keys; a host that keeps the state
+// without a page gives Key to Config.OnKey, ahead of its own handling. It reacts to the
// characters in KeyEvent.Text of an unmodified key, which a window delivers there only
// for the platforms and focus that report typed characters as keys; everywhere else it
// is never called with one and does nothing.
diff --git a/base/slider.go b/base/slider.go
index 7375484db..49a39f699 100644
--- a/base/slider.go
+++ b/base/slider.go
@@ -191,8 +191,9 @@ func (f *Frame) SettleSlider(n *Node) {
// Key moves a focused slider with Base UI's pattern: arrows move by one Step (or a
// hundredth of the range without one), Shift+arrow and PageUp/PageDown by a large step
-// of 10 value units, and Home and End take it to its ends. Give it to Config.OnKey (or
-// call it from yours); it ignores every other key and every other focus. The next
+// of 10 value units, and Home and End take it to its ends. A page routes a declared
+// Slider its keys; a host that keeps the state without a page gives Key to
+// Config.OnKey. It ignores every other key and every other focus. The next
// declaration's Changed reports it.
func (s *SliderState) Key(event gfx.KeyEvent) gfx.EventResult {
if s.ID.IsZero() || event.Target != s.ID || s.off {
diff --git a/ui/command/command.go b/ui/command/command.go
index 0fd106261..26c997f55 100644
--- a/ui/command/command.go
+++ b/ui/command/command.go
@@ -3,11 +3,14 @@
// caller owns the query, the filtered results, the selection and the scroll
// position, and the wrapper paints the surface and routes its input.
//
-// palette := &command.State{
-// Query: query, Selected: selected,
+// // Once, with the model:
+// m.palette = command.State{
// Filter: func(query string) { /* rebuild m.results */ },
// Choose: func(index int) { /* run m.results[index] */ },
// }
+//
+// // Every paint:
+// palette := &m.palette
// palette.Clear()
// palette.Group("Suggestions")
// palette.Item("Open workspace", "⌘O")
From 15be1f140b2170da6b02bfc00bceaa634573ffe5 Mon Sep 17 00:00:00 2001
From: t8y2 <1156263951@qq.com>
Date: Sun, 22 Nov 2026 01:43:00 +0800
Subject: [PATCH 35/47] feat(ui): make a page and its Table whole in package ui
alone
- ui.Run takes a PageConfig, as OpenWindow does, so a one-window
application sets its theme and styles without NewPage, Configure and
RunCanvas. Callers, guides, docs and the viva new template follow.
- ui re-exports the vocabulary its own API takes: Identity, the event and
canvas types a Control and a Draw use, font weights, shadow levels, text
direction and alignment, ButtonVariant with its variants, TableColumn
with its alignments, and the control looks a recipe returns.
- Box.Variant sets a button's variant chosen at run time. Variants do not
combine; the overlay guide's Ghost().Destructive() was a solid red
button and is now a ghost with the Danger color.
- A Table is whole as declared: the page routes it the keys that move its
selection, a click selects a row as a List's does, TableState.Changed
reports either, and Headers without Columns share the width. A dev
build stops a Table with neither, which painted nothing.
The paired Motty commit sets variants with Box.Variant and lets the
keychain table report its own selection.
---
base/attrcheck_dev.go | 5 +
base/attrcheck_dev_test.go | 7 ++
base/box.go | 8 ++
base/elements.go | 17 ++-
base/page.go | 8 +-
base/table.go | 70 ++++++++++--
cmd/viva/initfiles/AGENTS.md.txt | 2 +-
cmd/viva/initfiles/main.go.txt | 2 +-
docs/skills/building-with-viva/SKILL.md | 2 +-
docs/upgrading.md | 2 +-
examples/guides/hello/main.go | 2 +-
examples/guides/overlay/main.go | 4 +-
examples/guides/page/main.go | 2 +-
examples/guides/paintinpage/main.go | 2 +-
examples/guides/table/main.go | 13 +--
examples/guides/textfield/main.go | 2 +-
examples/guides/webview/main.go | 2 +-
ui/app_facade.go | 17 +--
ui/doc.go | 2 +-
ui/rowidentity_test.go | 4 +-
ui/table_whole_test.go | 55 ++++++++++
ui/vocab.go | 102 +++++++++++++++++-
.../content/guides/en/declarative-layout.md | 17 ++-
.../content/guides/en/drawing-and-layout.md | 2 +-
website/content/guides/en/getting-started.md | 2 +-
website/content/guides/en/overlays.md | 4 +-
.../content/guides/en/system-integration.md | 2 +-
website/content/guides/en/text-input.md | 2 +-
.../content/guides/zh/declarative-layout.md | 17 ++-
.../content/guides/zh/drawing-and-layout.md | 2 +-
website/content/guides/zh/getting-started.md | 2 +-
website/content/guides/zh/overlays.md | 4 +-
.../content/guides/zh/system-integration.md | 2 +-
website/content/guides/zh/text-input.md | 2 +-
34 files changed, 316 insertions(+), 72 deletions(-)
create mode 100644 ui/table_whole_test.go
diff --git a/base/attrcheck_dev.go b/base/attrcheck_dev.go
index 53892933d..7c2fb8df4 100644
--- a/base/attrcheck_dev.go
+++ b/base/attrcheck_dev.go
@@ -32,6 +32,11 @@ func (n *Node) markAttr(a uint8) { n.attrs |= a }
// checkAttributesOf reports the generic attributes n cannot use.
func (f *Frame) checkAttributesOf(n *Node) {
name := kindAttributeName(n)
+ if n.Kind == kindTable && int(n.Aux) < len(WidgetsOf(f).tables) {
+ if spec := &WidgetsOf(f).tables[n.Aux].spec; len(spec.Columns) == 0 && len(spec.Headers) == 0 {
+ f.badAttribute(n, name, "rows without Columns or Headers", "a Table lays its cells out in its columns; give it Headers (the columns share its width) or Columns")
+ }
+ }
if n.Flags&FlagChildren != 0 && !f.attributeChildContainer(n) {
f.badAttribute(n, name, "Children", "only containers and the controls with a content slot take Children; use Label, Caption or the control's own content")
}
diff --git a/base/attrcheck_dev_test.go b/base/attrcheck_dev_test.go
index 7ea6fc08b..ff575f4b8 100644
--- a/base/attrcheck_dev_test.go
+++ b/base/attrcheck_dev_test.go
@@ -196,3 +196,10 @@ func TestAttributesThatDoNothingReport(t *testing.T) {
})
}
}
+
+// A Table with neither Columns nor Headers has nothing to lay its cells out in.
+func TestATableWithoutColumnsIsReported(t *testing.T) {
+ expectAttributePanic(t, func(f *Frame) {
+ f.Table(&TableState{}, TableSpec{Rows: tree.Sub(page, tree.Name("attr-table")), Source: &devTableRows{n: 1}})
+ }, "Table", "rows without Columns or Headers")
+}
diff --git a/base/box.go b/base/box.go
index f5a4e0bcc..9370c14d1 100644
--- a/base/box.go
+++ b/base/box.go
@@ -424,6 +424,14 @@ func (b Box) TextDirection(direction gfx.TextDirection) Box {
return b
}
+// Variant gives a button its look among the theme's variants, for one chosen at
+// run time; Secondary, Outline, Ghost, Link, Destructive and DestructiveOutline
+// name each one. A button has one variant: the last one set replaces the ones
+// before it, so a default can be given first and replaced by a condition.
+// Variants do not combine: Ghost then Destructive is the solid destructive
+// button, and the quiet one is a Ghost with the theme's Danger as its Color.
+func (b Box) Variant(v style.Variant) Box { return b.setVariant(v) }
+
// Button variants and sizes.
func (b Box) Secondary() Box { return b.setVariant(style.VariantSecondary) }
func (b Box) Outline() Box { return b.setVariant(style.VariantOutline) }
diff --git a/base/elements.go b/base/elements.go
index 19846c536..daa44f692 100644
--- a/base/elements.go
+++ b/base/elements.go
@@ -255,7 +255,10 @@ 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.
+// 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 given Headers and no Columns shares its width between them.
func Table(c C, state *TableState, spec TableSpec) Box {
p := c.page
if spec.Rows == 0 || spec.Header == 0 {
@@ -267,7 +270,17 @@ func Table(c C, state *TableState, spec TableSpec) Box {
spec.Header = p.tree.Sub(scope, gfx.Index(1))
}
}
- return c.f.Table(state, spec)
+ if p.tableKeyRoute == nil {
+ p.keyRoute, p.tableKeyRoute = (*Page).RouteKey, (*Page).tableKey
+ }
+ if state.changedAt != p.epoch {
+ state.changed = false
+ }
+ b := c.f.Table(state, spec)
+ if row, ok := b.RowClicked(); ok {
+ state.choose(row, p.epoch)
+ }
+ return b
}
// TextField adds a text field editing value, a string of the model or a Field; the
diff --git a/base/page.go b/base/page.go
index deaa86563..4db1cd808 100644
--- a/base/page.go
+++ b/base/page.go
@@ -18,7 +18,7 @@ package base
// })
// }
//
-// ui.Run(app.Config{Title: "Hosts", Width: 480, Height: 360}, m.page)
+// ui.Run(app.Config{Title: "Hosts", Width: 480, Height: 360}, ui.PageConfig{View: m.page})
//
// Identity has one rule a user needs: an element is named by its place among the
// elements of its kind in its parent, and a Key names a row, so that the row and
@@ -321,6 +321,7 @@ type Page struct {
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)
@@ -465,6 +466,11 @@ func (p *Page) RouteKey(event gfx.KeyEvent) (gfx.EventResult, bool) {
return result, true
}
}
+ if p.tableKeyRoute != nil {
+ if result, ok := p.tableKeyRoute(p, event); ok {
+ return result, true
+ }
+ }
if p.sliderRoute != nil {
if result, ok := p.sliderRoute(p, event); ok {
return result, true
diff --git a/base/table.go b/base/table.go
index 845bcba62..f56e88011 100644
--- a/base/table.go
+++ b/base/table.go
@@ -115,8 +115,12 @@ type TableState struct {
// 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
+ selected int32 // 1 + the row, or 0
+ // 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
+ changedAt uint32
sortColumn int32 // 1 + the column, or 0
descending bool
reveal bool // scroll the selected row into view at the next paint
@@ -135,6 +139,21 @@ type TableState struct {
// Selected is the selected row, or -1.
func (s *TableState) Selected() int { return int(s.selected) - 1 }
+// 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.
+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
+ }
+ 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) }
@@ -163,11 +182,10 @@ func (s *TableState) Wheel(event gfx.ScrollEvent) gfx.EventResult { return s.Scr
// 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). Give
-// it to Config.OnKey, or call it from yours; it ignores every other key and any other
-// focus, and reports Handled only for the keys it used.
-//
-// config.OnKey = m.table.Key
+// (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.
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{}
@@ -200,6 +218,25 @@ func (s *TableState) Key(event gfx.KeyEvent) gfx.EventResult {
return gfx.EventResult{Handled: true, Repaint: true, Focus: s.scope.At(row), FocusVisible: true}
}
+// tableKey gives a key to the Table whose row has the keyboard: TableState.Key,
+// for the tables of the last paint.
+func (p *Page) tableKey(event gfx.KeyEvent) (gfx.EventResult, bool) {
+ if event.Release {
+ return gfx.EventResult{}, false
+ }
+ 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
+ }
+ return result, true
+ }
+ }
+ return gfx.EventResult{}, false
+}
+
type TableDecl struct {
spec TableSpec
state *TableState
@@ -208,6 +245,9 @@ type TableDecl struct {
// and paints from. It keeps its capacity across frames, so a warm table
// fits no heading into a new allocation.
columns []style.TableColumn
+ // even is a table declared with Headers and no Columns: its columns share its
+ // width equally, the last taking what rounding leaves.
+ even bool
// fontSize and foreground are the element's explicit text style: what the
// recipe's spec default is replaced with when the element set one.
fontSize float32
@@ -249,7 +289,7 @@ func (f *Frame) Table(state *TableState, spec TableSpec) Box {
rows = max(spec.Source.Len(), 0)
}
decl := TableDecl{spec: spec, state: state, rows: rows}
- if spec.FitHeadings && index < cap(*decls) {
+ if (spec.FitHeadings || len(spec.Columns) == 0) && index < cap(*decls) {
// Reuse the fitted columns of this table from the last paint even though
// the fit itself waits for the element's FontSize in resolveTables.
decl.columns = (*decls)[:cap(*decls)][index].columns
@@ -275,6 +315,14 @@ func (f *Frame) resolveTables() {
if n.Flags&flagHasColor != 0 {
decl.foreground, decl.hasForeground = n.Color, true
}
+ if len(decl.spec.Columns) == 0 && len(decl.spec.Headers) > 0 {
+ // Columns are shared out when the table's width is known (paintTable);
+ // until then each is one that takes what is left.
+ decl.columns = append(decl.columns[:0], make([]style.TableColumn, len(decl.spec.Headers))...)
+ clear(decl.columns)
+ decl.spec.Columns, decl.even = decl.columns, true
+ continue
+ }
if !decl.spec.FitHeadings || f.Surface == nil || len(decl.spec.Columns) == 0 {
continue
}
@@ -411,6 +459,12 @@ func (f *Frame) paintTable(n *Node) {
// that do not fit move the whole grid across, with the header riding along —
// and never inside a ScrollArea, whose viewport (sideways or not) owns the
// table's width; such a table is only ever clipped.
+ if t.even {
+ share := float32(math.Floor(float64(r.Width / float32(len(t.spec.Columns)))))
+ for i := range t.spec.Columns[:len(t.spec.Columns)-1] {
+ t.spec.Columns[i].Width = share
+ }
+ }
declaredWidth := tableColumnsWidth(t.spec.Columns)
flexibleLast := len(t.spec.Columns) == 0 || t.spec.Columns[len(t.spec.Columns)-1].Width <= 0
selfContained := true
diff --git a/cmd/viva/initfiles/AGENTS.md.txt b/cmd/viva/initfiles/AGENTS.md.txt
index 7f90e27bf..4704a1e67 100644
--- a/cmd/viva/initfiles/AGENTS.md.txt
+++ b/cmd/viva/initfiles/AGENTS.md.txt
@@ -448,7 +448,7 @@ func (m *model) page(c ui.C) {
### Buttons and controls
-- Buttons (the plain one is the primary; there is no `Primary()`): `Secondary`, `Outline`, `Ghost`, `Link`, `Destructive`, `DestructiveOutline`,
+- Buttons (the plain one is the primary; there is no `Primary()`): `Secondary`, `Outline`, `Ghost`, `Link`, `Destructive`, `DestructiveOutline`, or `Variant(v)` for one chosen at run time (the last variant set wins; they do not combine),
`XSmall`, `Small`, `Large`, `IconOnly`, `Disabled(cond bool)` (so `ui.Button(c, "-").Disabled(m.n <= 0)`, no `if`).
- A control call returns a `ui.Box` (there is no `ui.Box` constructor); keep it when you need it later: `filter := ui.Button(c, "Filter")`.
A bound Checkbox, Switch, Choice or Tabs writes its value where it is declared, so a click you do not read still changes it;
diff --git a/cmd/viva/initfiles/main.go.txt b/cmd/viva/initfiles/main.go.txt
index 2a61e7316..46693571d 100644
--- a/cmd/viva/initfiles/main.go.txt
+++ b/cmd/viva/initfiles/main.go.txt
@@ -38,7 +38,7 @@ func config() app.Config {
func main() {
m := &model{}
- if err := ui.Run(config(), m.page); err != nil {
+ if err := ui.Run(config(), ui.PageConfig{View: m.page}); err != nil {
log.Fatal(err)
}
}
diff --git a/docs/skills/building-with-viva/SKILL.md b/docs/skills/building-with-viva/SKILL.md
index 4c92582ad..f95417755 100644
--- a/docs/skills/building-with-viva/SKILL.md
+++ b/docs/skills/building-with-viva/SKILL.md
@@ -38,7 +38,7 @@ If you are in a checkout of Viva itself, its `AGENTS.md` is the authority and ov
## 3. How a screen is written
-A page is `func (m *model) page(c ui.C)`, opened with `ui.Run(config, m.page)` or `ui.NewPage(ui.PageConfig{View: m.page}).Config(base)`. It runs again on every redraw, declares what is on screen with value types, and keeps no layout cache. State lives in the model; a click changes it where the control is declared.
+A page is `func (m *model) page(c ui.C)`, opened with `ui.Run(config, ui.PageConfig{View: m.page})` or `ui.NewPage(ui.PageConfig{View: m.page}).Config(base)`. It runs again on every redraw, declares what is on screen with value types, and keeps no layout cache. State lives in the model; a click changes it where the control is declared.
```go
type model struct {
diff --git a/docs/upgrading.md b/docs/upgrading.md
index a47c4c70a..48d23332c 100644
--- a/docs/upgrading.md
+++ b/docs/upgrading.md
@@ -109,7 +109,7 @@ page.Draw(canvas, bounds, func(c ui.C) {
Keep the `Page` in application state, not in a per-paint local: it owns the
page's identities, focus and retained state. For a whole window, use
-`ui.Run(config, declaration)` or `ui.Configure(page, config)` to wire the window.
+`ui.Run(config, ui.PageConfig{View: declaration})` or `ui.Configure(page, config)` to wire the window.
`PageConfig.View` is a declaration function, not the removed `View` type.
An embedded host forwards input through `Page.Key`, `Page.Pointer`,
diff --git a/examples/guides/hello/main.go b/examples/guides/hello/main.go
index 8878bcf19..e4d5f36ab 100644
--- a/examples/guides/hello/main.go
+++ b/examples/guides/hello/main.go
@@ -24,7 +24,7 @@ func (m *model) page(c ui.C) {
func main() {
m := &model{}
- if err := ui.Run(app.Config{Title: "Hello", Width: 480, Height: 240}, m.page); err != nil {
+ if err := ui.Run(app.Config{Title: "Hello", Width: 480, Height: 240}, ui.PageConfig{View: m.page}); err != nil {
log.Fatal(err)
}
}
diff --git a/examples/guides/overlay/main.go b/examples/guides/overlay/main.go
index c325debae..296d94a50 100644
--- a/examples/guides/overlay/main.go
+++ b/examples/guides/overlay/main.go
@@ -28,7 +28,7 @@ func (m *model) page(c ui.C) {
if ui.Button(c, "New file").Ghost().Clicked() {
m.menuOpen, m.status = false, "Created"
}
- if ui.Button(c, "Delete…").Ghost().Destructive().Clicked() {
+ if ui.Button(c, "Delete…").Ghost().Color(c.Theme().Danger).Clicked() {
m.menuOpen, m.dialogOpen = false, true
}
})
@@ -48,7 +48,7 @@ func (m *model) page(c ui.C) {
func main() {
m := &model{}
- if err := ui.Run(app.Config{Title: "Overlays", Width: 640, Height: 360}, m.page); err != nil {
+ if err := ui.Run(app.Config{Title: "Overlays", Width: 640, Height: 360}, ui.PageConfig{View: m.page}); err != nil {
log.Fatal(err)
}
}
diff --git a/examples/guides/page/main.go b/examples/guides/page/main.go
index 2454eeb70..d82773ca9 100644
--- a/examples/guides/page/main.go
+++ b/examples/guides/page/main.go
@@ -114,7 +114,7 @@ func (m *model) row(c ui.C, h *host) {
}
func main() {
- if err := ui.Run(app.Config{Title: "Viva fleet", Width: 460, Height: 560}, newModel().page); err != nil {
+ if err := ui.Run(app.Config{Title: "Viva fleet", Width: 460, Height: 560}, ui.PageConfig{View: newModel().page}); err != nil {
log.Fatal(err)
}
}
diff --git a/examples/guides/paintinpage/main.go b/examples/guides/paintinpage/main.go
index 418f84bc3..c3d329b8e 100644
--- a/examples/guides/paintinpage/main.go
+++ b/examples/guides/paintinpage/main.go
@@ -51,7 +51,7 @@ func (m *model) bars(d *ui.DrawContext) {
func main() {
m := &model{samples: []float32{0.3, 0.6, 0.45}}
- if err := ui.Run(app.Config{Title: "Samples", Width: 480, Height: 300}, m.page); err != nil {
+ if err := ui.Run(app.Config{Title: "Samples", Width: 480, Height: 300}, ui.PageConfig{View: m.page}); err != nil {
log.Fatal(err)
}
}
diff --git a/examples/guides/table/main.go b/examples/guides/table/main.go
index 34fde6668..17dc45560 100644
--- a/examples/guides/table/main.go
+++ b/examples/guides/table/main.go
@@ -7,7 +7,6 @@ import (
"sort"
"github.com/vivaui/viva/app"
- "github.com/vivaui/viva/components"
"github.com/vivaui/viva/ui"
)
@@ -25,8 +24,9 @@ func newModel() *model {
}}
}
-// page declares the table. A header click sorts the rows and a row click
-// selects it; the table keeps the selection and the scroll position itself.
+// 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
+// position itself.
func (m *model) page(c ui.C) {
ui.Column(c).Fill().Pad(24).Gap(12).Children(func() {
ui.Text(c, "Servers").FontSize(20).Bold()
@@ -35,11 +35,8 @@ func (m *model) page(c ui.C) {
Sortable: []bool{true, true, true},
Source: &m.rows,
Striped: true,
- Columns: []components.TableColumn{{Width: 200}, {Width: 120}, {}},
+ Columns: []ui.TableColumn{{Width: 200}, {Width: 120}, {}},
})
- if row, ok := table.RowClicked(); ok {
- m.table.Select(row)
- }
if column, ok := table.HeaderClicked(); ok {
m.table.SortBy(column)
m.sortRows()
@@ -67,7 +64,7 @@ func (m *model) sortRows() {
}
func main() {
- if err := ui.Run(app.Config{Title: "Servers", Width: 720, Height: 480}, newModel().page); err != nil {
+ if err := ui.Run(app.Config{Title: "Servers", Width: 720, Height: 480}, ui.PageConfig{View: newModel().page}); err != nil {
log.Fatal(err)
}
}
diff --git a/examples/guides/textfield/main.go b/examples/guides/textfield/main.go
index 3f6b6bce4..f582ae35f 100644
--- a/examples/guides/textfield/main.go
+++ b/examples/guides/textfield/main.go
@@ -29,7 +29,7 @@ func (m *model) page(c ui.C) {
func main() {
m := &model{}
- if err := ui.Run(app.Config{Title: "Form", Width: 480, Height: 240}, m.page); err != nil {
+ if err := ui.Run(app.Config{Title: "Form", Width: 480, Height: 240}, ui.PageConfig{View: m.page}); err != nil {
log.Fatal(err)
}
}
diff --git a/examples/guides/webview/main.go b/examples/guides/webview/main.go
index 714cba375..838f54e66 100644
--- a/examples/guides/webview/main.go
+++ b/examples/guides/webview/main.go
@@ -91,7 +91,7 @@ func main() {
m := &model{}
m.web.OnReady = m.open
config := app.Config{Title: "Web view", Width: 760, Height: 520, Web: &m.web}
- if err := ui.Run(config, m.page); err != nil {
+ if err := ui.Run(config, ui.PageConfig{View: m.page}); err != nil {
log.Fatal(err)
}
}
diff --git a/ui/app_facade.go b/ui/app_facade.go
index 77e20ed5c..8c16151c3 100644
--- a/ui/app_facade.go
+++ b/ui/app_facade.go
@@ -74,13 +74,18 @@ func Configure(page *Page, base app.Config) app.Config {
// systemAppearance is the platform's appearance, which a window page follows.
func systemAppearance() window.Appearance { return app.SystemAppearance() }
-// Run opens a window that declares view, and blocks until it closes: an
-// application in one call. The config's Tree, Paint, TextInput and OnScroll are
-// the page's (see Configure).
-func Run(config app.Config, View func(C)) error {
- page := NewPage(PageConfig{View: View, Appearance: systemAppearance})
+// Run opens a window that shows page, and blocks until it closes: an application
+// in one call. page is what OpenWindow takes: its View declares what the window
+// shows, and its Theme, Styles and the rest configure the page. The config's
+// Tree, Paint, TextInput and OnScroll are the page's (see Configure).
+//
+// ui.Run(app.Config{Title: "Hosts", Width: 480, Height: 360}, ui.PageConfig{View: m.page})
+func Run(config app.Config, page PageConfig) error {
+ if page.Appearance == nil {
+ page.Appearance = systemAppearance
+ }
var canvas gfx.Canvas
- return app.RunCanvas(Configure(page, config), &canvas)
+ return app.RunCanvas(Configure(NewPage(page), config), &canvas)
}
// OpenWindow opens a window of application that paints page, and returns it. It
diff --git a/ui/doc.go b/ui/doc.go
index 1cffdbbbf..87b9561cb 100644
--- a/ui/doc.go
+++ b/ui/doc.go
@@ -12,7 +12,7 @@
// })
// }
//
-// ui.Run(app.Config{Title: "Settings", Width: 480, Height: 320}, m.GetPage())
+// ui.Run(app.Config{Title: "Settings", Width: 480, Height: 320}, ui.PageConfig{View: m.GetPage()})
//
// Controls write into the values they are given, a list's rows are keyed with
// c.Key, a long list is a List, a part that rarely changes a Memo, and Popover and
diff --git a/ui/rowidentity_test.go b/ui/rowidentity_test.go
index 9b9577eb1..2f432ad89 100644
--- a/ui/rowidentity_test.go
+++ b/ui/rowidentity_test.go
@@ -177,9 +177,9 @@ func TestTableRowIDLastDeclarationAndZeroState(t *testing.T) {
second := false
var state ui.TableState
d := openPage(t, func(c ui.C) {
- ui.Table(c, &state, ui.TableSpec{Rows: rows, Source: &m.rows, RowHeight: 20})
+ ui.Table(c, &state, ui.TableSpec{Rows: rows, Columns: []ui.TableColumn{{}}, Source: &m.rows, RowHeight: 20})
if second {
- ui.Table(c, &state, ui.TableSpec{Rows: other, Source: &m.rows, RowHeight: 20})
+ ui.Table(c, &state, ui.TableSpec{Rows: other, Columns: []ui.TableColumn{{}}, Source: &m.rows, RowHeight: 20})
}
})
firstID, ok := state.RowID(0)
diff --git a/ui/table_whole_test.go b/ui/table_whole_test.go
new file mode 100644
index 000000000..1e5fb2d30
--- /dev/null
+++ b/ui/table_whole_test.go
@@ -0,0 +1,55 @@
+package ui_test
+
+import (
+ "testing"
+
+ "github.com/vivaui/viva/gfx"
+ "github.com/vivaui/viva/ui"
+)
+
+type wholeRows struct{}
+
+func (wholeRows) Len() int { return 3 }
+func (wholeRows) Cell(row, column int) string {
+ return []string{"alpha", "beta", "gamma"}[row] + []string{"", ":22"}[column]
+}
+
+// A Table is a whole control as declared: with only Headers its columns share its
+// width, a click selects the row, and the arrow keys move the selection without
+// the application handing the keys to it.
+func TestATableIsWholeAsDeclared(t *testing.T) {
+ var state ui.TableState
+ chosen := -1
+ d := openPage(t, func(c ui.C) {
+ ui.Table(c, &state, ui.TableSpec{Headers: []string{"Host", "Port"}, Source: wholeRows{}}).Width(400).Height(200)
+ if state.Changed() {
+ chosen = state.Selected()
+ }
+ })
+ at := map[string]float32{}
+ for _, label := range d.driver.Snapshot().Labels {
+ at[label.Value] = label.Bounds.X
+ }
+ host, hasHost := at["alpha"]
+ port, hasPort := at["alpha:22"]
+ if !hasHost || !hasPort || port < host+150 {
+ t.Fatalf("columns from the Headers alone: Host at %v (%v), Port at %v (%v)", host, hasHost, port, hasPort)
+ }
+ d.click("beta")
+ if state.Selected() != 1 || chosen != 1 {
+ t.Fatalf("a click on a row selected %d; the page saw %d chosen", state.Selected(), chosen)
+ }
+ chosen = -1
+ d.repaint()
+ if chosen != -1 {
+ t.Fatal("Changed stayed true in the paint after the click")
+ }
+ d.key(gfx.KeyDown)
+ if state.Selected() != 2 || d.Focused() != "gamma" || chosen != 2 {
+ t.Fatalf("Down selected %d with the focus on %q; the page saw %d chosen", state.Selected(), d.Focused(), chosen)
+ }
+ d.key(gfx.KeyHome)
+ if state.Selected() != 0 {
+ t.Fatalf("Home selected %d", state.Selected())
+ }
+}
diff --git a/ui/vocab.go b/ui/vocab.go
index f0f74a15e..5fbb92e37 100644
--- a/ui/vocab.go
+++ b/ui/vocab.go
@@ -1,6 +1,11 @@
package ui
-import "github.com/vivaui/viva/base"
+import (
+ "github.com/vivaui/viva/base"
+ "github.com/vivaui/viva/gfx"
+ "github.com/vivaui/viva/style"
+ "github.com/vivaui/viva/text"
+)
// The words of package gfx a page uses, so a page imports ui alone. They are
// package base's names, the behavior layer's vocabulary; ui re-exports them as
@@ -22,3 +27,98 @@ func RGB(red, green, blue uint8) Color { return base.RGB(red, green, blue) }
// RGBA is a color from 8-bit channels and an opacity from 0 to 1.
func RGBA(red, green, blue uint8, alpha float32) Color { return base.RGBA(red, green, blue, alpha) }
+
+// Identity is the identity of a control: what ID, Key and Part name, what a
+// Handlers target is, what a DialogSpec's buttons are.
+type Identity = gfx.ID
+
+// The values a custom control's Handlers and a Draw callback work with.
+type (
+ Canvas = gfx.Canvas
+ Bitmap = gfx.Bitmap
+ KeyEvent = gfx.KeyEvent
+ PointerEvent = gfx.PointerEvent
+ ScrollEvent = gfx.ScrollEvent
+ EventResult = gfx.EventResult
+ Modifiers = gfx.Modifiers
+ Key = gfx.Key
+ Role = gfx.Role
+ // ControlState is the hovered, pressed, focused, selected and disabled state
+ // a recipe and a Draw callback are given.
+ ControlState = gfx.State
+ // TextEditor is the editor a Field binds to.
+ TextEditor = text.Editor
+)
+
+// Font weights, for Box.Weight.
+const (
+ WeightRegular = gfx.WeightRegular
+ WeightMedium = gfx.WeightMedium
+ WeightSemibold = gfx.WeightSemibold
+ WeightBold = gfx.WeightBold
+)
+
+// ShadowLevel is an elevation, for Box.Shadow.
+type ShadowLevel = gfx.ShadowLevel
+
+const (
+ ShadowNone = gfx.ShadowNone
+ ShadowXS = gfx.ShadowXS
+ ShadowSM = gfx.ShadowSM
+ ShadowMD = gfx.ShadowMD
+ ShadowLG = gfx.ShadowLG
+)
+
+// TextDirection is a paragraph's direction, for Box.TextDirection.
+type TextDirection = gfx.TextDirection
+
+const (
+ DirectionAuto = gfx.DirectionAuto
+ DirectionLTR = gfx.DirectionLTR
+ DirectionRTL = gfx.DirectionRTL
+)
+
+// TextAlignment places a field's text, for Field.Alignment.
+type TextAlignment = gfx.Alignment
+
+const (
+ TextAlignLeft = gfx.AlignLeft
+ TextAlignCenter = gfx.AlignCenter
+ TextAlignRight = gfx.AlignRight
+ TextAlignStart = gfx.AlignStart
+ TextAlignEnd = gfx.AlignEnd
+)
+
+// ButtonVariant is a button's look among the theme's variants, for Box.Variant
+// and the specs whose buttons take one.
+type ButtonVariant = style.Variant
+
+const (
+ ButtonDefault = style.VariantDefault
+ ButtonDestructive = style.VariantDestructive
+ ButtonOutline = style.VariantOutline
+ ButtonSecondary = style.VariantSecondary
+ ButtonGhost = style.VariantGhost
+ ButtonLink = style.VariantLink
+ ButtonDestructiveOutline = style.VariantDestructiveOutline
+)
+
+// The looks a control's recipe returns, for Box.ButtonRecipe and its siblings.
+type (
+ ButtonLook = style.ButtonLook
+ SwitchLook = style.SwitchLook
+ CheckboxLook = style.CheckboxLook
+ TextEntryLook = style.TextEntryLook
+)
+
+// TableColumn is the width and alignment of one column of a Table.
+type TableColumn = style.TableColumn
+
+// TableAlignment places the text of a table column.
+type TableAlignment = style.TableAlignment
+
+const (
+ TableAlignLeft = style.TableAlignLeft
+ TableAlignCenter = style.TableAlignCenter
+ TableAlignRight = style.TableAlignRight
+)
diff --git a/website/content/guides/en/declarative-layout.md b/website/content/guides/en/declarative-layout.md
index aa905ccd5..d16d78bf7 100644
--- a/website/content/guides/en/declarative-layout.md
+++ b/website/content/guides/en/declarative-layout.md
@@ -54,7 +54,7 @@ func (m *model) page(c ui.C) {
})
}
-ui.Run(app.Config{Title: "Settings", Width: 480, Height: 320}, m.page)
+ui.Run(app.Config{Title: "Settings", Width: 480, Height: 320}, ui.PageConfig{View: m.page})
```
`ui.Choice` and `ui.Tabs` are one tab stop each: Left and Right (Up and Down for vertical tabs) move to the next enabled option, wrapping, and choose it; Home and End go to the first and last.
@@ -247,7 +247,7 @@ func (m *model) row(c ui.C, h *host) {
}
func main() {
- if err := ui.Run(app.Config{Title: "Viva fleet", Width: 460, Height: 560}, newModel().page); err != nil {
+ if err := ui.Run(app.Config{Title: "Viva fleet", Width: 460, Height: 560}, ui.PageConfig{View: newModel().page}); err != nil {
log.Fatal(err)
}
}
@@ -314,7 +314,6 @@ import (
"sort"
"github.com/vivaui/viva/app"
- "github.com/vivaui/viva/components"
"github.com/vivaui/viva/ui"
)
@@ -332,8 +331,9 @@ func newModel() *model {
}}
}
-// page declares the table. A header click sorts the rows and a row click
-// selects it; the table keeps the selection and the scroll position itself.
+// 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
+// position itself.
func (m *model) page(c ui.C) {
ui.Column(c).Fill().Pad(24).Gap(12).Children(func() {
ui.Text(c, "Servers").FontSize(20).Bold()
@@ -342,11 +342,8 @@ func (m *model) page(c ui.C) {
Sortable: []bool{true, true, true},
Source: &m.rows,
Striped: true,
- Columns: []components.TableColumn{{Width: 200}, {Width: 120}, {}},
+ Columns: []ui.TableColumn{{Width: 200}, {Width: 120}, {}},
})
- if row, ok := table.RowClicked(); ok {
- m.table.Select(row)
- }
if column, ok := table.HeaderClicked(); ok {
m.table.SortBy(column)
m.sortRows()
@@ -374,7 +371,7 @@ func (m *model) sortRows() {
}
func main() {
- if err := ui.Run(app.Config{Title: "Servers", Width: 720, Height: 480}, newModel().page); err != nil {
+ if err := ui.Run(app.Config{Title: "Servers", Width: 720, Height: 480}, ui.PageConfig{View: newModel().page}); err != nil {
log.Fatal(err)
}
}
diff --git a/website/content/guides/en/drawing-and-layout.md b/website/content/guides/en/drawing-and-layout.md
index e960dedea..1716792cd 100644
--- a/website/content/guides/en/drawing-and-layout.md
+++ b/website/content/guides/en/drawing-and-layout.md
@@ -66,7 +66,7 @@ func (m *model) bars(d *ui.DrawContext) {
func main() {
m := &model{samples: []float32{0.3, 0.6, 0.45}}
- if err := ui.Run(app.Config{Title: "Samples", Width: 480, Height: 300}, m.page); err != nil {
+ if err := ui.Run(app.Config{Title: "Samples", Width: 480, Height: 300}, ui.PageConfig{View: m.page}); err != nil {
log.Fatal(err)
}
}
diff --git a/website/content/guides/en/getting-started.md b/website/content/guides/en/getting-started.md
index e6c51cd2f..d17452c6b 100644
--- a/website/content/guides/en/getting-started.md
+++ b/website/content/guides/en/getting-started.md
@@ -60,7 +60,7 @@ func (m *model) page(c ui.C) {
func main() {
m := &model{}
- if err := ui.Run(app.Config{Title: "Hello", Width: 480, Height: 240}, m.page); err != nil {
+ if err := ui.Run(app.Config{Title: "Hello", Width: 480, Height: 240}, ui.PageConfig{View: m.page}); err != nil {
log.Fatal(err)
}
}
diff --git a/website/content/guides/en/overlays.md b/website/content/guides/en/overlays.md
index 76ce8db3e..cbfc968fe 100644
--- a/website/content/guides/en/overlays.md
+++ b/website/content/guides/en/overlays.md
@@ -45,7 +45,7 @@ func (m *model) page(c ui.C) {
if ui.Button(c, "New file").Ghost().Clicked() {
m.menuOpen, m.status = false, "Created"
}
- if ui.Button(c, "Delete…").Ghost().Destructive().Clicked() {
+ if ui.Button(c, "Delete…").Ghost().Color(c.Theme().Danger).Clicked() {
m.menuOpen, m.dialogOpen = false, true
}
})
@@ -65,7 +65,7 @@ func (m *model) page(c ui.C) {
func main() {
m := &model{}
- if err := ui.Run(app.Config{Title: "Overlays", Width: 640, Height: 360}, m.page); err != nil {
+ if err := ui.Run(app.Config{Title: "Overlays", Width: 640, Height: 360}, ui.PageConfig{View: m.page}); err != nil {
log.Fatal(err)
}
}
diff --git a/website/content/guides/en/system-integration.md b/website/content/guides/en/system-integration.md
index 4fe615ee4..4925eaa90 100644
--- a/website/content/guides/en/system-integration.md
+++ b/website/content/guides/en/system-integration.md
@@ -143,7 +143,7 @@ func main() {
m := &model{}
m.web.OnReady = m.open
config := app.Config{Title: "Web view", Width: 760, Height: 520, Web: &m.web}
- if err := ui.Run(config, m.page); err != nil {
+ if err := ui.Run(config, ui.PageConfig{View: m.page}); err != nil {
log.Fatal(err)
}
}
diff --git a/website/content/guides/en/text-input.md b/website/content/guides/en/text-input.md
index 226986c70..bc0f87b1d 100644
--- a/website/content/guides/en/text-input.md
+++ b/website/content/guides/en/text-input.md
@@ -44,7 +44,7 @@ func (m *model) page(c ui.C) {
func main() {
m := &model{}
- if err := ui.Run(app.Config{Title: "Form", Width: 480, Height: 240}, m.page); err != nil {
+ if err := ui.Run(app.Config{Title: "Form", Width: 480, Height: 240}, ui.PageConfig{View: m.page}); err != nil {
log.Fatal(err)
}
}
diff --git a/website/content/guides/zh/declarative-layout.md b/website/content/guides/zh/declarative-layout.md
index 5650ccd1b..2646a4e7c 100644
--- a/website/content/guides/zh/declarative-layout.md
+++ b/website/content/guides/zh/declarative-layout.md
@@ -54,7 +54,7 @@ func (m *model) page(c ui.C) {
})
}
-ui.Run(app.Config{Title: "Settings", Width: 480, Height: 320}, m.page)
+ui.Run(app.Config{Title: "Settings", Width: 480, Height: 320}, ui.PageConfig{View: m.page})
```
`ui.Choice` 和 `ui.Tabs` 各占一个 Tab 停靠点:左右方向键(垂直的标签页用上下键)移动到下一个可用选项并选中它,到头会回绕;Home 和 End 去第一个和最后一个。
@@ -248,7 +248,7 @@ func (m *model) row(c ui.C, h *host) {
}
func main() {
- if err := ui.Run(app.Config{Title: "Viva fleet", Width: 460, Height: 560}, newModel().page); err != nil {
+ if err := ui.Run(app.Config{Title: "Viva fleet", Width: 460, Height: 560}, ui.PageConfig{View: newModel().page}); err != nil {
log.Fatal(err)
}
}
@@ -315,7 +315,6 @@ import (
"sort"
"github.com/vivaui/viva/app"
- "github.com/vivaui/viva/components"
"github.com/vivaui/viva/ui"
)
@@ -333,8 +332,9 @@ func newModel() *model {
}}
}
-// page declares the table. A header click sorts the rows and a row click
-// selects it; the table keeps the selection and the scroll position itself.
+// 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
+// position itself.
func (m *model) page(c ui.C) {
ui.Column(c).Fill().Pad(24).Gap(12).Children(func() {
ui.Text(c, "Servers").FontSize(20).Bold()
@@ -343,11 +343,8 @@ func (m *model) page(c ui.C) {
Sortable: []bool{true, true, true},
Source: &m.rows,
Striped: true,
- Columns: []components.TableColumn{{Width: 200}, {Width: 120}, {}},
+ Columns: []ui.TableColumn{{Width: 200}, {Width: 120}, {}},
})
- if row, ok := table.RowClicked(); ok {
- m.table.Select(row)
- }
if column, ok := table.HeaderClicked(); ok {
m.table.SortBy(column)
m.sortRows()
@@ -375,7 +372,7 @@ func (m *model) sortRows() {
}
func main() {
- if err := ui.Run(app.Config{Title: "Servers", Width: 720, Height: 480}, newModel().page); err != nil {
+ if err := ui.Run(app.Config{Title: "Servers", Width: 720, Height: 480}, ui.PageConfig{View: newModel().page}); err != nil {
log.Fatal(err)
}
}
diff --git a/website/content/guides/zh/drawing-and-layout.md b/website/content/guides/zh/drawing-and-layout.md
index c13153991..976a9d029 100644
--- a/website/content/guides/zh/drawing-and-layout.md
+++ b/website/content/guides/zh/drawing-and-layout.md
@@ -66,7 +66,7 @@ func (m *model) bars(d *ui.DrawContext) {
func main() {
m := &model{samples: []float32{0.3, 0.6, 0.45}}
- if err := ui.Run(app.Config{Title: "Samples", Width: 480, Height: 300}, m.page); err != nil {
+ if err := ui.Run(app.Config{Title: "Samples", Width: 480, Height: 300}, ui.PageConfig{View: m.page}); err != nil {
log.Fatal(err)
}
}
diff --git a/website/content/guides/zh/getting-started.md b/website/content/guides/zh/getting-started.md
index 4ea597bcf..56f9f7559 100644
--- a/website/content/guides/zh/getting-started.md
+++ b/website/content/guides/zh/getting-started.md
@@ -60,7 +60,7 @@ func (m *model) page(c ui.C) {
func main() {
m := &model{}
- if err := ui.Run(app.Config{Title: "Hello", Width: 480, Height: 240}, m.page); err != nil {
+ if err := ui.Run(app.Config{Title: "Hello", Width: 480, Height: 240}, ui.PageConfig{View: m.page}); err != nil {
log.Fatal(err)
}
}
diff --git a/website/content/guides/zh/overlays.md b/website/content/guides/zh/overlays.md
index 6297b77c4..76afcad78 100644
--- a/website/content/guides/zh/overlays.md
+++ b/website/content/guides/zh/overlays.md
@@ -45,7 +45,7 @@ func (m *model) page(c ui.C) {
if ui.Button(c, "New file").Ghost().Clicked() {
m.menuOpen, m.status = false, "Created"
}
- if ui.Button(c, "Delete…").Ghost().Destructive().Clicked() {
+ if ui.Button(c, "Delete…").Ghost().Color(c.Theme().Danger).Clicked() {
m.menuOpen, m.dialogOpen = false, true
}
})
@@ -65,7 +65,7 @@ func (m *model) page(c ui.C) {
func main() {
m := &model{}
- if err := ui.Run(app.Config{Title: "Overlays", Width: 640, Height: 360}, m.page); err != nil {
+ if err := ui.Run(app.Config{Title: "Overlays", Width: 640, Height: 360}, ui.PageConfig{View: m.page}); err != nil {
log.Fatal(err)
}
}
diff --git a/website/content/guides/zh/system-integration.md b/website/content/guides/zh/system-integration.md
index 7f7d71ec4..5d1baff22 100644
--- a/website/content/guides/zh/system-integration.md
+++ b/website/content/guides/zh/system-integration.md
@@ -143,7 +143,7 @@ func main() {
m := &model{}
m.web.OnReady = m.open
config := app.Config{Title: "Web view", Width: 760, Height: 520, Web: &m.web}
- if err := ui.Run(config, m.page); err != nil {
+ if err := ui.Run(config, ui.PageConfig{View: m.page}); err != nil {
log.Fatal(err)
}
}
diff --git a/website/content/guides/zh/text-input.md b/website/content/guides/zh/text-input.md
index 7b3c78ee5..af7df9ede 100644
--- a/website/content/guides/zh/text-input.md
+++ b/website/content/guides/zh/text-input.md
@@ -44,7 +44,7 @@ func (m *model) page(c ui.C) {
func main() {
m := &model{}
- if err := ui.Run(app.Config{Title: "Form", Width: 480, Height: 240}, m.page); err != nil {
+ if err := ui.Run(app.Config{Title: "Form", Width: 480, Height: 240}, ui.PageConfig{View: m.page}); err != nil {
log.Fatal(err)
}
}
From d5da72e6bd75c767a5940810700d4846dd692f3f Mon Sep 17 00:00:00 2001
From: t8y2 <1156263951@qq.com>
Date: Sun, 22 Nov 2026 02:22:24 +0800
Subject: [PATCH 36/47] feat(ui): open overlays on a bool and label form
controls by default
- ui.AlertDialog takes the *bool it is open on, as Modal does, and reports
the confirming action; its identities are named from the bool unless the
spec names them, and the keyboard starts on Cancel.
- PopoverWith takes open before its spec, the order Modal and Drawer use.
- ui.MenuAt opens a menu against a rectangle of the application's own
surface, flipped and kept in the window as an anchored Menu is.
- A Dialog that names no initial focus gives the keyboard to the first
control of its body, as Modal does, once its body is declared.
- A FormField's title labels the first control its children declare, as
an HTML label does, unless For names another; TextFieldID edits a model
string as well as a Field.
The paired Motty commit moves its callers and replaces the slots it laid
out only to anchor menus with MenuAt.
---
base/alert_dialog.go | 49 +++++++++++++++++--
base/dialog.go | 13 +++++
base/elements.go | 32 ++++++++----
base/form_field.go | 44 +++++++++++++++--
base/frame.go | 1 +
base/menu.go | 47 +++++++++++++++++-
base/page.go | 1 +
docs/skills/building-with-viva/SKILL.md | 2 +-
examples/guides/overlay/main.go | 2 +-
examples/guides/webview/main.go | 2 +-
internal/componentdemo/alert_dialog.go | 36 +++++++-------
internal/componentdemo/catalog_a_test.go | 4 +-
internal/componentdemo/page_usage.go | 4 +-
internal/componentdemo/popover.go | 20 ++++----
internal/componentdemo/state.go | 3 ++
ui/alert_dialog_page_test.go | 38 ++++++++++++++
ui/dialog_focus_test.go | 36 ++++++++++++++
ui/facade.go | 18 +++++--
ui/form_field_label_test.go | 43 ++++++++++++++++
ui/menu_at_test.go | 36 ++++++++++++++
ui/menu_paint.go | 2 +-
ui/popover_test.go | 14 +++---
ui/presence_parity_test.go | 8 +--
website/content/guides/en/overlays.md | 2 +-
.../content/guides/en/system-integration.md | 2 +-
website/content/guides/zh/overlays.md | 2 +-
.../content/guides/zh/system-integration.md | 2 +-
27 files changed, 386 insertions(+), 77 deletions(-)
create mode 100644 ui/alert_dialog_page_test.go
create mode 100644 ui/dialog_focus_test.go
create mode 100644 ui/form_field_label_test.go
create mode 100644 ui/menu_at_test.go
diff --git a/base/alert_dialog.go b/base/alert_dialog.go
index 7ecc4ccd0..a7fff83ab 100644
--- a/base/alert_dialog.go
+++ b/base/alert_dialog.go
@@ -1,6 +1,8 @@
package base
import (
+ "unsafe"
+
"github.com/vivaui/viva/gfx"
"github.com/vivaui/viva/style"
)
@@ -58,15 +60,52 @@ func (f *Frame) AlertDialog(spec AlertDialogSpec) Box {
return root
}
-// AlertDialog declares a confirmation on a page, as Dialog does: the page routes
-// its keys, pointer and shortcuts with the modal open. It declares no children;
-// declare it where it is open.
-func AlertDialog(c C, spec AlertDialogSpec) Box {
+// AlertDialog asks the user to confirm while *open, as Modal shows a dialog: a
+// scrim, the title and description, and the confirming action beside an outline
+// cancel action. It reports true in the paint that delivers the confirming
+// action. That action, the cancel action and Escape set *open to false; a press on
+// the scrim does not, as an alert dialog must be answered. The page routes its
+// keys, pointer and shortcuts while it is open, gives the keyboard to the cancel
+// action as it opens and back to where it was as it closes.
+//
+// if ui.AlertDialog(c, &m.confirmDelete, ui.AlertDialogSpec{
+// Title: "Delete host?", Description: "This cannot be undone.",
+// ActionLabel: "Delete", CancelLabel: "Cancel", ActionVariant: ui.ButtonDestructive,
+// }) {
+// m.deleteHost()
+// }
+//
+// Scope, ActionID and CancelID are named from open when the spec leaves them
+// zero; a page that addresses the actions itself (a test, a shortcut) names them.
+func AlertDialog(c C, open *bool, spec AlertDialogSpec) bool {
if c == nil || c.page == nil || c.f == nil {
panic("ui: AlertDialog is for a page")
}
p := c.page
p.ForbidInMemo("AlertDialog")
+ if !*open {
+ return false
+ }
p.overlay = true
- return c.f.AlertDialog(spec)
+ if spec.Scope.IsZero() || spec.ActionID.IsZero() || spec.CancelID.IsZero() {
+ scope := p.BoundScope(pkAlertDialog, unsafe.Pointer(open))
+ if spec.Scope.IsZero() {
+ spec.Scope = scope.At(0)
+ }
+ if spec.ActionID.IsZero() {
+ spec.ActionID = scope.At(1)
+ }
+ if spec.CancelID.IsZero() {
+ spec.CancelID = scope.At(2)
+ }
+ }
+ if spec.InitialFocusID.IsZero() {
+ spec.InitialFocusID = spec.CancelID
+ }
+ id, chosen := c.f.AlertDialog(spec).Chosen()
+ if !chosen {
+ return false
+ }
+ *open = false
+ return id == spec.ActionID
}
diff --git a/base/dialog.go b/base/dialog.go
index 868bd4125..f7182e52f 100644
--- a/base/dialog.go
+++ b/base/dialog.go
@@ -38,6 +38,19 @@ type DialogDecl struct {
layer uint16
}
+// resolveDialogFocus gives each dialog that names no InitialFocusID the first
+// control of its body, else of its footer, else its close button, as a modal
+// dialog takes the keyboard as it opens. Its body and footer are declared after
+// it, so this waits for the whole declaration.
+func (f *Frame) resolveDialogFocus() {
+ decls := WidgetsOf(f).dialogs
+ for i := range decls {
+ if decls[i].spec.InitialFocusID.IsZero() {
+ f.focusFirstControlOf(&decls[i])
+ }
+ }
+}
+
// Dialog declares a dialog on a page whose targets and layer the application
// names itself: DialogSpec.Scope, DismissID, CloseID and Layer keep the
// identities the application dispatches, as they do for frame.Dialog. Most
diff --git a/base/elements.go b/base/elements.go
index daa44f692..eba7ccac2 100644
--- a/base/elements.go
+++ b/base/elements.go
@@ -309,16 +309,25 @@ func textFieldOf[T TextValue](c C, Value T, Label, placeholder string, Base bool
// TextFieldID is TextField for a field the application already names: id is the
// field's identity in the page's Tree, so a window's own input routing, an
-// initial focus or a test can address it. The page still gives the platform its
-// editor, as TextField does. Field.Bind gives it an editor the application keeps
-// and reads itself.
+// initial focus or a test can address it. It edits value, a string of the model
+// or a Field, as TextField does, and the page still gives the platform its
+// editor. Field.Bind gives it an editor the application keeps and reads itself.
//
-// ui.TextFieldID(c, m.searchID, &m.searchField, "Search", "")
-func TextFieldID(c C, ID gfx.ID, field *Field, Label, placeholder string) Box {
+// ui.TextFieldID(c, m.searchID, &m.query, "Search", "")
+func TextFieldID[T TextValue](c C, ID gfx.ID, Value T, Label, placeholder string) Box {
+ p := c.page
+ var field *Field
+ switch v := any(Value).(type) {
+ case *Field:
+ field = v
+ case *string:
+ // The string's editor is kept under the name its pointer is given, as
+ // TextField keeps it; only the element takes the application's identity.
+ field, _ = fieldOf(p, pkField, v)
+ }
if field == nil {
- panic("ui: TextFieldID needs a Field")
+ panic("ui: TextFieldID needs a string or a Field to edit")
}
- p := c.page
b := c.f.Field(field, ID, Label, placeholder)
c.f.bindField(b, field)
p.fields = append(p.fields, fieldEntry{ID: ID, field: field})
@@ -372,12 +381,12 @@ func TextAreaID(c C, ID gfx.ID, field *Field, Label, placeholder string) Box {
// if more.Clicked() { m.menu = !m.menu }
// ui.Popover(c, more, &m.menu, func() { ... })
func Popover(c C, Anchor Box, open *bool, body func()) bool {
- return PopoverWith(c, Anchor, PopoverSpec{Align: Start}, open, body)
+ return PopoverWith(c, Anchor, open, PopoverSpec{Align: Start}, body)
}
// PopoverWith is Popover with a spec: the side, alignment, width and the rest of
// PopoverSpec. The Scope and DismissID it leaves zero are made from open.
-func PopoverWith(c C, Anchor Box, spec PopoverSpec, open *bool, body func()) bool {
+func PopoverWith(c C, Anchor Box, open *bool, spec PopoverSpec, body func()) bool {
p := c.page
p.ForbidInMemo("Popover")
if !*open {
@@ -493,7 +502,10 @@ func (p *Page) Describe(ID gfx.ID) string { return p.tree.Text(ID) }
// footer, the one that takes the keyboard as it opens; the close button when it has
// none.
func (f *Frame) focusFirstControl(dialog Box) {
- d := &WidgetsOf(f).dialogs[dialog.N().Aux]
+ f.focusFirstControlOf(&WidgetsOf(f).dialogs[dialog.N().Aux])
+}
+
+func (f *Frame) focusFirstControlOf(d *DialogDecl) {
for _, part := range [2]int32{d.body, d.footer} {
if id := f.FirstControl(part); !id.IsZero() {
d.spec.InitialFocusID = id
diff --git a/base/form_field.go b/base/form_field.go
index 3c389a7b2..3b9893ed7 100644
--- a/base/form_field.go
+++ b/base/form_field.go
@@ -39,6 +39,9 @@ type FormFieldState struct {
Label string
Palette *Theme
+ // control is what the title labels when For is not set: the first control
+ // the field's children declare, found as each paint lays the field out.
+ control gfx.ID
layout field.Layout
paint func(*DrawContext)
}
@@ -55,9 +58,11 @@ type FormFieldState struct {
// The field's children are its control: declare one (a Row, a Select, a
// Combobox, a control of the application's own); the field measures the title,
// places the control at the control slot of components.BeginField and paints
-// the title around it. It does not bind a value, does not label the control
-// (there is no For), and does not clip: a Select's or Combobox's popup may
-// leave the field's bounds.
+// the title around it. The title labels the first control its children declare,
+// as an HTML label labels the first labelable control inside it: pressing the
+// title focuses and clicks it, and assistive technology reads the title as its
+// name. For names another control instead. The field does not bind a value and
+// does not clip: a Select's or Combobox's popup may leave the field's bounds.
//
// A field with no explicit height is as tall as components.BeginField in the
// same bounds, including the room BeginField reserves for a description and an
@@ -89,10 +94,37 @@ func (state *FormFieldState) spec() field.Spec {
return field.Spec{
Title: state.Label, Description: state.Description, Error: state.Error,
Orientation: state.Orientation, Required: state.Required,
- Invalid: state.Invalid, Control: state.For,
+ Invalid: state.Invalid, Control: state.labeled(),
}
}
+// labeled is the control the title labels: For, else the first control of the
+// field's children.
+func (state *FormFieldState) labeled() gfx.ID {
+ if !state.For.IsZero() {
+ return state.For
+ }
+ return state.control
+}
+
+// firstLabelable is the first control under node i, in declaration order and
+// depth first, that a title can label: one with an identity the keyboard takes.
+func (f *Frame) firstLabelable(i int32) gfx.ID {
+ n := &f.Nodes[i]
+ if !n.ID.IsZero() {
+ switch n.Kind {
+ case kindButton, kindToggle, kindSplitButton, kindCheckbox, kindSwitch, kindInput, kindTextarea, kindSlider, kindSelect:
+ return n.ID
+ }
+ }
+ for c := n.First; c >= 0; c = f.Nodes[c].Next {
+ if id := f.firstLabelable(c); !id.IsZero() {
+ return id
+ }
+ }
+ return gfx.ID{}
+}
+
// MeasureWidth reports no preferred width: a form field takes the width its
// row gives it, so give it a Width, FillWidth or Grow.
func (state *FormFieldState) MeasureWidth(*LayoutContext) float32 { return 0 }
@@ -120,6 +152,10 @@ func (state *FormFieldState) PlaceHeight(ctx *LayoutContext, bounds Rect) {
if ctx.Count() > 1 {
panic("ui: FormField takes one control child; wrap them in a Row or Column")
}
+ state.control = gfx.ID{}
+ if ctx.Count() == 1 && state.For.IsZero() {
+ state.control = ctx.Frame.firstLabelable(ctx.children[0])
+ }
state.layout = field.Measure(*state.Palette, bounds, state.spec())
if ctx.Count() == 1 {
control := state.layout.Control
diff --git a/base/frame.go b/base/frame.go
index a4348c8a8..fb07317b1 100644
--- a/base/frame.go
+++ b/base/frame.go
@@ -375,6 +375,7 @@ func (f *Frame) End() {
f.checkAttributes()
f.applyRecipes()
f.resolveTables()
+ f.resolveDialogFocus()
root := &f.Nodes[0]
f.measure(AxisX)
root.Rect.X, root.Rect.Width = f.bounds.X, f.bounds.Width
diff --git a/base/menu.go b/base/menu.go
index 96f622e72..b01c9f58f 100644
--- a/base/menu.go
+++ b/base/menu.go
@@ -54,6 +54,38 @@ func Menu(c C, Anchor Box, open *bool, body func(*MenuItems)) {
p.DeclareMenu(c, menu, scope, open, Anchor.i, nil, body)
}
+// AnchorRect is the rectangle the menu opens against: its anchor element's, or the
+// one MenuAt was given, as of the last layout.
+func (m *MenuItems) AnchorRect() Rect {
+ if m.Anchor >= 0 && m.f != nil && int(m.Anchor) < len(m.f.Nodes) {
+ return m.f.Nodes[m.Anchor].Rect
+ }
+ return m.at
+}
+
+// MenuAt is Menu against a rectangle instead of an element: a part of the
+// application's own surface (a canvas cell, a region of a Control, a toolbar the
+// page did not lay out), in the page's coordinates. It opens below it, or Above or
+// Beside it as Menu does, flipped and kept inside the window by the same rules.
+// The keyboard goes back to where it was when it closes.
+//
+// ui.MenuAt(c, &m.tabMenu, m.tabRect, func(menu *ui.MenuItems) {
+// if menu.Item("Close tab").Clicked() { m.closeTab() }
+// })
+//
+// Not inside a Memo.
+func MenuAt(c C, open *bool, anchor Rect, body func(*MenuItems)) {
+ p := c.page
+ p.ForbidInMemo("Menu")
+ if !*open {
+ return
+ }
+ scope := p.BoundScope(pkMenu, unsafe.Pointer(open))
+ menu := stateIn[MenuItems](p, scope, "menu")
+ menu.context = false
+ p.DeclareMenu(c, menu, scope, open, -1, &menuOrigin{open: open, at: anchor, anchored: true}, body)
+}
+
// ContextMenu shows the items body declares at the pointer when target is pressed
// with the secondary button, or at the target when it has the focus and Shift+F10
// is pressed, as shadcn's ContextMenu. It behaves as a Menu then, but Tab does not
@@ -138,7 +170,11 @@ func contextMenu(c C, target Box, Bound gfx.Scope, opened *menuOrigin, body func
// The application owns when it opens; MenuItems owns the rows and dismissal.
type menuOrigin struct {
open *bool
- at Rect
+ // anchored makes at the rectangle the menu opens against, flipped and kept in
+ // the frame as an element anchor is, rather than the point a context menu
+ // opens at.
+ anchored bool
+ at Rect
}
// contextTarget is a ContextMenu declared in the last paint, which Shift+F10 on its
@@ -686,6 +722,15 @@ func (p *Page) DeclareMenu(c C, menu *MenuItems, scope gfx.Scope, open *bool, An
default:
popup.BelowBox(anchorBox, 4, Start)
}
+ } else if opened != nil && opened.anchored {
+ switch menu.side {
+ case menuAbove:
+ popup.Above(menu.at, 4, Start)
+ case MenuBeside:
+ popup.Beside(menu.at, 4, Start)
+ default:
+ popup.Below(menu.at, 4, Start)
+ }
} else {
height = min(height, max(f.bounds.Height-2*DropdownMenuPadding, 0))
clamped := ClampOverlay(gfx.Point{X: menu.at.X, Y: menu.at.Y}, gfx.Size{Width: width, Height: height}, f.bounds, DropdownMenuPadding)
diff --git a/base/page.go b/base/page.go
index 4db1cd808..7f789625e 100644
--- a/base/page.go
+++ b/base/page.go
@@ -162,6 +162,7 @@ const (
pkList
pkDisclosure
pkProgress
+ pkAlertDialog
pkKinds
)
diff --git a/docs/skills/building-with-viva/SKILL.md b/docs/skills/building-with-viva/SKILL.md
index f95417755..2d71655fe 100644
--- a/docs/skills/building-with-viva/SKILL.md
+++ b/docs/skills/building-with-viva/SKILL.md
@@ -76,7 +76,7 @@ func (m *model) page(c ui.C) {
### Dialogs, menus and popups
- `ui.Modal(c, &m.open, "Title", body, footer)` or `ui.ModalWith(..., ui.ModalSpec{...}, ...)`. The title is required; Escape, the close button and a press on the scrim set `m.open` to false, so do not write an Escape handler. `ui.Dialog(c, ui.DialogSpec{...})` is the form whose identities you name: `Scope`, `DismissID`, `CloseID`, `InitialFocusID`, `.Header`, `.Body`, `.Footer`, `.Dismissed()`.
-- `ui.Popover(c, anchor, &m.open, body)` / `ui.PopoverWith(c, anchor, ui.PopoverSpec{...}, &m.open, body)`; `ui.Menu(c, anchor, &m.open, func(menu *ui.MenuItems) { ... })` with `menu.Item("Rename").Clicked()`, `menu.Sub(label, body)`; `ui.ContextMenu(c, target, func(menu *ui.MenuItems) { ... })`; `ui.Drawer(c, &m.open, title, ui.DrawerSpec{...}, body, footer)`.
+- `ui.Popover(c, anchor, &m.open, body)` / `ui.PopoverWith(c, anchor, &m.open, ui.PopoverSpec{...}, body)`; `ui.Menu(c, anchor, &m.open, func(menu *ui.MenuItems) { ... })` with `menu.Item("Rename").Clicked()`, `menu.Sub(label, body)`; `ui.ContextMenu(c, target, func(menu *ui.MenuItems) { ... })`; `ui.Drawer(c, &m.open, title, ui.DrawerSpec{...}, body, footer)`.
- An application overlay is `ui.Overlay(c, ui.OverlaySpec{Band: ui.LayerPaneChrome, Bounds: r})` (or `ui.LayerDrag`): it takes no room, paints below Viva's menus and dialogs, and a `Canvas.Block` over its empty surface keeps presses from the page behind.
- Toasts: keep a `ui.Toaster`, `m.toaster.Show(title, text, ui.ToastSuccess)`, paint `ui.Toasts(c, &m.toaster)` once; `ShowAction(..., "Undo")` + `Acted()`, `ToastLoading` + `Done(id, ...)`, `Toaster.Position`.
diff --git a/examples/guides/overlay/main.go b/examples/guides/overlay/main.go
index 296d94a50..f8a529d81 100644
--- a/examples/guides/overlay/main.go
+++ b/examples/guides/overlay/main.go
@@ -24,7 +24,7 @@ func (m *model) page(c ui.C) {
// A popover hangs off its anchor while menuOpen is true. A press outside it
// or Escape closes it, and the press goes on to what is under the pointer;
// the focus goes back to the anchor.
- ui.PopoverWith(c, actions, ui.PopoverSpec{Width: 180, Align: ui.Start}, &m.menuOpen, func() {
+ ui.PopoverWith(c, actions, &m.menuOpen, ui.PopoverSpec{Width: 180, Align: ui.Start}, func() {
if ui.Button(c, "New file").Ghost().Clicked() {
m.menuOpen, m.status = false, "Created"
}
diff --git a/examples/guides/webview/main.go b/examples/guides/webview/main.go
index 838f54e66..0a38179ac 100644
--- a/examples/guides/webview/main.go
+++ b/examples/guides/webview/main.go
@@ -73,7 +73,7 @@ func (m *model) page(c ui.C) {
m.menuOpen = !m.menuOpen
}
ui.Text(c, m.status).Muted()
- ui.PopoverWith(c, menu, ui.PopoverSpec{Width: 220, Align: ui.Start}, &m.menuOpen, func() {
+ ui.PopoverWith(c, menu, &m.menuOpen, ui.PopoverSpec{Width: 220, Align: ui.Start}, func() {
if ui.Button(c, "Say hello to the page").Ghost().Clicked() && m.view != nil {
m.view.PostMessage("hello from Viva")
m.menuOpen = false
diff --git a/internal/componentdemo/alert_dialog.go b/internal/componentdemo/alert_dialog.go
index ce6a4c165..c5b568fbc 100644
--- a/internal/componentdemo/alert_dialog.go
+++ b/internal/componentdemo/alert_dialog.go
@@ -1,7 +1,6 @@
package componentdemo
import (
- "github.com/vivaui/viva/components"
"github.com/vivaui/viva/gfx"
"github.com/vivaui/viva/ui"
)
@@ -18,17 +17,21 @@ components.BeginAlertDialog(canvas, theme, viewport, options).
Paint("Delete this project?", "This cannot be undone.", "Delete", "Cancel")
if canvas.Clicked(m.confirmID) || canvas.Clicked(m.cancelID) {
open = false
-}`, PageSnippet: `ui.AlertDialog(c, ui.AlertDialogSpec{
+}`, PageSnippet: `if ui.AlertDialog(c, &m.confirmDelete, ui.AlertDialogSpec{
Title: "Permanently delete this project?",
Description: "This cannot be undone. Local data will be removed.",
- Scope: m.scope, ActionID: m.confirmID, CancelID: m.cancelID,
ActionLabel: "Delete", CancelLabel: "Cancel",
-})`, PageSnippetZh: `ui.AlertDialog(c, ui.AlertDialogSpec{
+ ActionVariant: ui.ButtonDestructive,
+}) {
+ m.deleteProject()
+}`, PageSnippetZh: `if ui.AlertDialog(c, &m.confirmDelete, ui.AlertDialogSpec{
Title: "永久删除这个项目?",
Description: "此操作无法撤销,本地数据将被移除。",
- Scope: m.scope, ActionID: m.confirmID, CancelID: m.cancelID,
ActionLabel: "删除", CancelLabel: "取消",
-})`},
+ ActionVariant: ui.ButtonDestructive,
+}) {
+ m.deleteProject()
+}`},
{ID: "media", Title: "带媒体的小尺寸", Description: "预留可由调用方绘制的媒体区域。", Snippet: `dialog := components.BeginAlertDialog(canvas, theme, viewport, components.AlertDialogOptions{
Layer: 8, Scope: m.scope, ActionID: m.confirmID, CancelID: m.cancelID,
Size: components.AlertDialogSmall,
@@ -78,16 +81,14 @@ var (
alertDialogScope = tree.ID(alertDialogUI, "scope")
)
-const alertDialogOpenFlag uint64 = 1
-
-func initializeAlertDialog(state *State) { state.flags |= alertDialogOpenFlag }
+func initializeAlertDialog(state *State) { state.alertOpen = true }
func (state *State) paintAlertDialog(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) {
- if state.flags&alertDialogOpenFlag == 0 {
+ if !state.alertOpen {
state.drawPage(canvas, theme, size, 320, state.Text("操作已取消", "Action canceled"), func(c ui.C) {
label := state.Text("再次打开警告", "Reopen alert")
if ui.Button(c, label).Hit(alertDialogOpen, label).Clicked() {
- state.flags |= alertDialogOpenFlag
+ state.alertOpen = true
}
})
return
@@ -107,26 +108,23 @@ func (state *State) paintAlertDialog(canvas *gfx.Canvas, theme gfx.Theme, size g
dialog.Footer(func() {
cancel, replace := state.Text("取消", "Cancel"), state.Text("替换", "Replace")
if ui.Button(c, cancel).Outline().Hit(alertDialogCancel, cancel).Clicked() {
- state.flags &^= alertDialogOpenFlag
+ state.alertOpen = false
}
if ui.Button(c, replace).Hit(alertDialogAction, replace).Clicked() {
- state.flags &^= alertDialogOpenFlag
+ state.alertOpen = false
}
})
if dialog.Dismissed() {
- state.flags &^= alertDialogOpenFlag
+ state.alertOpen = false
}
return
}
- dialog := ui.AlertDialog(c, ui.AlertDialogSpec{
+ ui.AlertDialog(c, &state.alertOpen, ui.AlertDialogSpec{
Title: state.Text("永久删除这个项目?", "Permanently delete this project?"),
Description: state.Text("此操作无法撤销,本地数据将被移除。", "This cannot be undone. Local data will be removed."),
Scope: alertDialogScope, ActionID: alertDialogAction, CancelID: alertDialogCancel,
ActionLabel: state.Text("删除", "Delete"), CancelLabel: state.Text("取消", "Cancel"),
- ActionVariant: components.ButtonDestructive,
+ ActionVariant: ui.ButtonDestructive,
})
- if id, ok := dialog.Chosen(); ok && (id == alertDialogAction || id == alertDialogCancel) {
- state.flags &^= alertDialogOpenFlag
- }
})
}
diff --git a/internal/componentdemo/catalog_a_test.go b/internal/componentdemo/catalog_a_test.go
index 1e46ad590..9a0f995c6 100644
--- a/internal/componentdemo/catalog_a_test.go
+++ b/internal/componentdemo/catalog_a_test.go
@@ -151,8 +151,8 @@ func TestGroupAClicksChangeCallerState(t *testing.T) {
}{
{"accordion", "default", gfx.ID{}, "状态由谁持有?", func(s *State) bool { return s.flags == 3 }},
{"accordion", "disabled", gfx.ID{}, "状态由谁持有?", func(s *State) bool { return s.flags == 1 }},
- {"alert-dialog", "default", alertDialogAction, "", func(s *State) bool { return s.flags&alertDialogOpenFlag == 0 }},
- {"alert-dialog", "media", alertDialogCancel, "", func(s *State) bool { return s.flags&alertDialogOpenFlag == 0 }},
+ {"alert-dialog", "default", alertDialogAction, "", func(s *State) bool { return !s.alertOpen }},
+ {"alert-dialog", "media", alertDialogCancel, "", func(s *State) bool { return !s.alertOpen }},
{"attachment", "default", attachmentItem.At(0), "", func(s *State) bool { return s.values[0] == 1 }},
{"breadcrumb", "default", breadcrumbLink.At(0), "", func(s *State) bool { return s.values[0] == 1 }},
{"bubble", "conversation", bubbleReaction, "", func(s *State) bool { return s.flags == 1 }},
diff --git a/internal/componentdemo/page_usage.go b/internal/componentdemo/page_usage.go
index f911b9730..04a15eac0 100644
--- a/internal/componentdemo/page_usage.go
+++ b/internal/componentdemo/page_usage.go
@@ -22,10 +22,10 @@ var pageUsage = map[string]string{
"slider": `ui.Slider(c, &m.volume).Range(0, 100)`,
"tabs": `ui.Tabs(c, &m.tab, tabs, tabLabel)`,
"dialog": `ui.Dialog(c, ui.DialogSpec{Title: "Edit host", Scope: scope, DismissID: dismiss})`,
- "alert-dialog": `ui.AlertDialog(c, ui.AlertDialogSpec{Title: "Delete?", ActionLabel: "Delete", CancelLabel: "Cancel", ActionID: action, CancelID: cancel})`,
+ "alert-dialog": `ui.AlertDialog(c, &m.confirm, ui.AlertDialogSpec{Title: "Delete?", ActionLabel: "Delete", CancelLabel: "Cancel"})`,
"drawer": `ui.Drawer(c, &m.open, "Host", ui.DrawerSpec{Side: ui.DrawerRight}, body, footer)`,
"sheet": `ui.Drawer(c, &m.open, "Details", ui.DrawerSpec{Side: ui.DrawerRight}, body, footer)`,
- "popover": `ui.PopoverWith(c, anchor, ui.PopoverSpec{Title: "Details"}, &m.open, body)`,
+ "popover": `ui.PopoverWith(c, anchor, &m.open, ui.PopoverSpec{Title: "Details"}, body)`,
"dropdown-menu": `ui.Menu(c, anchor, &m.open, func(menu *ui.MenuItems) { menu.Item("Rename") })`,
"context-menu": `ui.ContextMenu(c, row, func(menu *ui.MenuItems) { menu.Item("Delete") })`,
"table": `bills := ui.TableRows{
diff --git a/internal/componentdemo/popover.go b/internal/componentdemo/popover.go
index 6f17a8f2e..bb6728b54 100644
--- a/internal/componentdemo/popover.go
+++ b/internal/componentdemo/popover.go
@@ -24,20 +24,20 @@ trigger := ui.Button(c, "Open details").Outline().Self(ui.Start)
if trigger.Clicked() {
open = !open
}
-ui.PopoverWith(c, trigger, ui.PopoverSpec{
+ui.PopoverWith(c, trigger, &open, ui.PopoverSpec{
Title: "Native surface",
Description: "Clamped to the current viewport without timers.",
Scope: m.scope, DismissID: m.dismissID,
-}, &open, func() {})`, PageSnippetZh: `open := false
+}, func() {})`, PageSnippetZh: `open := false
trigger := ui.Button(c, "Open details").Outline().Self(ui.Start)
if trigger.Clicked() {
open = !open
}
-ui.PopoverWith(c, trigger, ui.PopoverSpec{
+ui.PopoverWith(c, trigger, &open, ui.PopoverSpec{
Title: "Native surface",
Description: "Clamped to the current viewport without timers.",
Scope: m.scope, DismissID: m.dismissID,
-}, &open, func() {})`},
+}, func() {})`},
{ID: "custom-body", Title: "自定义内容", Description: "使用 Begin/End 槽位在浮层正文中追加状态。", Snippet: `label := "Diagnostics disabled"
if enabled {
label = "Diagnostics enabled"
@@ -55,11 +55,11 @@ if trigger.Clicked() {
open = !open
}
enabled := false
-ui.PopoverWith(c, trigger, ui.PopoverSpec{
+ui.PopoverWith(c, trigger, &open, ui.PopoverSpec{
Title: "Build status",
Description: "The stable host owns this overlay state.",
Scope: m.scope, DismissID: m.dismissID,
-}, &open, func() {
+}, func() {
label := "Diagnostics disabled"
if enabled {
label = "Diagnostics enabled"
@@ -73,11 +73,11 @@ if trigger.Clicked() {
open = !open
}
enabled := false
-ui.PopoverWith(c, trigger, ui.PopoverSpec{
+ui.PopoverWith(c, trigger, &open, ui.PopoverSpec{
Title: "Build status",
Description: "The stable host owns this overlay state.",
Scope: m.scope, DismissID: m.dismissID,
-}, &open, func() {
+}, func() {
label := "Diagnostics disabled"
if enabled {
label = "Diagnostics enabled"
@@ -112,10 +112,10 @@ func (state *State) paintPopover(canvas *gfx.Canvas, theme gfx.Theme, size gfx.S
if state.exampleID == "custom-body" {
title, description = "Build status", "The stable host owns this overlay state."
}
- ui.PopoverWith(c, trigger, ui.PopoverSpec{
+ ui.PopoverWith(c, trigger, &demo.open, ui.PopoverSpec{
Title: title, Description: description,
Scope: popoverScope, DismissID: popoverDismiss,
- }, &demo.open, func() {
+ }, func() {
if state.exampleID != "custom-body" {
return
}
diff --git a/internal/componentdemo/state.go b/internal/componentdemo/state.go
index f8bfa762e..4014e85d1 100644
--- a/internal/componentdemo/state.go
+++ b/internal/componentdemo/state.go
@@ -98,6 +98,9 @@ func componentLess(left, right Component) bool {
func Catalog() []Component { return catalog }
type State struct {
+ // alertOpen is whether the alert dialog example is open: the bool a page
+ // gives ui.AlertDialog lives in the model, as an application's does.
+ alertOpen bool
componentID string
exampleID string
descriptor *Component
diff --git a/ui/alert_dialog_page_test.go b/ui/alert_dialog_page_test.go
new file mode 100644
index 000000000..6c828ece2
--- /dev/null
+++ b/ui/alert_dialog_page_test.go
@@ -0,0 +1,38 @@
+package ui_test
+
+import (
+ "testing"
+
+ "github.com/vivaui/viva/gfx"
+ "github.com/vivaui/viva/ui"
+)
+
+// An alert dialog on a page opens on its bool, as a Modal does: the keyboard
+// starts on Cancel, the confirming action reports true and closes it, and Escape
+// closes it without confirming.
+func TestAPageAlertDialogConfirmsOnItsBool(t *testing.T) {
+ open, confirmed := true, 0
+ d := openPage(t, func(c ui.C) {
+ ui.Button(c, "Delete host")
+ if ui.AlertDialog(c, &open, ui.AlertDialogSpec{
+ Title: "Delete host?", Description: "This cannot be undone.",
+ ActionLabel: "Delete", CancelLabel: "Cancel", ActionVariant: ui.ButtonDestructive,
+ }) {
+ confirmed++
+ }
+ })
+ if d.Focused() != "Cancel" {
+ t.Fatalf("the alert dialog opened with the keyboard on %q", d.Focused())
+ }
+ d.click("Delete")
+ if open || confirmed != 1 {
+ t.Fatalf("the confirming action left open=%v and confirmed %d times", open, confirmed)
+ }
+
+ open = true
+ d.repaint()
+ d.key(gfx.KeyEscape)
+ if open || confirmed != 1 {
+ t.Fatalf("Escape left open=%v and confirmed %d times", open, confirmed)
+ }
+}
diff --git a/ui/dialog_focus_test.go b/ui/dialog_focus_test.go
new file mode 100644
index 000000000..a3d78010c
--- /dev/null
+++ b/ui/dialog_focus_test.go
@@ -0,0 +1,36 @@
+package ui_test
+
+import (
+ "testing"
+
+ "github.com/vivaui/viva/gfx"
+ "github.com/vivaui/viva/ui"
+)
+
+// A Dialog whose spec names no initial focus takes the keyboard on the first
+// control of its body as it opens, as a Modal does, and gives it back to the
+// control that opened it as it closes.
+func TestADialogTakesTheKeyboardOnItsFirstControl(t *testing.T) {
+ open := false
+ d := openPage(t, func(c ui.C) {
+ if ui.Button(c, "Open dialog").Clicked() {
+ open = true
+ }
+ if open {
+ dialog := ui.Dialog(c, ui.DialogSpec{Title: "Rename", Scope: gfx.Item(900), DismissID: gfx.Item(901), CloseID: gfx.Item(902)})
+ dialog.Body(func() { ui.Button(c, "First") })
+ if dialog.Dismissed() {
+ open = false
+ }
+ }
+ })
+ d.key(gfx.KeyTab)
+ d.key(gfx.KeyEnter)
+ if d.Focused() != "First" {
+ t.Fatalf("the dialog opened with the keyboard on %q", d.Focused())
+ }
+ d.key(gfx.KeyEscape)
+ if open || d.Focused() != "Open dialog" {
+ t.Fatalf("closing: open %v, keyboard on %q", open, d.Focused())
+ }
+}
diff --git a/ui/facade.go b/ui/facade.go
index 08f04d5fe..0e492360a 100644
--- a/ui/facade.go
+++ b/ui/facade.go
@@ -294,9 +294,9 @@ func TextField[T TextValue](c C, Value T, Label, placeholder string) Box {
return base.TextField(c, Value, Label, placeholder)
}
-func TextFieldID(c C, ID gfx.ID, field *Field, Label, placeholder string) Box {
+func TextFieldID[T TextValue](c C, ID gfx.ID, Value T, Label, placeholder string) Box {
useField()
- return base.TextFieldID(c, ID, field, Label, placeholder)
+ return base.TextFieldID(c, ID, Value, Label, placeholder)
}
func TextFieldBase[T TextValue](c C, Value T, Label, placeholder string) Box {
@@ -333,7 +333,10 @@ func BindIconHover(state *base.IconHoverState, ID gfx.ID) IconHover {
func Dialog(c C, spec DialogSpec) Box { useDialog(); return base.Dialog(c, spec) }
-func AlertDialog(c C, spec AlertDialogSpec) Box { useAlert(); return base.AlertDialog(c, spec) }
+func AlertDialog(c C, open *bool, spec AlertDialogSpec) bool {
+ useAlert()
+ return base.AlertDialog(c, open, spec)
+}
func Drawer(c C, open *bool, title string, spec DrawerSpec, body, footer func()) bool {
useDrawer()
@@ -355,9 +358,9 @@ func Popover(c C, Anchor Box, open *bool, body func()) bool {
return base.Popover(c, Anchor, open, body)
}
-func PopoverWith(c C, Anchor Box, spec PopoverSpec, open *bool, body func()) bool {
+func PopoverWith(c C, Anchor Box, open *bool, spec PopoverSpec, body func()) bool {
usePopover()
- return base.PopoverWith(c, Anchor, spec, open, body)
+ return base.PopoverWith(c, Anchor, open, spec, body)
}
func Menu(c C, Anchor Box, open *bool, body func(*MenuItems)) {
@@ -365,6 +368,11 @@ func Menu(c C, Anchor Box, open *bool, body func(*MenuItems)) {
base.Menu(c, Anchor, open, body)
}
+func MenuAt(c C, open *bool, anchor Rect, body func(*MenuItems)) {
+ useMenu()
+ base.MenuAt(c, open, anchor, body)
+}
+
func ContextMenu(c C, target Box, body func(*MenuItems)) {
useMenu()
base.ContextMenu(c, target, body)
diff --git a/ui/form_field_label_test.go b/ui/form_field_label_test.go
new file mode 100644
index 000000000..1ef188e98
--- /dev/null
+++ b/ui/form_field_label_test.go
@@ -0,0 +1,43 @@
+package ui_test
+
+import (
+ "testing"
+
+ "github.com/vivaui/viva/ui"
+)
+
+// A form field's title labels the control its children declare, as an HTML
+// label labels the control inside it: pressing the title focuses the field.
+// TextFieldID edits a model string under the application's own identity.
+func TestAFormFieldTitleLabelsItsControl(t *testing.T) {
+ var row ui.FormFieldState
+ email := ""
+ id := ui.Identity{}
+ d := openPage(t, func(c ui.C) {
+ if id.IsZero() {
+ id = ui.ID(c)
+ }
+ ui.FormField(c, &row, "Work email").FillWidth().Children(func() {
+ ui.TextFieldID(c, id, &email, "Email", "you@example.com").FillWidth()
+ })
+ })
+ var title ui.Rect
+ for _, hit := range d.driver.Snapshot().Hits {
+ if hit.IsLabel && hit.Label == "Work email" {
+ title = hit.Bounds
+ }
+ }
+ if title.Width <= 0 {
+ t.Fatal("the title labels no control")
+ }
+ if err := d.driver.Click(title.X+2, title.Y+title.Height/2); err != nil {
+ t.Fatal(err)
+ }
+ if d.Focused() != "Email" || d.driver.Snapshot().Focused != id {
+ t.Fatalf("pressing the title put the keyboard on %q", d.Focused())
+ }
+ d.typeText("a@b.c")
+ if email != "a@b.c" {
+ t.Fatalf("the field edited %q into the model", email)
+ }
+}
diff --git a/ui/menu_at_test.go b/ui/menu_at_test.go
new file mode 100644
index 000000000..f157995b4
--- /dev/null
+++ b/ui/menu_at_test.go
@@ -0,0 +1,36 @@
+package ui_test
+
+import (
+ "testing"
+
+ "github.com/vivaui/viva/ui"
+)
+
+// A menu opened against a rectangle of the application's own surface opens
+// below it, flips above it at the bottom of the window, and works as a Menu.
+func TestMenuAtOpensAgainstARectangle(t *testing.T) {
+ open, renamed := true, false
+ anchor := ui.Rect{X: 40, Y: 40, Width: 80, Height: 24}
+ d := openPage(t, func(c ui.C) {
+ ui.Text(c, "surface")
+ ui.MenuAt(c, &open, anchor, func(menu *ui.MenuItems) {
+ if menu.Item("Rename").Clicked() {
+ renamed = true
+ }
+ menu.Item("Delete")
+ })
+ })
+ if item := d.hit("Rename"); item.Bounds.Y < anchor.Y+anchor.Height {
+ t.Fatalf("a menu under room opened at %v, over its anchor %v", item.Bounds, anchor)
+ }
+
+ anchor.Y = 450 // the window is 480 tall: no room below
+ d.repaint()
+ if item := d.hit("Delete"); item.Bounds.Y+item.Bounds.Height > anchor.Y {
+ t.Fatalf("a menu at the bottom opened at %v, not above its anchor %v", item.Bounds, anchor)
+ }
+ d.click("Rename")
+ if !renamed || open {
+ t.Fatalf("choosing an item: renamed %v, still open %v", renamed, open)
+ }
+}
diff --git a/ui/menu_paint.go b/ui/menu_paint.go
index 1de4090d6..9293490e9 100644
--- a/ui/menu_paint.go
+++ b/ui/menu_paint.go
@@ -105,7 +105,7 @@ func paintAt(m *MenuItems, Surface *gfx.Canvas, Palette *Theme, bounds Rect, lay
} else {
side := components.OverlayRight // the edge the menu slides in from, its anchor's
if m.Parent == nil {
- anchor := f.Nodes[m.Anchor].Rect
+ anchor := m.AnchorRect()
switch {
case m.GetSide() == MenuBeside:
if bounds.X+bounds.Width <= anchor.X+anchor.Width/2 {
diff --git a/ui/popover_test.go b/ui/popover_test.go
index 77b13aca1..32ed3d267 100644
--- a/ui/popover_test.go
+++ b/ui/popover_test.go
@@ -18,7 +18,7 @@ func TestPopoverHeaderAndFixedBody(t *testing.T) {
var body ui.Box
d := openPage(t, func(c ui.C) {
more := ui.Button(c, "More")
- ui.PopoverWith(c, more, ui.PopoverSpec{Width: 200, Title: "Transfers", Description: long}, &open, func() {
+ ui.PopoverWith(c, more, &open, ui.PopoverSpec{Width: 200, Title: "Transfers", Description: long}, func() {
body = ui.Column(c).FillWidth().Height(120).Children(func() { ui.Text(c, "Body") })
})
})
@@ -60,7 +60,7 @@ func TestPopoverHeaderToBodyFollowsSurfacePadding(t *testing.T) {
var body ui.Box
d := openPageWith(t, ui.PageConfig{Theme: &theme, View: func(c ui.C) {
more := ui.Button(c, "More")
- ui.PopoverWith(c, more, ui.PopoverSpec{Width: 300, Title: "Transfers", Description: "Active transfers"}, &open, func() {
+ ui.PopoverWith(c, more, &open, ui.PopoverSpec{Width: 300, Title: "Transfers", Description: "Active transfers"}, func() {
body = ui.Column(c).FillWidth().Height(40).Children(func() { ui.Text(c, "Body") })
})
}}, app.Config{})
@@ -89,7 +89,7 @@ func TestPopoverAlignOffset(t *testing.T) {
d := openPage(t, func(c ui.C) {
ui.Column(c).Pad(20).Children(func() {
more := ui.Button(c, "More").Width(200)
- ui.PopoverWith(c, more, ui.PopoverSpec{Side: components.PopoverBottom, Align: ui.Start, AlignOffset: shift, Width: 100}, &open, func() {
+ ui.PopoverWith(c, more, &open, ui.PopoverSpec{Side: components.PopoverBottom, Align: ui.Start, AlignOffset: shift, Width: 100}, func() {
body = ui.Column(c).FillWidth().Height(40)
})
})
@@ -110,7 +110,7 @@ func TestPopoverCanBeAHoverPreview(t *testing.T) {
open := true
d := openPage(t, func(c ui.C) {
anchor := ui.Button(c, "Anchor")
- ui.PopoverWith(c, anchor, ui.PopoverSpec{Title: "Details", Width: 200, Radius: 10, NoDismiss: true}, &open, func() {
+ ui.PopoverWith(c, anchor, &open, ui.PopoverSpec{Title: "Details", Width: 200, Radius: 10, NoDismiss: true}, func() {
ui.Text(c, "Body")
})
})
@@ -136,7 +136,7 @@ func TestPopoverMarginKeepsClearOfTheWindowEdge(t *testing.T) {
openPage(t, func(c ui.C) {
ui.Row(c).FillWidth().Justify(ui.End).Children(func() {
anchor := ui.Button(c, "Anchor").Width(100)
- ui.PopoverWith(c, anchor, ui.PopoverSpec{Side: components.PopoverBottom, Align: ui.Start, Width: 200, Margin: margin}, &open, func() {
+ ui.PopoverWith(c, anchor, &open, ui.PopoverSpec{Side: components.PopoverBottom, Align: ui.Start, Width: 200, Margin: margin}, func() {
body = ui.Column(c).FillWidth().Height(40)
})
})
@@ -156,7 +156,7 @@ func TestPopoverPaddingInsetsTheBody(t *testing.T) {
var body ui.Box
openPage(t, func(c ui.C) {
anchor := ui.Button(c, "Anchor")
- ui.PopoverWith(c, anchor, ui.PopoverSpec{Width: 200, Padding: padding}, &open, func() {
+ ui.PopoverWith(c, anchor, &open, ui.PopoverSpec{Width: 200, Padding: padding}, func() {
body = ui.Column(c).FillWidth().Height(40)
})
})
@@ -175,7 +175,7 @@ func TestPopoverInstantKeepsTheLayout(t *testing.T) {
var body ui.Box
openPage(t, func(c ui.C) {
anchor := ui.Button(c, "Anchor")
- ui.PopoverWith(c, anchor, ui.PopoverSpec{Width: 200, Instant: instant}, &open, func() {
+ ui.PopoverWith(c, anchor, &open, ui.PopoverSpec{Width: 200, Instant: instant}, func() {
body = ui.Column(c).FillWidth().Height(40)
})
})
diff --git a/ui/presence_parity_test.go b/ui/presence_parity_test.go
index 0692b358d..01871ccee 100644
--- a/ui/presence_parity_test.go
+++ b/ui/presence_parity_test.go
@@ -96,9 +96,9 @@ func TestPagePopoverAnimatesLikeTheComponentsPopover(t *testing.T) {
newClock := newParityClock()
view := func(c ui.C) {
slot := ui.Slot(c).Absolute().Left(anchor.X).Top(anchor.Y).Size(anchor.Width, anchor.Height)
- ui.PopoverWith(c, slot, ui.PopoverSpec{
+ ui.PopoverWith(c, slot, &open, ui.PopoverSpec{
Scope: gfx.Item(7), Side: components.PopoverBottom, Align: ui.Start, Offset: 2, Width: width,
- }, &open, func() {
+ }, func() {
ui.Slot(c).FillWidth().Height(bodyHeight)
})
}
@@ -156,9 +156,9 @@ func TestPagePopoverWithInstantAppearsAtOnce(t *testing.T) {
clock := newParityClock()
view := func(c ui.C) {
slot := ui.Slot(c).Absolute().Left(100).Top(100).Size(40, 20)
- ui.PopoverWith(c, slot, ui.PopoverSpec{
+ ui.PopoverWith(c, slot, &open, ui.PopoverSpec{
Scope: gfx.Item(7), Side: components.PopoverBottom, Align: ui.Start, Offset: 2, Width: 200, Instant: true,
- }, &open, func() {
+ }, func() {
ui.Slot(c).FillWidth().Height(120)
})
}
diff --git a/website/content/guides/en/overlays.md b/website/content/guides/en/overlays.md
index cbfc968fe..f4502a395 100644
--- a/website/content/guides/en/overlays.md
+++ b/website/content/guides/en/overlays.md
@@ -41,7 +41,7 @@ func (m *model) page(c ui.C) {
// A popover hangs off its anchor while menuOpen is true. A press outside it
// or Escape closes it, and the press goes on to what is under the pointer;
// the focus goes back to the anchor.
- ui.PopoverWith(c, actions, ui.PopoverSpec{Width: 180, Align: ui.Start}, &m.menuOpen, func() {
+ ui.PopoverWith(c, actions, &m.menuOpen, ui.PopoverSpec{Width: 180, Align: ui.Start}, func() {
if ui.Button(c, "New file").Ghost().Clicked() {
m.menuOpen, m.status = false, "Created"
}
diff --git a/website/content/guides/en/system-integration.md b/website/content/guides/en/system-integration.md
index 4925eaa90..278d3a3aa 100644
--- a/website/content/guides/en/system-integration.md
+++ b/website/content/guides/en/system-integration.md
@@ -125,7 +125,7 @@ func (m *model) page(c ui.C) {
m.menuOpen = !m.menuOpen
}
ui.Text(c, m.status).Muted()
- ui.PopoverWith(c, menu, ui.PopoverSpec{Width: 220, Align: ui.Start}, &m.menuOpen, func() {
+ ui.PopoverWith(c, menu, &m.menuOpen, ui.PopoverSpec{Width: 220, Align: ui.Start}, func() {
if ui.Button(c, "Say hello to the page").Ghost().Clicked() && m.view != nil {
m.view.PostMessage("hello from Viva")
m.menuOpen = false
diff --git a/website/content/guides/zh/overlays.md b/website/content/guides/zh/overlays.md
index 76afcad78..3d06ce1a2 100644
--- a/website/content/guides/zh/overlays.md
+++ b/website/content/guides/zh/overlays.md
@@ -41,7 +41,7 @@ func (m *model) page(c ui.C) {
// A popover hangs off its anchor while menuOpen is true. A press outside it
// or Escape closes it, and the press goes on to what is under the pointer;
// the focus goes back to the anchor.
- ui.PopoverWith(c, actions, ui.PopoverSpec{Width: 180, Align: ui.Start}, &m.menuOpen, func() {
+ ui.PopoverWith(c, actions, &m.menuOpen, ui.PopoverSpec{Width: 180, Align: ui.Start}, func() {
if ui.Button(c, "New file").Ghost().Clicked() {
m.menuOpen, m.status = false, "Created"
}
diff --git a/website/content/guides/zh/system-integration.md b/website/content/guides/zh/system-integration.md
index 5d1baff22..95bac7c4a 100644
--- a/website/content/guides/zh/system-integration.md
+++ b/website/content/guides/zh/system-integration.md
@@ -125,7 +125,7 @@ func (m *model) page(c ui.C) {
m.menuOpen = !m.menuOpen
}
ui.Text(c, m.status).Muted()
- ui.PopoverWith(c, menu, ui.PopoverSpec{Width: 220, Align: ui.Start}, &m.menuOpen, func() {
+ ui.PopoverWith(c, menu, &m.menuOpen, ui.PopoverSpec{Width: 220, Align: ui.Start}, func() {
if ui.Button(c, "Say hello to the page").Ghost().Clicked() && m.view != nil {
m.view.PostMessage("hello from Viva")
m.menuOpen = false
From ac5b0922a72ded6d67f50221b625bf4c9600f88c Mon Sep 17 00:00:00 2001
From: ccq <76206374+caichangqing1120@users.noreply.github.com>
Date: Sun, 22 Nov 2026 08:38:42 +0800
Subject: [PATCH 37/47] test(web): exercise wake while the page is open
---
app/run_canvas_js_test.go | 75 ++++++++++++++++++++++-----------------
1 file changed, 43 insertions(+), 32 deletions(-)
diff --git a/app/run_canvas_js_test.go b/app/run_canvas_js_test.go
index 3d95a4dbd..caf3f785d 100644
--- a/app/run_canvas_js_test.go
+++ b/app/run_canvas_js_test.go
@@ -21,14 +21,52 @@ func captureWeb(t *testing.T) *web.Config {
}
func TestRunCanvasHandsTheApplicationToThePage(t *testing.T) {
- got := captureWeb(t)
var tree gfx.Tree
var invalidator Invalidator
canvas := &gfx.Canvas{}
- woken := false
+ wakeCount, requests := 0, 0
+ updated := false
forwarded := [2]float32{}
+ previous := runWeb
+ t.Cleanup(func() { runWeb = previous })
+ runWeb = func(got web.Config) error {
+ if got.Title != "Notes" || got.Width <= 0 || got.Height <= 0 {
+ t.Errorf("page got title %q and size %dx%d, want the title and the default size", got.Title, got.Width, got.Height)
+ }
+ if got.Canvas != canvas {
+ t.Error("the page must paint into the caller's canvas")
+ }
+ if got.Paint == nil || got.TextInput == nil {
+ t.Error("Paint and TextInput must reach the page")
+ }
+ if got.ForwardWheel == nil || got.Waker == nil || got.OnWake == nil || got.OnClosed == nil {
+ t.Fatal("wheel, wake and close handlers must reach the page")
+ }
+ got.ForwardWheel(1.5, -2.5)
+ if forwarded != [2]float32{1.5, -2.5} {
+ t.Errorf("the page forwarded %v, want the application's callback", forwarded)
+ }
+ got.Waker.Bind(func() { requests++ })
+ defer got.Waker.Unbind()
+ if !invalidator.Post(func() { updated = true }) || requests != 1 || updated {
+ t.Fatal("Post must schedule a page wake without running the update inline")
+ }
+ got.OnWake()
+ got.OnClosed()
+ if invalidator.Post(func() { t.Error("late update ran") }) {
+ t.Error("a closed page must refuse posts")
+ }
+ got.OnWake()
+ return nil
+ }
err := RunCanvas(Config{
- Title: "Notes", Tree: &tree, Invalidator: &invalidator, OnWake: func() { woken = true },
+ Title: "Notes", Tree: &tree, Invalidator: &invalidator,
+ OnWake: func() {
+ wakeCount++
+ if !updated {
+ t.Error("the page must apply the posted update before OnWake")
+ }
+ },
Paint: func(*gfx.Canvas, gfx.Size) {},
TextInput: func(TextInputContext) *TextInput { return nil },
ForwardWheel: func(deltaX, deltaY float32) { forwarded = [2]float32{deltaX, deltaY} },
@@ -36,35 +74,8 @@ func TestRunCanvasHandsTheApplicationToThePage(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- if got.Title != "Notes" || got.Width <= 0 || got.Height <= 0 {
- t.Errorf("page got title %q and size %dx%d, want the title and the default size", got.Title, got.Width, got.Height)
- }
- if got.Canvas != canvas {
- t.Error("the page must paint into the caller's canvas")
- }
- if got.Paint == nil || got.TextInput == nil {
- t.Error("Paint and TextInput must reach the page")
- }
- if got.ForwardWheel == nil {
- t.Fatal("ForwardWheel must reach the page")
- }
- got.ForwardWheel(1.5, -2.5)
- if forwarded != [2]float32{1.5, -2.5} {
- t.Errorf("the page forwarded %v, want the application's callback", forwarded)
- }
- if got.Waker == nil {
- t.Fatal("an Invalidator must reach the page as its waker")
- }
- got.OnWake()
- if !woken {
- t.Error("OnWake must reach the page")
- }
- // What the page binds is what Invalidator.Invalidate calls.
- called := false
- got.Waker.Bind(func() { called = true })
- invalidator.Invalidate()
- if !called {
- t.Error("Invalidate must wake the page")
+ if wakeCount != 1 || requests != 1 {
+ t.Errorf("got %d requested wakes and %d callbacks, want one each before close", requests, wakeCount)
}
}
From 83c1fc6c11c8e896d09aa08e7e0f51e3fd8974b0 Mon Sep 17 00:00:00 2001
From: Dean Cen
Date: Sun, 22 Nov 2026 08:44:47 +0800
Subject: [PATCH 38/47] feat(app): open a window maximized from Config
---
.github/workflows/ci.yml | 4 +-
app/app.go | 12 +++--
app/driver.go | 10 ++++-
app/driver_window_test.go | 26 +++++++++++
app/run.go | 1 +
app/run_canvas.go | 1 +
internal/platform/contract.go | 8 +++-
internal/platform/linux/gtk_input_linux.go | 6 ++-
internal/platform/linux/gtk_window_linux.go | 12 +++++
.../platform/linux/window_controls_linux.go | 11 +++++
.../linux/window_controls_linux_test.go | 35 +++++++++++++++
internal/platform/linux/window_linux.go | 3 ++
.../windows/maximized_windows_test.go | 44 +++++++++++++++++++
.../platform/windows/status_item_windows.go | 1 +
internal/platform/windows/window_windows.go | 2 +
15 files changed, 165 insertions(+), 11 deletions(-)
create mode 100644 internal/platform/windows/maximized_windows_test.go
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 8ef49427b..b3647a3b1 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -166,7 +166,7 @@ jobs:
# The Linux package is not part of the sharded run (it drives X11), so the
# titlebar contracts that do not need a server name their tests here.
- name: Titlebar and window contracts
- run: go test ./internal/platform/linux -run '^Test(MaximizeButtonSetsBothDirections|PreviewMovePreservesSizeAndFocus|AClipboardImageIsOfferedAsPNGAndNoText|SetClipboardImageClaimsTheClipboardAndDropsOtherFlavours)$' -count=1 -v
+ run: go test ./internal/platform/linux -run '^Test(MaximizeButtonSetsBothDirections|OpeningMaximizedAsksForBothDirectionsBeforeMapping|PreviewMovePreservesSizeAndFocus|AClipboardImageIsOfferedAsPNGAndNoText|SetClipboardImageClaimsTheClipboardAndDropsOtherFlavours)$' -count=1 -v
- name: Native X11 drag preview and notification
env:
VIVA_TEST_PREVIEW_XVFB: '1'
@@ -357,7 +357,7 @@ jobs:
# native structure ABI tests are here for the same reason: they build only
# on Windows.
- name: Material contracts and controls (WARP)
- run: go test ./internal/platform/windows ./ui ./components ./headless ./app -run 'Test(Backdrop|WindowBackdrop|Notification|TaskbarCreated|CompositionClear|CompositionFallback|CompositionCreation|CustomBackdrop|AcrylicAccent|LegacyAcrylic|RoundedOutline|Translucent|MonospaceFamilies|FontWeights|(The)?MonoWeights|(The)?InterfaceWeights|EveryListedFamilyResolves|EngineReportsTheFontsUnderline|AlwaysOnTop|SaveDialogCheckbox|FileIcon|NativeStructureABI|ResizePresents|WindowSwapChain|LiveResize|FlipWindowResize|RedrawWaits|ContinuousRedraw|NoOpFrame|SameSize|ZeroSize|ResizeTimer|RedrawQueue|NativeRedrawMessage|CompositionSupersededFrame|DragPreview)' -count=1 -v
+ run: go test ./internal/platform/windows ./ui ./components ./headless ./app -run 'Test(Backdrop|WindowBackdrop|OpeningMaximized|Notification|TaskbarCreated|CompositionClear|CompositionFallback|CompositionCreation|CustomBackdrop|AcrylicAccent|LegacyAcrylic|RoundedOutline|Translucent|MonospaceFamilies|FontWeights|(The)?MonoWeights|(The)?InterfaceWeights|EveryListedFamilyResolves|EngineReportsTheFontsUnderline|AlwaysOnTop|SaveDialogCheckbox|FileIcon|NativeStructureABI|ResizePresents|WindowSwapChain|LiveResize|FlipWindowResize|RedrawWaits|ContinuousRedraw|NoOpFrame|SameSize|ZeroSize|ResizeTimer|RedrawQueue|NativeRedrawMessage|CompositionSupersededFrame|DragPreview)' -count=1 -v
- name: Web view partitions
run: go test ./internal/platform/windows -run '^Test(APageWithoutAPartitionAsksForNoProfileOfItsOwn|APartitionNamesTheWebView2Profile|AnEphemeralPartitionIsAnOffTheRecordProfile|EphemeralPagesWithoutAPartitionEachGetAProfileOfTheirOwn)$' -count=1 -v
- name: Terminal keyboard routing
diff --git a/app/app.go b/app/app.go
index df91cad41..7f4fc62fa 100644
--- a/app/app.go
+++ b/app/app.go
@@ -79,7 +79,12 @@ type Config struct {
// (kept on a screen); an X11 window manager places the window's frame there,
// so the content area sits below the title bar. Window.Frame reports where it
// really is.
- Origin *gfx.Point
+ Origin *gfx.Point
+ // Maximized asks the window manager to open the window maximized on Windows
+ // and Linux, while keeping Width, Height and Origin as its restored floating
+ // bounds. Opening maximized reports it through OnMaximize, like maximizing
+ // later does. Ignored on macOS, web, and WindowPanel.
+ Maximized bool
WindowMode WindowMode
// TitlebarHeight is the height in logical pixels of the strip the
// application paints under a custom titlebar's traffic lights, where the
@@ -219,8 +224,9 @@ type Config struct {
// OnMaximize runs on the window thread when the window is maximized or
// restored on Windows and Linux, including by the system (the window
// manager, the taskbar, or a keyboard shortcut), not only by Viva's own
- // window controls. On macOS, windows zoom or enter full screen instead,
- // and this callback is not invoked.
+ // window controls, and once when a window opens maximized. On macOS,
+ // windows zoom or enter full screen instead, and this callback is not
+ // invoked.
OnMaximize func(maximized bool)
// OnFullscreen runs on the window thread after the host observes a
diff --git a/app/driver.go b/app/driver.go
index 99d95b5be..fc9271b5e 100644
--- a/app/driver.go
+++ b/app/driver.go
@@ -117,7 +117,7 @@ func NewDriver(config Config, canvas *gfx.Canvas) (*Driver, error) {
canvas = &gfx.Canvas{}
}
driver := &Driver{config: normalized, canvas: canvas, wakeSent: make(chan struct{}, 1),
- origin: normalized.originPoint()}
+ origin: normalized.originPoint(), maximized: normalized.Maximized}
driver.frame = gfx.Rect{X: driver.origin.X, Y: driver.origin.Y, Width: float32(normalized.Width), Height: float32(normalized.Height)}
liveDrivers.Acquire()
@@ -167,6 +167,11 @@ func NewDriver(config Config, canvas *gfx.Canvas) (*Driver, error) {
return nil, err
}
built = true
+ // A window that opens maximized reports it like one maximized later, so an
+ // application hears the same state from every adapter.
+ if normalized.Maximized && normalized.OnMaximize != nil {
+ normalized.OnMaximize(true)
+ }
return driver, nil
}
@@ -378,7 +383,8 @@ func (driver *Driver) SetMaximized(maximized bool) error {
return nil
}
-// Maximized reports the state SetMaximized last reported.
+// Maximized reports whether the window is maximized: the state it opened in, then
+// what SetMaximized last reported.
func (driver *Driver) Maximized() bool { return driver.maximized }
// HitTest returns the front-most enabled interaction target at a logical-pixel
diff --git a/app/driver_window_test.go b/app/driver_window_test.go
index df8aba577..ef2519d39 100644
--- a/app/driver_window_test.go
+++ b/app/driver_window_test.go
@@ -84,3 +84,29 @@ func TestDriverReportsWindowFrameAndMinimizeState(t *testing.T) {
t.Fatalf("maximize changes = %v", maximizes)
}
}
+
+func TestDriverStartsMaximizedFromConfig(t *testing.T) {
+ var maximizes []bool
+ driver, err := NewDriver(Config{
+ Width: 640, Height: 480,
+ Maximized: true,
+ OnMaximize: func(maximized bool) { maximizes = append(maximizes, maximized) },
+ }, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer driver.Close()
+
+ if !driver.Maximized() {
+ t.Fatal("Driver did not start maximized from Config.Maximized")
+ }
+ if err := driver.SetMaximized(false); err != nil {
+ t.Fatal(err)
+ }
+ if driver.Maximized() {
+ t.Fatal("Maximized did not clear after restore")
+ }
+ if len(maximizes) != 2 || !maximizes[0] || maximizes[1] {
+ t.Fatalf("maximize changes = %v, want [true false]", maximizes)
+ }
+}
diff --git a/app/run.go b/app/run.go
index e568aa86a..5091f62cb 100644
--- a/app/run.go
+++ b/app/run.go
@@ -28,6 +28,7 @@ func Run(config Config) error {
Height: normalized.Height,
MinWidth: normalized.MinWidth,
MinHeight: normalized.MinHeight,
+ Maximized: normalized.Maximized,
WindowMode: platform.WindowMode(normalized.WindowMode),
WindowMaterials: normalized.windowMaterials(),
TitlebarHeight: normalized.TitlebarHeight,
diff --git a/app/run_canvas.go b/app/run_canvas.go
index 25610d553..9d68e883f 100644
--- a/app/run_canvas.go
+++ b/app/run_canvas.go
@@ -168,6 +168,7 @@ func nativeWindowConfig(normalized *Config, painter *painter) (platform.Config,
Title: normalized.Title, Class: normalized.Class, Icon: normalized.Icon.platform(), Width: normalized.Width, Height: normalized.Height,
MinWidth: normalized.MinWidth, MinHeight: normalized.MinHeight,
Origin: normalized.originPoint(), HasOrigin: normalized.Origin != nil,
+ Maximized: normalized.Maximized,
WindowMode: platform.WindowMode(normalized.WindowMode),
WindowMaterials: normalized.windowMaterials(),
TitlebarHeight: normalized.TitlebarHeight,
diff --git a/internal/platform/contract.go b/internal/platform/contract.go
index 7ecbf8780..8f3e40edd 100644
--- a/internal/platform/contract.go
+++ b/internal/platform/contract.go
@@ -39,8 +39,12 @@ type Config struct {
MinHeight int
// Origin, when HasOrigin, is where the top-left of the content area opens, in
// screen coordinates. Without one the system places the window.
- Origin gfx.Point
- HasOrigin bool
+ Origin gfx.Point
+ HasOrigin bool
+ // Maximized asks the window manager to open the window maximized on
+ // platforms that support maximization, keeping Width, Height and Origin as
+ // its restored floating bounds.
+ Maximized bool
WindowMode WindowMode
// TitlebarHeight is the height in logical pixels of the strip a custom
// titlebar leaves for the application. Zero means DefaultTitlebarHeight.
diff --git a/internal/platform/linux/gtk_input_linux.go b/internal/platform/linux/gtk_input_linux.go
index dd50a539f..193c87a80 100644
--- a/internal/platform/linux/gtk_input_linux.go
+++ b/internal/platform/linux/gtk_input_linux.go
@@ -437,12 +437,14 @@ func (w *gtkWindow) stateChanged(e *gdkEventWindowState) {
}
if e.Changed&gdkWindowStateMaximized != 0 {
- w.maximized = e.New&gdkWindowStateMaximized != 0
+ maximized := e.New&gdkWindowStateMaximized != 0
+ changed := maximized != w.maximized
+ w.maximized = maximized
w.regionsDirty = true
if w.wl != nil {
w.wl.updateRegions(w, int32(w.width+0.5), int32(w.height+0.5))
}
- if w.config.OnMaximize != nil {
+ if changed && w.config.OnMaximize != nil {
w.config.OnMaximize(w.maximized)
}
if w.config.OnRedraw != nil {
diff --git a/internal/platform/linux/gtk_window_linux.go b/internal/platform/linux/gtk_window_linux.go
index 45432b538..10a8d69fc 100644
--- a/internal/platform/linux/gtk_window_linux.go
+++ b/internal/platform/linux/gtk_window_linux.go
@@ -248,6 +248,18 @@ func (a *gtkApplication) OpenWindow(config platform.Config) (platform.Window, er
}
})
}
+ if config.Maximized && config.WindowMode != platform.WindowPanel && config.WindowMode != platform.WindowPreview {
+ g.windowMaximize(w.toplevel)
+ // The state event that confirms it may come after the loop starts, or not at
+ // all on a compositor of its own: report the state the window opens in now,
+ // as the other adapters do, and let the event only report changes.
+ if !w.maximized {
+ w.maximized = true
+ if config.OnMaximize != nil {
+ config.OnMaximize(true)
+ }
+ }
+ }
g.widgetShowAll(w.toplevel)
if a.firstErr != nil {
err := a.firstErr
diff --git a/internal/platform/linux/window_controls_linux.go b/internal/platform/linux/window_controls_linux.go
index a3e0c9cdf..bac82042c 100644
--- a/internal/platform/linux/window_controls_linux.go
+++ b/internal/platform/linux/window_controls_linux.go
@@ -148,6 +148,17 @@ func (win *window) sendToRoot(atom uint32, data [5]uint32) {
win.api.flush(win.connection)
}
+// requestInitialMaximized asks for the maximized state before the window is mapped, and
+// records the request the way toggleMaximize does: a window manager that answers with a
+// ConfigureNotify before it rewrites _NET_WM_STATE would otherwise leave the frame
+// thinking it is floating, and report the maximized rectangle through OnFrameChange.
+func (win *window) requestInitialMaximized() {
+ win.frame.maximizePending = true
+ win.frame.maximizeTarget = true
+ states := [2]uint32{win.frame.maximizedVertical, win.frame.maximizedHorizontal}
+ win.api.changeProperty(win.connection, xcbPropertyReplace, win.id, win.frame.stateAtom, xcbAtomAtom, 32, uint32(len(states)), unsafe.Pointer(&states[0]))
+}
+
func (win *window) minimize() {
win.sendToRoot(win.frame.changeStateAtom, [5]uint32{iconicState})
}
diff --git a/internal/platform/linux/window_controls_linux_test.go b/internal/platform/linux/window_controls_linux_test.go
index bbf5e0682..78a274a94 100644
--- a/internal/platform/linux/window_controls_linux_test.go
+++ b/internal/platform/linux/window_controls_linux_test.go
@@ -119,3 +119,38 @@ func TestTitlebarDoubleClickSlopTolerantToJitter(t *testing.T) {
t.Fatal("two presses with small cursor jitter should make a double click on HiDPI")
}
}
+
+// A window that opens maximized asks before it is mapped, and records the request
+// so a ConfigureNotify that arrives before the manager's property does not make the
+// frame report its floating bounds as the maximized one.
+func TestOpeningMaximizedAsksForBothDirectionsBeforeMapping(t *testing.T) {
+ var mode, kind, items uint32
+ var property uint32
+ var values []uint32
+ win := &window{
+ connection: 1, id: 2,
+ api: &xcbAPI{
+ changeProperty: func(_ uintptr, m uint8, _ uint32, p, k uint32, _ uint8, n uint32, data unsafe.Pointer) xcbVoidCookie {
+ mode, property, kind, items = uint32(m), p, k, n
+ values = append([]uint32(nil), unsafe.Slice((*uint32)(data), n)...)
+ return xcbVoidCookie{}
+ },
+ },
+ frame: frameState{
+ stateAtom: 10,
+ maximizedVertical: 20,
+ maximizedHorizontal: 30,
+ },
+ }
+ win.requestInitialMaximized()
+ if mode != xcbPropertyReplace || property != 10 || kind != xcbAtomAtom || items != 2 {
+ t.Fatalf("initial request = mode %d property %d kind %d items %d", mode, property, kind, items)
+ }
+ if len(values) != 2 || values[0] != 20 || values[1] != 30 {
+ t.Fatalf("initial state = %v, want both directions", values)
+ }
+ if !win.frame.maximizePending || !win.frame.maximizeTarget {
+ t.Fatalf("initial request pending=%t target=%t, want it recorded as asked for",
+ win.frame.maximizePending, win.frame.maximizeTarget)
+ }
+}
diff --git a/internal/platform/linux/window_linux.go b/internal/platform/linux/window_linux.go
index f8f1f21c5..ac5124cd3 100644
--- a/internal/platform/linux/window_linux.go
+++ b/internal/platform/linux/window_linux.go
@@ -1566,6 +1566,9 @@ func (application *linuxApplication) openWindow(config platform.Config) (*window
return nil, fmt.Errorf("%w: %v", platform.ErrDragPreviewUnsupported, err)
}
}
+ if config.Maximized && config.WindowMode != platform.WindowPanel && config.WindowMode != platform.WindowPreview && win.frame.stateAtom != 0 {
+ win.requestInitialMaximized()
+ }
api.mapWindow(connection, win.id)
if api.flush(connection) <= 0 || api.connectionHasError(connection) != 0 {
win.close()
diff --git a/internal/platform/windows/maximized_windows_test.go b/internal/platform/windows/maximized_windows_test.go
new file mode 100644
index 000000000..45f251f77
--- /dev/null
+++ b/internal/platform/windows/maximized_windows_test.go
@@ -0,0 +1,44 @@
+package windows
+
+import (
+ "fmt"
+ "runtime"
+ "testing"
+
+ "github.com/vivaui/viva/internal/platform"
+ "github.com/vivaui/viva/internal/render"
+)
+
+// A window asked to open maximized is the zoomed window Win32 would have shown,
+// and the application is told the state it opened in, as it is when maximizing
+// later.
+func TestOpeningMaximizedShowsAZoomedWindow(t *testing.T) {
+ runtime.LockOSThread()
+ defer runtime.UnlockOSThread()
+ var maximizes []bool
+ err := RunApplication(func(application platform.Application) error {
+ opened, err := application.OpenWindow(platform.Config{
+ Title: "Viva maximized test", Width: 640, Height: 400, Maximized: true,
+ OnResize: func(platform.Size) (platform.Frame, error) {
+ return platform.Frame{Update: render.Update{Rebuild: true}}, nil
+ },
+ OnMaximize: func(maximized bool) { maximizes = append(maximizes, maximized) },
+ })
+ if err != nil {
+ return err
+ }
+ defer opened.Close()
+ window := opened.(*nativeWindow)
+ zoomed, _, _ := isZoomed.Call(window.state.window)
+ if zoomed == 0 {
+ return fmt.Errorf("IsZoomed = 0, want the window shown maximized")
+ }
+ return nil
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(maximizes) != 1 || !maximizes[0] {
+ t.Fatalf("maximize reports = %v, want [true]", maximizes)
+ }
+}
diff --git a/internal/platform/windows/status_item_windows.go b/internal/platform/windows/status_item_windows.go
index 62224896a..9b1b506bf 100644
--- a/internal/platform/windows/status_item_windows.go
+++ b/internal/platform/windows/status_item_windows.go
@@ -49,6 +49,7 @@ const (
swHide = 0
swShow = 5
swShowNoActivate = 4
+ swShowMaximized = 3
swRestore = 9
smSmallIconWidth = 49
monitorNearest = 2
diff --git a/internal/platform/windows/window_windows.go b/internal/platform/windows/window_windows.go
index 294943567..56204e497 100644
--- a/internal/platform/windows/window_windows.go
+++ b/internal/platform/windows/window_windows.go
@@ -449,6 +449,8 @@ func (application *windowsApplication) OpenWindow(config platform.Config) (platf
state.paintPending = true
showWindow.Call(state.window, swShowNoActivate)
invalidateRect.Call(state.window, 0, 0)
+ } else if config.Maximized {
+ showWindow.Call(state.window, swShowMaximized)
} else {
showWindow.Call(state.window, 1)
}
From 669b9fb7b89f23d966929311aa66d5c2133c00db Mon Sep 17 00:00:00 2001
From: t8y2 <1156263951@qq.com>
Date: Sun, 22 Nov 2026 08:45:33 +0800
Subject: [PATCH 39/47] fix(text): find a click's offset and a word's range
without scanning the line
- OffsetAt bisected nothing: it measured the caret at every boundary,
each a prefix as long as the line, so a click on a 10 000-character
line took 99 ms. Carets grow with the offset on a line read one way, so
NearestBoundary bisects grapheme boundaries (88 us); a bidirectional
line resolves once instead of once per boundary. The measurer and
fixed-pitch paths share it, and stop on cluster boundaries instead of
between a letter and its combining mark.
- WordRange, LineRange and the painter's rangeIsSpace converted the whole
value to []rune on every pointer move of a word or line drag (2 ms and
4 MB for 1 MB of text); they read the string in place (0.3 ms, no
allocation).
Randomized tests hold both to the results of the old forms.
---
app/painter.go | 15 +++--
gfx/text_engine.go | 19 +------
gfx/text_engine_test.go | 24 +++++++-
internal/textmetrics/bidi.go | 60 +++++++++++++++++++-
internal/textmetrics/offset_test.go | 62 +++++++++++++++++++++
text/editing.go | 78 +++++++++++++++++---------
text/word_range_test.go | 85 +++++++++++++++++++++++++++++
7 files changed, 294 insertions(+), 49 deletions(-)
create mode 100644 internal/textmetrics/offset_test.go
create mode 100644 text/word_range_test.go
diff --git a/app/painter.go b/app/painter.go
index 2d9641714..dcd57593c 100644
--- a/app/painter.go
+++ b/app/painter.go
@@ -467,14 +467,19 @@ func placeUnitSelection(value string, index, unit int, anchor text.Range) TextRa
}
}
-// rangeIsSpace reports whether a range of value holds only whitespace.
+// rangeIsSpace reports whether a range of value, in runes, holds only whitespace.
+// It reads value in place, so a drag by words through a long text allocates
+// nothing here.
func rangeIsSpace(value string, r text.Range) bool {
- runes := []rune(value)
- start, end := max(0, min(r.Start, len(runes))), max(0, min(r.End, len(runes)))
- for _, r := range runes[start:end] {
- if !unicode.IsSpace(r) {
+ index := 0
+ for _, c := range value {
+ if index >= r.End {
+ break
+ }
+ if index >= r.Start && !unicode.IsSpace(c) {
return false
}
+ index++
}
return true
}
diff --git a/gfx/text_engine.go b/gfx/text_engine.go
index e84556419..e6ab4f953 100644
--- a/gfx/text_engine.go
+++ b/gfx/text_engine.go
@@ -250,23 +250,10 @@ func (referenceEngine) OffsetAt(value string, size, weight, x float32) int {
}
// offsetAtByPrefix is the character boundary of value whose prefix width is nearest to
-// x: OffsetAt for a measurer that only knows widths.
+// x: OffsetAt for a measurer that only knows widths. Boundaries are those of grapheme
+// clusters, so a click never lands between a letter and its marks.
func offsetAtByPrefix(value string, x float32, width func(prefix string) float32) int {
- best, bestDistance := 0, abs32(x-width(""))
- for offset := range value {
- if offset == 0 {
- continue
- }
- if distance := abs32(x - width(value[:offset])); distance < bestDistance {
- best, bestDistance = offset, distance
- }
- }
- if len(value) > 0 {
- if distance := abs32(x - width(value)); distance < bestDistance {
- best = len(value)
- }
- }
- return best
+ return textmetrics.NearestBoundary(value, x, func(offset int) float32 { return width(value[:offset]) })
}
// clampOffset is offset limited to [0, len(value)] and moved back to the start of the
diff --git a/gfx/text_engine_test.go b/gfx/text_engine_test.go
index e992ed2cc..6aba2f051 100644
--- a/gfx/text_engine_test.go
+++ b/gfx/text_engine_test.go
@@ -1,6 +1,9 @@
package gfx
-import "testing"
+import (
+ "testing"
+ "unicode/utf8"
+)
// halfEngine measures every character as half the size and counts its calls.
type halfEngine struct{ widths, carets, selections, hits int }
@@ -222,3 +225,22 @@ func TestAnEngineSelectionDoesNotMakeTheCallersBufferEscape(t *testing.T) {
t.Errorf("TextSelection allocated %v times per call", allocations)
}
}
+
+// A measurer that only knows widths still puts the caret on a character boundary: a
+// click that lands between a letter and its combining mark goes to one side of the
+// cluster, never inside it.
+func TestTextOffsetAtWithAMeasurerKeepsClustersWhole(t *testing.T) {
+ var canvas Canvas
+ canvas.SetMeasurer(func(value string, size, weight float32) float32 {
+ return float32(utf8.RuneCountInString(value)) * 10
+ })
+ value := "éx" // é as e and a combining acute, then x
+ for _, x := range []float32{8, 10, 12, 18} {
+ if got := canvas.TextOffsetAt(value, 10, 0, x); got != 0 && got != 3 {
+ t.Fatalf("a click at %v put the caret at %d, inside é", x, got)
+ }
+ }
+ if got := canvas.TextOffsetAt(value, 10, 0, 22); got != 3 {
+ t.Fatalf("a click just past é put the caret at %d, want after it", got)
+ }
+}
diff --git a/internal/textmetrics/bidi.go b/internal/textmetrics/bidi.go
index 6d7438b5d..0a52920a4 100644
--- a/internal/textmetrics/bidi.go
+++ b/internal/textmetrics/bidi.go
@@ -322,16 +322,72 @@ func absf(v float32) float32 {
// OffsetAt is the byte offset of the character boundary nearest to x, a distance in
// logical pixels from the left end of the line, which a click at x puts the caret at.
+// Of two boundaries as near, the earlier.
func OffsetAt(value string, size, weight float32, x float32) int {
+ if !bidi.NeedsBidi(value) {
+ return NearestBoundary(value, x, func(offset int) float32 { return Width(value[:offset], size, weight) })
+ }
+ // A line read in more than one direction has carets that do not grow with the
+ // offset: every boundary is measured, against one resolution of the line.
+ table := weightIndex(weight)
+ b := bidiPool.Get().(*bidiLine)
+ b.resolve(value, table)
best, bestDistance := 0, float32(-1)
for offset := 0; ; {
- d := absf(Caret(value, size, weight, offset) - x)
+ d := absf(float32(b.edge(value, offset))*size/unitsPerEm - x)
if bestDistance < 0 || d < bestDistance {
best, bestDistance = offset, d
}
if offset >= len(value) {
- return best
+ break
}
offset = grapheme.Next(value, offset)
}
+ b.release()
+ return best
+}
+
+// NearestBoundary is the grapheme cluster boundary of value whose caret is nearest to
+// x, given carets that do not decrease along the line: caret(offset) is the caret at a
+// boundary. Of two boundaries as near, the earlier, and of a run of boundaries at one
+// caret (characters with no advance), the first. It measures a logarithmic number of
+// boundaries, so a click on a long line costs its length times that, not its square.
+func NearestBoundary(value string, x float32, caret func(offset int) float32) int {
+ if len(value) == 0 || x <= caret(0) {
+ return 0
+ }
+ lo := len(value)
+ if caret(lo) >= x {
+ // The first boundary whose caret reaches x, found by bisection: hi reaches
+ // it, lo does not.
+ var hi int
+ lo, hi = 0, len(value)
+ for {
+ mid := snap(value, lo+(hi-lo)/2)
+ if mid <= lo {
+ if mid = grapheme.Next(value, lo); mid >= hi {
+ break
+ }
+ }
+ if caret(mid) >= x {
+ hi = mid
+ } else {
+ lo = mid
+ }
+ }
+ // lo is the boundary before hi: hi when nearer, else lo.
+ if caret(hi)-x < x-caret(lo) {
+ return hi
+ }
+ }
+ // lo is the answer's caret; the first boundary at it is the answer.
+ at := caret(lo)
+ for lo > 0 {
+ before := grapheme.Prev(value, lo)
+ if caret(before) != at {
+ break
+ }
+ lo = before
+ }
+ return lo
}
diff --git a/internal/textmetrics/offset_test.go b/internal/textmetrics/offset_test.go
new file mode 100644
index 000000000..5afdf0e9d
--- /dev/null
+++ b/internal/textmetrics/offset_test.go
@@ -0,0 +1,62 @@
+package textmetrics
+
+import (
+ "math/rand/v2"
+ "strconv"
+ "strings"
+ "testing"
+
+ "github.com/vivaui/viva/internal/grapheme"
+)
+
+// bruteOffset is what OffsetAt meant before it bisected: every boundary measured,
+// the first of the nearest kept.
+func bruteOffset(value string, size, weight, x float32) int {
+ best, bestDistance := 0, float32(-1)
+ for offset := 0; ; {
+ d := absf(Caret(value, size, weight, offset) - x)
+ if bestDistance < 0 || d < bestDistance {
+ best, bestDistance = offset, d
+ }
+ if offset >= len(value) {
+ return best
+ }
+ offset = grapheme.Next(value, offset)
+ }
+}
+
+// Whatever the line and wherever the click, the bisected offset is the one measuring
+// every boundary finds: letters with marks, zero-width characters, wide ideographs,
+// emoji sequences and right-to-left text included.
+func TestOffsetAtFindsTheNearestBoundary(t *testing.T) {
+ pieces := []string{"a", "W", " ", "é", "", "中", "👩💻", "א", "ب", "ẍ̣", "1"}
+ random := rand.New(rand.NewPCG(7, 11))
+ for round := range 2000 {
+ var b strings.Builder
+ for range random.IntN(16) {
+ b.WriteString(pieces[random.IntN(len(pieces))])
+ }
+ value := b.String()
+ width := Width(value, 14, 0)
+ for range 8 {
+ x := random.Float32()*(width+20) - 10
+ if got, want := OffsetAt(value, 14, 0, x), bruteOffset(value, 14, 0, x); got != want {
+ t.Fatalf("round %d: OffsetAt(%q, x=%v) = %d, want %d", round, value, x, got, want)
+ }
+ }
+ }
+}
+
+// A click on a long line measures a logarithmic number of its boundaries.
+func BenchmarkOffsetAt(b *testing.B) {
+ for _, n := range []int{100, 1000, 10000} {
+ value := strings.Repeat("the quick brown fox ", n/20+1)[:n]
+ x := Width(value, 14, 0) * 0.6
+ b.Run(strconv.Itoa(n), func(b *testing.B) {
+ b.ReportAllocs()
+ for b.Loop() {
+ OffsetAt(value, 14, 0, x)
+ }
+ })
+ }
+}
diff --git a/text/editing.go b/text/editing.go
index 528da98f9..5795804c4 100644
--- a/text/editing.go
+++ b/text/editing.go
@@ -3,6 +3,9 @@ package text
import (
"strings"
"unicode"
+ "unicode/utf8"
+
+ "github.com/vivaui/viva/internal/grapheme"
)
// SingleLine folds pasted lines and tabs into spaces and drops other control
@@ -89,51 +92,76 @@ func (editor *Editor) MoveWord(forward, extend bool) {
}
// WordRange returns the run around a pointer position, on grapheme boundaries.
+// It reads value in place: what it walks is the word, and the rune index is found
+// by counting, so a drag that extends a selection by words through a long text
+// allocates nothing.
func WordRange(value string, index int) Range {
- runes := []rune(value)
- if len(runes) == 0 {
+ at, index, ok := lastRuneAt(value, index)
+ if !ok {
return Range{}
}
- index = max(0, min(index, len(runes)-1))
- start := 0
- for next := nextBoundary(runes, start); next <= index; next = nextBoundary(runes, start) {
- start = next
+ start := at
+ for start > 0 && !grapheme.Boundary(value, start) {
+ _, size := utf8.DecodeLastRuneInString(value[:start])
+ start -= size
}
- kind := wordClass(runes[start])
- end := nextBoundary(runes, start)
+ first, _ := utf8.DecodeRuneInString(value[start:])
+ kind := wordClass(first)
+ end := grapheme.Next(value, start)
for start > 0 {
- previous := previousBoundary(runes, start)
- if wordClass(runes[previous]) != kind {
+ previous := grapheme.Prev(value, start)
+ if r, _ := utf8.DecodeRuneInString(value[previous:]); wordClass(r) != kind {
break
}
start = previous
}
- for end < len(runes) && wordClass(runes[end]) == kind {
- end = nextBoundary(runes, end)
+ for end < len(value) {
+ if r, _ := utf8.DecodeRuneInString(value[end:]); wordClass(r) != kind {
+ break
+ }
+ end = grapheme.Next(value, end)
+ }
+ return Range{
+ Start: index - utf8.RuneCountInString(value[start:at]),
+ End: index + utf8.RuneCountInString(value[at:end]),
}
- return Range{Start: start, End: end}
}
// LineRange returns the logical line around a pointer position, including its
// trailing newline when it has one. It is the selection a triple click takes.
func LineRange(value string, index int) Range {
- runes := []rune(value)
- if len(runes) == 0 {
+ at, index, ok := lastRuneAt(value, index)
+ if !ok {
return Range{}
}
- index = max(0, min(index, len(runes)-1))
- start := index
- for start > 0 && runes[start-1] != '\n' {
- start--
+ start := strings.LastIndexByte(value[:at], '\n') + 1
+ end := len(value)
+ if newline := strings.IndexByte(value[at:], '\n'); newline >= 0 {
+ end = at + newline + 1 // the newline belongs to the line it ends
}
- end := index
- for end < len(runes) && runes[end] != '\n' {
- end++
+ return Range{
+ Start: index - utf8.RuneCountInString(value[start:at]),
+ End: index + utf8.RuneCountInString(value[at:end]),
}
- if end < len(runes) {
- end++ // the newline belongs to the line it ends
+}
+
+// lastRuneAt is the byte offset of the rune at index in value, index clamped to
+// the runes value has (the last one past its end), and the clamped index; ok is
+// false for an empty value.
+func lastRuneAt(value string, index int) (at, clamped int, ok bool) {
+ if value == "" {
+ return 0, 0, false
+ }
+ index = max(index, 0)
+ n, last := 0, 0
+ for offset := range value {
+ if n == index {
+ return offset, index, true
+ }
+ last = offset
+ n++
}
- return Range{Start: start, End: end}
+ return last, n - 1, true
}
// DeleteWord removes a selection or a word as one undo unit. Undo restores the
diff --git a/text/word_range_test.go b/text/word_range_test.go
new file mode 100644
index 000000000..5e9b96e6b
--- /dev/null
+++ b/text/word_range_test.go
@@ -0,0 +1,85 @@
+package text
+
+import (
+ "math/rand/v2"
+ "strings"
+ "testing"
+)
+
+// The []rune forms WordRange and LineRange had: what the string forms must find.
+func runeWordRange(value string, index int) Range {
+ runes := []rune(value)
+ if len(runes) == 0 {
+ return Range{}
+ }
+ index = max(0, min(index, len(runes)-1))
+ start := 0
+ for next := nextBoundary(runes, start); next <= index; next = nextBoundary(runes, start) {
+ start = next
+ }
+ kind := wordClass(runes[start])
+ end := nextBoundary(runes, start)
+ for start > 0 {
+ previous := previousBoundary(runes, start)
+ if wordClass(runes[previous]) != kind {
+ break
+ }
+ start = previous
+ }
+ for end < len(runes) && wordClass(runes[end]) == kind {
+ end = nextBoundary(runes, end)
+ }
+ return Range{Start: start, End: end}
+}
+
+func runeLineRange(value string, index int) Range {
+ runes := []rune(value)
+ if len(runes) == 0 {
+ return Range{}
+ }
+ index = max(0, min(index, len(runes)-1))
+ start := index
+ for start > 0 && runes[start-1] != '\n' {
+ start--
+ }
+ end := index
+ for end < len(runes) && runes[end] != '\n' {
+ end++
+ }
+ if end < len(runes) {
+ end++
+ }
+ return Range{Start: start, End: end}
+}
+
+// Whatever the text and the index, reading the string in place finds the word and
+// the line the rune form found: marks, emoji sequences, flags, CJK and newlines.
+func TestWordAndLineRangeReadTheStringInPlace(t *testing.T) {
+ pieces := []string{"a", "_", "7", " ", "\n", ".", "/", "é", "中文", "👩💻", "🇯🇵", "🇯", "x̣", "\t", "-"}
+ random := rand.New(rand.NewPCG(3, 5))
+ for round := range 3000 {
+ var b strings.Builder
+ for range random.IntN(14) {
+ b.WriteString(pieces[random.IntN(len(pieces))])
+ }
+ value := b.String()
+ for index := -1; index <= len([]rune(value))+1; index++ {
+ if got, want := WordRange(value, index), runeWordRange(value, index); got != want {
+ t.Fatalf("round %d: WordRange(%q, %d) = %v, want %v", round, value, index, got, want)
+ }
+ if got, want := LineRange(value, index), runeLineRange(value, index); got != want {
+ t.Fatalf("round %d: LineRange(%q, %d) = %v, want %v", round, value, index, got, want)
+ }
+ }
+ }
+}
+
+// A drag by words through a long text costs the word, not a copy of the text.
+func BenchmarkWordRange(b *testing.B) {
+ value := strings.Repeat("connect to host-01.example.com over ssh\n", 25000) // about 1 MB
+ index := len([]rune(value)) / 2
+ b.ReportAllocs()
+ for b.Loop() {
+ WordRange(value, index)
+ }
+}
From 09af469f1d5cc15a6aa66f715b51c6f7a66821d0 Mon Sep 17 00:00:00 2001
From: t8y2 <1156263951@qq.com>
Date: Sun, 22 Nov 2026 08:45:33 +0800
Subject: [PATCH 40/47] fix(text): keep the editor's text across edits and
convert offsets in place
- The Editor stores runes and cached its String until the next edit,
which rebuilt it from every rune: typing in a 1 MB document re-encoded
1 MB per keystroke (9.7 ms for an insert and a delete). An edit now
records how much of the cached text's head and tail it left alone, and
String rebuilds only what lies between, once however many edits came
between two reads (0.25 ms), so an input method's many small edits do
not cost a copy each.
- text gains ByteOffsetOf, ByteRange, UTF16Offset and RuneIndexAtUTF16,
which read a string in place. macOS answered every text event by
building a whole Editor to convert the selection to UTF-16; it, the
Linux surrounding text, the Windows character position query and the
copy and cut path use them now, and the surrounding text stays valid
UTF-8 for the bus.
Viva-only: no API a caller uses changes.
---
internal/platform/darwin/callback.go | 14 ++--
internal/platform/darwin/platform.go | 11 ++-
internal/platform/linux/surrounding.go | 34 ++++++--
internal/platform/text_editing.go | 7 +-
.../platform/windows/ime_request_windows.go | 17 +++-
text/editor.go | 13 ++-
text/offsets.go | 84 +++++++++++++++++++
text/text_cache_test.go | 78 +++++++++++++++++
text/units.go | 73 ++++++++++++++++
text/units_test.go | 38 +++++++++
10 files changed, 335 insertions(+), 34 deletions(-)
create mode 100644 text/text_cache_test.go
create mode 100644 text/units.go
create mode 100644 text/units_test.go
diff --git a/internal/platform/darwin/callback.go b/internal/platform/darwin/callback.go
index dcce9f129..f6693b104 100644
--- a/internal/platform/darwin/callback.go
+++ b/internal/platform/darwin/callback.go
@@ -1055,7 +1055,6 @@ func deliverTextInputEvent(state *runState, view unsafe.Pointer, event TextEvent
}
func utf16Range(value string, start, length int) text.Range {
- editor := text.NewEditor(value)
if start < 0 {
start = 0
}
@@ -1063,17 +1062,16 @@ func utf16Range(value string, start, length int) text.Range {
length = 0
}
return text.Range{
- Start: editor.UTF16ToRuneIndex(start),
- End: editor.UTF16ToRuneIndex(start + length),
+ Start: text.RuneIndexAtUTF16(value, start),
+ End: text.RuneIndexAtUTF16(value, start+length),
}
}
func updateText(view unsafe.Pointer, state TextState, endsComposition, render bool) error {
- editor := text.NewEditor(state.Value)
- selectedStart := editor.RuneIndexToUTF16(state.Selection.Start)
- selectedEnd := editor.RuneIndexToUTF16(state.Selection.End)
- markedStart := editor.RuneIndexToUTF16(state.Composition.Start)
- markedEnd := editor.RuneIndexToUTF16(state.Composition.End)
+ selectedStart := text.UTF16Offset(state.Value, state.Selection.Start)
+ selectedEnd := text.UTF16Offset(state.Value, state.Selection.End)
+ markedStart := text.UTF16Offset(state.Value, state.Composition.Start)
+ markedEnd := text.UTF16Offset(state.Value, state.Composition.End)
var data *C.uchar
if state.Value != "" {
diff --git a/internal/platform/darwin/platform.go b/internal/platform/darwin/platform.go
index ca4cab14b..84397da87 100644
--- a/internal/platform/darwin/platform.go
+++ b/internal/platform/darwin/platform.go
@@ -837,7 +837,7 @@ func needsSceneShader(config Config) bool {
}
func validateTextState(state TextState) error {
- runeCount := len([]rune(state.Value))
+ runeCount := utf8.RuneCountInString(state.Value)
if !validTextRange(state.Selection, runeCount) {
return fmt.Errorf("darwin: invalid text selection %+v for %d runes", state.Selection, runeCount)
}
@@ -853,11 +853,10 @@ func validTextRange(value text.Range, length int) bool {
func makeNativeTextInput(input TextInput, value unsafe.Pointer) C.viva_text_input_config {
syncMonoFamilies()
- editor := text.NewEditor(input.State.Value)
- selectedStart := editor.RuneIndexToUTF16(input.State.Selection.Start)
- selectedEnd := editor.RuneIndexToUTF16(input.State.Selection.End)
- markedStart := editor.RuneIndexToUTF16(input.State.Composition.Start)
- markedEnd := editor.RuneIndexToUTF16(input.State.Composition.End)
+ selectedStart := text.UTF16Offset(input.State.Value, input.State.Selection.Start)
+ selectedEnd := text.UTF16Offset(input.State.Value, input.State.Selection.End)
+ markedStart := text.UTF16Offset(input.State.Value, input.State.Composition.Start)
+ markedEnd := text.UTF16Offset(input.State.Value, input.State.Composition.End)
return C.viva_text_input_config{
utf8: (*C.uchar)(value),
utf8_length: C.size_t(len(input.State.Value)),
diff --git a/internal/platform/linux/surrounding.go b/internal/platform/linux/surrounding.go
index 2678390da..26d71356b 100644
--- a/internal/platform/linux/surrounding.go
+++ b/internal/platform/linux/surrounding.go
@@ -1,6 +1,11 @@
package linux
-import "github.com/vivaui/viva/text"
+import (
+ "strings"
+ "unicode/utf8"
+
+ "github.com/vivaui/viva/text"
+)
// What an input method is told of the text around the caret, and how what it asks
// to delete maps back to the field.
@@ -25,19 +30,32 @@ type surrounding struct {
// surroundingOf builds the window from a field's state. The selection is ordered,
// so the anchor is its start and the caret its end.
+//
+// It reads the field's text in place: only the window it sends is cut out of it,
+// so a long document does not cost a copy per request.
func surroundingOf(state surroundingState) surrounding {
- runes := []rune(state.Value)
+ value := state.Value
+ count := utf8.RuneCountInString(value)
selection, composition := state.Selection, state.Composition
cutStart, cutLength := 0, 0
- if state.Composing && composition.End > composition.Start && composition.End <= len(runes) {
+ if state.Composing && composition.End > composition.Start && composition.End <= count {
+ start, end := text.ByteRange(value, composition)
+ value = value[:start] + value[end:]
cutStart, cutLength = composition.Start, composition.End-composition.Start
- runes = append(runes[:cutStart:cutStart], runes[composition.End:]...)
+ count -= cutLength
selection = text.Range{Start: cutStart, End: cutStart}
}
- selection.Start, selection.End = min(max(selection.Start, 0), len(runes)), min(max(selection.End, 0), len(runes))
- from, to := max(selection.Start-surroundingLimit, 0), min(selection.End+surroundingLimit, len(runes))
+ selection.Start, selection.End = min(max(selection.Start, 0), count), min(max(selection.End, 0), count)
+ from, to := max(selection.Start-surroundingLimit, 0), min(selection.End+surroundingLimit, count)
+ start, end := text.ByteRange(value, text.Range{Start: from, End: to})
+ window := value[start:end]
+ if !utf8.ValidString(window) {
+ // The bus carries only well-formed UTF-8; a malformed byte reads as the
+ // replacement character, as it counts as one rune of the field.
+ window = strings.ToValidUTF8(window, "\uFFFD")
+ }
result := surrounding{
- Text: string(runes[from:to]), Cursor: selection.End - from, Anchor: selection.Start - from,
+ Text: window, Cursor: selection.End - from, Anchor: selection.Start - from,
base: from, cutLength: cutLength,
}
if cutLength > 0 {
@@ -57,7 +75,7 @@ type surroundingState struct {
// caret onto the field's characters. It fails for a request outside the window,
// or one that reaches across text being composed.
func (window surrounding) fieldRange(offset, count int) (text.Range, bool) {
- length := len([]rune(window.Text))
+ length := utf8.RuneCountInString(window.Text)
start := window.Cursor + offset
end := start + count
if count <= 0 || start < 0 || end > length {
diff --git a/internal/platform/text_editing.go b/internal/platform/text_editing.go
index d4d1db8fa..d09983bb3 100644
--- a/internal/platform/text_editing.go
+++ b/internal/platform/text_editing.go
@@ -4,6 +4,7 @@ import (
"strings"
"github.com/vivaui/viva/internal/input"
+ "github.com/vivaui/viva/text"
)
// TextClipboardAction recognizes the standard clipboard chords and returns 'c',
@@ -186,13 +187,11 @@ func TextClipboardEvent(state TextState, secure bool, action byte, read func() (
if secure || action != 'c' && action != 'x' {
return TextEvent{}, false, nil
}
- runes := []rune(state.Value)
- start := max(0, min(state.Selection.Start, len(runes)))
- end := max(start, min(state.Selection.End, len(runes)))
+ start, end := text.ByteRange(state.Value, text.Range{Start: max(state.Selection.Start, 0), End: max(state.Selection.Start, state.Selection.End)})
if start == end {
return TextEvent{}, false, nil
}
- if err := write(string(runes[start:end])); err != nil {
+ if err := write(state.Value[start:end]); err != nil {
return TextEvent{}, false, err
}
if action == 'x' {
diff --git a/internal/platform/windows/ime_request_windows.go b/internal/platform/windows/ime_request_windows.go
index 3c1bc356a..071995d0f 100644
--- a/internal/platform/windows/ime_request_windows.go
+++ b/internal/platform/windows/ime_request_windows.go
@@ -2,9 +2,11 @@ package windows
import (
"unicode/utf16"
+ "unicode/utf8"
"unsafe"
"github.com/vivaui/viva/internal/platform"
+ "github.com/vivaui/viva/text"
)
// An input method asks the application about its text with WM_IME_REQUEST: where a
@@ -96,14 +98,21 @@ func (state *windowState) queryCharacterPosition(parameter uintptr) uintptr {
return 0
}
input := &state.textInput
- runes := []rune(state.textState.Value)
+ value := state.textState.Value
anchor := state.textState.Selection.End
composition := state.textState.Composition
index := anchor
- if state.textState.Composing && validTextRange(composition, len(runes)) {
+ if state.textState.Composing && validTextRange(composition, utf8.RuneCountInString(value)) {
+ // Walk the composition in place, a UTF-16 unit count at a time, to the
+ // character the request names; the field's text is not copied.
index = composition.Start
- for units := 0; index < composition.End && units < int(request.CharPos); index++ {
- units += utf16.RuneLen(runes[index])
+ units := 0
+ for _, r := range value[text.ByteOffsetOf(value, composition.Start):] {
+ if index >= composition.End || units >= int(request.CharPos) {
+ break
+ }
+ units += utf16.RuneLen(r)
+ index++
}
}
x, y, height := state.caretCell()
diff --git a/text/editor.go b/text/editor.go
index b7f52b3a0..3ce5e195c 100644
--- a/text/editor.go
+++ b/text/editor.go
@@ -108,6 +108,12 @@ type Editor struct {
// frame does not allocate; every mutation of runes clears textValid.
text string
textValid bool
+ // textBase says text is the value as it was before the edits since, and
+ // that its first keepPrefix runes and its last keepSuffix runes (the last
+ // keepSuffixBytes bytes) are still the value's: String then rebuilds only
+ // what lies between, once, however many edits came between two reads.
+ textBase bool
+ keepPrefix, keepSuffix, keepSuffixBytes int
// offsets remembers the last rune/byte pair ByteOffset and RuneIndex
// resolved, so a caret that moves or types a little is found by walking from
@@ -148,8 +154,7 @@ func (editor *Editor) String() string {
editor.compositionBaseValid = false
}
if !editor.textValid {
- editor.text = string(editor.runes)
- editor.textValid = true
+ editor.rebuildText()
}
return editor.text
}
@@ -629,7 +634,7 @@ func (editor *Editor) replaceRunes(target Range, replacement []rune, overwrite b
if lines != nil && lines.labels != nil {
lines.labels.ops.replace(lines.labels, context.line, change.removed, replacement)
}
- editor.textValid = false
+ editor.spliceText(target.Start, target.End, replacement)
editor.offsets.trim(target.Start)
delta := len(replacement) - removed
if delta > 0 {
@@ -1011,6 +1016,7 @@ func (editor *Editor) replaceExact(start, removed int, replacement []rune) {
if lines != nil && lines.labels != nil {
lines.labels.ops.replace(lines.labels, context.line, editor.runes[start:end], replacement)
}
+ editor.spliceText(start, end, replacement)
delta := len(replacement) - (end - start)
if delta > 0 {
editor.runes = append(editor.runes, make([]rune, delta)...)
@@ -1021,7 +1027,6 @@ func (editor *Editor) replaceExact(start, removed int, replacement []rune) {
}
copy(editor.runes[start:], replacement)
editor.lastReplaceStart = start
- editor.textValid = false
editor.offsets.trim(start)
editor.recordEdit(edit)
if lines != nil {
diff --git a/text/offsets.go b/text/offsets.go
index cbee80bcc..ba20f8a5b 100644
--- a/text/offsets.go
+++ b/text/offsets.go
@@ -16,6 +16,90 @@ func (memo *offsetMemo) trim(start int) {
}
}
+// spliceText records an edit that replaces runes [start, end) with replacement,
+// made before the runes change, against the cached String: the runes before start
+// and after end are still the cached text's, so the next String keeps them and
+// encodes only what changed. Keeping the bytes is a copy, where building the
+// text from every rune encodes the whole document; and an input method's many
+// small edits between two reads cost one rebuild, not one copy each.
+func (editor *Editor) spliceText(start, end int, replacement []rune) {
+ tail := len(editor.runes) - end
+ switch {
+ case editor.textValid:
+ editor.keepPrefix, editor.keepSuffix = start, tail
+ editor.keepSuffixBytes = len(editor.text) - editor.byteAt(start) - runesBytes(editor.runes[start:end])
+ editor.textValid, editor.textBase = false, true
+ case editor.textBase:
+ editor.keepPrefix = min(editor.keepPrefix, start)
+ if tail < editor.keepSuffix {
+ // The edit reaches into the kept tail: what it covers of it is no
+ // longer the cached text's.
+ editor.keepSuffixBytes -= runesBytes(editor.runes[len(editor.runes)-editor.keepSuffix : end])
+ editor.keepSuffix = tail
+ }
+ }
+}
+
+// rebuildText makes text the value again: from the cached text's kept ends and the
+// runes between them when it has them, else from every rune.
+func (editor *Editor) rebuildText() {
+ if editor.textBase {
+ middle := editor.runes[editor.keepPrefix : len(editor.runes)-editor.keepSuffix]
+ head := editor.prefixBytes(editor.keepPrefix)
+ editor.text = editor.text[:head] + string(middle) + editor.text[len(editor.text)-editor.keepSuffixBytes:]
+ } else {
+ editor.text = string(editor.runes)
+ }
+ editor.textValid, editor.textBase = true, false
+}
+
+// prefixBytes is how many bytes the first index runes take, walked from the start
+// or from the last offset asked for, which stays valid for the runes before an
+// edit. Unlike byteAt it does not read the cached text, which may be stale.
+func (editor *Editor) prefixBytes(index int) int {
+ at, offset := 0, 0
+ if editor.offsets.index <= index {
+ at, offset = editor.offsets.index, editor.offsets.offset
+ }
+ for ; at < index; at++ {
+ offset += runeBytes(editor.runes[at])
+ }
+ editor.offsets = offsetMemo{index: index, offset: offset}
+ return offset
+}
+
+func runesBytes(runes []rune) int {
+ total := 0
+ for _, character := range runes {
+ total += runeBytes(character)
+ }
+ return total
+}
+
+// byteAt is the byte offset of rune index in the cached text, walked from the
+// nearest of its start, its end and the last offset asked for, which it then
+// remembers. The cached text must be valid.
+func (editor *Editor) byteAt(index int) int {
+ at, offset := editor.offsets.index, editor.offsets.offset
+ if index < at {
+ if index <= at-index {
+ at, offset = 0, 0
+ }
+ } else if len(editor.runes)-index < index-at {
+ at, offset = len(editor.runes), len(editor.text)
+ }
+ for at < index {
+ offset += runeBytes(editor.runes[at])
+ at++
+ }
+ for at > index {
+ at--
+ offset -= runeBytes(editor.runes[at])
+ }
+ editor.offsets = offsetMemo{index: at, offset: offset}
+ return offset
+}
+
// ByteOffset converts a rune index, as Caret and Selection count, to the byte
// offset of that rune in String: what a component that works on the UTF-8 text
// wants. An index outside the text is clamped. The walk starts from whichever
diff --git a/text/text_cache_test.go b/text/text_cache_test.go
new file mode 100644
index 000000000..0d37d53c2
--- /dev/null
+++ b/text/text_cache_test.go
@@ -0,0 +1,78 @@
+package text
+
+import (
+ "math/rand/v2"
+ "strconv"
+ "strings"
+ "testing"
+)
+
+// Through any sequence of edits, the text String keeps between them is the text the
+// runes spell: typing, pasting, deleting both ways and by words, replacing a
+// selection, composing with an input method, undoing and redoing.
+func TestStringStaysTheTextAcrossEdits(t *testing.T) {
+ pieces := []string{"a", "é", "中文", "😀", "👩💻", "\n", " ", "x̣", "hello world"}
+ random := rand.New(rand.NewPCG(9, 4))
+ for round := range 300 {
+ editor := NewEditor(strings.Repeat("seed text ", random.IntN(4)))
+ _ = editor.String()
+ for step := range 60 {
+ piece := pieces[random.IntN(len(pieces))]
+ length := editor.RuneCount()
+ switch random.IntN(11) {
+ case 0, 1:
+ editor.Insert(piece)
+ case 2:
+ editor.Paste(piece + piece)
+ case 3:
+ editor.DeleteBackward()
+ case 4:
+ editor.DeleteForward()
+ case 5:
+ editor.DeleteWord(random.IntN(2) == 0)
+ case 6:
+ a, b := random.IntN(length+1), random.IntN(length+1)
+ editor.SetSelection(Range{Start: min(a, b), End: max(a, b)})
+ editor.Insert(piece)
+ case 7:
+ editor.MoveTo(random.IntN(length+1), false)
+ case 8:
+ editor.SetMarkedText(piece, Range{Start: 0, End: len([]rune(piece))})
+ if random.IntN(2) == 0 {
+ editor.Unmark()
+ } else {
+ editor.CancelComposition()
+ }
+ case 9:
+ editor.Undo()
+ case 10:
+ editor.Redo()
+ }
+ if random.IntN(3) == 0 {
+ continue // edits between two Strings still keep the cache right
+ }
+ if got, want := editor.String(), string(editor.runes); got != want {
+ t.Fatalf("round %d step %d: String() = %q, the runes spell %q", round, step, got, want)
+ }
+ }
+ }
+}
+
+// Typing in a large document costs the edit and a copy of its bytes, not encoding
+// every rune again.
+func BenchmarkTypeInLargeDocument(b *testing.B) {
+ for _, size := range []int{1 << 14, 1 << 20} {
+ b.Run(strconv.Itoa(size), func(b *testing.B) {
+ editor := NewEditor(strings.Repeat("abcdefghij", size/10))
+ editor.MoveTo(editor.RuneCount()/2, false)
+ _ = editor.String()
+ b.ReportAllocs()
+ for b.Loop() {
+ editor.Insert("x")
+ _ = editor.String()
+ editor.DeleteBackward()
+ _ = editor.String()
+ }
+ })
+ }
+}
diff --git a/text/units.go b/text/units.go
new file mode 100644
index 000000000..0c27fdd60
--- /dev/null
+++ b/text/units.go
@@ -0,0 +1,73 @@
+package text
+
+import "unicode/utf8"
+
+// The conversions between a Range, which counts runes, and the offsets a platform
+// text service counts in: bytes of UTF-8, or UTF-16 code units. They read the
+// string in place and allocate nothing, so a platform that answers every text
+// event with the selection in its own units does not copy the field's text.
+
+// ByteOffsetOf is the byte offset in value of the rune at index: the start of that
+// rune, or len(value) for an index at or past the end.
+func ByteOffsetOf(value string, index int) int {
+ if index <= 0 {
+ return 0
+ }
+ n := 0
+ for offset := range value {
+ if n == index {
+ return offset
+ }
+ n++
+ }
+ return len(value)
+}
+
+// ByteRange is r in byte offsets of value, each end clamped to it.
+func ByteRange(value string, r Range) (start, end int) {
+ return ByteOffsetOf(value, r.Start), ByteOffsetOf(value, r.End)
+}
+
+// UTF16Offset is the number of UTF-16 code units before the rune at index in
+// value: two for every rune outside the Basic Multilingual Plane, one for the
+// others. An index past the end counts the whole of value.
+func UTF16Offset(value string, index int) int {
+ units, n := 0, 0
+ for _, r := range value {
+ if n >= index {
+ break
+ }
+ units += utf16Len(r)
+ n++
+ }
+ return units
+}
+
+// RuneIndexAtUTF16 is the index of the rune that starts units UTF-16 code units
+// into value, or of the rune whose pair those units fall inside: the nearest rune
+// boundary at or before them.
+func RuneIndexAtUTF16(value string, units int) int {
+ if units <= 0 {
+ return 0
+ }
+ consumed, n := 0, 0
+ for _, r := range value {
+ width := utf16Len(r)
+ if consumed+width > units {
+ return n
+ }
+ consumed += width
+ n++
+ if consumed == units {
+ return n
+ }
+ }
+ return n
+}
+
+func utf16Len(r rune) int {
+ if r > 0xffff && r <= utf8.MaxRune {
+ return 2
+ }
+ return 1
+}
diff --git a/text/units_test.go b/text/units_test.go
new file mode 100644
index 000000000..3f9a0a2da
--- /dev/null
+++ b/text/units_test.go
@@ -0,0 +1,38 @@
+package text
+
+import (
+ "math/rand/v2"
+ "strings"
+ "testing"
+)
+
+// The string conversions agree with the editor's own, rune for rune: characters
+// outside the Basic Multilingual Plane take two UTF-16 units, a malformed byte one
+// rune and one unit, and every index past either end is clamped.
+func TestUnitConversionsAgreeWithTheEditor(t *testing.T) {
+ pieces := []string{"a", "é", "中", "😀", "👩💻", "\xff", "\n", "𝄞"}
+ random := rand.New(rand.NewPCG(1, 2))
+ for range 1000 {
+ var b strings.Builder
+ for range random.IntN(12) {
+ b.WriteString(pieces[random.IntN(len(pieces))])
+ }
+ value := b.String()
+ editor := NewEditor(value)
+ runes := []rune(value)
+ for index := -1; index <= len(runes)+1; index++ {
+ if got, want := UTF16Offset(value, index), editor.RuneIndexToUTF16(index); got != want {
+ t.Fatalf("UTF16Offset(%q, %d) = %d, want %d", value, index, got, want)
+ }
+ want := len(string(runes[:max(0, min(index, len(runes)))]))
+ if got := ByteOffsetOf(value, index); got != want && !strings.ContainsRune(value, 0xfffd) && !strings.Contains(value, "\xff") {
+ t.Fatalf("ByteOffsetOf(%q, %d) = %d, want %d", value, index, got, want)
+ }
+ }
+ for units := -1; units <= 2*len(runes)+1; units++ {
+ if got, want := RuneIndexAtUTF16(value, units), editor.UTF16ToRuneIndex(units); got != want {
+ t.Fatalf("RuneIndexAtUTF16(%q, %d) = %d, want %d", value, units, got, want)
+ }
+ }
+ }
+}
From 0c27804367811dea5dbbe0faaf0588f420fca441 Mon Sep 17 00:00:00 2001
From: t8y2 <1156263951@qq.com>
Date: Sun, 22 Nov 2026 08:59:29 +0800
Subject: [PATCH 41/47] perf(app): drop the semantic tree and payload copy
nobody read
The painter kept a semantic.Tree, its ids and a drained change list in
step with every hit, and a second copy of the accessibility payload to
tell whether it changed. Nothing outside tests read the tree: platforms
receive the flat payload. syncSemantics now updates the payload entry by
entry and reports whether any entry changed, and internal/semantic keeps
only the role enum.
On a page of 4 000 hits a structural repaint takes 412 us instead of
563 us, the first frame 133 us and 0.90 MB instead of 172 us and 1.10 MB,
and each hit retains 984 bytes instead of 1 492.
Viva-only.
---
app/accessibility_test.go | 4 -
app/painter.go | 138 ++++----------
app/painter_leak_test.go | 16 +-
app/text_input_test.go | 19 +-
internal/semantic/doc.go | 2 +-
internal/semantic/role.go | 32 ++++
internal/semantic/tree.go | 338 ---------------------------------
internal/semantic/tree_test.go | 125 ------------
8 files changed, 79 insertions(+), 595 deletions(-)
create mode 100644 internal/semantic/role.go
delete mode 100644 internal/semantic/tree.go
delete mode 100644 internal/semantic/tree_test.go
diff --git a/app/accessibility_test.go b/app/accessibility_test.go
index 530b8edb7..44be689e3 100644
--- a/app/accessibility_test.go
+++ b/app/accessibility_test.go
@@ -57,10 +57,6 @@ func TestAccessibilityNodesCarryInvalid(t *testing.T) {
if len(painter.accessibility) != 1 || !painter.accessibility[0].Invalid {
t.Fatalf("accessibility = %+v", painter.accessibility)
}
- node, ok := painter.semantics.Get(painter.semanticIDs[0])
- if !ok || !node.Invalid {
- t.Fatalf("semantic node = %+v", node)
- }
}
func TestAccessibilityPressClicksOnceAndIgnoresDisabledControls(t *testing.T) {
diff --git a/app/painter.go b/app/painter.go
index dcd57593c..980a7d7eb 100644
--- a/app/painter.go
+++ b/app/painter.go
@@ -57,23 +57,21 @@ type painter struct {
nativeText platform.TextInput
// keys follows the keys of a terminal that asked for releases (see
// TextInput.KeyReleases).
- keys interaction.Keys
- textEnabled bool
- canvas *gfx.Canvas
- size gfx.Size
- focus interaction.Focus
- pointer interaction.Pointer
- frame *framebuild.Builder
- semantics *semantic.Tree
- semanticIDs []semantic.ID
- accessibility []platform.AccessibilityNode
- lastAccess []platform.AccessibilityNode
- semanticChanges []semantic.Change
- reusedHits int // publishes that kept the previous regions and semantics
- views []platform.NativeView // the native views of this publish
- lastViews []platform.NativeView // the ones last sent
- covers []gfx.Rect // backing of the views' Covers
- hitScratch []gfx.Hit
+ keys interaction.Keys
+ textEnabled bool
+ canvas *gfx.Canvas
+ size gfx.Size
+ focus interaction.Focus
+ pointer interaction.Pointer
+ frame *framebuild.Builder
+ // accessibility is the payload the platform last received: each sync
+ // rewrites only the entries that changed, and publishes it when one did.
+ accessibility []platform.AccessibilityNode
+ reusedHits int // publishes that kept the previous regions and semantics
+ views []platform.NativeView // the native views of this publish
+ lastViews []platform.NativeView // the ones last sent
+ covers []gfx.Rect // backing of the views' Covers
+ hitScratch []gfx.Hit
// publishedHits is the hit list the regions and the semantic tree were last
// built from. Comparing it byte for byte (the strings keep the previous
// allocations alive, so equal pointers mean equal bytes) lets a repaint that
@@ -92,7 +90,6 @@ type painter struct {
publishedComposing bool
publishedTextField bool
hitsPublished bool
- semanticsDirty bool
labelNames map[gfx.ID]string
labelNamePeak int
// controls draws the window buttons of a custom titlebar, on platforms where
@@ -155,10 +152,7 @@ func newPainterWithClock(canvas *gfx.Canvas, config *Config, clock func() time.D
canvas: canvas,
size: gfx.Size{Width: float32(config.Width), Height: float32(config.Height)},
frame: framebuild.New(canvas),
- semantics: semantic.NewWithCapacity("Viva", len(canvas.Hits())+1),
- semanticIDs: make([]semantic.ID, 0, len(canvas.Hits())+1),
accessibility: make([]platform.AccessibilityNode, 0, len(canvas.Hits())+1),
- lastAccess: make([]platform.AccessibilityNode, 0, len(canvas.Hits())+1),
}
painter.onTextEvent = painter.applyTextEvent
painter.clipboardText = func() string {
@@ -191,7 +185,6 @@ func newPainterWithClock(canvas *gfx.Canvas, config *Config, clock func() time.D
}
}
painter.frame.MarkInitialBitmapUploads()
- painter.lastAccess = append(painter.lastAccess[:0], painter.accessibility...)
return painter, nil
}
@@ -1000,10 +993,9 @@ func (painter *painter) publish() (platform.Frame, error) {
// keeps the payload from the previous publish.
structuresUnchanged := painter.structuresUnchanged()
if !hitStructuresUnchanged || !structuresUnchanged {
- painter.syncSemantics(!hitStructuresUnchanged && structuresUnchanged)
+ changed := painter.syncSemantics(!hitStructuresUnchanged && structuresUnchanged)
painter.recordHitStructures()
- if !sameAccessibility(painter.accessibility, painter.lastAccess) {
- painter.lastAccess = append(painter.lastAccess[:0], painter.accessibility...)
+ if changed {
frame.Accessibility = painter.accessibility
}
}
@@ -1077,18 +1069,9 @@ func sameNativeView(a, b platform.NativeView) bool {
// the frame that was just returned remains valid; its old arrays are released
// once the platform has consumed it.
func (painter *painter) trim() {
- // A scene and semantic tree keep their free slots for reuse. That is right
- // for a page that stays large, but after a large page is replaced by a
- // small one the slots are pure retention. Rebuild both from the small
- // frame instead of carrying the peak for the rest of the session.
+ // The frame's scene keeps its free slots for reuse; after a large page is
+ // replaced by a small one it rebuilds from the small frame (Builder.Trim).
painter.frame.Trim()
- const trimAt, trimRatio = 4096, 4
- if slots := painter.semantics.Slots(); slots > trimAt && painter.semantics.Len()*trimRatio < slots {
- painter.semantics = semantic.NewWithCapacity("Viva", len(painter.hitScratch)+1)
- painter.semanticIDs = painter.semanticIDs[:0]
- painter.semanticChanges = painter.semanticChanges[:0]
- painter.semanticsDirty = true
- }
painter.canvas.Trim()
painter.focus.Trim()
painter.hitScratch = framebuild.TrimCapacity(painter.hitScratch)
@@ -1096,9 +1079,6 @@ func (painter *painter) trim() {
painter.semanticDirty = framebuild.TrimCapacity(painter.semanticDirty)
painter.publishedReturns = framebuild.TrimCapacity(painter.publishedReturns)
painter.accessibility = framebuild.TrimCapacity(painter.accessibility)
- painter.lastAccess = framebuild.TrimCapacity(painter.lastAccess)
- painter.semanticChanges = framebuild.TrimCapacity(painter.semanticChanges)
- painter.semanticIDs = framebuild.TrimCapacity(painter.semanticIDs)
if painter.labelNamePeak > 4096 && len(painter.labelNames)*4 < painter.labelNamePeak {
painter.labelNames = nil
painter.labelNamePeak = 0
@@ -1513,7 +1493,7 @@ func sameRegionHit(published, current *gfx.Hit) bool {
// publish uses it for the second check, after syncTextInput has had its say;
// the hits cannot change in between, so the expensive memcmp runs once.
func (painter *painter) structuresUnchanged() bool {
- if !painter.hitsPublished || painter.semanticsDirty || !painter.focus.PendingFocus().IsZero() {
+ if !painter.hitsPublished || !painter.focus.PendingFocus().IsZero() {
return false
}
if painter.focus.Focused() != painter.publishedFocus ||
@@ -1567,13 +1547,11 @@ func (painter *painter) recordHitStructures() {
painter.publishedComposing = painter.activeText.State.Composing
}
painter.hitsPublished = true
- painter.semanticsDirty = false
}
-// syncSemantics mirrors the canvas hit list into the retained semantic tree
-// and the flattened accessibility payload.
-func (painter *painter) syncSemantics(incremental bool) {
- root := painter.semantics.Root()
+// syncSemantics mirrors the canvas hit list into the accessibility payload, entry
+// by entry, and reports whether any entry changed: the payload to publish.
+func (painter *painter) syncSemantics(incremental bool) (changed bool) {
// Blocks are occluders, not targets: they have no accessible meaning. Labels
// are no nodes either; their words name the control they label.
hits := painter.hitScratch[:0]
@@ -1685,7 +1663,7 @@ func (painter *painter) syncSemantics(incremental bool) {
if fast && labelled && (needsLabelMap || pendingCount > 0) {
fast = false
}
- if fast && len(hits) != len(painter.semanticIDs) {
+ if fast && len(hits) != len(painter.accessibility) {
fast = false
}
if fast {
@@ -1707,21 +1685,16 @@ func (painter *painter) syncSemantics(incremental bool) {
continue
}
painter.accessibility[index] = node
- painter.semantics.Set(painter.semanticIDs[index], semanticNode(hits[index], focused))
+ changed = true
}
- painter.semanticChanges = painter.semantics.DrainChanges(painter.semanticChanges[:0])
- return
- }
- common := len(painter.semanticIDs)
- if len(hits) < common {
- common = len(hits)
+ return changed
}
// The accessible payload is compared entry by entry: a repaint that changes
- // one label must not rewrite the semantic tree or a thousand identical
- // accessibility nodes. The retained payload is also the previous entry's
- // copy, so an equal node means neither structure has anything to update.
+ // one label rewrites one node, not a thousand identical ones, and one that
+ // changes none publishes nothing.
focused := painter.focus.Focused()
previous := painter.accessibility
+ changed = len(hits) != len(previous)
if len(hits) < len(previous) {
clear(previous[len(hits):])
}
@@ -1731,29 +1704,15 @@ func (painter *painter) syncSemantics(incremental bool) {
painter.accessibility = make([]platform.AccessibilityNode, len(hits))
copy(painter.accessibility, previous)
}
- for index := 0; index < common; index++ {
+ for index := range hits {
node := painter.accessibilityNode(&hits[index], focused)
if index < len(previous) && previous[index] == node {
continue
}
painter.accessibility[index] = node
- painter.semantics.Set(painter.semanticIDs[index], semanticNode(hits[index], focused))
+ changed = true
}
- for index := common; index < len(hits); index++ {
- node := painter.accessibilityNode(&hits[index], focused)
- painter.accessibility[index] = node
- id, _ := painter.semantics.Add(root, semanticNode(hits[index], focused))
- painter.semanticIDs = append(painter.semanticIDs, id)
- }
- if len(hits) < len(painter.semanticIDs) {
- for _, id := range painter.semanticIDs[len(hits):] {
- painter.semantics.Remove(id)
- }
- painter.semanticIDs = painter.semanticIDs[:len(hits)]
- }
- // The tree is only mirrored natively below; reusing the scratch avoids
- // allocating a discarded change list every time the hit set changes.
- painter.semanticChanges = painter.semantics.DrainChanges(painter.semanticChanges[:0])
+ return changed
}
// accessibilityNode is the payload entry for one hit.
@@ -1833,27 +1792,6 @@ func (painter *painter) nameFromLabels(controls []gfx.Hit) {
}
}
-func semanticNode(hit gfx.Hit, focused gfx.ID) semantic.Node {
- return semantic.Node{
- Role: semanticRole(hit.Role),
- Label: hit.Label,
- Value: hit.Value,
- Hint: hit.Hint,
- Bounds: semantic.Rect{X: hit.Bounds.X, Y: hit.Bounds.Y, Width: hit.Bounds.Width, Height: hit.Bounds.Height},
- Focusable: hit.Focusable,
- 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,
- }
-}
-
func semanticRole(role gfx.Role) semantic.Role {
switch role {
case gfx.RoleLink:
@@ -1903,18 +1841,6 @@ func semanticRole(role gfx.Role) semantic.Role {
}
}
-func sameAccessibility(left, right []platform.AccessibilityNode) bool {
- if len(left) != len(right) {
- return false
- }
- for index := range left {
- if left[index] != right[index] {
- return false
- }
- }
- return true
-}
-
// windowActions makes the set of operations the window buttons need, for the
// platform adapter to fill, or nil when the system draws the buttons.
func (painter *painter) windowActions() *platform.WindowActions {
diff --git a/app/painter_leak_test.go b/app/painter_leak_test.go
index dfd64cb60..6f194c284 100644
--- a/app/painter_leak_test.go
+++ b/app/painter_leak_test.go
@@ -34,18 +34,18 @@ func TestAPageThatIsRemovedLeavesNothingRetained(t *testing.T) {
}
settle(0)
- scenes, semantics, rectangles := painter.frame.Graph().Len(), painter.semantics.Len(), len(painter.frame.Rectangles())
+ scenes, nodes, rectangles := painter.frame.Graph().Len(), len(painter.accessibility), len(painter.frame.Rectangles())
for round := 0; round < 5; round++ {
settle(12)
- if painter.frame.Graph().Len() <= scenes || painter.semantics.Len() <= semantics {
+ if painter.frame.Graph().Len() <= scenes || len(painter.accessibility) <= nodes {
t.Fatal("the busy page retained nothing; the test is not exercising what it claims")
}
settle(0)
if got := painter.frame.Graph().Len(); got != scenes {
t.Fatalf("round %d: the scene holds %d nodes after the page was removed, %d before it was shown", round, got, scenes)
}
- if got := painter.semantics.Len(); got != semantics {
- t.Fatalf("round %d: the semantic tree holds %d nodes after the page was removed, %d before", round, got, semantics)
+ if got := len(painter.accessibility); got != nodes {
+ t.Fatalf("round %d: the accessibility payload holds %d nodes after the page was removed, %d before", round, got, nodes)
}
if got := len(painter.frame.Rectangles()); got != rectangles {
t.Fatalf("round %d: the renderer holds %d rectangles after the page was removed, %d before", round, got, rectangles)
@@ -72,11 +72,11 @@ func TestALargePageThenASmallOneReleasesSlots(t *testing.T) {
}
}
settle(5000)
- if painter.frame.Graph().Slots() < 5000 || painter.semantics.Slots() < 5000 {
- t.Fatalf("the large page did not allocate its slots: graph=%d semantics=%d", painter.frame.Graph().Slots(), painter.semantics.Slots())
+ if painter.frame.Graph().Slots() < 5000 || cap(painter.accessibility) < 5000 {
+ t.Fatalf("the large page did not allocate its slots: graph=%d accessibility=%d", painter.frame.Graph().Slots(), cap(painter.accessibility))
}
settle(1)
- if painter.frame.Graph().Slots() > 64 || painter.semantics.Slots() > 64 {
- t.Fatalf("the small page kept the large page's slots: graph=%d semantics=%d", painter.frame.Graph().Slots(), painter.semantics.Slots())
+ if painter.frame.Graph().Slots() > 64 || cap(painter.accessibility) > 4096 {
+ t.Fatalf("the small page kept the large page's slots: graph=%d accessibility=%d", painter.frame.Graph().Slots(), cap(painter.accessibility))
}
}
diff --git a/app/text_input_test.go b/app/text_input_test.go
index ac779ebee..2cf895baa 100644
--- a/app/text_input_test.go
+++ b/app/text_input_test.go
@@ -323,23 +323,16 @@ func TestSecureFieldIsMaskedForThePlatformAndSilentForAccessibility(t *testing.T
if enabled == nil || !enabled.Secure {
t.Fatalf("the platform was not told to mask the field: %+v", enabled)
}
+ checked := 0
for _, node := range painter.accessibility {
if node.Value != "" || strings.Contains(node.Label, "hunter2") {
t.Fatalf("native accessibility node exposes the password: %+v", node)
}
- if node.Role == uint8(semantic.RoleTextField) && !node.Secure {
- t.Fatalf("native accessibility node is not marked secure: %+v", node)
- }
- }
- checked := 0
- for _, id := range painter.semanticIDs {
- node, ok := painter.semantics.Get(id)
- if !ok || node.Role != semantic.RoleTextField {
- continue
- }
- checked++
- if node.Value != "" || !node.Secure {
- t.Fatalf("semantic node = %+v, want a secure field without a value", node)
+ if node.Role == uint8(semantic.RoleTextField) {
+ if !node.Secure {
+ t.Fatalf("native accessibility node is not marked secure: %+v", node)
+ }
+ checked++
}
}
if checked != 1 {
diff --git a/internal/semantic/doc.go b/internal/semantic/doc.go
index 5d4fd671a..c24b23cb6 100644
--- a/internal/semantic/doc.go
+++ b/internal/semantic/doc.go
@@ -1,2 +1,2 @@
-// Package semantic owns the platform-neutral accessibility tree.
+// Package semantic names the platform-neutral accessibility roles.
package semantic
diff --git a/internal/semantic/role.go b/internal/semantic/role.go
new file mode 100644
index 000000000..9284a8c55
--- /dev/null
+++ b/internal/semantic/role.go
@@ -0,0 +1,32 @@
+package semantic
+
+// Role describes the accessible purpose of a node: the platform-neutral role an
+// accessibility node carries to each platform's own.
+type Role uint8
+
+const (
+ RoleApplication Role = iota + 1
+ RoleGroup
+ RoleButton
+ RoleText
+ RoleTextField
+ RoleCheckbox
+ RoleSlider
+ RoleImage
+ RoleLink
+ RoleRadio
+ RoleTab
+ RoleMenuItem
+ RoleCombobox
+ RoleSwitch
+ RoleMenu
+ RoleMenubar
+ RoleListBox
+ RoleOption
+ RoleGrid
+ RoleGridCell
+ RoleHeading
+ RoleStatus
+ RoleSeparator
+ RoleProgress
+)
diff --git a/internal/semantic/tree.go b/internal/semantic/tree.go
deleted file mode 100644
index 36a256ac0..000000000
--- a/internal/semantic/tree.go
+++ /dev/null
@@ -1,338 +0,0 @@
-package semantic
-
-// ID is a stable generational semantic-node identity.
-type ID uint64
-
-// Role describes the accessible purpose of a node.
-type Role uint8
-
-const (
- RoleApplication Role = iota + 1
- RoleGroup
- RoleButton
- RoleText
- RoleTextField
- RoleCheckbox
- RoleSlider
- RoleImage
- RoleLink
- RoleRadio
- RoleTab
- RoleMenuItem
- RoleCombobox
- RoleSwitch
- RoleMenu
- RoleMenubar
- RoleListBox
- RoleOption
- RoleGrid
- RoleGridCell
- RoleHeading
- RoleStatus
- RoleSeparator
- RoleProgress
-)
-
-// Operation describes an incremental accessibility-tree update.
-type Operation uint8
-
-const (
- OperationUpsert Operation = iota + 1
- OperationDelete
-)
-
-// Rect is an accessibility bounds rectangle in logical window pixels.
-type Rect struct {
- X float32
- Y float32
- Width float32
- Height float32
-}
-
-// Node describes platform-neutral accessible state.
-type Node struct {
- Role Role
- Label string
- Value string
- Hint string
- Bounds Rect
- Focusable bool
- Focused bool
- Disabled bool
- Checked bool
- Mixed bool
- Selected bool
- Expanded bool
- Multiline bool
- ReadOnly bool
- // Invalid marks a control whose value failed validation.
- Invalid bool
- Secure bool
- Hidden bool
-}
-
-// Change is one coalesced platform accessibility update.
-type Change struct {
- ID ID
- Operation Operation
- Parent ID
- PreviousSibling ID
- Node Node
-}
-
-type entry struct {
- parent ID
- firstChild ID
- lastChild ID
- previous ID
- next ID
- data Node
- generation uint32
- alive bool
- queued bool
- published bool
- pendingFree bool
-}
-
-// Tree stores semantic nodes independently from visual scene nodes.
-type Tree struct {
- nodes []entry
- free []uint32
- dirty []ID
- scratch []ID
- root ID
-}
-
-// New creates a semantic tree with an application root.
-func New(label string) *Tree {
- tree := &Tree{nodes: make([]entry, 1, 8), dirty: make([]ID, 0, 8)}
- tree.nodes[0] = entry{
- data: Node{Role: RoleApplication, Label: label},
- generation: 1,
- alive: true,
- }
- tree.root = makeID(0, 1)
- tree.markDirty(tree.root, &tree.nodes[0])
- return tree
-}
-
-// NewWithCapacity creates a tree sized for an expected total node count.
-func NewWithCapacity(label string, capacity int) *Tree {
- if capacity < 1 {
- capacity = 1
- }
- tree := New(label)
- nodes := make([]entry, 1, capacity)
- nodes[0] = tree.nodes[0]
- tree.nodes = nodes
- tree.dirty = make([]ID, 0, capacity)
- tree.nodes[0].queued = false
- tree.markDirty(tree.root, &tree.nodes[0])
- return tree
-}
-
-// Root returns the permanent application root.
-func (tree *Tree) Root() ID {
- return tree.root
-}
-
-// Add appends a semantic node below parent.
-func (tree *Tree) Add(parent ID, data Node) (ID, bool) {
- parentNode, ok := tree.live(parent)
- if !ok || data.Role == 0 || data.Role == RoleApplication {
- return 0, false
- }
- index := tree.allocate()
- parentNode, _ = tree.live(parent)
- current := &tree.nodes[index]
- current.parent = parent
- current.data = data
- current.alive = true
- id := makeID(index, current.generation)
- if parentNode.lastChild == 0 {
- parentNode.firstChild = id
- parentNode.lastChild = id
- } else {
- last, _ := tree.live(parentNode.lastChild)
- last.next = id
- current.previous = parentNode.lastChild
- parentNode.lastChild = id
- }
- tree.markDirty(id, current)
- return id, true
-}
-
-// Set updates one node and coalesces repeated changes.
-func (tree *Tree) Set(id ID, data Node) bool {
- current, ok := tree.live(id)
- if !ok || data.Role == 0 || (id != tree.root && data.Role == RoleApplication) {
- return false
- }
- if current.data == data {
- return false
- }
- current.data = data
- tree.markDirty(id, current)
- return true
-}
-
-// Get returns one live semantic node.
-func (tree *Tree) Get(id ID) (Node, bool) {
- current, ok := tree.live(id)
- if !ok {
- return Node{}, false
- }
- return current.data, true
-}
-
-// Remove deletes a semantic subtree. The application root cannot be removed.
-func (tree *Tree) Remove(id ID) bool {
- current, ok := tree.live(id)
- if !ok || id == tree.root {
- return false
- }
- tree.detach(current)
- tree.scratch = append(tree.scratch[:0], id)
- for cursor := 0; cursor < len(tree.scratch); cursor++ {
- currentID := tree.scratch[cursor]
- currentNode, exists := tree.live(currentID)
- if !exists {
- continue
- }
- for child := currentNode.firstChild; child != 0; {
- childNode, childExists := tree.live(child)
- if !childExists {
- break
- }
- next := childNode.next
- tree.scratch = append(tree.scratch, child)
- child = next
- }
- }
- for index := len(tree.scratch) - 1; index >= 0; index-- {
- currentID := tree.scratch[index]
- currentNode, exists := tree.live(currentID)
- if exists {
- currentNode.alive = false
- currentNode.pendingFree = true
- tree.markDirty(currentID, currentNode)
- }
- }
- return true
-}
-
-// DrainChanges appends coalesced semantic changes to destination.
-func (tree *Tree) DrainChanges(destination []Change) []Change {
- for _, id := range tree.dirty {
- index, current, ok := tree.entry(id)
- if !ok || !current.queued {
- continue
- }
- current.queued = false
- if current.pendingFree {
- if current.published {
- destination = append(destination, Change{ID: id, Operation: OperationDelete})
- }
- tree.reclaim(index, current)
- continue
- }
- destination = append(destination, Change{
- ID: id,
- Operation: OperationUpsert,
- Parent: current.parent,
- PreviousSibling: current.previous,
- Node: current.data,
- })
- current.published = true
- }
- tree.dirty = tree.dirty[:0]
- return destination
-}
-
-// PendingChanges returns the number of distinct dirty semantic nodes.
-func (tree *Tree) PendingChanges() int {
- return len(tree.dirty)
-}
-
-func (tree *Tree) detach(current *entry) {
- parent, _ := tree.live(current.parent)
- if current.previous == 0 {
- parent.firstChild = current.next
- } else {
- previous, _ := tree.live(current.previous)
- previous.next = current.next
- }
- if current.next == 0 {
- parent.lastChild = current.previous
- } else {
- next, _ := tree.live(current.next)
- next.previous = current.previous
- }
-}
-
-func (tree *Tree) allocate() uint32 {
- if len(tree.free) == 0 {
- index := uint32(len(tree.nodes))
- tree.nodes = append(tree.nodes, entry{generation: 1})
- return index
- }
- last := len(tree.free) - 1
- index := tree.free[last]
- tree.free = tree.free[:last]
- generation := tree.nodes[index].generation
- tree.nodes[index] = entry{generation: generation}
- return index
-}
-
-func (tree *Tree) reclaim(index uint32, current *entry) {
- nextGeneration := current.generation + 1
- if nextGeneration == 0 {
- nextGeneration = 1
- }
- *current = entry{generation: nextGeneration}
- tree.free = append(tree.free, index)
-}
-
-func (tree *Tree) markDirty(id ID, current *entry) {
- if current.queued {
- return
- }
- current.queued = true
- tree.dirty = append(tree.dirty, id)
-}
-
-func (tree *Tree) live(id ID) (*entry, bool) {
- _, current, ok := tree.entry(id)
- return current, ok && current.alive
-}
-
-func (tree *Tree) entry(id ID) (uint32, *entry, bool) {
- index, generation, ok := splitID(id)
- if !ok || int(index) >= len(tree.nodes) {
- return 0, nil, false
- }
- current := &tree.nodes[index]
- if current.generation != generation {
- return 0, nil, false
- }
- return index, current, true
-}
-
-func makeID(index uint32, generation uint32) ID {
- return ID(uint64(generation)<<32 | uint64(index+1))
-}
-
-func splitID(id ID) (uint32, uint32, bool) {
- index := uint32(id)
- generation := uint32(uint64(id) >> 32)
- if index == 0 || generation == 0 {
- return 0, 0, false
- }
- return index - 1, generation, true
-}
-
-// Len is how many nodes are alive, the root included.
-func (tree *Tree) Len() int { return len(tree.nodes) - len(tree.free) }
-
-// Slots is how many node slots the tree has ever allocated; see Scene.Slots.
-func (tree *Tree) Slots() int { return len(tree.nodes) }
diff --git a/internal/semantic/tree_test.go b/internal/semantic/tree_test.go
deleted file mode 100644
index c08d4b2a3..000000000
--- a/internal/semantic/tree_test.go
+++ /dev/null
@@ -1,125 +0,0 @@
-package semantic
-
-import "testing"
-
-func TestTreeCoalescesLocalizedUpdates(t *testing.T) {
- tree := New("Viva")
- button, ok := tree.Add(tree.Root(), Node{Role: RoleButton, Label: "Save", Focusable: true})
- if !ok {
- t.Fatal("failed to add button")
- }
- tree.DrainChanges(nil)
-
- for index := 0; index < 100; index++ {
- tree.Set(button, Node{Role: RoleButton, Label: "Save", Value: string(rune('A' + index%26)), Focusable: true})
- }
- if tree.PendingChanges() != 1 {
- t.Fatalf("pending changes = %d, want 1", tree.PendingChanges())
- }
- changes := tree.DrainChanges(nil)
- if len(changes) != 1 || changes[0].ID != button || changes[0].Operation != OperationUpsert {
- t.Fatalf("changes = %+v", changes)
- }
- if changes := tree.DrainChanges(changes[:0]); len(changes) != 0 {
- t.Fatalf("unchanged drain produced %d changes", len(changes))
- }
-}
-
-func TestNewWithCapacityPublishesApplicationRoot(t *testing.T) {
- tree := NewWithCapacity("Viva", 10_000)
- changes := tree.DrainChanges(nil)
- if len(changes) != 1 || changes[0].ID != tree.Root() || changes[0].Node.Role != RoleApplication {
- t.Fatalf("initial changes = %+v", changes)
- }
-}
-
-func TestTreeDeletesChildrenBeforeParentAndRejectsStaleID(t *testing.T) {
- tree := New("Viva")
- group, _ := tree.Add(tree.Root(), Node{Role: RoleGroup})
- child, _ := tree.Add(group, Node{Role: RoleText, Label: "Child"})
- tree.DrainChanges(nil)
-
- if !tree.Remove(group) {
- t.Fatal("failed to remove group")
- }
- changes := tree.DrainChanges(nil)
- if len(changes) != 2 || changes[0].ID != child || changes[1].ID != group {
- t.Fatalf("delete order = %+v", changes)
- }
- reused, _ := tree.Add(tree.Root(), Node{Role: RoleButton})
- if reused == group || tree.Set(group, Node{Role: RoleGroup}) {
- t.Fatal("stale semantic ID remained valid")
- }
-}
-
-func TestTreeDropsUnpublishedCreateDelete(t *testing.T) {
- tree := New("Viva")
- tree.DrainChanges(nil)
- node, _ := tree.Add(tree.Root(), Node{Role: RoleText})
- tree.Remove(node)
- if changes := tree.DrainChanges(nil); len(changes) != 0 {
- t.Fatalf("unpublished node produced changes: %+v", changes)
- }
-}
-
-func TestTreeEmitsInvalidChange(t *testing.T) {
- tree := New("Viva")
- field, ok := tree.Add(tree.Root(), Node{Role: RoleTextField, Label: "Email", Focusable: true})
- if !ok {
- t.Fatal("failed to add field")
- }
- tree.DrainChanges(nil)
-
- tree.Set(field, Node{Role: RoleTextField, Label: "Email", Focusable: true, Invalid: true})
- changes := tree.DrainChanges(nil)
- if len(changes) != 1 || changes[0].ID != field || !changes[0].Node.Invalid {
- t.Fatalf("invalid change = %+v", changes)
- }
-
- tree.Set(field, Node{Role: RoleTextField, Label: "Email", Focusable: true})
- changes = tree.DrainChanges(changes[:0])
- if len(changes) != 1 || changes[0].Node.Invalid {
- t.Fatalf("valid change = %+v", changes)
- }
-}
-
-func BenchmarkSemanticNoChanges(b *testing.B) {
- tree, output, _ := benchmarkTree(b, 10_000)
- b.ReportAllocs()
- b.ResetTimer()
- for range b.N {
- output = tree.DrainChanges(output[:0])
- }
-}
-
-func BenchmarkSemanticLocalizedUpdate(b *testing.B) {
- tree, output, target := benchmarkTree(b, 10_000)
- b.ReportAllocs()
- b.ResetTimer()
- for index := range b.N {
- data := Node{Role: RoleButton, Label: "Button", Value: "0", Focusable: true}
- if index&1 == 0 {
- data.Value = "1"
- }
- tree.Set(target, data)
- output = tree.DrainChanges(output[:0])
- if len(output) != 1 {
- b.Fatalf("change count = %d", len(output))
- }
- }
-}
-
-func benchmarkTree(b *testing.B, count int) (*Tree, []Change, ID) {
- b.Helper()
- tree := NewWithCapacity("Viva", count+1)
- var target ID
- for index := 0; index < count; index++ {
- id, _ := tree.Add(tree.Root(), Node{Role: RoleButton, Label: "Button", Value: "0", Focusable: true})
- if index == count/2 {
- target = id
- }
- }
- output := make([]Change, 0, count+1)
- output = tree.DrainChanges(output)
- return tree, output[:0], target
-}
From 98bab0a937f466865e5a307ea87fcf8282178c55 Mon Sep 17 00:00:00 2001
From: t8y2 <1156263951@qq.com>
Date: Sun, 22 Nov 2026 09:14:33 +0800
Subject: [PATCH 42/47] fix(components): place select and combobox lists by the
popup rule
SingleSelect, MultiSelect and the hierarchy menu placed their lists with
their own rule (placePopupBelow and an inline copy of it): open above
whenever a 40 px row fit there, even when below had more room. They use
PlaceOverlay now, the rule popovers, menus and submenus follow: flip to
the side with more room. OverlayPlacement.Fit shortens the overlay to the
room on that side, as the positioner's size step does for a list that
scrolls, instead of shifting it back over its trigger.
The paired Motty commit places its three hand-positioned lists with it.
---
components/hierarchy_menu.go | 20 +-------------------
components/multi_select.go | 14 +-------------
components/place_list_test.go | 34 ++++++++++++++++++++++++++++++++++
components/popover.go | 31 +++++++++++++++++++++++++++++++
components/single_select.go | 2 +-
5 files changed, 68 insertions(+), 33 deletions(-)
create mode 100644 components/place_list_test.go
diff --git a/components/hierarchy_menu.go b/components/hierarchy_menu.go
index f35fd3f5c..afafc51ec 100644
--- a/components/hierarchy_menu.go
+++ b/components/hierarchy_menu.go
@@ -187,7 +187,7 @@ func PaintHierarchyMenu(canvas *gfx.Canvas, theme gfx.Theme, anchor gfx.Rect, m
}
popup := gfx.Rect{X: left, Y: anchor.Y + anchor.Height + 6, Width: widths[l], Height: height}
if l == first {
- placePopupBelow(&popup, anchor, height, o.Viewport)
+ placeList(&popup, anchor, height, o.Viewport)
} else {
prev, trigger := m.Panels[l-1], m.Triggers[l-1]
popup.X, popup.Y = prev.X+prev.Width-4, trigger.Y-4
@@ -407,24 +407,6 @@ func panelWidths(m *HierarchyMenuState, canvas *gfx.Canvas, theme gfx.Theme, anc
return widths, left, reverse
}
-// placePopupBelow keeps a popup inside the viewport: above the anchor when that
-// holds a usable row and below does not fit, shortened to what room is left.
-func placePopupBelow(popup *gfx.Rect, anchor gfx.Rect, height float32, viewport gfx.Rect) {
- if viewport.Height > 0 {
- top, bottom := viewport.Y+1, viewport.Y+viewport.Height-1
- if popup.Y+popup.Height > bottom {
- // Prefer the room above the anchor, but only when it holds a usable
- // row; otherwise the list scrolls inside what is left below.
- if above := anchor.Y - 6 - top; above >= min(height, 40) {
- popup.Height = min(height, above)
- popup.Y = anchor.Y - popup.Height - 6
- }
- }
- popup.Y = max(top, min(popup.Y, bottom-1))
- popup.Height = max(1, min(popup.Height, bottom-popup.Y))
- }
-}
-
// unionRect is the smallest rect holding both; the first rect starts it.
func unionRect(a, b gfx.Rect, first bool) gfx.Rect {
if first {
diff --git a/components/multi_select.go b/components/multi_select.go
index 507214a6a..1d6894306 100644
--- a/components/multi_select.go
+++ b/components/multi_select.go
@@ -131,19 +131,7 @@ func PaintMultiSelect(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, s *M
}
height := float32(max(1, min(len(choices), rows))*32 + 8)
layout.Popup = gfx.Rect{X: bounds.X, Y: bounds.Y + bounds.Height + 6, Width: bounds.Width, Height: height}
- if o.Viewport.Height > 0 {
- top, bottom := o.Viewport.Y+1, o.Viewport.Y+o.Viewport.Height-1
- if layout.Popup.Y+layout.Popup.Height > bottom {
- // Prefer room above for at least one usable row. Otherwise scroll
- // inside the space left below, even when that is less than a row.
- if above := bounds.Y - 6 - top; above >= min(height, 40) {
- layout.Popup.Height = min(height, above)
- layout.Popup.Y = bounds.Y - layout.Popup.Height - 6
- }
- }
- layout.Popup.Y = max(top, min(layout.Popup.Y, bottom-1))
- layout.Popup.Height = max(1, min(layout.Popup.Height, bottom-layout.Popup.Y))
- }
+ placeList(&layout.Popup, bounds, height, o.Viewport)
if floating {
canvas.PushOverlayClip(o.Viewport)
defer canvas.PopOverlayClip()
diff --git a/components/place_list_test.go b/components/place_list_test.go
new file mode 100644
index 000000000..cee5b3232
--- /dev/null
+++ b/components/place_list_test.go
@@ -0,0 +1,34 @@
+package components
+
+import (
+ "testing"
+
+ "github.com/vivaui/viva/gfx"
+)
+
+// A list goes to the side of its trigger with more room and is shortened to that
+// room, never covering the trigger: a trigger low in the window with a short
+// space below and a larger one above opens up; with more room below it stays
+// below even when the room above would hold a few rows.
+func TestAListOpensOnTheSideWithMoreRoom(t *testing.T) {
+ viewport := gfx.Rect{Width: 400, Height: 400}
+ cases := []struct {
+ name string
+ trigger gfx.Rect
+ above bool
+ }{
+ {"room above", gfx.Rect{X: 10, Y: 330, Width: 120, Height: 32}, true},
+ {"more room below", gfx.Rect{X: 10, Y: 60, Width: 120, Height: 32}, false},
+ }
+ for _, c := range cases {
+ popup := gfx.Rect{X: c.trigger.X, Width: c.trigger.Width}
+ placeList(&popup, c.trigger, 600, viewport)
+ if popup.Y < viewport.Y || popup.Y+popup.Height > viewport.Y+viewport.Height {
+ t.Fatalf("%s: list %v leaves the window", c.name, popup)
+ }
+ overlaps := popup.Y < c.trigger.Y+c.trigger.Height && popup.Y+popup.Height > c.trigger.Y
+ if overlaps || (popup.Y < c.trigger.Y) != c.above {
+ t.Fatalf("%s: list %v against trigger %v, want above=%v without covering it", c.name, popup, c.trigger, c.above)
+ }
+ }
+}
diff --git a/components/popover.go b/components/popover.go
index f4a10e86f..36f0cce47 100644
--- a/components/popover.go
+++ b/components/popover.go
@@ -298,6 +298,10 @@ type OverlayPlacement struct {
AlignOffset float32
// Margin is the distance the overlay keeps from the viewport's edges.
Margin float32
+ // Fit shortens the overlay to the room on the side it ends up on, as the
+ // positioner's size step does for a list that scrolls, instead of shifting
+ // it back over its anchor. The side is chosen first, by the same flip.
+ Fit bool
}
// PlaceOverlay returns where an overlay of size goes beside anchor inside
@@ -322,9 +326,36 @@ func PlaceOverlay(anchor gfx.Rect, size gfx.Size, viewport gfx.Rect, placement O
bounds, side = flipped, opposite
}
}
+ if placement.Fit {
+ switch side {
+ case OverlayBottom:
+ size.Height = min(size.Height, max(bottom-(anchor.Y+anchor.Height+placement.SideOffset), 1))
+ case OverlayTop:
+ size.Height = min(size.Height, max(anchor.Y-placement.SideOffset-top, 1))
+ case OverlayRight:
+ size.Width = min(size.Width, max(right-(anchor.X+anchor.Width+placement.SideOffset), 1))
+ case OverlayLeft:
+ size.Width = min(size.Width, max(anchor.X-placement.SideOffset-left, 1))
+ }
+ bounds = overlayBeside(anchor, size, side, placement)
+ }
return overlayClamp(bounds, viewport, placement.Margin), side
}
+// placeList puts a select's or a combobox's list, of its own left and width and
+// of height, under the trigger: flipped above when that has more room, and
+// shortened to the room it has, so the list scrolls instead of covering the
+// trigger. It is PlaceOverlay's rule, the one every popup of the theme follows.
+func placeList(popup *gfx.Rect, trigger gfx.Rect, height float32, viewport gfx.Rect) {
+ if viewport.Width <= 0 || viewport.Height <= 0 {
+ return
+ }
+ anchor := gfx.Rect{X: popup.X, Y: trigger.Y, Width: popup.Width, Height: trigger.Height}
+ *popup, _ = PlaceOverlay(anchor, gfx.Size{Width: popup.Width, Height: height}, viewport, OverlayPlacement{
+ Side: OverlayBottom, Align: OverlayAlignStart, SideOffset: 6, Margin: 1, Fit: true,
+ })
+}
+
func overlayOpposite(side OverlaySide) OverlaySide {
switch side {
case OverlayTop:
diff --git a/components/single_select.go b/components/single_select.go
index 7adba2ed8..6684087c6 100644
--- a/components/single_select.go
+++ b/components/single_select.go
@@ -172,7 +172,7 @@ func PaintSingleSelect(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, s *
layout.Popup.X = max(o.Viewport.X+1, min(layout.Popup.X, o.Viewport.X+o.Viewport.Width-1-layout.Popup.Width))
}
}
- placePopupBelow(&layout.Popup, bounds, height, o.Viewport)
+ placeList(&layout.Popup, bounds, height, o.Viewport)
if floating {
canvas.PushOverlayClip(o.Viewport)
defer canvas.PopOverlayClip()
From c9b165f12b6513967801e006221be24472acfebe Mon Sep 17 00:00:00 2001
From: t8y2 <1156263951@qq.com>
Date: Sun, 22 Nov 2026 09:21:54 +0800
Subject: [PATCH 43/47] fix(components): animate single and multi select lists
like a Select
SingleSelect (ui.Combobox) and MultiSelect opened and closed their lists
at once, while Select, Popover and the menus faded and slid them from the
trigger's side. They begin the same presence around the list now, keyed
as a Select's is, so the exit keeps the list's last frame.
Viva-only.
---
components/multi_select.go | 6 +++++
components/select_presence_test.go | 38 ++++++++++++++++++++++++++++++
components/single_select.go | 6 +++++
3 files changed, 50 insertions(+)
create mode 100644 components/select_presence_test.go
diff --git a/components/multi_select.go b/components/multi_select.go
index 1d6894306..d26f5e694 100644
--- a/components/multi_select.go
+++ b/components/multi_select.go
@@ -137,6 +137,12 @@ func PaintMultiSelect(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, s *M
defer canvas.PopOverlayClip()
}
canvas.Block(layout.Popup)
+ // The list enters and leaves as a select's does: faded and slid from the
+ // trigger's side, its last frame kept while it leaves.
+ side := popupSideOf(layout.Popup, bounds)
+ canvas.BeginPresence(overlayKey(o.TriggerID, o.DismissID, o.Scope), overlaySurfacePart,
+ popupPresence(theme, overlayDuration, side), popupPivot(layout.Popup, side, bounds))
+ defer canvas.EndPresence()
canvas.Container(layout.Popup, gfx.RoleListBox, o.Label)
paintPopupSurface(canvas, &theme, layout.Popup, gfx.ShadowMD)
s.ScrollArea().BarID = o.ScrollID
diff --git a/components/select_presence_test.go b/components/select_presence_test.go
new file mode 100644
index 000000000..86b6c3562
--- /dev/null
+++ b/components/select_presence_test.go
@@ -0,0 +1,38 @@
+package components
+
+import (
+ "testing"
+ "time"
+
+ "github.com/vivaui/viva/gfx"
+)
+
+// A single select's list enters and leaves over frames, as a Select's does,
+// instead of appearing and vanishing at once.
+func TestSingleSelectListAnimates(t *testing.T) {
+ var canvas gfx.Canvas
+ now := time.Duration(0)
+ canvas.SetClock(func() time.Duration { return now })
+ state := &SingleSelectState{Open: true}
+ state.SetOptions([]SingleSelectOption{{Value: "alpha", Label: "alpha"}, {Value: "beta", Label: "beta"}})
+ paint := func() {
+ canvas.Reset()
+ canvas.BeginFrame()
+ PaintSingleSelect(&canvas, gfx.LightTheme(), gfx.Rect{X: 10, Y: 10, Width: 160, Height: 32}, state, SingleSelectOptions{
+ TriggerID: gfx.Item(1), DismissID: gfx.Item(2), Scope: gfx.Item(3),
+ Viewport: gfx.Rect{Width: 400, Height: 400},
+ })
+ canvas.EndFrame()
+ }
+ paint()
+ if _, animating := canvas.NextFrame(); !animating {
+ t.Fatal("an opening list asked for no next frame")
+ }
+ for range 30 {
+ now += 16 * time.Millisecond
+ paint()
+ }
+ if _, animating := canvas.NextFrame(); animating {
+ t.Fatal("the list was still animating half a second after it opened")
+ }
+}
diff --git a/components/single_select.go b/components/single_select.go
index 6684087c6..b2ef692b4 100644
--- a/components/single_select.go
+++ b/components/single_select.go
@@ -178,6 +178,12 @@ func PaintSingleSelect(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, s *
defer canvas.PopOverlayClip()
}
canvas.Block(layout.Popup)
+ // The list enters and leaves as a select's does: faded and slid from the
+ // trigger's side, its last frame kept while it leaves.
+ side := popupSideOf(layout.Popup, bounds)
+ canvas.BeginPresence(overlayKey(o.TriggerID, o.DismissID, o.Scope), overlaySurfacePart,
+ popupPresence(theme, overlayDuration, side), popupPivot(layout.Popup, side, bounds))
+ defer canvas.EndPresence()
canvas.Container(layout.Popup, gfx.RoleListBox, o.Label)
paintPopupSurface(canvas, &theme, layout.Popup, gfx.ShadowMD)
s.Scroll.BarID = o.ScrollID
From 4ad1fd1b30986e11b11d94a2c7b614167b3617ef Mon Sep 17 00:00:00 2001
From: t8y2 <1156263951@qq.com>
Date: Sun, 22 Nov 2026 09:31:56 +0800
Subject: [PATCH 44/47] fix(base): let go what a shrunken page held in its
reused arrays
Every frame refills its slices from zero, and a slice cut short keeps
what it held in its array: a page that stopped showing a 1 MB picture
kept it reachable through the frame's Images, the canvas's images, the
frame builder's last images and labels, and the painter's hit lists,
along with CustomLayouts and the strings of rows that were gone. Each of
those lists now records its length at the end of a frame and clears what
the next frame does not reach of it, a cost of what it shrank by, not of
its capacity; the canvas swaps the records with the lists a Memo keeps.
trimFlexCapacity also counts bytes, so 776-byte Extras no longer stay at
4 096 before a page that shrank gives them back.
Viva-only.
---
app/painter.go | 15 ++++++++----
base/frame.go | 35 +++++++++++++++++++--------
base/scratch.go | 27 ++++++++++++++++++---
gfx/canvas.go | 9 +++++++
gfx/replay.go | 16 +++++++++++++
internal/framebuild/framebuild.go | 19 +++++++++++++++
ui/frame_release_test.go | 39 +++++++++++++++++++++++++++++++
7 files changed, 142 insertions(+), 18 deletions(-)
create mode 100644 ui/frame_release_test.go
diff --git a/app/painter.go b/app/painter.go
index 980a7d7eb..03d8d69bf 100644
--- a/app/painter.go
+++ b/app/painter.go
@@ -67,11 +67,13 @@ type painter struct {
// accessibility is the payload the platform last received: each sync
// rewrites only the entries that changed, and publishes it when one did.
accessibility []platform.AccessibilityNode
- reusedHits int // publishes that kept the previous regions and semantics
- views []platform.NativeView // the native views of this publish
- lastViews []platform.NativeView // the ones last sent
- covers []gfx.Rect // backing of the views' Covers
- hitScratch []gfx.Hit
+ // tails are the lengths of the hit lists at the last trim; see ReleaseTail.
+ tails struct{ hitScratch, publishedHits, accessibility int }
+ reusedHits int // publishes that kept the previous regions and semantics
+ views []platform.NativeView // the native views of this publish
+ lastViews []platform.NativeView // the ones last sent
+ covers []gfx.Rect // backing of the views' Covers
+ hitScratch []gfx.Hit
// publishedHits is the hit list the regions and the semantic tree were last
// built from. Comparing it byte for byte (the strings keep the previous
// allocations alive, so equal pointers mean equal bytes) lets a repaint that
@@ -1074,6 +1076,9 @@ func (painter *painter) trim() {
painter.frame.Trim()
painter.canvas.Trim()
painter.focus.Trim()
+ framebuild.ReleaseTail(painter.hitScratch, &painter.tails.hitScratch)
+ framebuild.ReleaseTail(painter.publishedHits, &painter.tails.publishedHits)
+ framebuild.ReleaseTail(painter.accessibility, &painter.tails.accessibility)
painter.hitScratch = framebuild.TrimCapacity(painter.hitScratch)
painter.publishedHits = framebuild.TrimCapacity(painter.publishedHits)
painter.semanticDirty = framebuild.TrimCapacity(painter.semanticDirty)
diff --git a/base/frame.go b/base/frame.go
index fb07317b1..ced2c0644 100644
--- a/base/frame.go
+++ b/base/frame.go
@@ -284,14 +284,18 @@ type Frame struct {
Ellipses []gfx.EllipsisCache // the cut-off ends of wrapped texts, kept between frames
Wraps []wrapCache // the full line sets of wrapped texts, kept between frames
wrapCursor int
- scratch scratch // memory the layout borrows, see scratch.go
- layoutCtx LayoutContext // the context a CustomLayout is handed, reused
- Scrolls scrollStore // the ScrollStates of the page's ScrollAreas, by identity
- Parent int32
- bounds Rect
- gen uint32 // the paint this frame is declaring; a Box names it
- shiftedX bool // a CustomLayout moved children after their width was solved
- done bool
+ // tails is how long each reused slice that holds pointers was when the last
+ // frame ended: what lies past its length up to there is the last frame's,
+ // cleared by releaseTail so a page that shrank does not keep it reachable.
+ tails frameTails
+ scratch scratch // memory the layout borrows, see scratch.go
+ layoutCtx LayoutContext // the context a CustomLayout is handed, reused
+ Scrolls scrollStore // the ScrollStates of the page's ScrollAreas, by identity
+ Parent int32
+ bounds Rect
+ gen uint32 // the paint this frame is declaring; a Box names it
+ shiftedX bool // a CustomLayout moved children after their width was solved
+ done bool
}
// view keeps the memory a page is laid out in between frames. It is the engine
@@ -428,14 +432,25 @@ func (f *Frame) End() {
// (Rect, Clicked, TabClicked and so on) stay valid.
func (f *Frame) trim() {
// Cache entries past the wrapped texts this frame declared belong to a
- // larger page that is gone. Drop them before trimming the outer slices so
- // their strings do not stay reachable.
+ // larger page that is gone: they are cut off here and cleared below.
if f.wrapCursor < len(f.Wraps) {
f.Wraps = f.Wraps[:f.wrapCursor]
}
if f.wrapCursor < len(f.Ellipses) {
f.Ellipses = f.Ellipses[:f.wrapCursor]
}
+ // A slice cut short keeps what it held in its array: a picture an Image no
+ // longer shows, a CustomLayout, the strings of rows that are gone. Clear what
+ // this frame did not reach of what the last one did.
+ releaseTail(f.Nodes, &f.tails.nodes)
+ releaseTail(f.Exts, &f.tails.exts)
+ releaseTail(f.Images, &f.tails.images)
+ releaseTail(f.Lines, &f.tails.lines)
+ releaseTail(f.addons, &f.tails.addons)
+ releaseTail(f.States, &f.tails.states)
+ releaseTail(f.Stops, &f.tails.stops)
+ releaseTail(f.Wraps, &f.tails.wraps)
+ releaseTail(f.Ellipses, &f.tails.ellipses)
f.layoutCtx.children = trimFlexCapacity(f.layoutCtx.children)
f.Nodes = trimFlexCapacity(f.Nodes)
f.Images = trimFlexCapacity(f.Images)
diff --git a/base/scratch.go b/base/scratch.go
index a4aa212eb..d6da402bb 100644
--- a/base/scratch.go
+++ b/base/scratch.go
@@ -1,5 +1,7 @@
package base
+import "unsafe"
+
// scratch is the memory the layout borrows beyond the node tree, reused from frame to
// frame so a warm page allocates nothing.
type scratch struct {
@@ -12,13 +14,32 @@ type scratch struct {
func (s *scratch) reset() { s.abs = s.abs[:0] }
+// frameTails is the length each pointer-holding slice of a Frame had when the
+// last frame ended.
+type frameTails struct {
+ nodes, exts, images, lines, addons, states, stops, wraps, ellipses int
+}
+
+// releaseTail clears items[len(items):*end], what the last frame held past this
+// one's length, and records this length for the next. Everything past it was
+// cleared before, so the cost is what the slice shrank by, not its capacity.
+func releaseTail[T any](items []T, end *int) {
+ if *end > len(items) && *end <= cap(items) {
+ clear(items[len(items):*end])
+ }
+ *end = len(items)
+}
+
// trimFlexCapacity gives back a slice's backing array when it is far larger
// than its content. A page that once had a large table should not keep that
-// capacity for the view's whole life.
+// capacity for the view's whole life. Large is counted in elements and in
+// bytes: 4096 small ones, or 64 KiB of large ones such as a 776-byte Extra.
func trimFlexCapacity[T any](Items []T) []T {
- const minCapacity = 4096
+ const minCapacity, minBytes = 4096, 64 << 10
const ratio = 4
- if cap(Items) <= minCapacity || len(Items)*ratio >= cap(Items) {
+ var zero T
+ large := cap(Items) > minCapacity || uintptr(cap(Items))*unsafe.Sizeof(zero) > minBytes
+ if !large || len(Items)*ratio >= cap(Items) {
return Items
}
next := make([]T, len(Items), max(len(Items)*2, minCapacity/64))
diff --git a/gfx/canvas.go b/gfx/canvas.go
index a5b7db416..6ed8793e8 100644
--- a/gfx/canvas.go
+++ b/gfx/canvas.go
@@ -689,6 +689,7 @@ type Canvas struct {
triangles []Triangle
shadows []Shadow
images []Image
+ tails canvasTails // see releaseTail
nativeViews []NativeView
texts []Text
runs []TextRun
@@ -1060,6 +1061,14 @@ func (canvas *Canvas) Trim() {
if canvas.previous.keep {
canvas.trimPrevious()
}
+ // A list cut short by Reset keeps what it held in its array: a picture no
+ // longer drawn, the labels of hits that are gone. Clear what this paint did
+ // not reach of what an earlier one did.
+ releaseTail(canvas.images, &canvas.tails.images)
+ releaseTail(canvas.texts, &canvas.tails.texts)
+ releaseTail(canvas.hits, &canvas.tails.hits)
+ releaseTail(canvas.hitTexts, &canvas.tails.hitTexts)
+ releaseTail(canvas.nativeViews, &canvas.tails.nativeViews)
canvas.rectangles = trimCapacity(canvas.rectangles)
canvas.triangles = trimCapacity(canvas.triangles)
canvas.shadows = trimCapacity(canvas.shadows)
diff --git a/gfx/replay.go b/gfx/replay.go
index 6c3849839..081745b26 100644
--- a/gfx/replay.go
+++ b/gfx/replay.go
@@ -430,6 +430,21 @@ type previousPaint struct {
keep bool
epoch uint32
lists primitiveLists
+ tails canvasTails // the lists' tails, kept with them as they swap
+}
+
+// canvasTails is how long each pointer-holding list of a paint was when the
+// canvas last trimmed it: what lies past its length up to there is stale.
+type canvasTails struct{ images, texts, hits, hitTexts, nativeViews int }
+
+// releaseTail clears items[len(items):*end], what an earlier paint held past this
+// one's length, and records this length. Everything past it was cleared before,
+// so the cost is what the list shrank by, not its capacity.
+func releaseTail[T any](items []T, end *int) {
+ if *end > len(items) && *end <= cap(items) {
+ clear(items[len(items):*end])
+ }
+ *end = len(items)
}
// rotate starts a paint: with keep, the lists just painted become the previous
@@ -449,6 +464,7 @@ func (canvas *Canvas) rotate() {
canvas.hits, old.hits = old.hits[:0], canvas.hits
canvas.hitTexts, old.hitTexts = old.hitTexts[:0], canvas.hitTexts
canvas.nativeViews, old.nativeViews = old.nativeViews[:0], canvas.nativeViews
+ canvas.tails, canvas.previous.tails = canvas.previous.tails, canvas.tails
}
// trimPrevious gives back the previous paint's arrays after a large page, as Trim
diff --git a/internal/framebuild/framebuild.go b/internal/framebuild/framebuild.go
index 4219dfde2..1e34fee67 100644
--- a/internal/framebuild/framebuild.go
+++ b/internal/framebuild/framebuild.go
@@ -69,6 +69,7 @@ type Builder struct {
// back among the shapes.
clippedTextBefores []uint32
clippedImageBefores []uint32
+ tails struct{ labels, lastTexts, lastImages, clippedTexts, clippedImages int }
}
// New returns a builder for the canvas's current primitives.
@@ -171,6 +172,13 @@ func (builder *Builder) Trim() {
// replacements are stale retention.
builder.cellReplace = builder.cellReplace[:0]
}
+ // Lists refilled from zero keep what an earlier frame put past their length:
+ // pictures and label strings of a page that shrank. Clear that first.
+ ReleaseTail(builder.labels, &builder.tails.labels)
+ ReleaseTail(builder.lastTexts, &builder.tails.lastTexts)
+ ReleaseTail(builder.lastImages, &builder.tails.lastImages)
+ ReleaseTail(builder.clippedTexts, &builder.tails.clippedTexts)
+ ReleaseTail(builder.clippedImages, &builder.tails.clippedImages)
builder.shapeIDs = TrimCapacity(builder.shapeIDs)
builder.labels = TrimCapacity(builder.labels)
builder.lastTexts = TrimCapacity(builder.lastTexts)
@@ -193,6 +201,17 @@ func (builder *Builder) Trim() {
builder.changes = TrimCapacity(builder.changes)
}
+// ReleaseTail clears items[len(items):*end], what an earlier frame held past this
+// one's length, and records this length for the next call. Everything past it was
+// cleared before, so the cost is what the list shrank by, not its capacity: call
+// it once a frame on a list that is refilled from zero and holds pointers.
+func ReleaseTail[T any](items []T, end *int) {
+ if *end > len(items) && *end <= cap(items) {
+ clear(items[len(items):*end])
+ }
+ *end = len(items)
+}
+
// TrimCapacity gives back a slice's backing array when it is far larger than
// its contents. The contents are kept, so a frame already returned remains
// valid; its old array is released.
diff --git a/ui/frame_release_test.go b/ui/frame_release_test.go
new file mode 100644
index 000000000..4b6f590e7
--- /dev/null
+++ b/ui/frame_release_test.go
@@ -0,0 +1,39 @@
+package ui_test
+
+import (
+ "runtime"
+ "testing"
+ "time"
+
+ "github.com/vivaui/viva/ui"
+)
+
+// A picture the page stops showing is the garbage collector's once the frame
+// that last showed it is past: the frame's reused arrays do not keep it.
+func TestAPictureThePageNoLongerShowsIsReleased(t *testing.T) {
+ show := true
+ released := make(chan struct{}, 1)
+ pixels := make([]byte, 1<<20)
+ runtime.AddCleanup(&pixels[0], func(chan struct{}) { released <- struct{}{} }, released)
+ bitmap := ui.Bitmap{Pix: pixels, Width: 512, Height: 512, Stride: 2048, ID: 1}
+ pixels = nil
+ d := openPage(t, func(c ui.C) {
+ ui.Text(c, "gallery")
+ if show {
+ ui.Image(c, bitmap).Size(64, 64)
+ }
+ })
+ show, bitmap = false, ui.Bitmap{}
+ for range 3 {
+ d.repaint()
+ }
+ for range 20 {
+ runtime.GC()
+ select {
+ case <-released:
+ return
+ case <-time.After(10 * time.Millisecond):
+ }
+ }
+ t.Fatal("the picture is still reachable after the page stopped showing it")
+}
From 3b0da7079366a265ecb796d433f0bfff2e8bb460 Mon Sep 17 00:00:00 2001
From: t8y2 <1156263951@qq.com>
Date: Sun, 22 Nov 2026 09:47:33 +0800
Subject: [PATCH 45/47] perf(windows): call COM methods without allocating per
call
comCall was variadic and marked uintptrescapes, so every one of its 284
call sites allocated its argument slice, and every value whose address
a draw passed escaped to the heap: the frame constants, viewport, clear
color and a scissor per batch and per label, and a color and a matrix
per run of text in Direct2D. comCall0 to comCall7 take a fixed number of
arguments, and the values the draw loop and the text target hand over by
address live in the renderer and the target, as the Direct2D clip
already did. The test of the variadic limit goes with it.
Checked on the physical Windows machine: the renderer, Direct2D and text
tests pass; three that fail over SSH fail the same without this change.
Viva-only.
---
internal/platform/windows/api_windows.go | 61 ++++++--
internal/platform/windows/api_windows_test.go | 11 +-
.../platform/windows/composition_windows.go | 12 +-
internal/platform/windows/device_windows.go | 4 +-
.../windows/direct_call_windows_amd64.go | 2 +-
.../platform/windows/direct_ink_windows.go | 2 +-
internal/platform/windows/direct_windows.go | 28 ++--
.../platform/windows/dock_progress_windows.go | 6 +-
.../platform/windows/drag_windows_test.go | 58 +++----
internal/platform/windows/drop_windows.go | 4 +-
.../platform/windows/drop_windows_test.go | 12 +-
.../platform/windows/fidelity_windows_test.go | 2 +-
.../platform/windows/font_fallback_windows.go | 8 +-
.../platform/windows/font_register_windows.go | 20 +--
.../platform/windows/font_weights_windows.go | 10 +-
.../platform/windows/fonts_direct_windows.go | 12 +-
.../windows/fonts_direct_windows_test.go | 4 +-
.../platform/windows/grid_cache_windows.go | 10 +-
.../platform/windows/label_picture_windows.go | 6 +-
.../platform/windows/offscreen_windows.go | 14 +-
internal/platform/windows/renderer_windows.go | 135 +++++++++-------
.../platform/windows/save_checkbox_windows.go | 6 +-
internal/platform/windows/system_windows.go | 32 ++--
.../platform/windows/taskbar_icon_windows.go | 4 +-
internal/platform/windows/text_windows.go | 26 ++--
.../platform/windows/textengine_windows.go | 22 +--
internal/platform/windows/trim_windows.go | 6 +-
.../windows/web_bounds_windows_amd64.go | 2 +-
.../windows/web_bounds_windows_other.go | 2 +-
internal/platform/windows/web_windows.go | 144 +++++++++---------
internal/platform/windows/webview2_windows.go | 6 +-
.../window_icon_update_windows_test.go | 2 +-
.../windows/window_resize_windows_test.go | 6 +-
33 files changed, 369 insertions(+), 310 deletions(-)
diff --git a/internal/platform/windows/api_windows.go b/internal/platform/windows/api_windows.go
index 74c2cffc5..8e0ab2470 100644
--- a/internal/platform/windows/api_windows.go
+++ b/internal/platform/windows/api_windows.go
@@ -54,20 +54,63 @@ 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
+// 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
+// call site needs.
+
//go:uintptrescapes
-func comCall(object uintptr, index int, arguments ...uintptr) uintptr {
- var values [16]uintptr
- if len(arguments) >= len(values) {
- panic("windows: COM call exceeds argument limit")
- }
- values[0] = object
- copy(values[1:], arguments)
- result, _, _ := syscall.SyscallN(vtable(object, index), values[:len(arguments)+1]...)
+func comCall0(object uintptr, index int) uintptr {
+ result, _, _ := syscall.SyscallN(vtable(object, index), object)
+ return result
+}
+
+//go:uintptrescapes
+func comCall1(object uintptr, index int, a0 uintptr) uintptr {
+ result, _, _ := syscall.SyscallN(vtable(object, index), object, a0)
+ return result
+}
+
+//go:uintptrescapes
+func comCall2(object uintptr, index int, a0 uintptr, a1 uintptr) uintptr {
+ result, _, _ := syscall.SyscallN(vtable(object, index), object, a0, a1)
+ return result
+}
+
+//go:uintptrescapes
+func comCall3(object uintptr, index int, a0 uintptr, a1 uintptr, a2 uintptr) uintptr {
+ result, _, _ := syscall.SyscallN(vtable(object, index), object, a0, a1, a2)
return result
}
+
+//go:uintptrescapes
+func comCall4(object uintptr, index int, a0 uintptr, a1 uintptr, a2 uintptr, a3 uintptr) uintptr {
+ result, _, _ := syscall.SyscallN(vtable(object, index), object, a0, a1, a2, a3)
+ return result
+}
+
+//go:uintptrescapes
+func comCall5(object uintptr, index int, a0 uintptr, a1 uintptr, a2 uintptr, a3 uintptr, a4 uintptr) uintptr {
+ result, _, _ := syscall.SyscallN(vtable(object, index), object, a0, a1, a2, a3, a4)
+ return result
+}
+
+//go:uintptrescapes
+func comCall6(object uintptr, index int, a0 uintptr, a1 uintptr, a2 uintptr, a3 uintptr, a4 uintptr, a5 uintptr) uintptr {
+ result, _, _ := syscall.SyscallN(vtable(object, index), object, a0, a1, a2, a3, a4, a5)
+ return result
+}
+
+//go:uintptrescapes
+func comCall7(object uintptr, index int, a0 uintptr, a1 uintptr, a2 uintptr, a3 uintptr, a4 uintptr, a5 uintptr, a6 uintptr) uintptr {
+ result, _, _ := syscall.SyscallN(vtable(object, index), object, a0, a1, a2, a3, a4, a5, a6)
+ return result
+}
+
func release(object *uintptr) {
if *object != 0 {
- comCall(*object, 2)
+ comCall0(*object, 2)
*object = 0
}
}
diff --git a/internal/platform/windows/api_windows_test.go b/internal/platform/windows/api_windows_test.go
index eb95872b1..be8262130 100644
--- a/internal/platform/windows/api_windows_test.go
+++ b/internal/platform/windows/api_windows_test.go
@@ -123,18 +123,9 @@ func TestCOMCallKeepsPointersAlive(t *testing.T) {
table := [1]uintptr{callback}
object := struct{ Table *uintptr }{Table: &table[0]}
var output uint64
- status := comCall(uintptr(unsafe.Pointer(&object)), 0, uintptr(unsafe.Pointer(&output)))
+ status := comCall1(uintptr(unsafe.Pointer(&object)), 0, uintptr(unsafe.Pointer(&output)))
if status != 1 || output != 0x123456789abcdef0 {
t.Fatalf("COM call lost Go output pointer: %#x, %#x", status, output)
}
runtime.KeepAlive(table)
}
-
-func TestCOMCallArgumentLimit(t *testing.T) {
- defer func() {
- if recover() == nil {
- t.Fatal("overlong COM call was not rejected")
- }
- }()
- comCall(0, 0, make([]uintptr, 16)...)
-}
diff --git a/internal/platform/windows/composition_windows.go b/internal/platform/windows/composition_windows.go
index aad4eb88c..33246c8db 100644
--- a/internal/platform/windows/composition_windows.go
+++ b/internal/platform/windows/composition_windows.go
@@ -64,7 +64,7 @@ func (renderer *renderer) createCompositionDevice(software bool) error {
defer release(&factory)
desc := compositionSwapDesc{Width: 1, Height: 1, Format: 87, Samples: 1, Usage: 0x20, Buffers: 2, SwapEffect: 3, AlphaMode: 1}
// IDXGIFactory2::CreateSwapChainForComposition.
- if err := hresult(comCall(factory, 24, renderer.device, uintptr(unsafe.Pointer(&desc)), 0, uintptr(unsafe.Pointer(&renderer.swap)))); err != nil {
+ if err := hresult(comCall4(factory, 24, renderer.device, uintptr(unsafe.Pointer(&desc)), 0, uintptr(unsafe.Pointer(&renderer.swap)))); err != nil {
return err
}
// A null rendering device is valid when visuals contain swap chains only.
@@ -73,18 +73,18 @@ func (renderer *renderer) createCompositionDevice(software bool) error {
return err
}
// IDCompositionDevice::CreateTargetForHwnd, CreateVisual.
- if err := hresult(comCall(renderer.compositionDevice, 6, renderer.window, 1, uintptr(unsafe.Pointer(&renderer.compositionTarget)))); err != nil {
+ if err := hresult(comCall3(renderer.compositionDevice, 6, renderer.window, 1, uintptr(unsafe.Pointer(&renderer.compositionTarget)))); err != nil {
return err
}
- if err := hresult(comCall(renderer.compositionDevice, 7, uintptr(unsafe.Pointer(&renderer.compositionVisual)))); err != nil {
+ if err := hresult(comCall1(renderer.compositionDevice, 7, uintptr(unsafe.Pointer(&renderer.compositionVisual)))); err != nil {
return err
}
// IDCompositionVisual::SetContent; IDCompositionTarget::SetRoot.
- if err := hresult(comCall(renderer.compositionVisual, 15, renderer.swap)); err != nil {
+ if err := hresult(comCall1(renderer.compositionVisual, 15, renderer.swap)); err != nil {
return err
}
- if err := hresult(comCall(renderer.compositionTarget, 3, renderer.compositionVisual)); err != nil {
+ if err := hresult(comCall1(renderer.compositionTarget, 3, renderer.compositionVisual)); err != nil {
return err
}
- return hresult(comCall(renderer.compositionDevice, 3)) // Commit
+ return hresult(comCall0(renderer.compositionDevice, 3)) // Commit
}
diff --git a/internal/platform/windows/device_windows.go b/internal/platform/windows/device_windows.go
index 7ba75b62a..834fc182d 100644
--- a/internal/platform/windows/device_windows.go
+++ b/internal/platform/windows/device_windows.go
@@ -19,7 +19,7 @@ import (
// itself (ID3D11Device::GetDeviceRemovedReason), which any failing call can then
// be blamed on.
func (renderer *renderer) deviceLost() bool {
- return renderer.device != 0 && platform.DeviceLostCode(uint32(comCall(renderer.device, 39)))
+ return renderer.device != 0 && platform.DeviceLostCode(uint32(comCall0(renderer.device, 39)))
}
// recover makes the device, the swap chain and the pipeline again, on the
@@ -37,7 +37,7 @@ func (renderer *renderer) recover(software bool) error {
return err
}
region := box{Right: uint32(len(renderer.instances) * rectangleInstanceBytes), Bottom: 1, Back: 1}
- comCall(renderer.context, 48, renderer.buffer, 0, uintptr(unsafe.Pointer(®ion)), uintptr(unsafe.Pointer(&renderer.instances[0])), 0, 0)
+ comCall6(renderer.context, 48, renderer.buffer, 0, uintptr(unsafe.Pointer(®ion)), uintptr(unsafe.Pointer(&renderer.instances[0])), 0, 0)
return nil
}
diff --git a/internal/platform/windows/direct_call_windows_amd64.go b/internal/platform/windows/direct_call_windows_amd64.go
index da4769041..803149034 100644
--- a/internal/platform/windows/direct_call_windows_amd64.go
+++ b/internal/platform/windows/direct_call_windows_amd64.go
@@ -9,7 +9,7 @@ type directTextCall struct{}
func (*directTarget) initTextCall() {}
func (target *directTarget) drawTextLayout(x, y float32, layout uintptr, options uint32) {
- comCall(target.target, d2dDrawTextLayout, pointArgument(x, y), layout, target.brush, uintptr(options))
+ comCall4(target.target, d2dDrawTextLayout, pointArgument(x, y), layout, target.brush, uintptr(options))
}
func pointArgument(x, y float32) uintptr {
diff --git a/internal/platform/windows/direct_ink_windows.go b/internal/platform/windows/direct_ink_windows.go
index c7fb18117..f8d1e8c02 100644
--- a/internal/platform/windows/direct_ink_windows.go
+++ b/internal/platform/windows/direct_ink_windows.go
@@ -118,7 +118,7 @@ func (rasterizer *directRasterizer) measureInk(key inkKey) (platform.GridInk, er
}
defer release(&layout)
var metrics textMetrics
- if err := hresult(comCall(layout, writeGetMetrics, uintptr(unsafe.Pointer(&metrics)))); err != nil {
+ if err := hresult(comCall1(layout, writeGetMetrics, uintptr(unsafe.Pointer(&metrics)))); err != nil {
return platform.GridInk{}, err
}
// The cell sits in the middle of the bitmap with a size of room on each side, which is
diff --git a/internal/platform/windows/direct_windows.go b/internal/platform/windows/direct_windows.go
index d415d93e7..081068ee1 100644
--- a/internal/platform/windows/direct_windows.go
+++ b/internal/platform/windows/direct_windows.go
@@ -71,6 +71,8 @@ type directTarget struct {
scratch *textBitmap
width, height int // of the scratch bitmap
clip struct{ Left, Top, Right, Bottom float32 } // the rectangle pushClip hands Direct2D, kept here so that it is not allocated
+ color d2dColor // what setColor hands Direct2D, kept for the same reason
+ matrix d2dMatrix // what setTransform hands Direct2D
}
// d2dMatrix is D2D1_MATRIX_3X2_F: x' = M11*x + M21*y + DX, y' = M12*x + M22*y + DY.
@@ -85,12 +87,12 @@ func newDirectTarget(factory uintptr, alphaMode uint32) (*directTarget, error) {
// device; 96 dpi: label sizes are device pixels already.
properties := d2dRenderTargetProperties{Type: 1, Format: 87, AlphaMode: alphaMode, DPIX: 96, DPIY: 96}
var target uintptr
- if err := hresult(comCall(factory, d2dFactoryCreateDCTarget, uintptr(unsafe.Pointer(&properties)), uintptr(unsafe.Pointer(&target)))); err != nil {
+ if err := hresult(comCall2(factory, d2dFactoryCreateDCTarget, uintptr(unsafe.Pointer(&properties)), uintptr(unsafe.Pointer(&target)))); err != nil {
return nil, fmt.Errorf("windows: create Direct2D target: %w", err)
}
white := d2dColor{R: 1, G: 1, B: 1, A: 1}
direct := &directTarget{target: target}
- if err := hresult(comCall(target, d2dCreateSolidColorBrush, uintptr(unsafe.Pointer(&white)), 0, uintptr(unsafe.Pointer(&direct.brush)))); err != nil {
+ if err := hresult(comCall3(target, d2dCreateSolidColorBrush, uintptr(unsafe.Pointer(&white)), 0, uintptr(unsafe.Pointer(&direct.brush)))); err != nil {
direct.close()
return nil, fmt.Errorf("windows: create Direct2D brush: %w", err)
}
@@ -116,7 +118,7 @@ func (target *directTarget) bind(width, height int) (*textBitmap, error) {
return nil, err
}
bounds := rect{Right: int32(grown.Width), Bottom: int32(grown.Height)}
- if err := hresult(comCall(target.target, d2dBindDC, grown.dc, uintptr(unsafe.Pointer(&bounds)))); err != nil {
+ if err := hresult(comCall2(target.target, d2dBindDC, grown.dc, uintptr(unsafe.Pointer(&bounds)))); err != nil {
grown.close()
return nil, fmt.Errorf("windows: bind Direct2D target: %w", err)
}
@@ -131,28 +133,30 @@ func (target *directTarget) bind(width, height int) (*textBitmap, error) {
// begin sets the color and the antialiasing mode and starts drawing. The scratch bitmap
// holds the background: Direct2D draws over it.
func (target *directTarget) begin(foreground d2dColor, mode uint32) {
- comCall(target.brush, d2dSetColor, uintptr(unsafe.Pointer(&foreground)))
- comCall(target.target, d2dSetTextAntialiasMode, uintptr(mode))
- comCall(target.target, d2dBeginDraw)
+ target.setColor(foreground)
+ comCall1(target.target, d2dSetTextAntialiasMode, uintptr(mode))
+ comCall0(target.target, d2dBeginDraw)
}
func (target *directTarget) setColor(color d2dColor) {
- comCall(target.brush, d2dSetColor, uintptr(unsafe.Pointer(&color)))
+ target.color = color
+ comCall1(target.brush, d2dSetColor, uintptr(unsafe.Pointer(&target.color)))
}
func (target *directTarget) setTransform(matrix d2dMatrix) {
- comCall(target.target, d2dSetTransform, uintptr(unsafe.Pointer(&matrix)))
+ target.matrix = matrix
+ comCall1(target.target, d2dSetTransform, uintptr(unsafe.Pointer(&target.matrix)))
}
// pushClip limits what is drawn to the device columns [left, right) of a label height rows
// high, until popClip. The rectangle is in the target's transform, so push it before setting one.
func (target *directTarget) pushClip(left, right, height int) {
target.clip.Left, target.clip.Top, target.clip.Right, target.clip.Bottom = float32(left), 0, float32(right), float32(height)
- comCall(target.target, d2dPushAxisAlignedClip, uintptr(unsafe.Pointer(&target.clip)), d2dClipAliased)
+ comCall2(target.target, d2dPushAxisAlignedClip, uintptr(unsafe.Pointer(&target.clip)), d2dClipAliased)
}
func (target *directTarget) popClip() {
- comCall(target.target, d2dPopAxisAlignedClip)
+ comCall0(target.target, d2dPopAxisAlignedClip)
}
func (target *directTarget) draw(x, y float32, layout uintptr, options uint32) {
@@ -160,7 +164,7 @@ func (target *directTarget) draw(x, y float32, layout uintptr, options uint32) {
}
func (target *directTarget) end() error {
- if err := hresult(comCall(target.target, d2dEndDraw, 0, 0)); err != nil {
+ if err := hresult(comCall2(target.target, d2dEndDraw, 0, 0)); err != nil {
return fmt.Errorf("windows: end Direct2D drawing: %w", err)
}
return nil
@@ -407,7 +411,7 @@ func (rasterizer *directRasterizer) batchTarget(translucent bool) (*directTarget
// rectangle instead of to the bitmap's corner.
func (target *directTarget) pushClipRect(left, top, right, bottom int) {
target.clip.Left, target.clip.Top, target.clip.Right, target.clip.Bottom = float32(left), float32(top), float32(right), float32(bottom)
- comCall(target.target, d2dPushAxisAlignedClip, uintptr(unsafe.Pointer(&target.clip)), d2dClipAliased)
+ comCall2(target.target, d2dPushAxisAlignedClip, uintptr(unsafe.Pointer(&target.clip)), d2dClipAliased)
}
// fill sets the top left width by height pixels of the bitmap to color.
diff --git a/internal/platform/windows/dock_progress_windows.go b/internal/platform/windows/dock_progress_windows.go
index c9882b46c..4f56bbc64 100644
--- a/internal/platform/windows/dock_progress_windows.go
+++ b/internal/platform/windows/dock_progress_windows.go
@@ -64,9 +64,9 @@ func (application *windowsApplication) SetProgress(fraction float32) {
windowStates.Range(func(key, value any) bool {
window := value.(*windowState)
if window.application == application && window.window != 0 {
- comCall(list, taskbarSetProgressState, window.window, state)
+ comCall2(list, taskbarSetProgressState, window.window, state)
if known {
- comCall(list, taskbarSetProgressValue, window.window, done, progressScale)
+ comCall3(list, taskbarSetProgressValue, window.window, done, progressScale)
}
}
return true
@@ -95,7 +95,7 @@ func (application *windowsApplication) taskbarList() uintptr {
if hresult(status) != nil || list == 0 {
return 0
}
- if status := comCall(list, taskbarInit); hresult(status) != nil {
+ if status := comCall0(list, taskbarInit); hresult(status) != nil {
release(&list)
return 0
}
diff --git a/internal/platform/windows/drag_windows_test.go b/internal/platform/windows/drag_windows_test.go
index 29f736550..469bc8f0a 100644
--- a/internal/platform/windows/drag_windows_test.go
+++ b/internal/platform/windows/drag_windows_test.go
@@ -36,11 +36,11 @@ func TestTheDataObjectHandsOutTheFilesAsADropList(t *testing.T) {
data, object := newDragObject(paths)
defer runtime.KeepAlive(data)
format := fileFormat()
- if status := uint32(comCall(object, 5, uintptr(unsafe.Pointer(&format)))); status != sOK {
+ if status := uint32(comCall1(object, 5, uintptr(unsafe.Pointer(&format)))); status != sOK {
t.Fatalf("QueryGetData = %#x, want S_OK", status)
}
var medium storageMedium
- if status := uint32(comCall(object, 3, uintptr(unsafe.Pointer(&format)), uintptr(unsafe.Pointer(&medium)))); status != sOK {
+ if status := uint32(comCall2(object, 3, uintptr(unsafe.Pointer(&format)), uintptr(unsafe.Pointer(&medium)))); status != sOK {
t.Fatalf("GetData = %#x, want S_OK", status)
}
defer releaseStgMedium.Call(uintptr(unsafe.Pointer(&medium)))
@@ -64,7 +64,7 @@ func TestTheDataObjectHandsOutTheFilesAsADropList(t *testing.T) {
// Every answer is the target's own memory: a second question cannot be given
// the block the first one took.
var again storageMedium
- if status := uint32(comCall(object, 3, uintptr(unsafe.Pointer(&format)), uintptr(unsafe.Pointer(&again)))); status != sOK {
+ if status := uint32(comCall2(object, 3, uintptr(unsafe.Pointer(&format)), uintptr(unsafe.Pointer(&again)))); status != sOK {
t.Fatalf("the second GetData = %#x, want S_OK", status)
}
defer releaseStgMedium.Call(uintptr(unsafe.Pointer(&again)))
@@ -79,30 +79,30 @@ func TestTheDataObjectRefusesWhatItDoesNotOffer(t *testing.T) {
data, object := newDragObject([]string{`C:\Temp\one.txt`})
defer runtime.KeepAlive(data)
text := formatEtc{Format: 13 /* CF_UNICODETEXT */, Aspect: dvAspectContent, Index: lindexNone, Medium: tymedHGlobal}
- if status := uint32(comCall(object, 5, uintptr(unsafe.Pointer(&text)))); status != dvEFormatEtc {
+ if status := uint32(comCall1(object, 5, uintptr(unsafe.Pointer(&text)))); status != dvEFormatEtc {
t.Errorf("QueryGetData of text = %#x, want DV_E_FORMATETC", status)
}
var medium storageMedium
- if status := uint32(comCall(object, 3, uintptr(unsafe.Pointer(&text)), uintptr(unsafe.Pointer(&medium)))); status != dvEFormatEtc {
+ if status := uint32(comCall2(object, 3, uintptr(unsafe.Pointer(&text)), uintptr(unsafe.Pointer(&medium)))); status != dvEFormatEtc {
t.Errorf("GetData of text = %#x, want DV_E_FORMATETC", status)
}
thumbnail := fileFormat()
thumbnail.Aspect = 2 // DVASPECT_THUMBNAIL
- if status := uint32(comCall(object, 5, uintptr(unsafe.Pointer(&thumbnail)))); status != dvEFormatEtc {
+ if status := uint32(comCall1(object, 5, uintptr(unsafe.Pointer(&thumbnail)))); status != dvEFormatEtc {
t.Errorf("QueryGetData of a thumbnail = %#x, want DV_E_FORMATETC", status)
}
stream := fileFormat()
stream.Medium = 4 // TYMED_ISTREAM
- if status := uint32(comCall(object, 5, uintptr(unsafe.Pointer(&stream)))); status != dvEFormatEtc {
+ if status := uint32(comCall1(object, 5, uintptr(unsafe.Pointer(&stream)))); status != dvEFormatEtc {
t.Errorf("QueryGetData of a stream = %#x, want DV_E_FORMATETC", status)
}
- if status := uint32(comCall(object, 4, uintptr(unsafe.Pointer(&stream)), uintptr(unsafe.Pointer(&medium)))); status != eNotImpl {
+ if status := uint32(comCall2(object, 4, uintptr(unsafe.Pointer(&stream)), uintptr(unsafe.Pointer(&medium)))); status != eNotImpl {
t.Errorf("GetDataHere = %#x, want E_NOTIMPL", status)
}
- if status := uint32(comCall(object, 9, uintptr(unsafe.Pointer(&stream)), 0, 0, 0)); status != oleEAdviseNotSupported {
+ if status := uint32(comCall4(object, 9, uintptr(unsafe.Pointer(&stream)), 0, 0, 0)); status != oleEAdviseNotSupported {
t.Errorf("DAdvise = %#x, want OLE_E_ADVISENOTSUPPORTED", status)
}
- if status := uint32(comCall(object, 10, 1)); status != oleEAdviseNotSupported {
+ if status := uint32(comCall1(object, 10, 1)); status != oleEAdviseNotSupported {
t.Errorf("DUnadvise = %#x, want OLE_E_ADVISENOTSUPPORTED", status)
}
}
@@ -113,7 +113,7 @@ func TestTheFormatEnumeratorListsTheDropList(t *testing.T) {
data, object := newDragObject([]string{`C:\Temp\one.txt`})
defer runtime.KeepAlive(data)
var enum uintptr
- if status := uint32(comCall(object, 8, dataDirGet, uintptr(unsafe.Pointer(&enum)))); status != sOK {
+ if status := uint32(comCall2(object, 8, dataDirGet, uintptr(unsafe.Pointer(&enum)))); status != sOK {
t.Fatalf("EnumFormatEtc = %#x, want S_OK", status)
}
if enum == 0 {
@@ -121,34 +121,34 @@ func TestTheFormatEnumeratorListsTheDropList(t *testing.T) {
}
var offered formatEtc
var fetched uint32
- if status := uint32(comCall(enum, 3, 1, uintptr(unsafe.Pointer(&offered)), uintptr(unsafe.Pointer(&fetched)))); status != sOK || fetched != 1 {
+ if status := uint32(comCall3(enum, 3, 1, uintptr(unsafe.Pointer(&offered)), uintptr(unsafe.Pointer(&fetched)))); status != sOK || fetched != 1 {
t.Fatalf("Next(1) = %#x with %d formats, want S_OK with 1", status, fetched)
}
if offered.Format != cfHDrop || offered.Aspect != dvAspectContent || offered.Index != lindexNone || offered.Medium != tymedHGlobal {
t.Errorf("the format is %+v, want the list of files", offered)
}
- if status := uint32(comCall(enum, 3, 1, uintptr(unsafe.Pointer(&offered)), uintptr(unsafe.Pointer(&fetched)))); status != sFalse || fetched != 0 {
+ if status := uint32(comCall3(enum, 3, 1, uintptr(unsafe.Pointer(&offered)), uintptr(unsafe.Pointer(&fetched)))); status != sFalse || fetched != 0 {
t.Errorf("Next after the end = %#x with %d formats, want S_FALSE with 0", status, fetched)
}
- comCall(enum, 5) // Reset
- if status := uint32(comCall(enum, 3, 2, uintptr(unsafe.Pointer(&offered)), uintptr(unsafe.Pointer(&fetched)))); status != sFalse || fetched != 1 {
+ comCall0(enum, 5) // Reset
+ if status := uint32(comCall3(enum, 3, 2, uintptr(unsafe.Pointer(&offered)), uintptr(unsafe.Pointer(&fetched)))); status != sFalse || fetched != 1 {
t.Errorf("Next(2) = %#x with %d formats, want S_FALSE with 1", status, fetched)
}
- comCall(enum, 5)
- comCall(enum, 4, 1) // Skip
- if status := uint32(comCall(enum, 3, 1, uintptr(unsafe.Pointer(&offered)), uintptr(unsafe.Pointer(&fetched)))); status != sFalse || fetched != 0 {
+ comCall0(enum, 5)
+ comCall1(enum, 4, 1) // Skip
+ if status := uint32(comCall3(enum, 3, 1, uintptr(unsafe.Pointer(&offered)), uintptr(unsafe.Pointer(&fetched)))); status != sFalse || fetched != 0 {
t.Errorf("Next after Skip = %#x with %d formats, want S_FALSE with 0", status, fetched)
}
- comCall(enum, 5)
- if status := uint32(comCall(enum, 4, 2)); status != sFalse {
+ comCall0(enum, 5)
+ if status := uint32(comCall1(enum, 4, 2)); status != sFalse {
t.Errorf("Skip(2) with one format = %#x, want S_FALSE", status)
}
- comCall(enum, 5)
+ comCall0(enum, 5)
var clone uintptr
- if status := uint32(comCall(enum, 6, uintptr(unsafe.Pointer(&clone)))); status != sOK || clone == 0 {
+ if status := uint32(comCall1(enum, 6, uintptr(unsafe.Pointer(&clone)))); status != sOK || clone == 0 {
t.Fatalf("Clone = %#x, want S_OK with an enumerator", status)
}
- if status := uint32(comCall(clone, 3, 1, uintptr(unsafe.Pointer(&offered)), uintptr(unsafe.Pointer(&fetched)))); status != sOK || fetched != 1 {
+ if status := uint32(comCall3(clone, 3, 1, uintptr(unsafe.Pointer(&offered)), uintptr(unsafe.Pointer(&fetched)))); status != sOK || fetched != 1 {
t.Errorf("the clone's Next = %#x with %d formats, want S_OK with 1", status, fetched)
}
}
@@ -172,11 +172,11 @@ func TestTheDropSourceEndsTheDragWhereWindowsDoes(t *testing.T) {
{0, 0x10 | 8, sOK}, // MK_MBUTTON with MK_CONTROL beside it
{0, 8, dragdropSDrop}, // no button, only a modifier
} {
- if got := uint32(comCall(object, 3, test.escape, test.keys)); got != uint32(test.want) {
+ if got := uint32(comCall2(object, 3, test.escape, test.keys)); got != uint32(test.want) {
t.Errorf("QueryContinueDrag(escape=%d, keys=%#x) = %#x, want %#x", test.escape, test.keys, got, uint32(test.want))
}
}
- if got := uint32(comCall(object, 4, uintptr(platform.DragEffectCopy))); got != dragdropSUseDefaultCursors {
+ if got := uint32(comCall1(object, 4, uintptr(platform.DragEffectCopy))); got != dragdropSUseDefaultCursors {
t.Errorf("GiveFeedback = %#x, want DRAGDROP_S_USEDEFAULTCURSORS", got)
}
}
@@ -188,22 +188,22 @@ func TestTheObjectsAnswerForTheirOwnInterfaces(t *testing.T) {
data, object := newDragObject([]string{`C:\Temp\one.txt`})
defer runtime.KeepAlive(data)
var asked uintptr
- if status := uint32(comCall(object, 0, uintptr(unsafe.Pointer(&iidDataObject)), uintptr(unsafe.Pointer(&asked)))); status != sOK || asked != object {
+ if status := uint32(comCall2(object, 0, uintptr(unsafe.Pointer(&iidDataObject)), uintptr(unsafe.Pointer(&asked)))); status != sOK || asked != object {
t.Errorf("the data object answered IDataObject with %#x and %#x, want S_OK and itself", status, asked)
}
if data.refs != 2 {
t.Errorf("the data object counts %d references after one grant, want 2", data.refs)
}
asked = 1
- if status := uint32(comCall(object, 0, uintptr(unsafe.Pointer(&iidDropSource)), uintptr(unsafe.Pointer(&asked)))); status != eNoInterface || asked != 0 {
+ if status := uint32(comCall2(object, 0, uintptr(unsafe.Pointer(&iidDropSource)), uintptr(unsafe.Pointer(&asked)))); status != eNoInterface || asked != 0 {
t.Errorf("the data object answered IDropSource with %#x and %#x, want E_NOINTERFACE and no object", status, asked)
}
source, sourceObject := newDragSource()
defer runtime.KeepAlive(source)
- if status := uint32(comCall(sourceObject, 0, uintptr(unsafe.Pointer(&iidDropSource)), uintptr(unsafe.Pointer(&asked)))); status != sOK {
+ if status := uint32(comCall2(sourceObject, 0, uintptr(unsafe.Pointer(&iidDropSource)), uintptr(unsafe.Pointer(&asked)))); status != sOK {
t.Errorf("the drop source refused IDropSource with %#x", status)
}
- if status := uint32(comCall(sourceObject, 0, uintptr(unsafe.Pointer(&iidDataObject)), uintptr(unsafe.Pointer(&asked)))); status != eNoInterface {
+ if status := uint32(comCall2(sourceObject, 0, uintptr(unsafe.Pointer(&iidDataObject)), uintptr(unsafe.Pointer(&asked)))); status != eNoInterface {
t.Errorf("the drop source answered IDataObject with %#x, want E_NOINTERFACE", status)
}
}
diff --git a/internal/platform/windows/drop_windows.go b/internal/platform/windows/drop_windows.go
index 5efcc139d..27143f317 100644
--- a/internal/platform/windows/drop_windows.go
+++ b/internal/platform/windows/drop_windows.go
@@ -128,14 +128,14 @@ func dropRelease(this uintptr) uintptr {
// containsFiles reports whether a data object offers a list of files.
func containsFiles(data uintptr) bool {
format := formatEtc{Format: cfHDrop, Aspect: dvAspectContent, Index: -1, Medium: tymedHGlobal}
- return data != 0 && uint32(comCall(data, 5, uintptr(unsafe.Pointer(&format)))) == sOK
+ return data != 0 && uint32(comCall1(data, 5, uintptr(unsafe.Pointer(&format)))) == sOK
}
// filesOf reads the paths out of a data object that offers files.
func filesOf(data uintptr) []string {
format := formatEtc{Format: cfHDrop, Aspect: dvAspectContent, Index: -1, Medium: tymedHGlobal}
var medium storageMedium
- if hresult(comCall(data, 3, uintptr(unsafe.Pointer(&format)), uintptr(unsafe.Pointer(&medium)))) != nil {
+ if hresult(comCall2(data, 3, uintptr(unsafe.Pointer(&format)), uintptr(unsafe.Pointer(&medium)))) != nil {
return nil
}
defer releaseStgMedium.Call(uintptr(unsafe.Pointer(&medium)))
diff --git a/internal/platform/windows/drop_windows_test.go b/internal/platform/windows/drop_windows_test.go
index 2ed44589a..c46a99da3 100644
--- a/internal/platform/windows/drop_windows_test.go
+++ b/internal/platform/windows/drop_windows_test.go
@@ -205,7 +205,7 @@ func TestAWindowFollowsAnOLEDragOverIt(t *testing.T) {
}
const copyEffect, allEffects = 1, 1 | 2 | 4
effect := uint32(allEffects)
- comCall(target, 3, object, 0, at(40, 20), uintptr(unsafe.Pointer(&effect)))
+ comCall4(target, 3, object, 0, at(40, 20), uintptr(unsafe.Pointer(&effect)))
if event := next(); event.Phase != platform.FileDropOver || event.X < 39 || event.X > 41 || event.Y < 19 || event.Y > 21 {
t.Fatalf("enter reported %+v", event)
}
@@ -213,19 +213,19 @@ func TestAWindowFollowsAnOLEDragOverIt(t *testing.T) {
t.Fatalf("a point that takes files answered effect %d, want copy", effect)
}
effect = allEffects
- comCall(target, 4, 0, at(60, 30), uintptr(unsafe.Pointer(&effect)))
+ comCall3(target, 4, 0, at(60, 30), uintptr(unsafe.Pointer(&effect)))
if event := next(); event.Phase != platform.FileDropOver || event.X < 59 || event.X > 61 {
t.Fatalf("move reported %+v", event)
}
- comCall(target, 5)
+ comCall0(target, 5)
if event := next(); event.Phase != platform.FileDropLeave {
t.Fatalf("leave reported %+v", event)
}
effect = allEffects
- comCall(target, 3, object, 0, at(10, 10), uintptr(unsafe.Pointer(&effect)))
+ comCall4(target, 3, object, 0, at(10, 10), uintptr(unsafe.Pointer(&effect)))
next()
effect = allEffects
- comCall(target, 6, object, 0, at(70, 40), uintptr(unsafe.Pointer(&effect)))
+ comCall4(target, 6, object, 0, at(70, 40), uintptr(unsafe.Pointer(&effect)))
event := next()
if event.Phase != platform.FileDropDrop || len(event.Paths) != 2 || event.Paths[0] != `C:\Temp\one.txt` || event.X < 69 || event.X > 71 {
t.Fatalf("drop reported %+v", event)
@@ -246,7 +246,7 @@ func TestAWindowThatRefusesFilesShowsTheNoDropCursor(t *testing.T) {
defer closeWindow()
data := &fakeDataObject{table: &fakeDataTable, drop: buildDrop(t, true, 0, 0, `C:\Temp\one.txt`)}
effect := uint32(1 | 2 | 4)
- comCall(uintptr(unsafe.Pointer(state.drop)), 3, uintptr(unsafe.Pointer(data)), 0, 0, uintptr(unsafe.Pointer(&effect)))
+ comCall4(uintptr(unsafe.Pointer(state.drop)), 3, uintptr(unsafe.Pointer(data)), 0, 0, uintptr(unsafe.Pointer(&effect)))
if effect != 0 {
t.Fatalf("a refusing point answered effect %d", effect)
}
diff --git a/internal/platform/windows/fidelity_windows_test.go b/internal/platform/windows/fidelity_windows_test.go
index 0b40c1bcf..6e2e6953c 100644
--- a/internal/platform/windows/fidelity_windows_test.go
+++ b/internal/platform/windows/fidelity_windows_test.go
@@ -55,7 +55,7 @@ func nativeColorImage(t *testing.T, rasterizer *directRasterizer, c textsharp.Ca
defer release(&layout)
var line lineMetrics
var lines uint32
- comCall(layout, writeGetLineMetrics, uintptr(unsafe.Pointer(&line)), 1, uintptr(unsafe.Pointer(&lines)))
+ comCall3(layout, writeGetLineMetrics, uintptr(unsafe.Pointer(&line)), 1, uintptr(unsafe.Pointer(&lines)))
scratch, err := rasterizer.opaque.bind(width, height)
if err != nil {
t.Fatal(err)
diff --git a/internal/platform/windows/font_fallback_windows.go b/internal/platform/windows/font_fallback_windows.go
index fa1c6124e..0664ce5d0 100644
--- a/internal/platform/windows/font_fallback_windows.go
+++ b/internal/platform/windows/font_fallback_windows.go
@@ -40,12 +40,12 @@ func (rasterizer *directRasterizer) fontFallback(face gfx.MonoFace) uintptr {
func (rasterizer *directRasterizer) buildFontFallback(names []string) uintptr {
var factory2 uintptr
- if comCall(rasterizer.services.write, 0, uintptr(unsafe.Pointer(&writeFactory2IID)), uintptr(unsafe.Pointer(&factory2))) != 0 || factory2 == 0 {
+ if comCall2(rasterizer.services.write, 0, uintptr(unsafe.Pointer(&writeFactory2IID)), uintptr(unsafe.Pointer(&factory2))) != 0 || factory2 == 0 {
return 0
}
defer release(&factory2)
var builder uintptr
- if hresult(comCall(factory2, writeFactoryCreateFallbackBuilder, uintptr(unsafe.Pointer(&builder)))) != nil || builder == 0 {
+ if hresult(comCall1(factory2, writeFactoryCreateFallbackBuilder, uintptr(unsafe.Pointer(&builder)))) != nil || builder == 0 {
return 0
}
defer release(&builder)
@@ -75,10 +75,10 @@ func (rasterizer *directRasterizer) buildFontFallback(names []string) uintptr {
}
if system := rasterizer.engine.fallback; system != 0 {
// What none of the families has is left to the system, as before.
- comCall(builder, writeBuilderAddMappings, system)
+ comCall1(builder, writeBuilderAddMappings, system)
}
var fallback uintptr
- if hresult(comCall(builder, writeBuilderCreateFontFallback, uintptr(unsafe.Pointer(&fallback)))) != nil {
+ if hresult(comCall1(builder, writeBuilderCreateFontFallback, uintptr(unsafe.Pointer(&fallback)))) != nil {
return 0
}
return fallback
diff --git a/internal/platform/windows/font_register_windows.go b/internal/platform/windows/font_register_windows.go
index cdb376b4b..ff8f4d4f0 100644
--- a/internal/platform/windows/font_register_windows.go
+++ b/internal/platform/windows/font_register_windows.go
@@ -126,16 +126,16 @@ func newFontCollection(files []string) (collection uintptr, err error) {
if err := hresult(status); err != nil {
return 0, err
}
- if comCall(factory, 0, uintptr(unsafe.Pointer(&writeFactory3IID)), uintptr(unsafe.Pointer(&factory3))) != 0 || factory3 == 0 {
+ if comCall2(factory, 0, uintptr(unsafe.Pointer(&writeFactory3IID)), uintptr(unsafe.Pointer(&factory3))) != 0 || factory3 == 0 {
return 0, errors.New("windows: DirectWrite cannot add fonts at run time before Windows 10 version 1607")
}
- if err := hresult(comCall(factory3, writeFactory3GetSystemFontSet, uintptr(unsafe.Pointer(&systemSet)))); err != nil {
+ if err := hresult(comCall1(factory3, writeFactory3GetSystemFontSet, uintptr(unsafe.Pointer(&systemSet)))); err != nil {
return 0, err
}
- if err := hresult(comCall(factory3, writeFactory3CreateFontSetBuilder, uintptr(unsafe.Pointer(&builder)))); err != nil {
+ if err := hresult(comCall1(factory3, writeFactory3CreateFontSetBuilder, uintptr(unsafe.Pointer(&builder)))); err != nil {
return 0, err
}
- if err := hresult(comCall(builder, writeSetBuilderAddFontSet, systemSet)); err != nil {
+ if err := hresult(comCall1(builder, writeSetBuilderAddFontSet, systemSet)); err != nil {
return 0, err
}
for _, path := range files {
@@ -143,10 +143,10 @@ func newFontCollection(files []string) (collection uintptr, err error) {
return 0, err
}
}
- if err := hresult(comCall(builder, writeSetBuilderCreateFontSet, uintptr(unsafe.Pointer(&fontSet)))); err != nil {
+ if err := hresult(comCall1(builder, writeSetBuilderCreateFontSet, uintptr(unsafe.Pointer(&fontSet)))); err != nil {
return 0, err
}
- if err := hresult(comCall(factory3, writeFactory3CollectionFromFontSet, fontSet, uintptr(unsafe.Pointer(&collection)))); err != nil {
+ if err := hresult(comCall2(factory3, writeFactory3CollectionFromFontSet, fontSet, uintptr(unsafe.Pointer(&collection)))); err != nil {
return 0, err
}
return collection, nil
@@ -159,13 +159,13 @@ func addFontFaces(factory, factory3, builder uintptr, path string) error {
return err
}
var file uintptr
- if err := hresult(comCall(factory, writeFactoryCreateFontFileReference, uintptr(unsafe.Pointer(name)), 0, uintptr(unsafe.Pointer(&file)))); err != nil {
+ if err := hresult(comCall3(factory, writeFactoryCreateFontFileReference, uintptr(unsafe.Pointer(name)), 0, uintptr(unsafe.Pointer(&file)))); err != nil {
return err
}
defer release(&file)
var supported int32
var fileType, faceType, faces uint32
- if err := hresult(comCall(file, writeFontFileAnalyze, uintptr(unsafe.Pointer(&supported)), uintptr(unsafe.Pointer(&fileType)), uintptr(unsafe.Pointer(&faceType)), uintptr(unsafe.Pointer(&faces)))); err != nil {
+ if err := hresult(comCall4(file, writeFontFileAnalyze, uintptr(unsafe.Pointer(&supported)), uintptr(unsafe.Pointer(&fileType)), uintptr(unsafe.Pointer(&faceType)), uintptr(unsafe.Pointer(&faces)))); err != nil {
return err
}
if supported == 0 || faces == 0 {
@@ -173,10 +173,10 @@ func addFontFaces(factory, factory3, builder uintptr, path string) error {
}
for index := uint32(0); index < faces; index++ {
var reference uintptr
- if err := hresult(comCall(factory3, writeFactory3CreateFaceReference, file, uintptr(index), 0, uintptr(unsafe.Pointer(&reference)))); err != nil {
+ if err := hresult(comCall4(factory3, writeFactory3CreateFaceReference, file, uintptr(index), 0, uintptr(unsafe.Pointer(&reference)))); err != nil {
return err
}
- status := comCall(builder, writeSetBuilderAddFace, reference)
+ status := comCall1(builder, writeSetBuilderAddFace, reference)
release(&reference)
if err := hresult(status); err != nil {
return err
diff --git a/internal/platform/windows/font_weights_windows.go b/internal/platform/windows/font_weights_windows.go
index 191f6667f..7e949fc1f 100644
--- a/internal/platform/windows/font_weights_windows.go
+++ b/internal/platform/windows/font_weights_windows.go
@@ -32,24 +32,24 @@ func FontWeights(family string) []int {
return nil
}
var index, exists uint32
- if err := hresult(comCall(collection, writeCollectionFindFamilyName, uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(&index)), uintptr(unsafe.Pointer(&exists)))); err != nil || exists == 0 {
+ if err := hresult(comCall3(collection, writeCollectionFindFamilyName, uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(&index)), uintptr(unsafe.Pointer(&exists)))); err != nil || exists == 0 {
return nil
}
var list uintptr
- if err := hresult(comCall(collection, writeCollectionGetFontFamily, uintptr(index), uintptr(unsafe.Pointer(&list)))); err != nil || list == 0 {
+ if err := hresult(comCall2(collection, writeCollectionGetFontFamily, uintptr(index), uintptr(unsafe.Pointer(&list)))); err != nil || list == 0 {
return nil
}
defer release(&list)
// GetFontCount returns the count itself, as GetFontFamilyCount does.
- count := uint32(comCall(list, writeFontListGetFontCount))
+ count := uint32(comCall0(list, writeFontListGetFontCount))
weights := make([]int, 0, count)
for face := uint32(0); face < count; face++ {
var font uintptr
- if err := hresult(comCall(list, writeFontListGetFont, uintptr(face), uintptr(unsafe.Pointer(&font)))); err != nil || font == 0 {
+ if err := hresult(comCall2(list, writeFontListGetFont, uintptr(face), uintptr(unsafe.Pointer(&font)))); err != nil || font == 0 {
continue
}
// GetWeight returns the DWRITE_FONT_WEIGHT itself.
- weight := int(uint32(comCall(font, writeFontGetWeight)))
+ weight := int(uint32(comCall0(font, writeFontGetWeight)))
release(&font)
if !slices.Contains(weights, weight) {
weights = append(weights, weight)
diff --git a/internal/platform/windows/fonts_direct_windows.go b/internal/platform/windows/fonts_direct_windows.go
index c81dd65ea..d2bfb7e89 100644
--- a/internal/platform/windows/fonts_direct_windows.go
+++ b/internal/platform/windows/fonts_direct_windows.go
@@ -67,7 +67,7 @@ func collectionFamilyNames(services *textServices) ([]string, bool) {
}
defer unlock()
// GetFontFamilyCount returns the count itself; it takes no out parameter.
- count := uint32(comCall(collection, writeCollectionGetFontFamilyCount))
+ count := uint32(comCall0(collection, writeCollectionGetFontFamilyCount))
names := make([]string, 0, count)
for index := uint32(0); index < count; index++ {
name, ok := collectionFamilyName(collection, index)
@@ -96,7 +96,7 @@ func openCollection(services *textServices) (collection uintptr, unlock func(),
}
customFonts.RUnlock()
system := uintptr(0)
- status := comCall(services.write, writeFactoryGetSystemFontCollection, uintptr(unsafe.Pointer(&system)), 0)
+ status := comCall2(services.write, writeFactoryGetSystemFontCollection, uintptr(unsafe.Pointer(&system)), 0)
if err := hresult(status); err != nil || system == 0 {
return 0, func() {}, false
}
@@ -107,21 +107,21 @@ func openCollection(services *textServices) (collection uintptr, unlock func(),
// font lists first — the name CreateTextFormat resolves.
func collectionFamilyName(collection uintptr, index uint32) (string, bool) {
var family uintptr
- if err := hresult(comCall(collection, writeCollectionGetFontFamily, uintptr(index), uintptr(unsafe.Pointer(&family)))); err != nil || family == 0 {
+ if err := hresult(comCall2(collection, writeCollectionGetFontFamily, uintptr(index), uintptr(unsafe.Pointer(&family)))); err != nil || family == 0 {
return "", false
}
defer release(&family)
var strings uintptr
- if err := hresult(comCall(family, writeFontFamilyGetFamilyNames, uintptr(unsafe.Pointer(&strings)))); err != nil || strings == 0 {
+ if err := hresult(comCall1(family, writeFontFamilyGetFamilyNames, uintptr(unsafe.Pointer(&strings)))); err != nil || strings == 0 {
return "", false
}
defer release(&strings)
var length uint32
- if err := hresult(comCall(strings, writeStringsGetStringLength, 0, uintptr(unsafe.Pointer(&length)))); err != nil || length == 0 {
+ if err := hresult(comCall2(strings, writeStringsGetStringLength, 0, uintptr(unsafe.Pointer(&length)))); err != nil || length == 0 {
return "", false
}
buffer := make([]uint16, length+1)
- if err := hresult(comCall(strings, writeStringsGetString, 0, uintptr(unsafe.Pointer(&buffer[0])), uintptr(len(buffer)))); err != nil {
+ if err := hresult(comCall3(strings, writeStringsGetString, 0, uintptr(unsafe.Pointer(&buffer[0])), uintptr(len(buffer)))); err != nil {
return "", false
}
return syscall.UTF16ToString(buffer), true
diff --git a/internal/platform/windows/fonts_direct_windows_test.go b/internal/platform/windows/fonts_direct_windows_test.go
index 6c01d7490..10753e206 100644
--- a/internal/platform/windows/fonts_direct_windows_test.go
+++ b/internal/platform/windows/fonts_direct_windows_test.go
@@ -10,7 +10,7 @@ import (
// the way every text format here resolves one.
func familyExists(services *textServices, name string) (bool, error) {
var collection uintptr
- if err := hresult(comCall(services.write, writeFactoryGetSystemFontCollection, uintptr(unsafe.Pointer(&collection)), 0)); err != nil || collection == 0 {
+ if err := hresult(comCall2(services.write, writeFactoryGetSystemFontCollection, uintptr(unsafe.Pointer(&collection)), 0)); err != nil || collection == 0 {
return false, err
}
defer release(&collection)
@@ -19,7 +19,7 @@ func familyExists(services *textServices, name string) (bool, error) {
return false, err
}
var index, exists uint32
- if err := hresult(comCall(collection, writeCollectionFindFamilyName, uintptr(unsafe.Pointer(wide)), uintptr(unsafe.Pointer(&index)), uintptr(unsafe.Pointer(&exists)))); err != nil {
+ if err := hresult(comCall3(collection, writeCollectionFindFamilyName, uintptr(unsafe.Pointer(wide)), uintptr(unsafe.Pointer(&index)), uintptr(unsafe.Pointer(&exists)))); err != nil {
return false, err
}
return exists != 0, nil
diff --git a/internal/platform/windows/grid_cache_windows.go b/internal/platform/windows/grid_cache_windows.go
index 558c55159..506cfc646 100644
--- a/internal/platform/windows/grid_cache_windows.go
+++ b/internal/platform/windows/grid_cache_windows.go
@@ -108,19 +108,19 @@ func (rasterizer *directRasterizer) gridShaped(format gridFormatKey, handle uint
release(&layout)
}
}()
- if err := hresult(comCall(layout, writeGetMetrics, uintptr(unsafe.Pointer(&shaped.metrics)))); err != nil {
+ if err := hresult(comCall1(layout, writeGetMetrics, uintptr(unsafe.Pointer(&shaped.metrics)))); err != nil {
return nil, err
}
var lines uint32
- if err := hresult(comCall(layout, writeGetLineMetrics, uintptr(unsafe.Pointer(&shaped.line)), 1, uintptr(unsafe.Pointer(&lines)))); err != nil && lines == 0 {
+ if err := hresult(comCall3(layout, writeGetLineMetrics, uintptr(unsafe.Pointer(&shaped.line)), 1, uintptr(unsafe.Pointer(&lines)))); err != nil && lines == 0 {
return nil, err
}
all := uint64(shaped.chars) << 32
if run.Underline {
- comCall(layout, writeSetUnderline, 1, uintptr(all))
+ comCall2(layout, writeSetUnderline, 1, uintptr(all))
}
if run.Strike {
- comCall(layout, writeSetStrikethrough, 1, uintptr(all))
+ comCall2(layout, writeSetStrikethrough, 1, uintptr(all))
}
if !run.Ligatures && pitch > 0 && printableASCII(piece) {
// Every character stands on its cell, whatever the advance of the font.
@@ -143,7 +143,7 @@ func (rasterizer *directRasterizer) gridShaped(format gridFormatKey, handle uint
// setCharacterSpacing gives a layout direct-write's per-range character spacing.
func (rasterizer *directRasterizer) setCharacterSpacing(layout uintptr, trailing float32, span uint64) {
var extended uintptr
- if comCall(layout, 0, uintptr(unsafe.Pointer(&writeLayout1IID)), uintptr(unsafe.Pointer(&extended))) != 0 || extended == 0 {
+ if comCall2(layout, 0, uintptr(unsafe.Pointer(&writeLayout1IID)), uintptr(unsafe.Pointer(&extended))) != 0 || extended == 0 {
return
}
defer release(&extended)
diff --git a/internal/platform/windows/label_picture_windows.go b/internal/platform/windows/label_picture_windows.go
index 932071aa8..ac4aa95c9 100644
--- a/internal/platform/windows/label_picture_windows.go
+++ b/internal/platform/windows/label_picture_windows.go
@@ -144,7 +144,7 @@ func (renderer *renderer) pictureHasCompleteInk(label *labelTexture, scale float
value := label.label
err := renderer.direct.engine.drawStyle(value.Value, value.FontSize*scale, value.Weight, value.Italic, func(line *shapedLine) error {
var overhang [4]float32
- if err := hresult(comCall(line.layout, writeGetOverhangMetrics, uintptr(unsafe.Pointer(&overhang[0])))); err != nil {
+ if err := hresult(comCall1(line.layout, writeGetOverhangMetrics, uintptr(unsafe.Pointer(&overhang[0])))); err != nil {
return err
}
right := float64(1<<20) + float64(overhang[2]) - float64(line.left)
@@ -227,10 +227,10 @@ func (renderer *renderer) uploadLabelPicture(label *labelTexture, key labelPictu
picture := &labelPicture{key: key, x: left, y: top, width: right - left, height: bottom - top, lcd: label.lcd, complete: renderer.pictureHasCompleteInk(label, key.scale, key.skip, width)}
description := textureDesc{Width: uint32(picture.width), Height: uint32(picture.height), Mips: 1, Array: 1, Format: 87, Samples: 1, Usage: 1, Bind: 8}
data := resourceData{Data: unsafe.Pointer(&pixels[(top*width+left)*4]), Pitch: uint32(width * 4)}
- if err := hresult(comCall(renderer.device, 5, uintptr(unsafe.Pointer(&description)), uintptr(unsafe.Pointer(&data)), uintptr(unsafe.Pointer(&picture.texture)))); err != nil {
+ if err := hresult(comCall3(renderer.device, 5, uintptr(unsafe.Pointer(&description)), uintptr(unsafe.Pointer(&data)), uintptr(unsafe.Pointer(&picture.texture)))); err != nil {
return err
}
- if err := hresult(comCall(renderer.device, 7, picture.texture, 0, uintptr(unsafe.Pointer(&picture.view)))); err != nil {
+ if err := hresult(comCall3(renderer.device, 7, picture.texture, 0, uintptr(unsafe.Pointer(&picture.view)))); err != nil {
release(&picture.texture)
return err
}
diff --git a/internal/platform/windows/offscreen_windows.go b/internal/platform/windows/offscreen_windows.go
index eefd1daa4..f78a2a0ae 100644
--- a/internal/platform/windows/offscreen_windows.go
+++ b/internal/platform/windows/offscreen_windows.go
@@ -53,18 +53,18 @@ func NewOffscreen(width, height int, scale float64, clear platform.Color) (*Offs
renderer := &offscreen.renderer
description := textureDesc{Width: uint32(pixelWidth), Height: uint32(pixelHeight), Mips: 1, Array: 1, Format: 87, Samples: 1, Usage: 0, Bind: 0x20}
var target uintptr
- if err := hresult(comCall(renderer.device, 5, uintptr(unsafe.Pointer(&description)), 0, uintptr(unsafe.Pointer(&target)))); err != nil {
+ if err := hresult(comCall3(renderer.device, 5, uintptr(unsafe.Pointer(&description)), 0, uintptr(unsafe.Pointer(&target)))); err != nil {
offscreen.Close()
return nil, fmt.Errorf("create offscreen target: %w", err)
}
- status = comCall(renderer.device, 9, target, 0, uintptr(unsafe.Pointer(&renderer.target)))
+ status = comCall3(renderer.device, 9, target, 0, uintptr(unsafe.Pointer(&renderer.target)))
release(&target)
if err := hresult(status); err != nil {
offscreen.Close()
return nil, fmt.Errorf("create offscreen target view: %w", err)
}
description.Usage, description.Bind, description.CPU = 3, 0, 0x20000
- if err := hresult(comCall(renderer.device, 5, uintptr(unsafe.Pointer(&description)), 0, uintptr(unsafe.Pointer(&offscreen.staging)))); err != nil {
+ if err := hresult(comCall3(renderer.device, 5, uintptr(unsafe.Pointer(&description)), 0, uintptr(unsafe.Pointer(&offscreen.staging)))); err != nil {
offscreen.Close()
return nil, fmt.Errorf("create offscreen read-back texture: %w", err)
}
@@ -100,14 +100,14 @@ func (offscreen *Offscreen) Image() (*image.RGBA, error) {
return nil, err
}
var target uintptr
- comCall(renderer.target, 7, uintptr(unsafe.Pointer(&target))) // ID3D11View::GetResource
- comCall(renderer.context, 47, offscreen.staging, target) // CopyResource
+ comCall1(renderer.target, 7, uintptr(unsafe.Pointer(&target))) // ID3D11View::GetResource
+ comCall2(renderer.context, 47, offscreen.staging, target) // CopyResource
release(&target)
var mapped resourceData
- if err := hresult(comCall(renderer.context, 14, offscreen.staging, 0, 1, 0, uintptr(unsafe.Pointer(&mapped)))); err != nil {
+ if err := hresult(comCall5(renderer.context, 14, offscreen.staging, 0, 1, 0, uintptr(unsafe.Pointer(&mapped)))); err != nil {
return nil, fmt.Errorf("map offscreen read-back texture: %w", err)
}
- defer comCall(renderer.context, 15, offscreen.staging, 0)
+ defer comCall2(renderer.context, 15, offscreen.staging, 0)
result := image.NewRGBA(image.Rect(0, 0, width, height))
source := unsafe.Slice((*byte)(mapped.Data), int(mapped.Pitch)*(height-1)+width*4)
for y := 0; y < height; y++ {
diff --git a/internal/platform/windows/renderer_windows.go b/internal/platform/windows/renderer_windows.go
index 3af8a5a6b..28d4d47b1 100644
--- a/internal/platform/windows/renderer_windows.go
+++ b/internal/platform/windows/renderer_windows.go
@@ -127,6 +127,7 @@ func rectangleScissor(batch compositingBatch, scale float32, width, height int)
}
type renderer struct {
+ drawScratch drawScratch // what draw hands Direct3D by address
compositionState
window, device, context, swap, target uintptr
rectangleVertex, rectangleFragment, textVertex, textFragment uintptr
@@ -288,7 +289,7 @@ func (renderer *renderer) createWindowSwapChain() error {
Scaling: 1, SwapEffect: 3, // DXGI_SCALING_NONE, DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL
}
// IDXGIFactory2::CreateSwapChainForHwnd.
- status = comCall(factory, 15, renderer.device, renderer.window, uintptr(unsafe.Pointer(&description)), 0, 0, uintptr(unsafe.Pointer(&renderer.swap)))
+ status = comCall6(factory, 15, renderer.device, renderer.window, uintptr(unsafe.Pointer(&description)), 0, 0, uintptr(unsafe.Pointer(&renderer.swap)))
if err := hresult(status); err != nil {
return fmt.Errorf("create swap chain for window: %w", err)
}
@@ -297,7 +298,7 @@ func (renderer *renderer) createWindowSwapChain() error {
// only fills pixels a resize exposes, so its HRESULT is ignored: a failure must
// not fail device creation for hardware and WARP alike.
background := [4]float32{float32(renderer.color.Red), float32(renderer.color.Green), float32(renderer.color.Blue), float32(renderer.color.Alpha)}
- comCall(renderer.swap, 25, uintptr(unsafe.Pointer(&background)))
+ comCall1(renderer.swap, 25, uintptr(unsafe.Pointer(&background)))
return nil
}
@@ -314,33 +315,33 @@ func (renderer *renderer) createResources() error {
if index%2 != 0 {
method = 15
}
- status = comCall(renderer.device, method, uintptr(unsafe.Pointer(&code[0])), uintptr(len(code)), 0, uintptr(unsafe.Pointer(shader.Destination)))
+ status = comCall4(renderer.device, method, uintptr(unsafe.Pointer(&code[0])), uintptr(len(code)), 0, uintptr(unsafe.Pointer(shader.Destination)))
if err := hresult(status); err != nil {
return fmt.Errorf("create shader %d: %w", index, err)
}
}
buffer := bufferDesc{Bytes: uint32(unsafe.Sizeof(frameConstants{})), Bind: 4}
- if err := hresult(comCall(renderer.device, 3, uintptr(unsafe.Pointer(&buffer)), 0, uintptr(unsafe.Pointer(&renderer.constants)))); err != nil {
+ if err := hresult(comCall3(renderer.device, 3, uintptr(unsafe.Pointer(&buffer)), 0, uintptr(unsafe.Pointer(&renderer.constants)))); err != nil {
return err
}
blending := blendDesc{}
blending.Targets[0] = renderBlend{Enabled: 1, Source: 2, Destination: 6, Operation: 1, SourceAlpha: 2, DestinationAlpha: 6, AlphaOperation: 1, Mask: 15}
- if err := hresult(comCall(renderer.device, 20, uintptr(unsafe.Pointer(&blending)), uintptr(unsafe.Pointer(&renderer.blend)))); err != nil {
+ if err := hresult(comCall2(renderer.device, 20, uintptr(unsafe.Pointer(&blending)), uintptr(unsafe.Pointer(&renderer.blend)))); err != nil {
return err
}
// Text is blended per channel: the second output of the text shader is the factor
// that keeps the background (dual-source blending, SRC1 = 16..19 in D3D11_BLEND).
textBlending := blendDesc{}
textBlending.Targets[0] = renderBlend{Enabled: 1, Source: 2, Destination: 17, Operation: 1, SourceAlpha: 2, DestinationAlpha: 19, AlphaOperation: 1, Mask: 15}
- if err := hresult(comCall(renderer.device, 20, uintptr(unsafe.Pointer(&textBlending)), uintptr(unsafe.Pointer(&renderer.textBlend)))); err != nil {
+ if err := hresult(comCall2(renderer.device, 20, uintptr(unsafe.Pointer(&textBlending)), uintptr(unsafe.Pointer(&renderer.textBlend)))); err != nil {
return err
}
raster := rasterDesc{Fill: 3, Cull: 1, DepthClip: 1, Scissor: 1}
- if err := hresult(comCall(renderer.device, 22, uintptr(unsafe.Pointer(&raster)), uintptr(unsafe.Pointer(&renderer.raster)))); err != nil {
+ if err := hresult(comCall2(renderer.device, 22, uintptr(unsafe.Pointer(&raster)), uintptr(unsafe.Pointer(&renderer.raster)))); err != nil {
return err
}
sampler := samplerDesc{Filter: 0x15, AddressU: 3, AddressV: 3, AddressW: 3, MaxLOD: math.MaxFloat32}
- return hresult(comCall(renderer.device, 23, uintptr(unsafe.Pointer(&sampler)), uintptr(unsafe.Pointer(&renderer.sampler))))
+ return hresult(comCall2(renderer.device, 23, uintptr(unsafe.Pointer(&sampler)), uintptr(unsafe.Pointer(&renderer.sampler))))
}
// storeRectangles copies the changed instances and their layer and clip, then
@@ -425,7 +426,7 @@ func (renderer *renderer) apply(frame platform.Frame) error {
}
if count > 0 {
region := box{Left: uint32(first * rectangleInstanceBytes), Right: uint32((first + count) * rectangleInstanceBytes), Bottom: 1, Back: 1}
- comCall(renderer.context, 48, renderer.buffer, 0, uintptr(unsafe.Pointer(®ion)), uintptr(unsafe.Pointer(&renderer.instances[first])), 0, 0)
+ comCall6(renderer.context, 48, renderer.buffer, 0, uintptr(unsafe.Pointer(®ion)), uintptr(unsafe.Pointer(&renderer.instances[first])), 0, 0)
}
}
if frame.TextLabels != nil {
@@ -518,11 +519,11 @@ func (renderer *renderer) growInstanceBuffer(capacity int) error {
return fmt.Errorf("windows: rectangle buffer exceeds device limit")
}
description := bufferDesc{Bytes: uint32(capacity * rectangleInstanceBytes), Bind: 8, Misc: 0x40, Stride: rectangleInstanceBytes}
- if err := hresult(comCall(renderer.device, 3, uintptr(unsafe.Pointer(&description)), 0, uintptr(unsafe.Pointer(&renderer.buffer)))); err != nil {
+ if err := hresult(comCall3(renderer.device, 3, uintptr(unsafe.Pointer(&description)), 0, uintptr(unsafe.Pointer(&renderer.buffer)))); err != nil {
return err
}
view := resourceViewDesc{Dimension: 1, Fields: [4]uint32{0, uint32(capacity)}}
- if err := hresult(comCall(renderer.device, 7, renderer.buffer, uintptr(unsafe.Pointer(&view)), uintptr(unsafe.Pointer(&renderer.view)))); err != nil {
+ if err := hresult(comCall3(renderer.device, 7, renderer.buffer, uintptr(unsafe.Pointer(&view)), uintptr(unsafe.Pointer(&renderer.view)))); err != nil {
return err
}
renderer.capacity = capacity
@@ -567,17 +568,17 @@ func (renderer *renderer) presentWithSync(width, height int, scale float32, sync
headroom := renderer.resizeHeadroom && sync == 0 && !renderer.usesComposition()
needResize, targetWidth, targetHeight := swapChainResize(renderer.bufferWidth, renderer.bufferHeight, width, height, renderer.target != 0, headroom)
if needResize {
- comCall(renderer.context, 33, 0, 0, 0)
+ comCall3(renderer.context, 33, 0, 0, 0)
release(&renderer.target)
- comCall(renderer.context, 111) // Flush outstanding GPU commands before ResizeBuffers
- if err := hresult(comCall(renderer.swap, 13, 0, uintptr(targetWidth), uintptr(targetHeight), 0, 0)); err != nil {
+ comCall0(renderer.context, 111) // Flush outstanding GPU commands before ResizeBuffers
+ if err := hresult(comCall5(renderer.swap, 13, 0, uintptr(targetWidth), uintptr(targetHeight), 0, 0)); err != nil {
return fmt.Errorf("resize swap chain: %w", err)
}
var back uintptr
- if err := hresult(comCall(renderer.swap, 9, 0, uintptr(unsafe.Pointer(&textureIID)), uintptr(unsafe.Pointer(&back)))); err != nil {
+ if err := hresult(comCall3(renderer.swap, 9, 0, uintptr(unsafe.Pointer(&textureIID)), uintptr(unsafe.Pointer(&back)))); err != nil {
return fmt.Errorf("get swap-chain texture: %w", err)
}
- status := comCall(renderer.device, 9, back, 0, uintptr(unsafe.Pointer(&renderer.target)))
+ status := comCall3(renderer.device, 9, back, 0, uintptr(unsafe.Pointer(&renderer.target)))
release(&back)
if err := hresult(status); err != nil {
return err
@@ -588,7 +589,7 @@ func (renderer *renderer) presentWithSync(width, height int, scale float32, sync
if err := renderer.draw(width, height, scale); err != nil {
return err
}
- return hresult(comCall(renderer.swap, 8, sync, 0))
+ return hresult(comCall2(renderer.swap, 8, sync, 0))
}
// swapChainResize reports whether a present at width by height must resize the
@@ -617,38 +618,43 @@ func (renderer *renderer) draw(width, height int, scale float32) error {
if err := renderer.prepareLabels(scale, width); err != nil {
return err
}
- clear := [4]float32{float32(renderer.color.Red), float32(renderer.color.Green), float32(renderer.color.Blue), float32(renderer.color.Alpha)}
+ // What a draw call is handed by address lives in the renderer, not on the
+ // stack: an address converted for a COM call escapes, and would be a heap
+ // allocation per draw.
+ scratch := &renderer.drawScratch
+ scratch.clear = [4]float32{float32(renderer.color.Red), float32(renderer.color.Green), float32(renderer.color.Blue), float32(renderer.color.Alpha)}
if renderer.usesComposition() {
- clear[0] *= clear[3]
- clear[1] *= clear[3]
- clear[2] *= clear[3]
- }
- comCall(renderer.context, 50, renderer.target, uintptr(unsafe.Pointer(&clear)))
- comCall(renderer.context, 33, 1, uintptr(unsafe.Pointer(&renderer.target)), 0)
- comCall(renderer.context, 35, renderer.blend, 0, uintptr(^uint32(0)))
- comCall(renderer.context, 43, renderer.raster)
- viewport := viewport{Width: float32(width), Height: float32(height), MaxDepth: 1}
- comCall(renderer.context, 44, 1, uintptr(unsafe.Pointer(&viewport)))
+ scratch.clear[0] *= scratch.clear[3]
+ scratch.clear[1] *= scratch.clear[3]
+ scratch.clear[2] *= scratch.clear[3]
+ }
+ comCall2(renderer.context, 50, renderer.target, uintptr(unsafe.Pointer(&scratch.clear)))
+ comCall3(renderer.context, 33, 1, uintptr(unsafe.Pointer(&renderer.target)), 0)
+ comCall3(renderer.context, 35, renderer.blend, 0, uintptr(^uint32(0)))
+ comCall1(renderer.context, 43, renderer.raster)
+ scratch.viewport = viewport{Width: float32(width), Height: float32(height), MaxDepth: 1}
+ comCall2(renderer.context, 44, 1, uintptr(unsafe.Pointer(&scratch.viewport)))
// Scissoring is on for every draw, so the whole target is set first and a
// rectangle batch or label cut by a canvas clip narrows it for its own draw.
whole := scissorRect{Right: int32(width), Bottom: int32(height)}
- comCall(renderer.context, 45, 1, uintptr(unsafe.Pointer(&whole)))
- comCall(renderer.context, 24, 4)
- frame := frameConstants{Width: float32(width) / scale, Height: float32(height) / scale, PixelSize: 1 / scale}
- comCall(renderer.context, 48, renderer.constants, 0, 0, uintptr(unsafe.Pointer(&frame)), 0, 0)
- comCall(renderer.context, 7, 0, 1, uintptr(unsafe.Pointer(&renderer.constants))) // the vertex shaders
- comCall(renderer.context, 16, 0, 1, uintptr(unsafe.Pointer(&renderer.constants))) // the text pixel shader
+ renderer.setScissor(whole)
+ 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)
+ 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)
current := whole
- var cut scissorRect // the columns of one span of a grid line; one variable, since its address escapes
+ var cut scissorRect // the columns of one span of a grid line
for _, batch := range renderer.compositingBatches {
switch batch.Kind {
case compositeRectangles:
if boundKind != compositeRectangles {
- comCall(renderer.context, 35, renderer.blend, 0, uintptr(^uint32(0)))
- comCall(renderer.context, 11, renderer.rectangleVertex, 0, 0)
- comCall(renderer.context, 9, renderer.rectangleFragment, 0, 0)
- comCall(renderer.context, 25, 0, 1, uintptr(unsafe.Pointer(&renderer.view)))
+ comCall3(renderer.context, 35, renderer.blend, 0, uintptr(^uint32(0)))
+ comCall3(renderer.context, 11, renderer.rectangleVertex, 0, 0)
+ comCall3(renderer.context, 9, renderer.rectangleFragment, 0, 0)
+ comCall3(renderer.context, 25, 0, 1, uintptr(unsafe.Pointer(&renderer.view)))
boundKind = compositeRectangles
}
scissor, visible := rectangleScissor(batch, scale, width, height)
@@ -656,18 +662,18 @@ func (renderer *renderer) draw(width, height int, scale float32) error {
continue
}
if scissor != current {
- comCall(renderer.context, 45, 1, uintptr(unsafe.Pointer(&scissor)))
+ renderer.setScissor(scissor)
current = scissor
}
frame.InstanceOffset = uint32(batch.First)
- comCall(renderer.context, 48, renderer.constants, 0, 0, uintptr(unsafe.Pointer(&frame)), 0, 0)
- comCall(renderer.context, 21, 6, uintptr(batch.Count), 0, uintptr(batch.First))
+ comCall6(renderer.context, 48, renderer.constants, 0, 0, uintptr(unsafe.Pointer(frame)), 0, 0)
+ comCall4(renderer.context, 21, 6, uintptr(batch.Count), 0, uintptr(batch.First))
case compositeText:
if boundKind != compositeText {
- comCall(renderer.context, 35, renderer.textBlend, 0, uintptr(^uint32(0)))
- comCall(renderer.context, 11, renderer.textVertex, 0, 0)
- comCall(renderer.context, 9, renderer.textFragment, 0, 0)
- comCall(renderer.context, 10, 0, 1, uintptr(unsafe.Pointer(&renderer.sampler)))
+ comCall3(renderer.context, 35, renderer.textBlend, 0, uintptr(^uint32(0)))
+ comCall3(renderer.context, 11, renderer.textVertex, 0, 0)
+ comCall3(renderer.context, 9, renderer.textFragment, 0, 0)
+ comCall3(renderer.context, 10, 0, 1, uintptr(unsafe.Pointer(&renderer.sampler)))
boundKind = compositeText
}
for labelOffset := batch.First; labelOffset < batch.First+batch.Count; labelOffset++ {
@@ -704,14 +710,14 @@ func (renderer *renderer) draw(width, height int, scale float32) error {
frame.TextMode = 1
frame.TextColor = [4]float32{float32(label.label.Color.Red), float32(label.label.Color.Green), float32(label.label.Color.Blue), float32(label.label.Color.Alpha)}
}
- comCall(renderer.context, 8, 1, 1, uintptr(unsafe.Pointer(&label.view)))
+ comCall3(renderer.context, 8, 1, 1, uintptr(unsafe.Pointer(&label.view)))
if len(label.spans) == 0 {
- comCall(renderer.context, 48, renderer.constants, 0, 0, uintptr(unsafe.Pointer(&frame)), 0, 0)
+ comCall6(renderer.context, 48, renderer.constants, 0, 0, uintptr(unsafe.Pointer(frame)), 0, 0)
if scissor != current {
- comCall(renderer.context, 45, 1, uintptr(unsafe.Pointer(&scissor)))
+ renderer.setScissor(scissor)
current = scissor
}
- comCall(renderer.context, 13, 6, 0)
+ comCall2(renderer.context, 13, 6, 0)
continue
}
// A grid line has a color per run: its coverage is drawn once for each, cut to the
@@ -725,22 +731,37 @@ 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}
- comCall(renderer.context, 48, renderer.constants, 0, 0, uintptr(unsafe.Pointer(&frame)), 0, 0)
+ comCall6(renderer.context, 48, renderer.constants, 0, 0, uintptr(unsafe.Pointer(frame)), 0, 0)
if cut != current {
- comCall(renderer.context, 45, 1, uintptr(unsafe.Pointer(&cut)))
+ renderer.setScissor(cut)
current = cut
}
- comCall(renderer.context, 13, 6, 0)
+ comCall2(renderer.context, 13, 6, 0)
}
}
}
}
- var empty uintptr
- comCall(renderer.context, 8, 1, 1, uintptr(unsafe.Pointer(&empty)))
+ scratch.empty = 0
+ comCall3(renderer.context, 8, 1, 1, uintptr(unsafe.Pointer(&scratch.empty)))
renderer.submissions++
return nil
}
+// drawScratch holds what draw hands Direct3D by address; see draw.
+type drawScratch struct {
+ clear [4]float32
+ viewport viewport
+ scissor scissorRect
+ frame frameConstants
+ empty uintptr
+}
+
+// setScissor narrows the draws that follow to r.
+func (renderer *renderer) setScissor(r scissorRect) {
+ renderer.drawScratch.scissor = r
+ comCall2(renderer.context, 45, 1, uintptr(unsafe.Pointer(&renderer.drawScratch.scissor)))
+}
+
func (renderer *renderer) close() {
for index := range renderer.labels {
renderer.labels[index].close()
@@ -770,8 +791,8 @@ func (renderer *renderer) close() {
// device made again can draw the same scene.
func (renderer *renderer) releaseDevice() {
if renderer.context != 0 {
- comCall(renderer.context, 110)
- comCall(renderer.context, 111)
+ comCall0(renderer.context, 110)
+ comCall0(renderer.context, 111)
}
for index := range renderer.labels {
renderer.labels[index].dropTexture()
diff --git a/internal/platform/windows/save_checkbox_windows.go b/internal/platform/windows/save_checkbox_windows.go
index ee575119f..af6044aaf 100644
--- a/internal/platform/windows/save_checkbox_windows.go
+++ b/internal/platform/windows/save_checkbox_windows.go
@@ -16,7 +16,7 @@ var saveDialogCustomizeInterface = guid{
func addSaveDialogCheckbox(dialog uintptr, label string, checked bool) (uintptr, error) {
var custom uintptr
- if err := hresult(comCall(dialog, 0, uintptr(unsafe.Pointer(&saveDialogCustomizeInterface)), uintptr(unsafe.Pointer(&custom)))); err != nil {
+ if err := hresult(comCall2(dialog, 0, uintptr(unsafe.Pointer(&saveDialogCustomizeInterface)), uintptr(unsafe.Pointer(&custom)))); err != nil {
return 0, fmt.Errorf("windows: customize save file dialog: %w", err)
}
name, err := syscall.UTF16PtrFromString(strings.ReplaceAll(label, "&", "&&")) // a lone & would become a mnemonic
@@ -28,7 +28,7 @@ func addSaveDialogCheckbox(dialog uintptr, label string, checked bool) (uintptr,
if checked {
initial = 1
}
- if err := hresult(comCall(custom, 8, saveCheckboxControlID, uintptr(unsafe.Pointer(name)), initial)); err != nil {
+ if err := hresult(comCall3(custom, 8, saveCheckboxControlID, uintptr(unsafe.Pointer(name)), initial)); err != nil {
release(&custom)
return 0, fmt.Errorf("windows: add save checkbox: %w", err)
}
@@ -37,7 +37,7 @@ func addSaveDialogCheckbox(dialog uintptr, label string, checked bool) (uintptr,
func saveDialogCheckboxState(custom uintptr) (bool, error) {
var checked uint32
- if err := hresult(comCall(custom, 17, saveCheckboxControlID, uintptr(unsafe.Pointer(&checked)))); err != nil {
+ if err := hresult(comCall2(custom, 17, saveCheckboxControlID, uintptr(unsafe.Pointer(&checked)))); err != nil {
return false, fmt.Errorf("windows: read save checkbox: %w", err)
}
return checked != 0, nil
diff --git a/internal/platform/windows/system_windows.go b/internal/platform/windows/system_windows.go
index 007cecbdd..ddb7f862f 100644
--- a/internal/platform/windows/system_windows.go
+++ b/internal/platform/windows/system_windows.go
@@ -497,7 +497,7 @@ func OpenFiles(options OpenFileOptions) ([]string, bool, error) {
if err := configureFileDialog(dialog, options.Title, options.Filters, flags); err != nil {
return err
}
- status := uint32(comCall(dialog, 3, dialogOwner()))
+ status := uint32(comCall1(dialog, 3, dialogOwner()))
if status == dialogCanceled {
canceled = true
return nil
@@ -509,7 +509,7 @@ func OpenFiles(options OpenFileOptions) ([]string, bool, error) {
paths, err = dialogResults(dialog)
} else {
var item uintptr
- if err := hresult(comCall(dialog, 20, uintptr(unsafe.Pointer(&item)))); err != nil {
+ if err := hresult(comCall1(dialog, 20, uintptr(unsafe.Pointer(&item)))); err != nil {
return fmt.Errorf("windows: get open file result: %w", err)
}
defer release(&item)
@@ -537,7 +537,7 @@ func OpenDirectory(options OpenDirectoryOptions) (string, bool, error) {
if err := configureFileDialog(dialog, options.Title, nil, flags); err != nil {
return err
}
- status := uint32(comCall(dialog, 3, dialogOwner()))
+ status := uint32(comCall1(dialog, 3, dialogOwner()))
if status == dialogCanceled {
canceled = true
return nil
@@ -546,7 +546,7 @@ func OpenDirectory(options OpenDirectoryOptions) (string, bool, error) {
return fmt.Errorf("windows: show open directory dialog: %w", err)
}
var item uintptr
- if err := hresult(comCall(dialog, 20, uintptr(unsafe.Pointer(&item)))); err != nil {
+ 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)
@@ -592,7 +592,7 @@ func saveFile(options SaveFileOptions, checkboxLabel string, initial bool) (stri
if err != nil {
return err
}
- if err := hresult(comCall(dialog, 15, uintptr(unsafe.Pointer(name)))); err != nil {
+ if err := hresult(comCall1(dialog, 15, uintptr(unsafe.Pointer(name)))); err != nil {
return fmt.Errorf("windows: set save file name: %w", err)
}
}
@@ -601,11 +601,11 @@ func saveFile(options SaveFileOptions, checkboxLabel string, initial bool) (stri
if err != nil {
return err
}
- if err := hresult(comCall(dialog, 22, uintptr(unsafe.Pointer(extension)))); err != nil {
+ if err := hresult(comCall1(dialog, 22, uintptr(unsafe.Pointer(extension)))); err != nil {
return fmt.Errorf("windows: set save extension: %w", err)
}
}
- status := uint32(comCall(dialog, 3, dialogOwner()))
+ status := uint32(comCall1(dialog, 3, dialogOwner()))
if status == dialogCanceled {
canceled = true
return nil
@@ -614,7 +614,7 @@ func saveFile(options SaveFileOptions, checkboxLabel string, initial bool) (stri
return fmt.Errorf("windows: show save file dialog: %w", err)
}
var item uintptr
- if err := hresult(comCall(dialog, 20, uintptr(unsafe.Pointer(&item)))); err != nil {
+ if err := hresult(comCall1(dialog, 20, uintptr(unsafe.Pointer(&item)))); err != nil {
return fmt.Errorf("windows: get save file result: %w", err)
}
defer release(&item)
@@ -812,10 +812,10 @@ func createFileDialog(classID, interfaceID *guid) (uintptr, error) {
func configureFileDialog(dialog uintptr, title string, filters []FileFilter, flags uint32) error {
var current uint32
- if err := hresult(comCall(dialog, 10, uintptr(unsafe.Pointer(¤t)))); err != nil {
+ if err := hresult(comCall1(dialog, 10, uintptr(unsafe.Pointer(¤t)))); err != nil {
return fmt.Errorf("windows: get file dialog options: %w", err)
}
- if err := hresult(comCall(dialog, 9, uintptr(current|flags))); err != nil {
+ if err := hresult(comCall1(dialog, 9, uintptr(current|flags))); err != nil {
return fmt.Errorf("windows: set file dialog options: %w", err)
}
if title != "" {
@@ -823,7 +823,7 @@ func configureFileDialog(dialog uintptr, title string, filters []FileFilter, fla
if err != nil {
return err
}
- if err := hresult(comCall(dialog, 17, uintptr(unsafe.Pointer(value)))); err != nil {
+ if err := hresult(comCall1(dialog, 17, uintptr(unsafe.Pointer(value)))); err != nil {
return fmt.Errorf("windows: set file dialog title: %w", err)
}
}
@@ -844,7 +844,7 @@ func configureFileDialog(dialog uintptr, title string, filters []FileFilter, fla
strings[index*2], strings[index*2+1] = name, pattern
specs[index] = dialogFilter{Name: &name[0], Pattern: &pattern[0]}
}
- status := comCall(dialog, 4, uintptr(len(specs)), uintptr(unsafe.Pointer(&specs[0])))
+ status := comCall2(dialog, 4, uintptr(len(specs)), uintptr(unsafe.Pointer(&specs[0])))
runtime.KeepAlive(strings)
if err := hresult(status); err != nil {
return fmt.Errorf("windows: set file dialog filters: %w", err)
@@ -854,12 +854,12 @@ func configureFileDialog(dialog uintptr, title string, filters []FileFilter, fla
func dialogResults(dialog uintptr) ([]string, error) {
var array uintptr
- if err := hresult(comCall(dialog, 27, uintptr(unsafe.Pointer(&array)))); err != nil {
+ if err := hresult(comCall1(dialog, 27, uintptr(unsafe.Pointer(&array)))); err != nil {
return nil, fmt.Errorf("windows: get open file results: %w", err)
}
defer release(&array)
var count uint32
- if err := hresult(comCall(array, 7, uintptr(unsafe.Pointer(&count)))); err != nil {
+ if err := hresult(comCall1(array, 7, uintptr(unsafe.Pointer(&count)))); err != nil {
return nil, fmt.Errorf("windows: count open file results: %w", err)
}
if count > 1024 {
@@ -868,7 +868,7 @@ func dialogResults(dialog uintptr) ([]string, error) {
paths := make([]string, 0, count)
for index := uint32(0); index < count; index++ {
var item uintptr
- if err := hresult(comCall(array, 8, uintptr(index), uintptr(unsafe.Pointer(&item)))); err != nil {
+ if err := hresult(comCall2(array, 8, uintptr(index), uintptr(unsafe.Pointer(&item)))); err != nil {
return nil, fmt.Errorf("windows: get open file result %d: %w", index, err)
}
path, err := shellItemPath(item)
@@ -883,7 +883,7 @@ func dialogResults(dialog uintptr) ([]string, error) {
func shellItemPath(item uintptr) (string, error) {
var value uintptr
- if err := hresult(comCall(item, 5, fileSystemPath, uintptr(unsafe.Pointer(&value)))); err != nil {
+ if err := hresult(comCall2(item, 5, fileSystemPath, uintptr(unsafe.Pointer(&value)))); err != nil {
return "", fmt.Errorf("windows: get file system path: %w", err)
}
defer taskMemoryFree.Call(value)
diff --git a/internal/platform/windows/taskbar_icon_windows.go b/internal/platform/windows/taskbar_icon_windows.go
index dfca1d39c..296dac7eb 100644
--- a/internal/platform/windows/taskbar_icon_windows.go
+++ b/internal/platform/windows/taskbar_icon_windows.go
@@ -32,7 +32,7 @@ func setStringProperty(store uintptr, id uint32, text string) error {
}
key := propertyKey{Format: appModelKey, ID: id}
value := stringProperty{Kind: 31 /* VT_LPWSTR */, Text: encoded}
- return hresult(comCall(store, 6 /* SetValue */, uintptr(unsafe.Pointer(&key)), uintptr(unsafe.Pointer(&value))))
+ return hresult(comCall2(store, 6 /* SetValue */, uintptr(unsafe.Pointer(&key)), uintptr(unsafe.Pointer(&value))))
}
// WM_SETICON supplies an individual window. Explorer reads the group's picture
@@ -79,7 +79,7 @@ func (state *windowState) clearTaskbarIcon() {
for _, id := range []uint32{3, 5} {
key := propertyKey{Format: appModelKey, ID: id}
var empty stringProperty // VT_EMPTY releases the window's stored value.
- comCall(store, 6, uintptr(unsafe.Pointer(&key)), uintptr(unsafe.Pointer(&empty)))
+ comCall2(store, 6, uintptr(unsafe.Pointer(&key)), uintptr(unsafe.Pointer(&empty)))
}
state.taskbarIconSet = false
}
diff --git a/internal/platform/windows/text_windows.go b/internal/platform/windows/text_windows.go
index df70b8414..2ea2b96a8 100644
--- a/internal/platform/windows/text_windows.go
+++ b/internal/platform/windows/text_windows.go
@@ -425,7 +425,7 @@ 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.
- comCall(renderer.context, 48, label.texture, 0, 0, uintptr(unsafe.Pointer(&pixels[0])), uintptr(width*4), 0)
+ comCall6(renderer.context, 48, label.texture, 0, 0, uintptr(unsafe.Pointer(&pixels[0])), uintptr(width*4), 0)
label.scale, label.skip, label.stale = scale, skip, false
renderer.labelRebuilds++
return nil
@@ -434,10 +434,10 @@ func (renderer *renderer) uploadLabel(label *labelTexture, pixels []byte, scale
data := resourceData{Data: unsafe.Pointer(&pixels[0]), Pitch: uint32(width * 4)}
release(&label.view)
release(&label.texture)
- if err := hresult(comCall(renderer.device, 5, uintptr(unsafe.Pointer(&description)), uintptr(unsafe.Pointer(&data)), uintptr(unsafe.Pointer(&label.texture)))); err != nil {
+ if err := hresult(comCall3(renderer.device, 5, uintptr(unsafe.Pointer(&description)), uintptr(unsafe.Pointer(&data)), uintptr(unsafe.Pointer(&label.texture)))); err != nil {
return err
}
- if err := hresult(comCall(renderer.device, 7, label.texture, 0, uintptr(unsafe.Pointer(&label.view)))); err != nil {
+ if err := hresult(comCall3(renderer.device, 7, label.texture, 0, uintptr(unsafe.Pointer(&label.view)))); err != nil {
return err
}
label.scale = scale
@@ -567,7 +567,7 @@ func (services *textServices) measureWeightIn(typeface, value string, size float
}
defer release(&layout)
var metrics textMetrics
- if err := hresult(comCall(layout, 60, uintptr(unsafe.Pointer(&metrics)))); err != nil {
+ if err := hresult(comCall1(layout, 60, uintptr(unsafe.Pointer(&metrics)))); err != nil {
return text.Metrics{}, err
}
if metrics.Lines > 1024 {
@@ -575,7 +575,7 @@ func (services *textServices) measureWeightIn(typeface, value string, size float
}
lines := make([]lineMetrics, max(1, int(metrics.Lines)))
var count uint32
- if err := hresult(comCall(layout, 59, uintptr(unsafe.Pointer(&lines[0])), uintptr(len(lines)), uintptr(unsafe.Pointer(&count)))); err != nil {
+ if err := hresult(comCall3(layout, 59, uintptr(unsafe.Pointer(&lines[0])), uintptr(len(lines)), uintptr(unsafe.Pointer(&count)))); err != nil {
return text.Metrics{}, err
}
line := lines[0]
@@ -637,7 +637,7 @@ func (services *textServices) boxStrokes(typeface string, size, weight float32)
collection, owned := customFonts.collection, false
if collection == 0 {
customFonts.RUnlock()
- status := comCall(services.write, writeFactoryGetSystemFontCollection, uintptr(unsafe.Pointer(&collection)), 0)
+ status := comCall2(services.write, writeFactoryGetSystemFontCollection, uintptr(unsafe.Pointer(&collection)), 0)
if err = hresult(status); err != nil || collection == 0 {
return 0, 0
}
@@ -649,11 +649,11 @@ func (services *textServices) boxStrokes(typeface string, size, weight float32)
defer release(&collection)
}
var index, exists uint32
- if err := hresult(comCall(collection, writeCollectionFindFamilyName, uintptr(unsafe.Pointer(familyName)), uintptr(unsafe.Pointer(&index)), uintptr(unsafe.Pointer(&exists)))); err != nil || exists == 0 {
+ if err := hresult(comCall3(collection, writeCollectionFindFamilyName, uintptr(unsafe.Pointer(familyName)), uintptr(unsafe.Pointer(&index)), uintptr(unsafe.Pointer(&exists)))); err != nil || exists == 0 {
return 0, 0
}
var family, font uintptr
- if err := hresult(comCall(collection, writeCollectionGetFontFamily, uintptr(index), uintptr(unsafe.Pointer(&family)))); err != nil {
+ if err := hresult(comCall2(collection, writeCollectionGetFontFamily, uintptr(index), uintptr(unsafe.Pointer(&family)))); err != nil {
return 0, 0
}
defer release(&family)
@@ -661,26 +661,26 @@ func (services *textServices) boxStrokes(typeface string, size, weight float32)
stretchNormal = 5
styleNormal = 0
)
- if err := hresult(comCall(family, writeFontFamilyGetFirstMatchingFont, uintptr(services.monoWeight(weight)), stretchNormal, styleNormal, uintptr(unsafe.Pointer(&font)))); err != nil {
+ if err := hresult(comCall4(family, writeFontFamilyGetFirstMatchingFont, uintptr(services.monoWeight(weight)), stretchNormal, styleNormal, uintptr(unsafe.Pointer(&font)))); err != nil {
return 0, 0
}
defer release(&font)
var fontMetrics writeFontMetrics
- if err := hresult(comCall(font, writeFontGetMetrics, uintptr(unsafe.Pointer(&fontMetrics)))); err != nil || fontMetrics.DesignUnitsPerEm == 0 {
+ if err := hresult(comCall1(font, writeFontGetMetrics, uintptr(unsafe.Pointer(&fontMetrics)))); err != nil || fontMetrics.DesignUnitsPerEm == 0 {
return 0, 0
}
var face uintptr
- if err := hresult(comCall(font, writeFontCreateFontFace, uintptr(unsafe.Pointer(&face)))); err != nil || face == 0 {
+ if err := hresult(comCall1(font, writeFontCreateFontFace, uintptr(unsafe.Pointer(&face)))); err != nil || face == 0 {
return 0, 0
}
defer release(&face)
codepoints := [2]uint32{0x2502, 0x2503} // │ ┃
var glyphs [2]uint16
- if err := hresult(comCall(face, writeFontFaceGetGlyphIndices, uintptr(unsafe.Pointer(&codepoints[0])), uintptr(len(codepoints)), uintptr(unsafe.Pointer(&glyphs[0])))); err != nil {
+ if err := hresult(comCall3(face, writeFontFaceGetGlyphIndices, uintptr(unsafe.Pointer(&codepoints[0])), uintptr(len(codepoints)), uintptr(unsafe.Pointer(&glyphs[0])))); err != nil {
return 0, 0
}
var glyphMetrics [2]writeGlyphMetrics
- if err := hresult(comCall(face, writeFontFaceGetDesignGlyphMetrics, uintptr(unsafe.Pointer(&glyphs[0])), uintptr(len(glyphs)), uintptr(unsafe.Pointer(&glyphMetrics[0])), 0)); err != nil {
+ if err := hresult(comCall4(face, writeFontFaceGetDesignGlyphMetrics, uintptr(unsafe.Pointer(&glyphs[0])), uintptr(len(glyphs)), uintptr(unsafe.Pointer(&glyphMetrics[0])), 0)); err != nil {
return 0, 0
}
em := float32(fontMetrics.DesignUnitsPerEm)
diff --git a/internal/platform/windows/textengine_windows.go b/internal/platform/windows/textengine_windows.go
index 329f2865d..ec54feaf8 100644
--- a/internal/platform/windows/textengine_windows.go
+++ b/internal/platform/windows/textengine_windows.go
@@ -261,8 +261,8 @@ func (engine *textEngine) initialize() error {
// The system's font fallback, named: a line is measured with the fonts that draw it.
// IDWriteFactory2 is Windows 8.1; before it, the layouts' default fallback applies.
var factory2 uintptr
- if comCall(engine.services.write, 0, uintptr(unsafe.Pointer(&writeFactory2IID)), uintptr(unsafe.Pointer(&factory2))) == 0 && factory2 != 0 {
- if hresult(comCall(factory2, writeFactoryGetSystemFontFallback, uintptr(unsafe.Pointer(&engine.fallback)))) != nil {
+ if comCall2(engine.services.write, 0, uintptr(unsafe.Pointer(&writeFactory2IID)), uintptr(unsafe.Pointer(&factory2))) == 0 && factory2 != 0 {
+ if hresult(comCall1(factory2, writeFactoryGetSystemFontFallback, uintptr(unsafe.Pointer(&engine.fallback)))) != nil {
engine.fallback = 0
}
release(&factory2)
@@ -278,8 +278,8 @@ func setFontFallback(format, fallback uintptr) {
return
}
var format1 uintptr
- if comCall(format, 0, uintptr(unsafe.Pointer(&writeTextFormat1IID)), uintptr(unsafe.Pointer(&format1))) == 0 && format1 != 0 {
- comCall(format1, writeFormatSetFontFallback, fallback)
+ if comCall2(format, 0, uintptr(unsafe.Pointer(&writeTextFormat1IID)), uintptr(unsafe.Pointer(&format1))) == 0 && format1 != 0 {
+ comCall1(format1, writeFormatSetFontFallback, fallback)
release(&format1)
}
}
@@ -350,12 +350,12 @@ func (engine *textEngine) shapeStyle(value string, size, weight float32, italic
// The paragraph reads right to left, so that the punctuation around a right-to-left
// line falls on the side it belongs; trailing alignment keeps its glyphs
// at the left of the layout, where the label's box starts.
- comCall(layout, writeSetTextAlignment, 1)
- comCall(layout, writeSetReadingDirection, 1)
+ comCall1(layout, writeSetTextAlignment, 1)
+ comCall1(layout, writeSetReadingDirection, 1)
}
line := &shapedLine{layout: layout, length: len(value)}
var metrics textMetrics
- if err := hresult(comCall(layout, writeGetMetrics, uintptr(unsafe.Pointer(&metrics)))); err != nil {
+ if err := hresult(comCall1(layout, writeGetMetrics, uintptr(unsafe.Pointer(&metrics)))); err != nil {
line.close()
return nil, err
}
@@ -365,7 +365,7 @@ func (engine *textEngine) shapeStyle(value string, size, weight float32, italic
}
rows := make([]lineMetrics, max(1, int(metrics.Lines)))
var count uint32
- if err := hresult(comCall(layout, writeGetLineMetrics, uintptr(unsafe.Pointer(&rows[0])), uintptr(len(rows)), uintptr(unsafe.Pointer(&count)))); err != nil {
+ if err := hresult(comCall3(layout, writeGetLineMetrics, uintptr(unsafe.Pointer(&rows[0])), uintptr(len(rows)), uintptr(unsafe.Pointer(&count)))); err != nil {
line.close()
return nil, err
}
@@ -413,7 +413,7 @@ func (engine *textEngine) ensureTables(line *shapedLine, value string) error {
position := uint32(unitAt[start])
var x, y float32
engine.hit = hitMetrics{}
- if err := hresult(comCall(line.layout, writeHitTestTextPosition, uintptr(position), 0, uintptr(unsafe.Pointer(&x)), uintptr(unsafe.Pointer(&y)), uintptr(unsafe.Pointer(&engine.hit)))); err != nil {
+ if err := hresult(comCall5(line.layout, writeHitTestTextPosition, uintptr(position), 0, uintptr(unsafe.Pointer(&x)), uintptr(unsafe.Pointer(&y)), uintptr(unsafe.Pointer(&engine.hit)))); err != nil {
return fmt.Errorf("windows: hit test: %w", err)
}
// The cluster DirectWrite reports, as bytes; a report that does not start here is
@@ -436,7 +436,7 @@ func (engine *textEngine) ensureTables(line *shapedLine, value string) error {
// The end of the line is the trailing edge of its last cluster.
last := int(tables.cluster[n-1])
var x, y float32
- if err := hresult(comCall(line.layout, writeHitTestTextPosition, uintptr(unitAt[last]), 1, uintptr(unsafe.Pointer(&x)), uintptr(unsafe.Pointer(&y)), uintptr(unsafe.Pointer(&engine.hit)))); err != nil {
+ if err := hresult(comCall5(line.layout, writeHitTestTextPosition, uintptr(unitAt[last]), 1, uintptr(unsafe.Pointer(&x)), uintptr(unsafe.Pointer(&y)), uintptr(unsafe.Pointer(&engine.hit)))); err != nil {
return fmt.Errorf("windows: hit test: %w", err)
}
tables.caret[n] = x - line.left
@@ -450,7 +450,7 @@ func (engine *textEngine) ensureTables(line *shapedLine, value string) error {
}
// A right-to-left cluster's box is not between its carets in logical order.
var count uint32
- if err := hresult(comCall(line.layout, writeHitTestTextRange, uintptr(unitAt[start]), uintptr(unitAt[next]-unitAt[start]), 0, 0,
+ if err := hresult(comCall7(line.layout, writeHitTestTextRange, uintptr(unitAt[start]), uintptr(unitAt[next]-unitAt[start]), 0, 0,
uintptr(unsafe.Pointer(&engine.ranges[0])), uintptr(len(engine.ranges)), uintptr(unsafe.Pointer(&count)))); err != nil && count == 0 {
return fmt.Errorf("windows: hit test range: %w", err)
}
diff --git a/internal/platform/windows/trim_windows.go b/internal/platform/windows/trim_windows.go
index 951334533..79e591314 100644
--- a/internal/platform/windows/trim_windows.go
+++ b/internal/platform/windows/trim_windows.go
@@ -35,12 +35,12 @@ func (renderer *renderer) trim() {
if renderer.device == 0 || renderer.context == 0 {
return
}
- comCall(renderer.context, 111) // ID3D11DeviceContext::Flush: lets destroyed objects go
+ comCall0(renderer.context, 111) // ID3D11DeviceContext::Flush: lets destroyed objects go
var dxgi uintptr
- if hresult(comCall(renderer.device, 0, uintptr(unsafe.Pointer(&dxgiDevice3IID)), uintptr(unsafe.Pointer(&dxgi)))) != nil {
+ if hresult(comCall2(renderer.device, 0, uintptr(unsafe.Pointer(&dxgiDevice3IID)), uintptr(unsafe.Pointer(&dxgi)))) != nil {
return // Windows 8.1 and earlier have no Trim
}
- comCall(dxgi, dxgiDevice3Trim)
+ comCall0(dxgi, dxgiDevice3Trim)
release(&dxgi)
}
diff --git a/internal/platform/windows/web_bounds_windows_amd64.go b/internal/platform/windows/web_bounds_windows_amd64.go
index 275f84ae8..704a14b4f 100644
--- a/internal/platform/windows/web_bounds_windows_amd64.go
+++ b/internal/platform/windows/web_bounds_windows_amd64.go
@@ -4,5 +4,5 @@ import "unsafe"
// putBounds sets the controller's bounds. A RECT is passed by reference on x64.
func putBounds(controller uintptr, bounds rect) {
- comCall(controller, controllerPutBounds, uintptr(unsafe.Pointer(&bounds)))
+ comCall1(controller, controllerPutBounds, uintptr(unsafe.Pointer(&bounds)))
}
diff --git a/internal/platform/windows/web_bounds_windows_other.go b/internal/platform/windows/web_bounds_windows_other.go
index 5e29e48dd..d3df37c13 100644
--- a/internal/platform/windows/web_bounds_windows_other.go
+++ b/internal/platform/windows/web_bounds_windows_other.go
@@ -7,5 +7,5 @@ package windows
func putBounds(controller uintptr, bounds rect) {
low := uintptr(uint32(bounds.Left)) | uintptr(uint32(bounds.Top))<<32
high := uintptr(uint32(bounds.Right)) | uintptr(uint32(bounds.Bottom))<<32
- comCall(controller, controllerPutBounds, low, high)
+ comCall2(controller, controllerPutBounds, low, high)
}
diff --git a/internal/platform/windows/web_windows.go b/internal/platform/windows/web_windows.go
index 2b483f343..c81a22985 100644
--- a/internal/platform/windows/web_windows.go
+++ b/internal/platform/windows/web_windows.go
@@ -249,19 +249,19 @@ func (page *windowsWeb) createController(environment uintptr) {
handler := newHandler(func(status, controller uintptr) uintptr {
if int32(uint32(status)) < 0 || controller == 0 || page.closed {
if page.closed && controller != 0 {
- comCall(controller, controllerClose)
+ comCall0(controller, controllerClose)
}
return 0
}
- comCall(controller, 1)
+ comCall0(controller, 1)
page.controller = controller
- comCall(controller, controllerGetWebView, uintptr(unsafe.Pointer(&page.view)))
+ comCall1(controller, controllerGetWebView, uintptr(unsafe.Pointer(&page.view)))
page.attach(environment)
return 0
})
name, inPrivate, options := controllerProfile(page.config)
if !options {
- comCall(environment, envCreateController, page.window, handler)
+ comCall2(environment, envCreateController, page.window, handler)
return
}
// A runtime too old to offer the options cannot make a page in a profile of its own, and must not
@@ -276,26 +276,26 @@ func (page *windowsWeb) createController(environment uintptr) {
// off the record when inPrivate is set.
func (page *windowsWeb) createOptionsController(environment, handler uintptr, name string, inPrivate bool) error {
var environment10 uintptr
- status := comCall(environment, 0, uintptr(unsafe.Pointer(&iidEnvironment10)), uintptr(unsafe.Pointer(&environment10)))
+ status := comCall2(environment, 0, uintptr(unsafe.Pointer(&iidEnvironment10)), uintptr(unsafe.Pointer(&environment10)))
if int32(uint32(status)) < 0 || environment10 == 0 {
return fmt.Errorf("%w: a page in a storage partition or an ephemeral page needs WebView2 Runtime 101 (SDK 1.0.1210.39) or newer", platform.ErrWebViewUnsupported)
}
- defer comCall(environment10, 2)
+ defer comCall0(environment10, 2)
var options uintptr
- if status := comCall(environment10, envCreateControllerOptions, uintptr(unsafe.Pointer(&options))); int32(uint32(status)) < 0 || options == 0 {
+ if status := comCall1(environment10, envCreateControllerOptions, uintptr(unsafe.Pointer(&options))); int32(uint32(status)) < 0 || options == 0 {
return fmt.Errorf("windows: make the WebView2 controller options: HRESULT %#x", uint32(status))
}
- defer comCall(options, 2)
+ defer comCall0(options, 2)
profile := wide(name)
- if status := comCall(options, optionsPutProfileName, uintptr(unsafe.Pointer(profile))); int32(uint32(status)) < 0 {
+ if status := comCall1(options, optionsPutProfileName, uintptr(unsafe.Pointer(profile))); int32(uint32(status)) < 0 {
return fmt.Errorf("windows: name the WebView2 profile %q: HRESULT %#x", name, uint32(status))
}
if inPrivate {
- if status := comCall(options, optionsPutInPrivateMode, 1); int32(uint32(status)) < 0 {
+ if status := comCall1(options, optionsPutInPrivateMode, 1); int32(uint32(status)) < 0 {
return fmt.Errorf("windows: turn on WebView2 InPrivate mode: HRESULT %#x", uint32(status))
}
}
- if status := comCall(environment10, envCreateControllerWithOptions, page.window, options, handler); int32(uint32(status)) < 0 {
+ if status := comCall3(environment10, envCreateControllerWithOptions, page.window, options, handler); int32(uint32(status)) < 0 {
return fmt.Errorf("windows: create the WebView2 controller in profile %q: HRESULT %#x", name, uint32(status))
}
return nil
@@ -317,35 +317,35 @@ func (page *windowsWeb) fail(err error) {
func (page *windowsWeb) attach(environment uintptr) {
view := page.view
var token int64
- comCall(view, viewAddMessageReceived, newHandler(func(_, args uintptr) uintptr {
+ comCall2(view, viewAddMessageReceived, newHandler(func(_, args uintptr) uintptr {
var text uintptr
- if comCall(args, messageTryGetString, uintptr(unsafe.Pointer(&text))) == 0 && page.config.OnMessage != nil {
+ if comCall1(args, messageTryGetString, uintptr(unsafe.Pointer(&text))) == 0 && page.config.OnMessage != nil {
page.config.OnMessage(wideString(text))
}
return 0
}), uintptr(unsafe.Pointer(&token)))
- comCall(view, viewAddNavStarting, newHandler(func(_, args uintptr) uintptr {
+ comCall2(view, viewAddNavStarting, newHandler(func(_, args uintptr) uintptr {
page.navigationStarting(args, true)
return 0
}), uintptr(unsafe.Pointer(&token)))
- comCall(view, viewAddFrameNavStarting, newHandler(func(_, args uintptr) uintptr {
+ comCall2(view, viewAddFrameNavStarting, newHandler(func(_, args uintptr) uintptr {
page.navigationStarting(args, false)
return 0
}), uintptr(unsafe.Pointer(&token)))
- comCall(view, viewAddNewWindowRequested, newHandler(func(_, args uintptr) uintptr {
+ comCall2(view, viewAddNewWindowRequested, newHandler(func(_, args uintptr) uintptr {
page.newWindowRequested(args)
return 0
}), uintptr(unsafe.Pointer(&token)))
page.addDownloadHandler()
- comCall(view, viewAddContentLoading, newHandler(func(_, _ uintptr) uintptr {
+ comCall2(view, viewAddContentLoading, newHandler(func(_, _ uintptr) uintptr {
page.loaded(platform.WebLoadCommitted, page.sourceAddress(), platform.WebLoadNoError, "")
return 0
}), uintptr(unsafe.Pointer(&token)))
- comCall(view, viewAddNavCompleted, newHandler(func(_, args uintptr) uintptr {
+ comCall2(view, viewAddNavCompleted, newHandler(func(_, args uintptr) uintptr {
page.navigationCompleted(args)
return 0
}), uintptr(unsafe.Pointer(&token)))
- comCall(view, viewAddProcessFailed, newHandler(func(_, args uintptr) uintptr {
+ comCall2(view, viewAddProcessFailed, newHandler(func(_, args uintptr) uintptr {
page.processFailed(args)
return 0
}), uintptr(unsafe.Pointer(&token)))
@@ -353,13 +353,13 @@ func (page *windowsWeb) attach(environment uintptr) {
if page.config.BridgeMainFrameOnly {
script = platform.WebBridgeMainFrameOnlyScript
}
- comCall(view, viewAddScriptOnCreate, uintptr(unsafe.Pointer(wide(script))), 0)
+ comCall2(view, viewAddScriptOnCreate, uintptr(unsafe.Pointer(wide(script))), 0)
if scheme := page.config.Scheme; scheme != nil && scheme.Name != "" {
- comCall(view, viewAddWebResourceReq, newHandler(func(_, args uintptr) uintptr {
+ comCall2(view, viewAddWebResourceReq, newHandler(func(_, args uintptr) uintptr {
page.serve(environment, args)
return 0
}), uintptr(unsafe.Pointer(&token)))
- comCall(view, viewAddResourceFilter, uintptr(unsafe.Pointer(wide("https://"+scheme.Name+webSchemeTLD+"/*"))), resourceContextAll)
+ comCall2(view, viewAddResourceFilter, uintptr(unsafe.Pointer(wide("https://"+scheme.Name+webSchemeTLD+"/*"))), resourceContextAll)
}
switch {
case page.config.HTML != "":
@@ -411,10 +411,10 @@ func (page *windowsWeb) navigationCompleted(args uintptr) {
code := platform.WebLoadNoError
var success int32
if args != 0 {
- comCall(args, navigationCompletedIsSuccess, uintptr(unsafe.Pointer(&success)))
+ comCall1(args, navigationCompletedIsSuccess, uintptr(unsafe.Pointer(&success)))
if success == 0 {
var status int32
- comCall(args, navigationCompletedError, uintptr(unsafe.Pointer(&status)))
+ comCall1(args, navigationCompletedError, uintptr(unsafe.Pointer(&status)))
code = platform.WebLoadErrorFromWebView2Status(status)
}
}
@@ -432,14 +432,14 @@ func (page *windowsWeb) processFailed(args uintptr) {
return
}
var kind int32
- comCall(args, processFailedKind, uintptr(unsafe.Pointer(&kind)))
+ comCall1(args, processFailedKind, uintptr(unsafe.Pointer(&kind)))
// A runtime older than ICoreWebView2ProcessFailedEventArgs2 says only the kind: -1 is the
// platform's way of hearing that nothing was said about why.
reason := int32(-1)
var detailed uintptr
- if status := comCall(args, 0, uintptr(unsafe.Pointer(&iidProcessFailedArgs2)), uintptr(unsafe.Pointer(&detailed))); status == 0 && detailed != 0 {
- comCall(detailed, processFailedReason, uintptr(unsafe.Pointer(&reason)))
- comCall(detailed, 2)
+ if status := comCall2(args, 0, uintptr(unsafe.Pointer(&iidProcessFailedArgs2)), uintptr(unsafe.Pointer(&detailed))); status == 0 && detailed != 0 {
+ comCall1(detailed, processFailedReason, uintptr(unsafe.Pointer(&reason)))
+ comCall0(detailed, 2)
}
failure, pageProcess := platform.WebProcessFailureFromWebView2(kind, reason)
if !pageProcess {
@@ -457,7 +457,7 @@ func (page *windowsWeb) sourceAddress() string {
return ""
}
var address uintptr
- comCall(page.view, viewGetSource, uintptr(unsafe.Pointer(&address)))
+ comCall1(page.view, viewGetSource, uintptr(unsafe.Pointer(&address)))
return wideString(address)
}
@@ -467,7 +467,7 @@ func (page *windowsWeb) documentTitle() string {
return ""
}
var title uintptr
- comCall(page.view, viewGetDocumentTitle, uintptr(unsafe.Pointer(&title)))
+ comCall1(page.view, viewGetDocumentTitle, uintptr(unsafe.Pointer(&title)))
return wideString(title)
}
@@ -487,13 +487,13 @@ func (page *windowsWeb) appAddress(address string) string {
// refused navigation is cancelled, so the foreign document is never fetched.
func (page *windowsWeb) navigationStarting(args uintptr, mainFrame bool) {
var address uintptr
- comCall(args, startingGetURI, uintptr(unsafe.Pointer(&address)))
+ comCall1(args, startingGetURI, uintptr(unsafe.Pointer(&address)))
url := wideString(address)
allowed := page.config.Navigate == nil
if !allowed {
var gesture, redirect int32
- comCall(args, startingGetUserGesture, uintptr(unsafe.Pointer(&gesture)))
- comCall(args, startingGetRedirected, uintptr(unsafe.Pointer(&redirect)))
+ comCall1(args, startingGetUserGesture, uintptr(unsafe.Pointer(&gesture)))
+ comCall1(args, startingGetRedirected, uintptr(unsafe.Pointer(&redirect)))
allowed = page.config.Navigate(platform.WebNavigation{
URL: page.appAddress(url),
MainFrame: mainFrame,
@@ -501,7 +501,7 @@ func (page *windowsWeb) navigationStarting(args uintptr, mainFrame bool) {
})
}
if !allowed {
- comCall(args, startingPutCancel, 1)
+ comCall1(args, startingPutCancel, 1)
if mainFrame {
page.refused, page.loading = true, false
}
@@ -524,9 +524,9 @@ func (page *windowsWeb) navigationStarting(args uintptr, mainFrame bool) {
// browser and a refused or nil NewWindow opens nothing.
func (page *windowsWeb) newWindowRequested(args uintptr) {
var address uintptr
- comCall(args, newWindowGetURI, uintptr(unsafe.Pointer(&address)))
+ comCall1(args, newWindowGetURI, uintptr(unsafe.Pointer(&address)))
url := page.appAddress(wideString(address))
- comCall(args, newWindowPutHandled, 1)
+ comCall1(args, newWindowPutHandled, 1)
if page.config.NewWindow == nil || !page.config.NewWindow(url) || !platform.OpenableURL(url) {
return
}
@@ -538,15 +538,15 @@ func (page *windowsWeb) newWindowRequested(args uintptr) {
// be refused; it is said once rather than pretended away.
func (page *windowsWeb) addDownloadHandler() {
var extended uintptr
- if err := hresult(comCall(page.view, 0, uintptr(unsafe.Pointer(&interfaceWebView4)), uintptr(unsafe.Pointer(&extended)))); err != nil || extended == 0 {
+ if err := hresult(comCall2(page.view, 0, uintptr(unsafe.Pointer(&interfaceWebView4)), uintptr(unsafe.Pointer(&extended)))); err != nil || extended == 0 {
if diag.Enabled(diag.Warn) {
diag.Report(diag.Warn, "web", "download", "the WebView2 runtime cannot report downloads (ICoreWebView2_4 is missing); Download cannot refuse them")
}
return
}
- defer comCall(extended, 2)
+ defer comCall0(extended, 2)
var token int64
- comCall(extended, viewAddDownloadStarting, newHandler(func(_, args uintptr) uintptr {
+ comCall2(extended, viewAddDownloadStarting, newHandler(func(_, args uintptr) uintptr {
page.downloadStarting(args)
return 0
}), uintptr(unsafe.Pointer(&token)))
@@ -557,30 +557,30 @@ func (page *windowsWeb) addDownloadHandler() {
// hidden either way.
func (page *windowsWeb) downloadStarting(args uintptr) {
var operation uintptr
- if comCall(args, downloadArgsGetOperation, uintptr(unsafe.Pointer(&operation))) != 0 || operation == 0 {
- comCall(args, downloadArgsPutCancel, 1)
+ if comCall1(args, downloadArgsGetOperation, uintptr(unsafe.Pointer(&operation))) != 0 || operation == 0 {
+ comCall1(args, downloadArgsPutCancel, 1)
return
}
var address uintptr
- comCall(operation, downloadGetURI, uintptr(unsafe.Pointer(&address)))
+ comCall1(operation, downloadGetURI, uintptr(unsafe.Pointer(&address)))
url := page.appAddress(wideString(address))
- comCall(args, downloadArgsPutHandled, 1)
+ comCall1(args, downloadArgsPutHandled, 1)
if page.config.Download == nil || !page.config.Download(url) {
- comCall(args, downloadArgsPutCancel, 1)
+ comCall1(args, downloadArgsPutCancel, 1)
return
}
suggested := ""
var result uintptr
- if comCall(args, downloadArgsGetResultPath, uintptr(unsafe.Pointer(&result))) == 0 && result != 0 {
+ if comCall1(args, downloadArgsGetResultPath, uintptr(unsafe.Pointer(&result))) == 0 && result != 0 {
suggested = filepath.Base(wideString(result))
}
folder := downloadsFolder()
if err := os.MkdirAll(folder, 0o700); err != nil {
- comCall(args, downloadArgsPutCancel, 1)
+ comCall1(args, downloadArgsPutCancel, 1)
return
}
destination := platform.FreeDownloadPath(folder, platform.DownloadFileName(suggested, url))
- comCall(args, downloadArgsPutResultPath, uintptr(unsafe.Pointer(wide(destination))))
+ comCall1(args, downloadArgsPutResultPath, uintptr(unsafe.Pointer(wide(destination))))
}
// downloadsFolder is the user's downloads folder: the known folder, which may have been moved
@@ -599,9 +599,9 @@ func downloadsFolder() string {
func (page *windowsWeb) serve(environment, args uintptr) {
scheme := page.config.Scheme
var request, address uintptr
- comCall(args, resourceArgsGetRequest, uintptr(unsafe.Pointer(&request)))
- comCall(request, resourceRequestGetURI, uintptr(unsafe.Pointer(&address)))
- comCall(request, 2)
+ comCall1(args, resourceArgsGetRequest, uintptr(unsafe.Pointer(&request)))
+ comCall1(request, resourceRequestGetURI, uintptr(unsafe.Pointer(&address)))
+ comCall0(request, 2)
parsed, err := url.Parse(wideString(address))
if err != nil || scheme == nil {
return
@@ -629,15 +629,15 @@ func (page *windowsWeb) answer(environment, args uintptr, answer platform.WebAns
stream, _, _ = createMemoryBlob.Call(0, 0)
}
var response uintptr
- comCall(environment, envCreateResponse, stream, uintptr(answer.Status),
+ comCall5(environment, envCreateResponse, stream, uintptr(answer.Status),
uintptr(unsafe.Pointer(wide(answer.Reason))), uintptr(unsafe.Pointer(wide(answer.HeaderBlock()))),
uintptr(unsafe.Pointer(&response)))
if response != 0 {
- comCall(args, resourceArgsPutResponse, response)
- comCall(response, 2)
+ comCall1(args, resourceArgsPutResponse, response)
+ comCall0(response, 2)
}
if stream != 0 {
- comCall(stream, 2)
+ comCall0(stream, 2)
}
}
@@ -646,7 +646,7 @@ func (page *windowsWeb) answer(environment, args uintptr, answer platform.WebAns
// page's window, which is where the runtime's objects may be touched.
func (page *windowsWeb) hold(args uintptr, path string) {
var deferral uintptr
- comCall(args, resourceArgsGetDeferral, uintptr(unsafe.Pointer(&deferral)))
+ comCall1(args, resourceArgsGetDeferral, uintptr(unsafe.Pointer(&deferral)))
if deferral == 0 {
return // the runtime will not wait, so there is nothing to answer into
}
@@ -680,12 +680,12 @@ func answerSchemeRequest(id uintptr) {
return
}
if entry.page.closed || entry.page.environment == nil || entry.page.environment.object == 0 {
- comCall(entry.deferral, 2)
+ comCall0(entry.deferral, 2)
return
}
entry.page.answer(entry.page.environment.object, entry.args, platform.AnswerWebResponse(entry.response, true))
- comCall(entry.deferral, deferralComplete)
- comCall(entry.deferral, 2)
+ comCall0(entry.deferral, deferralComplete)
+ comCall0(entry.deferral, 2)
}
// releaseAnswers lets go of the requests the runtime holds open for a page that is closing. An answer
@@ -701,7 +701,7 @@ func (page *windowsWeb) releaseAnswers() {
}
webAnswersMu.Unlock()
for _, entry := range held {
- comCall(entry.deferral, 2)
+ comCall0(entry.deferral, 2)
}
}
@@ -728,16 +728,16 @@ func (page *windowsWeb) mapAddress(address string) string {
func (page *windowsWeb) Load(address string) {
address = page.mapAddress(address)
- page.do(func() { comCall(page.view, viewNavigate, uintptr(unsafe.Pointer(wide(address)))) })
+ page.do(func() { comCall1(page.view, viewNavigate, uintptr(unsafe.Pointer(wide(address)))) })
}
func (page *windowsWeb) LoadHTML(html, base string) {
- page.do(func() { comCall(page.view, viewNavigateToString, uintptr(unsafe.Pointer(wide(html)))) })
+ page.do(func() { comCall1(page.view, viewNavigateToString, uintptr(unsafe.Pointer(wide(html)))) })
}
-func (page *windowsWeb) Reload() { page.do(func() { comCall(page.view, viewReload) }) }
-func (page *windowsWeb) Back() { page.do(func() { comCall(page.view, viewGoBack) }) }
-func (page *windowsWeb) Forward() { page.do(func() { comCall(page.view, viewGoForward) }) }
+func (page *windowsWeb) Reload() { page.do(func() { comCall0(page.view, viewReload) }) }
+func (page *windowsWeb) Back() { page.do(func() { comCall0(page.view, viewGoBack) }) }
+func (page *windowsWeb) Forward() { page.do(func() { comCall0(page.view, viewGoForward) }) }
// Title is the title of the page's current document, which the runtime keeps for the page it made:
// empty before it has one, and once the page has closed.
@@ -752,7 +752,7 @@ func (page *windowsWeb) canGo(slot int) bool {
return false
}
var can int32
- comCall(page.view, slot, uintptr(unsafe.Pointer(&can)))
+ comCall1(page.view, slot, uintptr(unsafe.Pointer(&can)))
return can != 0
}
@@ -764,7 +764,7 @@ func (page *windowsWeb) IsLoading() bool { return page.loading }
func (page *windowsWeb) ProcessFailure() platform.WebProcessFailure { return page.processFailure }
func (page *windowsWeb) Eval(script string) {
- page.do(func() { comCall(page.view, viewExecuteScript, uintptr(unsafe.Pointer(wide(script))), 0) })
+ page.do(func() { comCall2(page.view, viewExecuteScript, uintptr(unsafe.Pointer(wide(script))), 0) })
}
func (page *windowsWeb) PostMessage(text string) {
@@ -776,7 +776,7 @@ func (page *windowsWeb) PostMessage(text string) {
}
func (page *windowsWeb) Focus() {
- page.do(func() { comCall(page.controller, controllerMoveFocus, 0) })
+ page.do(func() { comCall1(page.controller, controllerMoveFocus, 0) })
}
func (page *windowsWeb) Close() {
@@ -793,9 +793,9 @@ func (page *windowsWeb) Close() {
func (page *windowsWeb) release() {
page.releaseAnswers()
if page.controller != 0 {
- comCall(page.controller, controllerClose)
- comCall(page.view, 2)
- comCall(page.controller, 2)
+ comCall0(page.controller, controllerClose)
+ comCall0(page.view, 2)
+ comCall0(page.controller, 2)
page.controller, page.view = 0, 0
}
for _, cover := range page.covers {
@@ -849,7 +849,7 @@ func (w *webHost) layout(page *windowsWeb, force bool) {
showWindow.Call(cover, swHide)
}
showWindow.Call(page.window, swHide)
- comCall(page.controller, controllerPutVisible, 0)
+ comCall1(page.controller, controllerPutVisible, 0)
page.shown = false
}
return
@@ -866,7 +866,7 @@ func (w *webHost) layout(page *windowsWeb, force bool) {
page.device, page.cutsSet, page.shown = device, append(page.cutsSet[:0], w.cuts...), true
width, height := device.Right-device.Left, device.Bottom-device.Top
setWindowPosition.Call(page.window, 0, uintptr(device.Left), uintptr(device.Top), uintptr(width), uintptr(height), swpNoActive|swpShow)
- comCall(page.controller, controllerPutVisible, 1)
+ comCall1(page.controller, controllerPutVisible, 1)
putBounds(page.controller, rect{Right: width, Bottom: height})
region, _, _ := createRectRgn.Call(0, 0, uintptr(width), uintptr(height))
logicalRadius := min(max(page.config.TopCornerRadius, 0), view.Bounds.Width/2, view.Bounds.Height)
diff --git a/internal/platform/windows/webview2_windows.go b/internal/platform/windows/webview2_windows.go
index 0d84119b7..88e7ac8e2 100644
--- a/internal/platform/windows/webview2_windows.go
+++ b/internal/platform/windows/webview2_windows.go
@@ -223,7 +223,7 @@ func (env *webEnvironment) leave() {
}
delete(webEnvironments, env.key)
if env.object != 0 {
- comCall(env.object, 2)
+ comCall0(env.object, 2)
env.object = 0
}
}
@@ -241,7 +241,7 @@ func (env *webEnvironment) join(userData string, then func(object uintptr, err e
env.waiting = append(env.waiting, then)
finish := func(object uintptr, err error) {
if object != 0 && env.pages == 0 && env.proxy != "" {
- comCall(object, 2) // every page closed while it started
+ comCall0(object, 2) // every page closed while it started
object = 0
}
env.object, env.failed = object, err
@@ -289,7 +289,7 @@ func (env *webEnvironment) join(userData string, then func(object uintptr, err e
finish(0, fmt.Errorf("windows: create the WebView2 environment: HRESULT %#x", uint32(status)))
return 0
}
- comCall(object, 1) // the runtime releases its reference when the call returns
+ comCall0(object, 1) // the runtime releases its reference when the call returns
finish(object, nil)
return 0
})
diff --git a/internal/platform/windows/window_icon_update_windows_test.go b/internal/platform/windows/window_icon_update_windows_test.go
index d3368fb7a..7b25e78a5 100644
--- a/internal/platform/windows/window_icon_update_windows_test.go
+++ b/internal/platform/windows/window_icon_update_windows_test.go
@@ -51,7 +51,7 @@ func TestWindowIconUpdatesOnTheWindowThread(t *testing.T) {
for id, want := range map[uint32]string{3: icon.ResourcePath + ",0", 5: "dev.viva.icon-test"} {
key := propertyKey{Format: appModelKey, ID: id}
var got stringProperty
- if err := hresult(comCall(store, 5 /* GetValue */, uintptr(unsafe.Pointer(&key)), uintptr(unsafe.Pointer(&got)))); err != nil {
+ if err := hresult(comCall2(store, 5 /* GetValue */, uintptr(unsafe.Pointer(&key)), uintptr(unsafe.Pointer(&got)))); err != nil {
t.Fatal(err)
}
if got.Kind != 31 || syscall.UTF16ToString(unsafe.Slice(got.Text, len(want)+1)) != want {
diff --git a/internal/platform/windows/window_resize_windows_test.go b/internal/platform/windows/window_resize_windows_test.go
index 3123761cb..d4bb524f6 100644
--- a/internal/platform/windows/window_resize_windows_test.go
+++ b/internal/platform/windows/window_resize_windows_test.go
@@ -62,7 +62,7 @@ func TestWindowSwapChainDoesNotStretchStaleFrames(t *testing.T) {
state := opened.(*nativeWindow).state
var description swapChainDesc1
// IDXGISwapChain1::GetDesc1.
- if err := hresult(comCall(state.renderer.swap, 18, uintptr(unsafe.Pointer(&description)))); err != nil {
+ if err := hresult(comCall1(state.renderer.swap, 18, uintptr(unsafe.Pointer(&description)))); err != nil {
return err
}
if description.Scaling != 1 { // DXGI_SCALING_NONE
@@ -70,7 +70,7 @@ func TestWindowSwapChainDoesNotStretchStaleFrames(t *testing.T) {
}
var background [4]float32
// IDXGISwapChain1::GetBackgroundColor follows SetBackgroundColor.
- if err := hresult(comCall(state.renderer.swap, 26, uintptr(unsafe.Pointer(&background)))); err != nil {
+ if err := hresult(comCall1(state.renderer.swap, 26, uintptr(unsafe.Pointer(&background)))); err != nil {
return err
}
color := state.renderer.color
@@ -645,7 +645,7 @@ func resizeTestPresentCount(t *testing.T, state *windowState) uint32 {
t.Helper()
var count uint32
// IDXGISwapChain::GetLastPresentCount.
- if err := hresult(comCall(state.renderer.swap, 17, uintptr(unsafe.Pointer(&count)))); err != nil {
+ if err := hresult(comCall1(state.renderer.swap, 17, uintptr(unsafe.Pointer(&count)))); err != nil {
t.Fatal(err)
}
return count
From 9ad1e9d7f8dffc6c8097b2dd9c8755039efb3150 Mon Sep 17 00:00:00 2001
From: t8y2 <1156263951@qq.com>
Date: Sun, 22 Nov 2026 09:56:35 +0800
Subject: [PATCH 46/47] perf(linux): load the xcb and Vulkan function tables
once per process
Every window, every clipboard read, every font-settings read and every
global shortcut registration opened libxcb and libc again and bound 58
functions (149 us and 522 allocations measured for the bindings alone),
and every window and offscreen target did the same for libvulkan. Both
tables are now process singletons behind sync.Once, failures included,
and kept for the life of the process as the Pango services already are,
so the close paths no longer dlclose them.
First step of ADR 0093 (Linux process-level resources). Viva-only.
---
internal/platform/linux/api_linux_test.go | 4 ++--
.../platform/linux/font_settings_linux.go | 1 -
.../platform/linux/global_shortcut_linux.go | 2 +-
.../platform/linux/shared_api_linux_test.go | 19 ++++++++++++++++++
internal/platform/linux/system_linux.go | 3 ---
internal/platform/linux/vulkan_linux.go | 17 ++++++++++++++--
internal/platform/linux/vulkan_probe_linux.go | 3 ---
internal/platform/linux/window_linux.go | 3 ---
internal/platform/linux/xcb_linux.go | 20 ++++++++++++++-----
9 files changed, 52 insertions(+), 20 deletions(-)
create mode 100644 internal/platform/linux/shared_api_linux_test.go
diff --git a/internal/platform/linux/api_linux_test.go b/internal/platform/linux/api_linux_test.go
index 2d09e363a..e0ae3b230 100644
--- a/internal/platform/linux/api_linux_test.go
+++ b/internal/platform/linux/api_linux_test.go
@@ -515,9 +515,9 @@ func TestVulkanWithoutDriverManifestDoesNotLoadDriver(t *testing.T) {
if vulkanDriverConfigured() {
t.Fatal("a missing ICD manifest counts as a Vulkan driver")
}
- _, err := loadVulkan()
+ _, err := openVulkan()
if !errors.Is(err, platform.ErrNoGraphics) {
- t.Fatalf("loadVulkan error = %v, want platform.ErrNoGraphics", err)
+ t.Fatalf("openVulkan error = %v, want platform.ErrNoGraphics", err)
}
}
diff --git a/internal/platform/linux/font_settings_linux.go b/internal/platform/linux/font_settings_linux.go
index ee0df6cac..2d22f7316 100644
--- a/internal/platform/linux/font_settings_linux.go
+++ b/internal/platform/linux/font_settings_linux.go
@@ -28,7 +28,6 @@ func readFontSettings() fontSettings {
}
defer func() {
api.disconnect(connection)
- api.close()
}()
tracker := &scaleTracker{api: api, connection: connection, screen: screen}
tracker.managerAtom, _ = api.atom(connection, "_XSETTINGS_S0")
diff --git a/internal/platform/linux/global_shortcut_linux.go b/internal/platform/linux/global_shortcut_linux.go
index 4d05f7bfd..43604cfa3 100644
--- a/internal/platform/linux/global_shortcut_linux.go
+++ b/internal/platform/linux/global_shortcut_linux.go
@@ -21,7 +21,7 @@ func RegisterGlobalShortcut(modifiers gfx.Modifiers, symbol uint32, pressed func
if err != nil {
return nil, err
}
- closeConnection := func() { api.disconnect(connection); api.close() }
+ closeConnection := func() { api.disconnect(connection) }
success := false
defer func() {
if !success {
diff --git a/internal/platform/linux/shared_api_linux_test.go b/internal/platform/linux/shared_api_linux_test.go
new file mode 100644
index 000000000..0158713ca
--- /dev/null
+++ b/internal/platform/linux/shared_api_linux_test.go
@@ -0,0 +1,19 @@
+package linux
+
+import "testing"
+
+// The libxcb and libvulkan function tables are the process's: every window, the
+// clipboard and the desktop settings share the one loaded first, and a machine
+// without the library is found once.
+func TestFunctionTablesAreLoadedOnce(t *testing.T) {
+ x1, xErr1 := loadXCB()
+ x2, xErr2 := loadXCB()
+ if x1 != x2 || xErr1 != xErr2 {
+ t.Fatalf("loadXCB gave %p, %v then %p, %v", x1, xErr1, x2, xErr2)
+ }
+ v1, vErr1 := loadVulkan()
+ v2, vErr2 := loadVulkan()
+ if v1 != v2 || vErr1 != vErr2 {
+ t.Fatalf("loadVulkan gave %p, %v then %p, %v", v1, vErr1, v2, vErr2)
+ }
+}
diff --git a/internal/platform/linux/system_linux.go b/internal/platform/linux/system_linux.go
index 9e350073b..3fd26f15e 100644
--- a/internal/platform/linux/system_linux.go
+++ b/internal/platform/linux/system_linux.go
@@ -348,7 +348,6 @@ func openSelectionRequest(name string) (api *xcbAPI, connection uintptr, request
func closeClipboardRequest(api *xcbAPI, connection uintptr, requestor uint32) {
api.destroyWindow(connection, requestor)
api.disconnect(connection)
- api.close()
}
// readSelectionBytes asks the selection owner to convert to target and returns
@@ -990,7 +989,6 @@ func openSystemConnection() (*xcbAPI, uintptr, *xcbScreen, error) {
if connection != 0 {
api.disconnect(connection)
}
- api.close()
return nil, 0, nil, fmt.Errorf("linux: connect to X server")
}
iterator := api.rootsIterator(api.getSetup(connection))
@@ -999,7 +997,6 @@ func openSystemConnection() (*xcbAPI, uintptr, *xcbScreen, error) {
}
if iterator.Data == nil || iterator.Remaining == 0 {
api.disconnect(connection)
- api.close()
return nil, 0, nil, fmt.Errorf("linux: X server has no screen")
}
return api, connection, iterator.Data, nil
diff --git a/internal/platform/linux/vulkan_linux.go b/internal/platform/linux/vulkan_linux.go
index 771ad657c..998efaa83 100644
--- a/internal/platform/linux/vulkan_linux.go
+++ b/internal/platform/linux/vulkan_linux.go
@@ -7,6 +7,7 @@ import (
"math"
"os"
"path/filepath"
+ "sync"
"unsafe"
"github.com/ebitengine/purego"
@@ -558,7 +559,20 @@ func vulkanDriverManifestsExist(paths []string) bool {
return false
}
+// loadVulkan is the process's libvulkan function table, loaded once and kept
+// for the life of the process; a machine without a driver is found once.
func loadVulkan() (*vulkanAPI, error) {
+ vulkanOnce.Do(func() { vulkanShared, vulkanErr = openVulkan() })
+ return vulkanShared, vulkanErr
+}
+
+var (
+ vulkanOnce sync.Once
+ vulkanShared *vulkanAPI
+ vulkanErr error
+)
+
+func openVulkan() (*vulkanAPI, error) {
if !vulkanDriverConfigured() {
return nil, noVulkan("Vulkan has no driver (no ICD manifest)", nil)
}
@@ -1503,8 +1517,7 @@ func (renderer *vulkanRenderer) close() {
if renderer.instance != 0 {
renderer.api.destroyInstance(renderer.instance, nil)
}
- purego.Dlclose(renderer.api.library)
- renderer.api = nil
+ renderer.api = nil // the function table is the process's: see loadVulkan
}
// noVulkan is the error for a machine that cannot draw: it wraps
diff --git a/internal/platform/linux/vulkan_probe_linux.go b/internal/platform/linux/vulkan_probe_linux.go
index 7220c2086..13f9e18a8 100644
--- a/internal/platform/linux/vulkan_probe_linux.go
+++ b/internal/platform/linux/vulkan_probe_linux.go
@@ -3,8 +3,6 @@ package linux
import (
"encoding/binary"
"sync"
-
- "github.com/ebitengine/purego"
)
// vkPhysicalDeviceTypeCPU is the type a software rasterizer reports (lavapipe).
@@ -29,7 +27,6 @@ func vulkanDeviceIsSoftware() bool {
softwareProbe.software = true
return
}
- defer purego.Dlclose(api.library)
renderer := &vulkanRenderer{api: api}
if err := renderer.createInstance(nil); err != nil {
softwareProbe.software = true
diff --git a/internal/platform/linux/window_linux.go b/internal/platform/linux/window_linux.go
index ac5124cd3..6fa133622 100644
--- a/internal/platform/linux/window_linux.go
+++ b/internal/platform/linux/window_linux.go
@@ -1363,7 +1363,6 @@ func (application *linuxApplication) openWindow(config platform.Config) (*window
if connection != 0 {
api.disconnect(connection)
}
- api.close()
return nil, fmt.Errorf("linux: connect to X server")
}
iterator := api.rootsIterator(api.getSetup(connection))
@@ -1372,7 +1371,6 @@ func (application *linuxApplication) openWindow(config platform.Config) (*window
}
if iterator.Data == nil || iterator.Remaining == 0 {
api.disconnect(connection)
- api.close()
return nil, fmt.Errorf("linux: X server has no screen")
}
win := &window{api: api, connection: connection, screen: iterator.Data}
@@ -1645,7 +1643,6 @@ func (win *window) close() {
win.connection = 0
}
if win.api != nil {
- win.api.close()
win.api = nil
}
}
diff --git a/internal/platform/linux/xcb_linux.go b/internal/platform/linux/xcb_linux.go
index 6fc07cfc1..029fd560a 100644
--- a/internal/platform/linux/xcb_linux.go
+++ b/internal/platform/linux/xcb_linux.go
@@ -2,6 +2,7 @@ package linux
import (
"fmt"
+ "sync"
"unsafe"
"github.com/ebitengine/purego"
@@ -350,7 +351,21 @@ type xcbAPI struct {
free func(unsafe.Pointer)
}
+// loadXCB is the process's libxcb and libc function table: loaded the first
+// time a window, the clipboard or a desktop setting needs it and kept for the
+// life of the process, as the Pango services are. A failure is kept too.
func loadXCB() (*xcbAPI, error) {
+ xcbOnce.Do(func() { xcbShared, xcbErr = openXCB() })
+ return xcbShared, xcbErr
+}
+
+var (
+ xcbOnce sync.Once
+ xcbShared *xcbAPI
+ xcbErr error
+)
+
+func openXCB() (*xcbAPI, error) {
library, err := purego.Dlopen("libxcb.so.1", purego.RTLD_NOW|purego.RTLD_LOCAL)
if err != nil {
return nil, fmt.Errorf("linux: load libxcb: %w", err)
@@ -422,11 +437,6 @@ func loadXCB() (*xcbAPI, error) {
return api, nil
}
-func (api *xcbAPI) close() {
- purego.Dlclose(api.libc)
- purego.Dlclose(api.library)
-}
-
func (api *xcbAPI) atom(connection uintptr, name string) (uint32, error) {
value := append([]byte(name), 0)
cookie := api.internAtom(connection, 0, uint16(len(value)-1), &value[0])
From a4a56fd34807102d9134410b101396ec03cbc302 Mon Sep 17 00:00:00 2001
From: Yao Jingxi <23722032@bjtu.edu.cn>
Date: Sun, 22 Nov 2026 10:06:19 +0800
Subject: [PATCH 47/47] ui: align panel wheel regressions with the current page
API
Follow the latest PopoverWith and AlertDialog bool-based API, document RouteWheel ownership, and keep the wheel scan's fixed lower bound so the common page path stays as cheap as upstream.
---
base/scroll.go | 10 ++++++----
ui/popover_wheel_test.go | 6 +++---
2 files changed, 9 insertions(+), 7 deletions(-)
diff --git a/base/scroll.go b/base/scroll.go
index 1705f5adb..e571b1740 100644
--- a/base/scroll.go
+++ b/base/scroll.go
@@ -307,8 +307,8 @@ func (s *ScrollState) BarGeometry(bounds Rect, barSize float32) ScrollAreaGeomet
// panel painted on the page that the pointer cannot reach through (an open Popover's
// panel, a Dialog, an AlertDialog or a Drawer) only the areas inside the panel are
// offered the wheel, wherever in the page the panel was declared, and an event none
-// of them can use stops at the panel, handled, rather than scrolling what is under it. It is the
-// function to give as Config.OnScroll for a page whose areas are all ScrollAreas;
+// of them can use stops at the panel, handled, rather than scrolling what is under it.
+// It is the function to give as Config.OnScroll for a page whose areas are all ScrollAreas;
// handle a Select's open list and a self-scrolling Table first, as they own the
// wheel while they are open or under the pointer. It reports an event that no area
// under the pointer can use, beside every such panel, as not handled.
@@ -336,8 +336,10 @@ func (f *Frame) wheelArea(panel int32, event gfx.ScrollEvent) (result gfx.EventR
if f.Surface != nil {
trap = f.Surface.TrappedFocusScope()
}
- first := int(max(panel, 0)) // what a panel holds is declared after its root
- for i := len(f.Nodes) - 1; i >= first; i-- {
+ for i := len(f.Nodes) - 1; i >= 0; i-- {
+ if int32(i) < panel { // what a panel holds is declared after its root
+ break
+ }
n := &f.Nodes[i]
if n.Ext == 0 || f.Exts[n.Ext].scrollState == nil {
continue
diff --git a/ui/popover_wheel_test.go b/ui/popover_wheel_test.go
index 2679f8e9b..e95967c88 100644
--- a/ui/popover_wheel_test.go
+++ b/ui/popover_wheel_test.go
@@ -23,7 +23,7 @@ func TestAWheelOverAPopoverStaysInThePanel(t *testing.T) {
d := openPage(t, func(c ui.C) {
ui.Column(c).Fill().Children(func() {
projects := ui.Button(c, "Projects")
- ui.PopoverWith(c, projects, ui.PopoverSpec{Width: 200}, &open, func() {
+ ui.PopoverWith(c, projects, &open, ui.PopoverSpec{Width: 200}, func() {
list = ui.Scroll(c).FillWidth().MaxHeight(150).Children(func() {
for range 20 {
ui.Slot(c).Height(30)
@@ -89,7 +89,7 @@ func TestATableInAPopoverTakesTheWheelAndTheTableUnderItDoesNot(t *testing.T) {
d := openPage(t, func(c ui.C) {
ui.Column(c).Fill().Children(func() {
projects := ui.Button(c, "Projects")
- ui.PopoverWith(c, projects, ui.PopoverSpec{Width: 200}, &open, func() {
+ ui.PopoverWith(c, projects, &open, ui.PopoverSpec{Width: 200}, func() {
panelTable = ui.Table(c, &inner, ui.TableSpec{
Columns: []components.TableColumn{{}}, Rows: gfx.Item(1).Scope(), Source: &rows,
}).FillWidth().Height(150)
@@ -169,7 +169,7 @@ func TestAlertDialogKeepsTheWheelFromTheTableBehindIt(t *testing.T) {
Columns: []components.TableColumn{{}}, Rows: tree.Sub(scope, tree.Name("rows")), Source: &rows,
}).Fill()
if open {
- ui.AlertDialog(c, ui.AlertDialogSpec{
+ ui.AlertDialog(c, &open, ui.AlertDialogSpec{
Title: "Discard changes?", Description: "This cannot be undone.",
Scope: scope.At(0), ActionID: scope.At(1), CancelID: scope.At(2),
ActionLabel: "Discard", CancelLabel: "Cancel",