gui: native WebView host as nested module yetano.dev/yetano/core/gui
Extracted from prototypes/yetano-webview (AP1): packages assets, document, bridge and window (macOS Cocoa/WKWebView via cgo, Windows Win32/WebView2 pure Go). No local HTTP listener or port: assets go through the WebView's resource handler, app routes through the native message binding. Own go.mod and gui/vX.Y.Z tags keep cgo and the WebView dependencies out of the main core module. Adds backend-free tests for the window's dispatch/destroy guards and a yet-gui migration guide. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
90132e2d76
commit
8c63d42a27
27 files changed
+4849
-3
No files matched your search
@@ -0,0 +1,241 @@
|
||||
// Package window is a narrow native WebView host:
|
||||
//
|
||||
// - macOS: own Cocoa host (darwin.m): NSWindow + WKWebView, cgo
|
||||
// - Windows: own Win32 host on github.com/jchv/go-webview2/pkg/edge
|
||||
// (WebView2 COM, pure Go)
|
||||
//
|
||||
// It offers exactly what the program needs: one message channel page -> Go
|
||||
// (window.__yetano_post), document-start scripts, Eval, UI-thread Dispatch
|
||||
// and a native resource handler for the app origin (BaseURL), which serves
|
||||
// the entry document, assets and local routes without any network listener,
|
||||
// with streaming response bodies.
|
||||
//
|
||||
// Thread rules: New, Init, Navigate, Run and Destroy run on the thread that
|
||||
// locked itself in this package's init (the main goroutine). Dispatch is safe
|
||||
// from any goroutine; Eval only inside a dispatched function. After Destroy,
|
||||
// Dispatch and queued closures are no-ops.
|
||||
package window
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// ResourceRequest is a request from the WebView for the app origin.
|
||||
type ResourceRequest struct {
|
||||
Method string
|
||||
URL string // absolute, e.g. "yetano://app/assets/x.css" or "https://yetano.invalid/rpc/add"
|
||||
Header http.Header
|
||||
Body []byte
|
||||
}
|
||||
|
||||
// ResourceWriter answers one ResourceRequest. Respond is called once, then
|
||||
// any number of Write calls (each is delivered to the page as it comes:
|
||||
// streaming), then Close. All methods are safe from any goroutine.
|
||||
type ResourceWriter interface {
|
||||
Respond(status int, header http.Header)
|
||||
Write(p []byte) (int, error)
|
||||
Close(err error)
|
||||
}
|
||||
|
||||
// ResourceHandler serves app-origin requests. ctx ends when the page drops
|
||||
// the request (where the backend reports that) or the window is destroyed.
|
||||
type ResourceHandler func(ctx context.Context, req *ResourceRequest, w ResourceWriter)
|
||||
|
||||
// Options for a new window.
|
||||
type Options struct {
|
||||
Title string
|
||||
Width int
|
||||
Height int
|
||||
Debug bool // developer tools
|
||||
DataPath string // WebView2 user data folder (Windows)
|
||||
OnMessage func(msg string)
|
||||
Resource ResourceHandler // nil: no native resource handler
|
||||
}
|
||||
|
||||
type backend interface {
|
||||
Init(js string)
|
||||
Navigate(url string)
|
||||
Run()
|
||||
Terminate()
|
||||
Dispatch(f func())
|
||||
Eval(js string)
|
||||
Destroy()
|
||||
}
|
||||
|
||||
// Window is a guarded native WebView window.
|
||||
type Window struct {
|
||||
mu sync.Mutex
|
||||
b backend
|
||||
alive bool
|
||||
name string
|
||||
base string
|
||||
dropped int
|
||||
}
|
||||
|
||||
// Debugf, if set, receives backend diagnostics.
|
||||
var Debugf func(format string, args ...any)
|
||||
|
||||
// ErrUnsupported is returned on platforms without a backend.
|
||||
var ErrUnsupported = errors.New("window: no native WebView backend for this platform")
|
||||
|
||||
// postShim defines window.__yetano_post on top of the backend's native
|
||||
// message channel. It is installed before any other init script.
|
||||
const postShimDarwin = `window.__yetano_post=function(m){window.webkit.messageHandlers.yetano.postMessage(JSON.stringify(m));return Promise.resolve();};`
|
||||
const postShimWindows = `window.__yetano_post=function(m){window.chrome.webview.postMessage(JSON.stringify(m));return Promise.resolve();};`
|
||||
|
||||
// New creates the native window. On failure it returns an error and nothing
|
||||
// has to be cleaned up.
|
||||
func New(opt Options) (*Window, error) {
|
||||
if opt.Width == 0 {
|
||||
opt.Width, opt.Height = 1100, 820
|
||||
}
|
||||
b, name, base, err := newBackend(opt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Window{b: b, alive: true, name: name, base: base}, nil
|
||||
}
|
||||
|
||||
// Backend names the native backend.
|
||||
func (w *Window) Backend() string { return w.name }
|
||||
|
||||
// BaseURL is the app origin served by the resource handler, without
|
||||
// trailing slash ("yetano://app", "https://yetano.invalid").
|
||||
func (w *Window) BaseURL() string { return w.base }
|
||||
|
||||
// Init adds a document-start script (every navigation, before page scripts).
|
||||
func (w *Window) Init(js string) { w.b.Init(js) }
|
||||
|
||||
// Navigate loads url.
|
||||
func (w *Window) Navigate(url string) { w.b.Navigate(url) }
|
||||
|
||||
// Run runs the UI loop until Terminate or the user closes the window.
|
||||
func (w *Window) Run() { w.b.Run() }
|
||||
|
||||
// Dispatch queues f on the UI thread. After Destroy it is dropped.
|
||||
func (w *Window) Dispatch(f func()) {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
if !w.alive {
|
||||
w.dropped++
|
||||
return
|
||||
}
|
||||
w.b.Dispatch(func() {
|
||||
w.mu.Lock()
|
||||
alive := w.alive
|
||||
w.mu.Unlock()
|
||||
if alive {
|
||||
f()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Eval runs js in the page; only on the UI thread.
|
||||
func (w *Window) Eval(js string) {
|
||||
w.mu.Lock()
|
||||
alive := w.alive
|
||||
w.mu.Unlock()
|
||||
if alive {
|
||||
w.b.Eval(js)
|
||||
}
|
||||
}
|
||||
|
||||
// Terminate ends Run from any goroutine.
|
||||
func (w *Window) Terminate() { w.Dispatch(func() { w.b.Terminate() }) }
|
||||
|
||||
// Destroy releases the native window. Idempotent; on the UI thread after Run.
|
||||
func (w *Window) Destroy() {
|
||||
w.mu.Lock()
|
||||
if !w.alive {
|
||||
w.mu.Unlock()
|
||||
return
|
||||
}
|
||||
w.alive = false
|
||||
w.mu.Unlock()
|
||||
w.b.Destroy()
|
||||
}
|
||||
|
||||
// snapshotter is implemented by backends that can render the page to PNG.
|
||||
type snapshotter interface {
|
||||
Snapshot(path string, done func(error))
|
||||
}
|
||||
|
||||
// Snapshot renders the current page into a PNG file (UI thread). done runs
|
||||
// on the UI thread. Backends without support report an error.
|
||||
func (w *Window) Snapshot(path string, done func(error)) {
|
||||
s, ok := w.b.(snapshotter)
|
||||
if !ok {
|
||||
done(errors.New("window: snapshot not supported by " + w.name))
|
||||
return
|
||||
}
|
||||
s.Snapshot(path, done)
|
||||
}
|
||||
|
||||
// appearancer is implemented by backends whose window chrome (title bar)
|
||||
// can follow the page's light/dark choice.
|
||||
type appearancer interface {
|
||||
SetAppearance(mode string)
|
||||
}
|
||||
|
||||
// SetAppearance makes the native window chrome light ("light"), dark
|
||||
// ("dark") or follow the system (anything else). UI thread. A no-op where
|
||||
// unsupported.
|
||||
func (w *Window) SetAppearance(mode string) {
|
||||
if a, ok := w.b.(appearancer); ok {
|
||||
a.SetAppearance(mode)
|
||||
}
|
||||
}
|
||||
|
||||
// SetAppIcon sets the application icon shown by the OS (macOS Dock) from
|
||||
// PNG bytes when the program does not run from an app bundle. Windows takes
|
||||
// the icon from the executable's resources instead. Call before New.
|
||||
func SetAppIcon(png []byte) { setAppIcon(png) }
|
||||
|
||||
// AccentColor is the user's system accent color as "#RRGGBB", or "" if
|
||||
// unknown. Safe to call before a window exists.
|
||||
func AccentColor() string { return accentColor() }
|
||||
|
||||
// DroppedDispatches counts Dispatch calls that arrived after Destroy.
|
||||
func (w *Window) DroppedDispatches() int {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
return w.dropped
|
||||
}
|
||||
|
||||
// taskTable tracks running resource requests so Destroy can cancel them.
|
||||
type taskTable struct {
|
||||
mu sync.Mutex
|
||||
tasks map[int64]context.CancelFunc
|
||||
}
|
||||
|
||||
func (t *taskTable) add(id int64, c context.CancelFunc) {
|
||||
t.mu.Lock()
|
||||
if t.tasks == nil {
|
||||
t.tasks = map[int64]context.CancelFunc{}
|
||||
}
|
||||
t.tasks[id] = c
|
||||
t.mu.Unlock()
|
||||
}
|
||||
|
||||
func (t *taskTable) cancel(id int64) {
|
||||
t.mu.Lock()
|
||||
c := t.tasks[id]
|
||||
delete(t.tasks, id)
|
||||
t.mu.Unlock()
|
||||
if c != nil {
|
||||
c()
|
||||
}
|
||||
}
|
||||
|
||||
func (t *taskTable) cancelAll() {
|
||||
t.mu.Lock()
|
||||
cs := t.tasks
|
||||
t.tasks = nil
|
||||
t.mu.Unlock()
|
||||
for _, c := range cs {
|
||||
c()
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user