From 8c63d42a277db502ad677807acbaf3821b06743d Mon Sep 17 00:00:00 2001 From: Bjoern Kalkbrenner Date: Fri, 23 Oct 2026 14:47:26 +0200 Subject: [PATCH] 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 --- ARCHITECTURE.md | 19 + README.md | 26 +- TODO.md | 8 +- gui/README.md | 158 ++++++++ gui/assets/mime.go | 56 +++ gui/assets/path.go | 103 +++++ gui/assets/resolver.go | 272 ++++++++++++++ gui/assets/resolver_test.go | 219 +++++++++++ gui/bridge/bridge.js | 422 +++++++++++++++++++++ gui/bridge/native.go | 72 ++++ gui/bridge/router.go | 265 +++++++++++++ gui/bridge/script.go | 32 ++ gui/bridge/session.go | 477 ++++++++++++++++++++++++ gui/bridge/session_test.go | 358 ++++++++++++++++++ gui/doc.go | 23 ++ gui/document/css.go | 267 +++++++++++++ gui/document/prepare.go | 295 +++++++++++++++ gui/document/prepare_test.go | 143 +++++++ gui/go.mod | 11 + gui/go.sum | 10 + gui/window/darwin.h | 21 ++ gui/window/darwin.m | 282 ++++++++++++++ gui/window/window.go | 241 ++++++++++++ gui/window/window_darwin.go | 283 ++++++++++++++ gui/window/window_other.go | 9 + gui/window/window_test.go | 75 ++++ gui/window/window_windows.go | 705 +++++++++++++++++++++++++++++++++++ 27 files changed, 4849 insertions(+), 3 deletions(-) create mode 100644 gui/README.md create mode 100644 gui/assets/mime.go create mode 100644 gui/assets/path.go create mode 100644 gui/assets/resolver.go create mode 100644 gui/assets/resolver_test.go create mode 100644 gui/bridge/bridge.js create mode 100644 gui/bridge/native.go create mode 100644 gui/bridge/router.go create mode 100644 gui/bridge/script.go create mode 100644 gui/bridge/session.go create mode 100644 gui/bridge/session_test.go create mode 100644 gui/doc.go create mode 100644 gui/document/css.go create mode 100644 gui/document/prepare.go create mode 100644 gui/document/prepare_test.go create mode 100644 gui/go.mod create mode 100644 gui/go.sum create mode 100644 gui/window/darwin.h create mode 100644 gui/window/darwin.m create mode 100644 gui/window/window.go create mode 100644 gui/window/window_darwin.go create mode 100644 gui/window/window_other.go create mode 100644 gui/window/window_test.go create mode 100644 gui/window/window_windows.go diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index c0b4ae6..9a4c67b 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -250,3 +250,22 @@ exists to do so (`config create`, `config upgrade --write`). YAML tree, the templates and, via reflection on the program's struct, which keys exist. It started as `yamase-core/pkg/configcmd` and moved here unchanged in behavior when the other meta-repos needed it. + +## core/gui: a nested module, not a package of this one + +The WebView host needs cgo and Cocoa/WebKit on macOS and +`go-webview2`/`x/sys/windows` on Windows; a CLI or daemon importing +`core/paths` must not inherit any of that. So `gui/` has its own +`go.mod` (`yetano.dev/yetano/core/gui`), its own prefixed tags +(`gui/vX.Y.Z`) and its own Go version, while living in the same +repository (one vanity import, one history). It does not import the main +module today; a consumer passes `DataPath` (WebView2 user data) from its +own `core/paths` resolver instead. + +Unlike `core/paths`, the GUI host *does* use one build-tagged file per OS +(`window_darwin.go` + `darwin.m`, `window_windows.go`, `window_other.go`): +these are real native bindings that can only be compiled for their OS, +the same exception the root AGENTS.md makes for +`paths/knownfolders_windows.go`. Everything above the window (`assets`, +`document`, `bridge`) is platform-free and unit-tested on any host; +browser behavior is verified by the prototype's in-window selftest. diff --git a/README.md b/README.md index 04520b6..f041845 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,11 @@ every Yetano program offers (`core/manual`, `core/completion`, docs/program-conventions.md in the meta-repository), and secret references in configuration (`core/secretref`). +The native WebView GUI host is a **separate, nested module**, +`yetano.dev/yetano/core/gui` (tags `gui/vX.Y.Z`), so this module keeps +its single dependency and stays free of cgo -- see +[gui/README.md](gui/README.md). + ```text yetano.dev/yetano/core yetano.dev/yetano/core/paths @@ -23,6 +28,12 @@ yetano.dev/yetano/core/doctor yetano.dev/yetano/core/configcmd yetano.dev/yetano/core/version yetano.dev/yetano/core/secretref + +yetano.dev/yetano/core/gui (own module, tags gui/vX.Y.Z) +yetano.dev/yetano/core/gui/assets +yetano.dev/yetano/core/gui/document +yetano.dev/yetano/core/gui/bridge +yetano.dev/yetano/core/gui/window ``` Target platforms: Linux, FreeBSD, macOS, Windows. No Unix assumptions @@ -349,7 +360,9 @@ one-line form for log lines and web UI footers. Tagged as plain semver on this repository (`v0.1.0`, ...), per the meta-repo `AGENTS.md`'s versioning rules: an existing tag is never -force-moved to a different commit. +force-moved to a different commit. The nested `gui` module has its own +prefixed tags (`gui/v0.1.0`, ...); a change there needs no main-module +tag and vice versa. ## core/secretref @@ -373,3 +386,14 @@ log.Print(r.Redact(err.Error())) // resolved values become "***" plain values it accepted before checks `IsReference` and treats anything else as a literal. Used by yavebu, yacry and yadenes. + +## core/gui (separate module) + +`yetano.dev/yetano/core/gui` is the native WebView host for desktop +programs (macOS: Cocoa + WKWebView; Windows: Win32 + WebView2): embedded +assets served through the WebView's own resource handler, the page's +`fetch`/XHR routed to Go handlers over the native message binding, +streaming, abort and reload handling -- never a local HTTP listener or +port. Packages `assets`, `document`, `bridge`, `window`; extracted from +`prototypes/yetano-webview` (AP1). Details, invariants, measured platform +pitfalls and the yet-gui migration: [gui/README.md](gui/README.md). diff --git a/TODO.md b/TODO.md index 8ffaa34..d9332ac 100644 --- a/TODO.md +++ b/TODO.md @@ -33,8 +33,12 @@ speculatively. docs/program-conventions.md in the meta-repository. - [x] macOS CLI/Service system-scope `RuntimeDir` is `/var/run/` (was `/run/`, which macOS does not have) -- v0.5.0. -- [ ] `core/gui`: the native WebView host from - `prototypes/yetano-webview` (yet-gui has a copy in `yet/gui/internal`). +- [x] `core/gui`: the native WebView host from + `prototypes/yetano-webview`, as the nested module + `yetano.dev/yetano/core/gui` (`gui/v0.1.0`). The prototype uses it. +- [ ] Move yet-gui off its copy in `yet/gui/internal` onto `core/gui` + (steps in [gui/README.md](gui/README.md)). +- [ ] `core/gui`: Linux/FreeBSD backend (WebKitGTK) -- see gui/README.md. ## Platform tuning diff --git a/gui/README.md b/gui/README.md new file mode 100644 index 0000000..5fef3af --- /dev/null +++ b/gui/README.md @@ -0,0 +1,158 @@ +# yetano.dev/yetano/core/gui + +The native WebView host shared by Yetano desktop programs: a native window +whose WebView shows embedded HTML/CSS/JS/WASM and sends the page's +`fetch`/`XMLHttpRequest` to Go handlers. **No local web server, no port, no +localhost listener** -- not in the program, not as a fallback. Every request +goes either through the WebView's native resource handler (custom scheme / +request interception) or through the native message binding. + +Extracted from the AP1 prototype `prototypes/yetano-webview` (meta-repo +`docs/yetano-ui/AP1-GO-WEBVIEW-PROTOTYP.md`), which remains its native +selftest bench; its README holds the measured evidence per platform. + +## Separate module + +```text +module yetano.dev/yetano/core/gui tags: gui/v0.1.0, gui/v0.2.0, ... +``` + +This directory is its own Go module, nested in the core repository, so the +main `yetano.dev/yetano/core` module keeps its single dependency +(`gopkg.in/yaml.v3`) and stays free of cgo. Its dependencies: +`golang.org/x/net/html` (tokenizer), `golang.org/x/sys/windows`, +`github.com/jchv/go-webview2/pkg/edge` (Windows only, MIT; loads +Microsoft's embedded WebView2Loader via `go-winloader`, ISC). Go 1.26. + +```sh +GOPRIVATE=teruna.dev,yetano.dev,yalsh.dev go get yetano.dev/yetano/core/gui@gui/v0.1.0 +``` + +Tags carry the `gui/` prefix (Go's rule for a module in a subdirectory); +the main module's `vX.Y.Z` tags do not version this one. Never move a tag. + +## API + +| Package | What | +|---|---| +| `gui/assets` | `NewResolver(sources...)` over `NewFSSource` (embed.FS), `NewDirSource` (os.Root), `NewZipFileSource`/`NewZipBytesSource`; first source that has a file wins, a read error does not fall through. `ValidatePath` (checked, never cleaned), `Join`, `DetectMIME`. | +| `gui/document` | `Prepare(ctx, res, entry, html, Options{Link})`: rewrites `assets:` / relative references in HTML and CSS (`img`, `srcset`, `script`, `link`, `style`, CSS `url()`/`@import`). Link mode -> `/assets/...` URLs, validated against the resolver; inline mode -> typed `data:` URLs (entry <= 1.5 MiB). | +| `gui/bridge` | `NewRouter(res)`, `Router.Handle("POST /rpc/x", h)`, `Router.SetDocument`, `Router.ServeNative` (for the window's resource handler), `Router.HTML` (Go-rendered fragments through `document`). `NewSession(router, Options)` speaks protocol v1 with the page (`hello`/`ready`, `req`/`res`, `chunk`/`end` streams, `abort`, generations). `InitScript(PageConfig)` is the page side (`bridge.js`). | +| `gui/window` | `New(Options{Title, Width, Height, Debug, DataPath, OnMessage, Resource})`, `Init`, `Navigate`, `Run`, `Dispatch`, `Eval`, `Terminate`, `Destroy`, `BaseURL`, `Snapshot` (macOS), `SetAppearance`, `SetAppIcon`, `AccentColor`. | + +## Wiring + +```go +res, _ := assets.NewResolver(assets.NewFSSource("embed", webFS)) +router := bridge.NewRouter(res) +router.SetDocument("index.html", true) // entry served via the resource handler +router.Handle("POST /rpc/add", addHandler) +sess := bridge.NewSession(router, bridge.Options{}) + +var origin string // requests only arrive after Navigate +w, err := window.New(window.Options{ + Title: "app", DataPath: webview2Dir, // Windows: from core/paths, see below + OnMessage: func(msg string) { sess.Post(json.RawMessage(msg)) }, + Resource: func(ctx context.Context, r *window.ResourceRequest, rw window.ResourceWriter) { + router.ServeNative(ctx, origin, r.Method, r.URL, r.Header, r.Body, rw) + }, +}) +if err != nil { sess.Close(); return err } +origin = w.BaseURL() +sess.Attach(w) +w.Init(bridge.InitScript(bridge.PageConfig{Transport: "native", Origin: origin, External: "reject"})) +w.Navigate(origin + "/") +w.Run() // main goroutine +sess.Close() // first: lock, cancel calls, bounded wait +w.Destroy() // then: native window, on the UI thread +``` + +The WebView2 user-data folder (`DataPath`) belongs under the program's +`core/paths` cache or data directory (`%LOCALAPPDATA%`, never roaming). + +## Invariants + +- **No listener, no ports, no localhost.** After a transport change, + re-check the running process (`lsof -nP -a -p PID -i`, `netstat -ano`). +- **Paths are checked, not cleaned** (`assets.ValidatePath`): `..`, `.`, + empty segments, `\`, `:`, NUL, absolute paths -> 400. `assets.Join` lets + trusted CSS use `..` inside the root; never for paths from the page. +- **Exactly one end per call/stream**; every end that does not come from Go + is reported to Go (`abort`). Calls of an old document generation fail + with `ErrStale`, their answers are dropped (Go and JS side). +- **Close order:** `Session.Close()` -> `Window.Destroy()` on the UI thread. + `Close` never waits for the UI thread. +- **Threads:** `window.New/Init/Navigate/Run/Destroy` only on the main + goroutine (package `window` locks it in `init`). `Eval` only inside a + `Dispatch`ed function. `Dispatch` after `Destroy` is a no-op. +- Routes are registered before the document starts (`Router.Freeze` in + `NewSession`); duplicates are errors; handler panics become a 500. +- Transport `native`: entry and `/assets/` via the resource handler, app + routes via the bridge (WebView2 buffers intercepted responses until EOF, + so streaming only works over the bridge on Windows). + +## Measured platform pitfalls + +| Pitfall | Handled in | +|---|---| +| WKWebView silently ignores `location.reload()` of a `data:` document | transport inline: reload via a Go route that navigates again | +| WebKit hands Blob/FormData bodies to `WKURLSchemeHandler` empty | `bridge.js` `needsSerialize` | +| WebKit tasks must not be touched after `stopURLSchemeTask` | `darwin.m` `onTask` looks them up in `tasks` | +| WebView2 reads intercepted response streams to EOF; `E_PENDING` fails the request | app routes stream over the bridge | +| WebView2 has no cancel for intercepted requests | `goStream.onDrop` cancels the `ctx` when the stream is released | +| A stale `WM_QUIT` makes the next `pkg/edge.Embed` crash | `settle()` before create and after `Destroy` | +| `PostThreadMessage` is lost during move/resize | `Dispatch` via `PostMessage` to the window | + +## Platforms + +| Platform | Backend | Origin | Status | +|---|---|---|---| +| macOS | `window/darwin.m`: NSWindow + WKWebView, cgo | `yetano://app` | natively verified (prototype selftest, yet-gui) | +| Windows | `window/window_windows.go`: Win32 + WebView2 via `pkg/edge`, pure Go | `https://yetano.invalid` | natively verified (Windows 11 amd64) | +| Linux/FreeBSD | -- | -- | builds; `window.New` returns `ErrUnsupported` (see TODO) | + +## Tests + +```sh +go vet ./... && GOOS=windows go vet ./... && go test -race ./... +``` + +Unit tests cover everything backend-free: resolver/path rules/MIME +(`assets`), HTML/CSS rewriting (`document`), router and the bridge protocol +against a fake UI (`bridge`), dispatch/destroy guards (`window`). Real +browser behavior is tested by the prototype's in-window selftest +(`make selftest`, `make selftest-windows` in `prototypes/yetano-webview`) +and yet-gui's (`make gui-selftest`). + +## TODO + +- Linux/FreeBSD backend: WebKitGTK, `webkit_web_context_register_uri_scheme` + (a `GInputStream`, so real streaming) + `WebKitUserContentManager` for + the message binding; own cgo host like `darwin.m`. +- Windows: own environment creation instead of `pkg/edge.Embed` (custom + `yetano://app` scheme, fixed-version runtime, no `log.Fatal` on COM + errors, explicit `Controller.Close`); `Snapshot` via `CapturePreview`. +- Bridge: back-pressure for streams, streaming uploads, XHR progress. +- AP2 (Lua/HTML templating) hooks in before `document.Prepare`. + +The full list with background lives in the prototype's `TODO.md`. + +## Migrating yet-gui (`yet/gui/internal` -> core/gui) + +`yet/gui/internal/{assets,document,bridge,window}` is a byte-identical copy +(apart from the import path) of what is now in this module. + +1. `cd yet/gui && GOPRIVATE=teruna.dev,yetano.dev,yalsh.dev go get yetano.dev/yetano/core/gui@gui/v0.1.0` +2. Replace the imports `yetano.dev/yetano/yet/gui/internal/` with + `yetano.dev/yetano/core/gui/` (`gofmt -r` or `sed`); the API is + unchanged, no call site changes. +3. `git rm -r gui/internal/{assets,document,bridge,window} gui/internal/README.md`, + `go mod tidy`. +4. `make gui-check`, `make gui-selftest` (macOS) and + `make gui-selftest-windows` -- the in-window selftests are the proof, + a cross-build is not. +5. Drop the "keep both copies in sync" notes (yet `docs/gui.md`, the + prototype's `AGENTS.md` already points here). + +A host fix from then on is a core/gui change plus a new `gui/vX.Y.Z` tag, +picked up by `go get` in every consumer. diff --git a/gui/assets/mime.go b/gui/assets/mime.go new file mode 100644 index 0000000..817f27c --- /dev/null +++ b/gui/assets/mime.go @@ -0,0 +1,56 @@ +package assets + +import ( + "bytes" + "fmt" + "net/http" + "path" + "strings" +) + +// Known types by extension. The extension wins; sniffing only fills gaps. +var mimeByExt = map[string]string{ + ".html": "text/html; charset=utf-8", + ".htm": "text/html; charset=utf-8", + ".css": "text/css; charset=utf-8", + ".js": "text/javascript; charset=utf-8", + ".mjs": "text/javascript; charset=utf-8", + ".json": "application/json", + ".txt": "text/plain; charset=utf-8", + ".svg": "image/svg+xml", + ".png": "image/png", + ".jpg": "image/jpeg", + ".jpeg": "image/jpeg", + ".gif": "image/gif", + ".webp": "image/webp", + ".ico": "image/x-icon", + ".ttf": "font/ttf", + ".otf": "font/otf", + ".woff": "font/woff", + ".woff2": "font/woff2", + ".wasm": "application/wasm", +} + +// strict extensions must never resolve to a generic type, and binary ones are +// checked against their magic bytes. +var wasmMagic = []byte{0x00, 'a', 's', 'm'} + +// DetectMIME returns the MIME type for name/data. +func DetectMIME(name string, data []byte) (string, error) { + ext := strings.ToLower(path.Ext(name)) + if m, ok := mimeByExt[ext]; ok { + if ext == ".wasm" && !bytes.HasPrefix(data, wasmMagic) { + return "", fmt.Errorf("%s: .wasm without WebAssembly magic bytes", name) + } + return m, nil + } + return http.DetectContentType(data), nil +} + +// BaseMIME strips parameters ("text/css; charset=utf-8" -> "text/css"). +func BaseMIME(m string) string { + if i := strings.IndexByte(m, ';'); i >= 0 { + m = m[:i] + } + return strings.TrimSpace(m) +} diff --git a/gui/assets/path.go b/gui/assets/path.go new file mode 100644 index 0000000..6b867c7 --- /dev/null +++ b/gui/assets/path.go @@ -0,0 +1,103 @@ +package assets + +import ( + "errors" + "fmt" + "path" + "strings" +) + +// ErrInvalidPath marks a virtual asset path that is rejected before any +// source is consulted (traversal, backslash, drive letter, UNC, NUL, ...). +var ErrInvalidPath = errors.New("invalid asset path") + +// URL prefixes that address the asset root. "/assets/x" and "assets:x" are +// the same identity "x". +const ( + PrefixSlash = "/assets/" + PrefixScheme = "assets:" +) + +// IsAssetRef reports whether ref uses one of the two asset reference forms. +func IsAssetRef(ref string) bool { + return strings.HasPrefix(ref, PrefixSlash) || strings.HasPrefix(ref, PrefixScheme) +} + +// SplitRef removes query and fragment from a reference. They never take part +// in the lookup. +func SplitRef(ref string) (p, suffix string) { + if i := strings.IndexAny(ref, "?#"); i >= 0 { + return ref[:i], ref[i:] + } + return ref, "" +} + +// FromRef turns "/assets/a/b.png?x#y" or "assets:a/b.png" into the canonical +// virtual path "a/b.png". The path is validated with ValidatePath; nothing is +// cleaned silently and nothing is percent-decoded here. +func FromRef(ref string) (string, error) { + p, _ := SplitRef(ref) + switch { + case strings.HasPrefix(p, PrefixSlash): + p = p[len(PrefixSlash):] + case strings.HasPrefix(p, PrefixScheme): + p = p[len(PrefixScheme):] + default: + return "", fmt.Errorf("%w: %q is not an asset reference", ErrInvalidPath, ref) + } + if err := ValidatePath(p); err != nil { + return "", err + } + return p, nil +} + +// ValidatePath accepts only canonical, relative, forward-slash paths inside +// the asset root. It rejects instead of cleaning: "a/../b" is an error, not +// "b". +func ValidatePath(p string) error { + bad := func(why string) error { return fmt.Errorf("%w: %q: %s", ErrInvalidPath, p, why) } + switch { + case p == "": + return bad("empty") + case strings.ContainsRune(p, 0): + return bad("NUL byte") + case strings.Contains(p, `\`): + return bad("backslash") + case strings.HasPrefix(p, "/"): + return bad("absolute") + case strings.Contains(p, ":"): + return bad("drive letter or scheme") + case strings.HasSuffix(p, "/"): + return bad("directory") + } + for _, seg := range strings.Split(p, "/") { + switch seg { + case "": + return bad("empty segment") + case ".", "..": + return bad("dot segment") + } + } + if path.Clean(p) != p { + return bad("not canonical") + } + return nil +} + +// Join resolves ref relative to the directory of base, both virtual paths. +// Unlike ValidatePath it may use ".." segments, as long as the canonical +// result stays inside the root. This is for references found inside trusted +// asset content (CSS url(), @import), not for paths coming from the browser. +func Join(base, ref string) (string, error) { + if strings.ContainsAny(ref, "\\\x00") { + return "", fmt.Errorf("%w: %q", ErrInvalidPath, ref) + } + joined := path.Join(path.Dir(base), ref) + if joined == "." || joined == ".." || strings.HasPrefix(joined, "../") || strings.HasPrefix(joined, "/") { + return "", fmt.Errorf("%w: %q relative to %q leaves the asset root", ErrInvalidPath, ref, base) + } + if err := ValidatePath(joined); err != nil { + return "", err + } + return joined, nil +} diff --git a/gui/assets/resolver.go b/gui/assets/resolver.go new file mode 100644 index 0000000..5bea964 --- /dev/null +++ b/gui/assets/resolver.go @@ -0,0 +1,272 @@ +// Package assets resolves virtual asset paths against an ordered list of +// sources (embedded folder, ZIP, embedded ZIP, explicit directory root). +package assets + +import ( + "archive/zip" + "bytes" + "context" + "errors" + "fmt" + "io" + "io/fs" + "os" + "strings" +) + +// DefaultMaxSize bounds a single resolved resource (also the uncompressed +// budget for a ZIP entry). +const DefaultMaxSize = 32 << 20 + +// Resource is one resolved asset. +type Resource struct { + Name string // canonical virtual path + MIME string + Bytes []byte + Source string // name of the source that served it +} + +// Source is one place assets can come from. Open must return an error +// wrapping fs.ErrNotExist for a missing file; any other error is a real +// failure and stops the lookup. +type Source interface { + Name() string + ReadFile(name string, max int64) ([]byte, error) + Close() error +} + +// Resolver looks a path up in its sources in order. It falls back to the +// next source only on "not found". +type Resolver struct { + sources []Source + max int64 +} + +// NewResolver builds a resolver over sources (at least one). +func NewResolver(sources ...Source) (*Resolver, error) { + if len(sources) == 0 { + return nil, errors.New("assets: no sources configured") + } + return &Resolver{sources: sources, max: DefaultMaxSize}, nil +} + +// Sources lists the source names in lookup order (for the diagnostic report). +func (r *Resolver) Sources() []string { + out := make([]string, len(r.sources)) + for i, s := range r.sources { + out[i] = s.Name() + } + return out +} + +// Resolve returns the resource for a canonical virtual path. +func (r *Resolver) Resolve(ctx context.Context, name string) (*Resource, error) { + if err := ValidatePath(name); err != nil { + return nil, err + } + for _, s := range r.sources { + if err := ctx.Err(); err != nil { + return nil, err + } + data, err := s.ReadFile(name, r.max) + if errors.Is(err, fs.ErrNotExist) { + continue + } + if err != nil { + return nil, fmt.Errorf("asset %q from %s: %w", name, s.Name(), err) + } + m, err := DetectMIME(name, data) + if err != nil { + return nil, fmt.Errorf("asset %q from %s: %w", name, s.Name(), err) + } + return &Resource{Name: name, MIME: m, Bytes: data, Source: s.Name()}, nil + } + return nil, fmt.Errorf("asset %q: %w (searched %s)", name, fs.ErrNotExist, strings.Join(r.Sources(), ", ")) +} + +// ResolveIn returns the resource from one named source only (diagnostics: +// "same bytes from every source"). +func (r *Resolver) ResolveIn(name, source string) (*Resource, error) { + if err := ValidatePath(name); err != nil { + return nil, err + } + for _, s := range r.sources { + if s.Name() != source { + continue + } + data, err := s.ReadFile(name, r.max) + if err != nil { + return nil, err + } + m, err := DetectMIME(name, data) + if err != nil { + return nil, err + } + return &Resource{Name: name, MIME: m, Bytes: data, Source: s.Name()}, nil + } + return nil, fmt.Errorf("no source %q", source) +} + +// Close closes all sources (ZIP archives, directory roots). +func (r *Resolver) Close() error { + var errs []error + for _, s := range r.sources { + errs = append(errs, s.Close()) + } + return errors.Join(errs...) +} + +func readLimited(rd io.Reader, max int64, name string) ([]byte, error) { + data, err := io.ReadAll(io.LimitReader(rd, max+1)) + if err != nil { + return nil, err + } + if int64(len(data)) > max { + return nil, fmt.Errorf("%s exceeds size limit of %d bytes", name, max) + } + return data, nil +} + +// --- fs.FS source (embed.FS, or any fs.FS) ------------------------------- + +type fsSource struct { + name string + fsys fs.FS +} + +// NewFSSource wraps an fs.FS whose root is the asset root (for embed.FS use +// fs.Sub(efs, "assets") first). +func NewFSSource(name string, fsys fs.FS) Source { return &fsSource{name: name, fsys: fsys} } + +func (s *fsSource) Name() string { return s.name } +func (s *fsSource) Close() error { return nil } +func (s *fsSource) ReadFile(name string, max int64) ([]byte, error) { + f, err := s.fsys.Open(name) + if err != nil { + return nil, err + } + defer f.Close() + st, err := f.Stat() + if err != nil { + return nil, err + } + if st.IsDir() { + return nil, fmt.Errorf("%s: %w (is a directory)", name, fs.ErrNotExist) + } + return readLimited(f, max, name) +} + +// --- directory source ---------------------------------------------------- + +type dirSource struct { + name string + root *os.Root +} + +// NewDirSource opens dir as an explicit asset root. os.Root keeps every +// lookup (including symlinks) inside dir. +func NewDirSource(dir string) (Source, error) { + root, err := os.OpenRoot(dir) + if err != nil { + return nil, fmt.Errorf("asset dir %s: %w", dir, err) + } + return &dirSource{name: "dir:" + dir, root: root}, nil +} + +func (s *dirSource) Name() string { return s.name } +func (s *dirSource) Close() error { return s.root.Close() } +func (s *dirSource) ReadFile(name string, max int64) ([]byte, error) { + f, err := s.root.Open(name) + if err != nil { + return nil, err + } + defer f.Close() + st, err := f.Stat() + if err != nil { + return nil, err + } + if st.IsDir() { + return nil, fmt.Errorf("%s: %w (is a directory)", name, fs.ErrNotExist) + } + return readLimited(f, max, name) +} + +// --- ZIP source ---------------------------------------------------------- + +type zipSource struct { + name string + zr *zip.Reader + prefix string + closer io.Closer + files map[string]*zip.File +} + +// NewZipFileSource opens a ZIP file on disk (never extracted). prefix is the +// directory inside the archive that is the asset root ("" = archive root). +func NewZipFileSource(file, prefix string) (Source, error) { + rc, err := zip.OpenReader(file) + if err != nil { + return nil, fmt.Errorf("asset zip %s: %w", file, err) + } + s, err := newZipSource("zip:"+file, &rc.Reader, prefix, rc) + if err != nil { + rc.Close() + return nil, err + } + return s, nil +} + +// NewZipBytesSource reads a ZIP held in memory (e.g. an embedded assets.zip). +func NewZipBytesSource(name string, data []byte, prefix string) (Source, error) { + zr, err := zip.NewReader(bytes.NewReader(data), int64(len(data))) + if err != nil { + return nil, fmt.Errorf("asset zip %s: %w", name, err) + } + return newZipSource(name, zr, prefix, nil) +} + +func newZipSource(name string, zr *zip.Reader, prefix string, closer io.Closer) (*zipSource, error) { + if prefix != "" { + if err := ValidatePath(prefix); err != nil { + return nil, fmt.Errorf("zip root: %w", err) + } + prefix += "/" + } + s := &zipSource{name: name, zr: zr, prefix: prefix, closer: closer, files: map[string]*zip.File{}} + for _, f := range zr.File { + if !strings.HasPrefix(f.Name, prefix) || strings.HasSuffix(f.Name, "/") { + continue + } + rel := f.Name[len(prefix):] + // Entries with unsafe names ("../x", "/etc/x", "a\\b") are never + // reachable: they simply do not get an identity. + if ValidatePath(rel) != nil { + continue + } + s.files[rel] = f + } + return s, nil +} + +func (s *zipSource) Name() string { return s.name } +func (s *zipSource) Close() error { + if s.closer != nil { + return s.closer.Close() + } + return nil +} +func (s *zipSource) ReadFile(name string, max int64) ([]byte, error) { + f, ok := s.files[name] + if !ok { + return nil, fmt.Errorf("%s: %w", name, fs.ErrNotExist) + } + if f.UncompressedSize64 > uint64(max) { + return nil, fmt.Errorf("%s: uncompressed size %d exceeds budget %d", name, f.UncompressedSize64, max) + } + rc, err := f.Open() + if err != nil { + return nil, err + } + defer rc.Close() + return readLimited(rc, max, name) +} diff --git a/gui/assets/resolver_test.go b/gui/assets/resolver_test.go new file mode 100644 index 0000000..1924c4f --- /dev/null +++ b/gui/assets/resolver_test.go @@ -0,0 +1,219 @@ +package assets + +import ( + "archive/zip" + "bytes" + "context" + "errors" + "io/fs" + "os" + "path/filepath" + "runtime" + "strings" + "testing" + "testing/fstest" +) + +func TestValidatePath(t *testing.T) { + ok := []string{"a", "images/logo.png", "a/b/c.wasm", "%2e%2e/x", "dir.with.dots/f"} + bad := []string{"", "/abs", "../x", "a/../b", "./a", "a//b", "a/", `a\b`, "C:/x", "c:x", "a\x00b", "assets:x", ".."} + for _, p := range ok { + if err := ValidatePath(p); err != nil { + t.Errorf("ValidatePath(%q) = %v, want ok", p, err) + } + } + for _, p := range bad { + if err := ValidatePath(p); !errors.Is(err, ErrInvalidPath) { + t.Errorf("ValidatePath(%q) = %v, want ErrInvalidPath", p, err) + } + } +} + +func TestFromRefBothForms(t *testing.T) { + for _, ref := range []string{"/assets/images/a.png", "assets:images/a.png", "/assets/images/a.png?v=1#x", "assets:images/a.png#frag"} { + got, err := FromRef(ref) + if err != nil || got != "images/a.png" { + t.Errorf("FromRef(%q) = %q, %v", ref, got, err) + } + } + for _, ref := range []string{"/other/x", "assets:../x", "/assets/", "/assets//etc/passwd"} { + if _, err := FromRef(ref); err == nil { + t.Errorf("FromRef(%q) accepted", ref) + } + } +} + +func TestJoinRelativeInsideRoot(t *testing.T) { + cases := map[[2]string]string{ + {"css/app.css", "../images/bg.png"}: "images/bg.png", + {"css/app.css", "fonts.css"}: "css/fonts.css", + {"css/a/b.css", "../../x.png"}: "x.png", + } + for in, want := range cases { + if got, err := Join(in[0], in[1]); err != nil || got != want { + t.Errorf("Join(%q,%q) = %q, %v; want %q", in[0], in[1], got, err, want) + } + } + for _, ref := range []string{"../../x.png", "../../../etc/passwd", `..\x`} { + if _, err := Join("css/app.css", ref); err == nil { + t.Errorf("Join escaped root with %q", ref) + } + } +} + +func TestMIME(t *testing.T) { + want := map[string]string{ + "a.css": "text/css", "a.js": "text/javascript", "a.svg": "image/svg+xml", "a.png": "image/png", + "a.ttf": "font/ttf", "a.woff2": "font/woff2", "a.json": "application/json", "a.ico": "image/x-icon", + } + for name, m := range want { + got, err := DetectMIME(name, []byte("x")) + if err != nil || BaseMIME(got) != m { + t.Errorf("%s: %q %v, want %s", name, got, err, m) + } + } + if m, err := DetectMIME("a.wasm", []byte("\x00asm\x01\x00\x00\x00")); err != nil || m != "application/wasm" { + t.Errorf("wasm: %q %v", m, err) + } + if _, err := DetectMIME("a.wasm", []byte("not wasm")); err == nil { + t.Error("fake .wasm accepted") + } + if m, _ := DetectMIME("noext", []byte("\x89PNG\r\n\x1a\n")); m != "image/png" { + t.Errorf("sniff fallback: %q", m) + } +} + +func zipBytes(t *testing.T, files map[string]string) []byte { + t.Helper() + var buf bytes.Buffer + zw := zip.NewWriter(&buf) + for name, data := range files { + w, err := zw.Create(name) + if err != nil { + t.Fatal(err) + } + w.Write([]byte(data)) + } + if err := zw.Close(); err != nil { + t.Fatal(err) + } + return buf.Bytes() +} + +func TestAllSourcesSameIdentity(t *testing.T) { + files := map[string]string{"index.html": "

hi

", "wasm/a.wasm": "\x00asm\x01\x00\x00\x00", "css/app.css": "body{}"} + mfs := fstest.MapFS{} + dir := t.TempDir() + for name, data := range files { + mfs[name] = &fstest.MapFile{Data: []byte(data)} + os.MkdirAll(filepath.Join(dir, filepath.Dir(name)), 0o755) + os.WriteFile(filepath.Join(dir, name), []byte(data), 0o644) + } + zipPath := filepath.Join(t.TempDir(), "assets.zip") + os.WriteFile(zipPath, zipBytes(t, files), 0o644) + dirSrc, err := NewDirSource(dir) + if err != nil { + t.Fatal(err) + } + zipSrc, err := NewZipFileSource(zipPath, "") + if err != nil { + t.Fatal(err) + } + embZip, err := NewZipBytesSource("embedzip", zipBytes(t, files), "") + if err != nil { + t.Fatal(err) + } + for _, s := range []Source{NewFSSource("embed", mfs), dirSrc, zipSrc, embZip} { + r, _ := NewResolver(s) + for name, data := range files { + res, err := r.Resolve(context.Background(), name) + if err != nil || string(res.Bytes) != data || res.Source != s.Name() { + t.Errorf("%s %s: %v", s.Name(), name, err) + } + } + if err := r.Close(); err != nil { + t.Errorf("close %s: %v", s.Name(), err) + } + } +} + +func TestFallbackOnlyOnNotFound(t *testing.T) { + first := fstest.MapFS{"a.txt": {Data: []byte("first")}} + second := fstest.MapFS{"a.txt": {Data: []byte("second")}, "b.txt": {Data: []byte("b")}} + r, _ := NewResolver(NewFSSource("one", first), NewFSSource("two", second)) + if res, _ := r.Resolve(context.Background(), "a.txt"); string(res.Bytes) != "first" { + t.Error("override order not respected") + } + if res, _ := r.Resolve(context.Background(), "b.txt"); res.Source != "two" { + t.Error("no fallback on not-found") + } + if _, err := r.Resolve(context.Background(), "c.txt"); !errors.Is(err, fs.ErrNotExist) { + t.Errorf("missing: %v", err) + } + // A real read error in the first source must not fall through. + boom := &errSource{err: errors.New("permission denied")} + r2, _ := NewResolver(boom, NewFSSource("two", second)) + if _, err := r2.Resolve(context.Background(), "b.txt"); err == nil || !strings.Contains(err.Error(), "permission denied") { + t.Errorf("read error swallowed: %v", err) + } +} + +type errSource struct{ err error } + +func (e *errSource) Name() string { return "err" } +func (e *errSource) Close() error { return nil } +func (e *errSource) ReadFile(string, int64) ([]byte, error) { return nil, e.err } + +func TestCorruptZipIsError(t *testing.T) { + p := filepath.Join(t.TempDir(), "bad.zip") + os.WriteFile(p, []byte("not a zip"), 0o644) + if _, err := NewZipFileSource(p, ""); err == nil { + t.Error("corrupt zip accepted") + } +} + +func TestZipUnsafeNamesAndBudget(t *testing.T) { + data := zipBytes(t, map[string]string{"../evil.txt": "x", "/abs.txt": "x", `a\b.txt`: "x", "assets/ok.txt": "ok", "big.bin": strings.Repeat("x", 2048)}) + s, err := NewZipBytesSource("z", data, "") + if err != nil { + t.Fatal(err) + } + for _, name := range []string{"evil.txt", "abs.txt"} { + if _, err := s.ReadFile(name, 1<<20); !errors.Is(err, fs.ErrNotExist) { + t.Errorf("%s reachable: %v", name, err) + } + } + if _, err := s.ReadFile("big.bin", 1024); err == nil || !strings.Contains(err.Error(), "budget") { + t.Errorf("budget not enforced: %v", err) + } + // Explicit zip root for archives that contain an assets/ folder. + s2, _ := NewZipBytesSource("z", data, "assets") + if b, err := s2.ReadFile("ok.txt", 1024); err != nil || string(b) != "ok" { + t.Errorf("zip root: %q %v", b, err) + } +} + +func TestDirSymlinkEscape(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("symlink creation needs privileges on Windows") + } + outside := t.TempDir() + os.WriteFile(filepath.Join(outside, "secret.txt"), []byte("secret"), 0o644) + root := t.TempDir() + if err := os.Symlink(filepath.Join(outside, "secret.txt"), filepath.Join(root, "link.txt")); err != nil { + t.Fatal(err) + } + if err := os.Symlink(outside, filepath.Join(root, "linkdir")); err != nil { + t.Fatal(err) + } + s, err := NewDirSource(root) + if err != nil { + t.Fatal(err) + } + defer s.Close() + for _, name := range []string{"link.txt", "linkdir/secret.txt"} { + if b, err := s.ReadFile(name, 1024); err == nil { + t.Errorf("%s escaped root: %q", name, b) + } + } +} diff --git a/gui/bridge/bridge.js b/gui/bridge/bridge.js new file mode 100644 index 0000000..9db0878 --- /dev/null +++ b/gui/bridge/bridge.js @@ -0,0 +1,422 @@ +// Yetano WebView bridge, protocol v1. Installed as a document-start script +// before any page script. Replaces window.fetch and window.XMLHttpRequest for +// page-local URLs ("/..." and "assets:...") and routes them through the single +// native binding __yetano_post to the Go host. No network listener is used. +(function () { + 'use strict'; + if (window.yetano && window.yetano.__installed) return; + window.__yetano_install_count = (window.__yetano_install_count || 0) + 1; + + var cfg = window.__yetano_config || {}; + var PROTO = 1; + var origFetch = typeof window.fetch === 'function' ? window.fetch.bind(window) : null; + var OrigXHR = window.XMLHttpRequest; + var nonce = Math.random().toString(36).slice(2) + Date.now().toString(36); + var gen = 0; + var seq = 0; + var pending = new Map(); + var stats = { staleDropped: 0, requests: 0 }; + + var readyResolve, readyReject, readySettled = false; + var ready = new Promise(function (res, rej) { readyResolve = res; readyReject = rej; }); + ready.catch(function () {}); // the rejection is reported to callers, not as unhandled + function settleReady(ok, v) { + if (readySettled) return; + readySettled = true; + clearTimeout(helloTimer); + (ok ? readyResolve : readyReject)(v); + } + + function post(msg) { + var fn = window.__yetano_post; + if (typeof fn !== 'function') return Promise.reject(new Error('native binding __yetano_post missing')); + try { return Promise.resolve(fn(msg)); } catch (e) { return Promise.reject(e); } + } + + // ---- receive --------------------------------------------------------- + window.__yetano_recv = function (m) { + if (!m || typeof m !== 'object') return; + if (m.t === 'ready') { + if (m.nonce !== nonce) return; + if (m.error) { settleReady(false, new Error('yetano bridge: ' + m.error)); return; } + gen = m.gen; + settleReady(true, { generation: m.gen, session: m.session, protocol: m.v }); + return; + } + if (m.t !== 'res' && m.t !== 'err' && m.t !== 'chunk' && m.t !== 'end') return; + var p = pending.get(m.id); + if (!p || m.gen !== gen) { stats.staleDropped++; return; } + switch (m.t) { + case 'res': + if (m.stream) p.startStream(m); + else p.resolve({ status: m.status, statusText: m.statusText || '', headers: m.headers || {}, body: b64dec(m.body || '') }); + break; + case 'chunk': p.chunk(b64dec(m.data || '')); break; + case 'end': p.end(); break; + default: { + var e = m.code === 'timeout' ? new DOMException('yetano: ' + m.message, 'TimeoutError') + : m.code === 'abort' ? new DOMException('yetano: ' + m.message, 'AbortError') + : new TypeError('yetano bridge ' + m.code + ': ' + m.message); + p.fail(e); + } + } + }; + + var helloTimer = setTimeout(function () { + settleReady(false, new Error('yetano bridge: handshake timed out')); + }, cfg.handshakeTimeoutMs || 5000); + post({ t: 'hello', v: cfg.protocolOverride || PROTO, nonce: nonce }).catch(function (e) { + settleReady(false, new Error('yetano bridge: hello failed: ' + e)); + }); + + // ---- helpers --------------------------------------------------------- + function b64enc(u8) { + var s = ''; + for (var i = 0; i < u8.length; i += 0x8000) { + s += String.fromCharCode.apply(null, u8.subarray(i, i + 0x8000)); + } + return btoa(s); + } + function b64dec(s) { + var bin = atob(s); + var u8 = new Uint8Array(bin.length); + for (var i = 0; i < bin.length; i++) u8[i] = bin.charCodeAt(i); + return u8; + } + function abortError(signal) { + return (signal && signal.reason !== undefined) ? signal.reason : new DOMException('The operation was aborted.', 'AbortError'); + } + // Local URLs are recognized on the raw string, before any URL() resolution + // (an inline entry document has an opaque data: origin). Absolute URLs on + // the app origin (native transport) count as local, too. + var NATIVE = cfg.transport === 'native'; + function localURL(u) { + if (typeof u !== 'string') return null; + if (u.indexOf('assets:') === 0) return u; + if (cfg.origin && u.indexOf(cfg.origin + '/') === 0) return u.slice(cfg.origin.length); + if (u.charAt(0) === '/' && u.charAt(1) !== '/') return u; + return null; + } + // For the native transport: "assets:x" is not loadable by the browser. + function nativeURL(local) { + return local.indexOf('assets:') === 0 ? '/assets/' + local.slice(7) : local; + } + function externalBlocked(u) { + return new TypeError('yetano: external request blocked by policy: ' + u); + } + async function toBytes(body, headers) { + function setType(t) { if (!headers['content-type']) headers['content-type'] = t; } + if (typeof body === 'string') { setType('text/plain;charset=UTF-8'); return new TextEncoder().encode(body); } + if (body instanceof URLSearchParams) { setType('application/x-www-form-urlencoded;charset=UTF-8'); return new TextEncoder().encode(body.toString()); } + if (body instanceof ArrayBuffer) return new Uint8Array(body); + if (ArrayBuffer.isView(body)) return new Uint8Array(body.buffer, body.byteOffset, body.byteLength); + if (typeof Blob !== 'undefined' && body instanceof Blob) { if (body.type) setType(body.type); return new Uint8Array(await body.arrayBuffer()); } + if (typeof FormData !== 'undefined' && body instanceof FormData) { + // Let the browser produce multipart/form-data (with its boundary). + var mp = new Response(body); + headers['content-type'] = mp.headers.get('content-type'); + return new Uint8Array(await mp.arrayBuffer()); + } + if (typeof ReadableStream !== 'undefined' && body instanceof ReadableStream) throw new TypeError('yetano: streaming request bodies are not supported (AP1 limit)'); + setType('text/plain;charset=UTF-8'); + return new TextEncoder().encode(String(body)); + } + + // request sends one call. The promise settles exactly once: with the + // response head (body bytes, or a ReadableStream for streamed responses) + // or with an error (abort, timeout, stale generation, transport). A stream + // ends exactly once, too: end, error, abort or reader cancel. Every end + // that is not initiated by Go is reported to Go (abort message). + async function request(d) { + await ready; + if (d.signal && d.signal.aborted) throw abortError(d.signal); + var id = String(++seq); + var myGen = gen; + stats.requests++; + return new Promise(function (resolve, reject) { + var timer = null, ctrl = null, settled = false; + function cleanup() { + pending.delete(id); + if (timer) { clearTimeout(timer); timer = null; } + if (d.signal) d.signal.removeEventListener('abort', onAbort); + } + function fail(e) { + if (!pending.has(id)) return; + cleanup(); + if (ctrl) { try { ctrl.error(e); } catch (x) {} } else if (!settled) { settled = true; reject(e); } + } + function onAbort() { fail(abortError(d.signal)); post({ t: 'abort', id: id, gen: myGen }); } + pending.set(id, { + resolve: function (v) { if (!pending.has(id)) return; cleanup(); settled = true; resolve(v); }, + fail: fail, + startStream: function (m) { + if (timer) { clearTimeout(timer); timer = null; } // the timeout covers the response head + var body = new ReadableStream({ + start: function (c) { ctrl = c; }, + cancel: function () { if (!pending.has(id)) return; cleanup(); post({ t: 'abort', id: id, gen: myGen }); } + }); + settled = true; + resolve({ status: m.status, statusText: m.statusText || '', headers: m.headers || {}, body: body, streaming: true }); + }, + chunk: function (u8) { if (ctrl) ctrl.enqueue(u8); }, + end: function () { if (!pending.has(id)) return; cleanup(); if (ctrl) ctrl.close(); } + }); + if (d.signal) d.signal.addEventListener('abort', onAbort, { once: true }); + var t = d.timeoutMs != null ? d.timeoutMs : (cfg.defaultTimeoutMs || 30000); + if (t > 0) { + timer = setTimeout(function () { + fail(new DOMException('yetano: request timed out after ' + t + ' ms', 'TimeoutError')); + post({ t: 'abort', id: id, gen: myGen, reason: 'timeout' }); + }, t); + } + post({ + t: 'req', id: id, gen: myGen, method: d.method, url: d.url, headers: d.headers, + body: d.body ? b64enc(d.body) : null, timeoutMs: t + }).catch(function (e) { fail(new TypeError('yetano bridge: transport failed: ' + e)); }); + }); + } + + // ---- fetch ----------------------------------------------------------- + // bridgeFetch: local requests as bridge messages (abort, timeout and + // document generation reach the Go handler; bodies are buffered). + async function bridgeFetch(input, init) { + init = init || {}; + var url = typeof input === 'string' ? input + : (typeof URL !== 'undefined' && input instanceof URL) ? input.href + : (input && input.url); + var local = localURL(url); + if (local === null) { + if (cfg.external === 'passthrough' && origFetch) return origFetch(input, init); + throw externalBlocked(url); + } + var method = String(init.method || 'GET').toUpperCase(); + var headers = {}; + new Headers(init.headers || {}).forEach(function (v, k) { headers[k] = v; }); + var body = null; + if (init.body != null) { + if (method === 'GET' || method === 'HEAD') throw new TypeError('yetano: ' + method + ' request cannot have a body'); + body = await toBytes(init.body, headers); + } + var r = await request({ method: method, url: local, headers: headers, body: body, signal: init.signal, timeoutMs: init.yetanoTimeout }); + var nullBody = method === 'HEAD' || r.status === 204 || r.status === 205 || r.status === 304; + return new Response(nullBody ? null : r.body, { status: r.status, statusText: r.statusText, headers: r.headers }); + } + bridgeFetch.yetano = true; + + // nativeFetch (native transport): assets come from the native resource + // handler (no size limit, real Response, ES modules); app routes use the + // bridge (abort/timeout/generation reach Go, streaming via chunk messages + // on every backend). init.yetanoTransport = 'native' | 'bridge' overrides. + function isAsset(local) { return local.indexOf('assets:') === 0 || local.indexOf('/assets/') === 0; } + async function nativeFetch(input, init) { + var url = typeof input === 'string' ? input + : (typeof URL !== 'undefined' && input instanceof URL) ? input.href + : (input && input.url); + var local = localURL(url); + if (local === null) { + if (cfg.external === 'passthrough') return origFetch(input, init); + throw externalBlocked(url); + } + var via = (init && init.yetanoTransport) || (isAsset(local) ? 'native' : 'bridge'); + if (via === 'bridge') return bridgeFetch(input, init); + if (typeof input === 'string' || (typeof URL !== 'undefined' && input instanceof URL)) input = nativeURL(local); + // WebKit hands Blob/FormData bodies to a URL scheme handler as empty + // (observed); serialize them here so every backend receives the bytes. + if (init && needsSerialize(init.body)) { + var headers = {}; + new Headers(init.headers || {}).forEach(function (v, k) { headers[k] = v; }); + var bytes = await toBytes(init.body, headers); + init = Object.assign({}, init, { body: bytes, headers: headers }); + } + return origFetch(input, init); + } + nativeFetch.yetano = true; + function needsSerialize(b) { + return b != null && ((typeof Blob !== 'undefined' && b instanceof Blob) || (typeof FormData !== 'undefined' && b instanceof FormData)); + } + var yetanoFetch = NATIVE ? nativeFetch : bridgeFetch; + window.fetch = yetanoFetch; + + // ---- XMLHttpRequest ------------------------------------------------- + // Local URLs go through the bridge (native transport: assets through the + // real XHR from the app origin); external URLs are delegated to the real + // XHR only with cfg.external === 'passthrough'. Re-opening or aborting an + // instance invalidates its earlier call (token), so a late reply for an old + // request never lands in the reused object. + function YetanoXHR() { + var et = new EventTarget(); + this._et = et; + this.upload = new EventTarget(); + this.readyState = 0; this.status = 0; this.statusText = ''; + this.response = null; this.responseText = ''; this.responseType = ''; this.responseURL = ''; + this.timeout = 0; this.withCredentials = false; + this._token = 0; this._reqHeaders = {}; this._respHeaders = {}; this._ctl = null; this._sent = false; + } + YetanoXHR.UNSENT = 0; YetanoXHR.OPENED = 1; YetanoXHR.HEADERS_RECEIVED = 2; YetanoXHR.LOADING = 3; YetanoXHR.DONE = 4; + ['UNSENT', 'OPENED', 'HEADERS_RECEIVED', 'LOADING', 'DONE'].forEach(function (k, i) { YetanoXHR.prototype[k] = i; }); + YetanoXHR.prototype.addEventListener = function (t, f, o) { this._et.addEventListener(t, f, o); }; + YetanoXHR.prototype.removeEventListener = function (t, f, o) { this._et.removeEventListener(t, f, o); }; + YetanoXHR.prototype.dispatchEvent = function (e) { return this._et.dispatchEvent(e); }; + YetanoXHR.prototype._fire = function (type, loaded, total) { + var ev = (type === 'readystatechange') ? new Event(type) + : new ProgressEvent(type, { lengthComputable: total != null, loaded: loaded || 0, total: total || 0 }); + var h = this['on' + type]; + if (typeof h === 'function') { try { h.call(this, ev); } catch (e) { setTimeout(function () { throw e; }); } } + this._et.dispatchEvent(ev); + }; + YetanoXHR.prototype._state = function (s) { this.readyState = s; this._fire('readystatechange'); }; + YetanoXHR.prototype.open = function (method, url, async) { + if (async === false) throw new DOMException('yetano: synchronous XMLHttpRequest is not supported', 'InvalidAccessError'); + this._token++; + if (this._ctl) { this._ctl.abort(); this._ctl = null; } + if (this._native) { this._native.abort(); this._native = null; } + this._method = String(method || 'GET').toUpperCase(); + this._url = String(url); + this._reqHeaders = {}; this._respHeaders = {}; this._sent = false; + this.status = 0; this.statusText = ''; this.response = null; this.responseText = ''; + this._state(1); + }; + YetanoXHR.prototype.setRequestHeader = function (k, v) { + if (this.readyState !== 1 || this._sent) throw new DOMException('setRequestHeader: invalid state', 'InvalidStateError'); + k = String(k).toLowerCase(); + this._reqHeaders[k] = this._reqHeaders[k] ? this._reqHeaders[k] + ', ' + v : String(v); + }; + YetanoXHR.prototype.overrideMimeType = function (m) { this._mime = m; }; + YetanoXHR.prototype.getResponseHeader = function (k) { + var v = this._respHeaders[String(k).toLowerCase()]; + return v === undefined ? null : v; + }; + YetanoXHR.prototype.getAllResponseHeaders = function () { + var h = this._respHeaders; + return Object.keys(h).sort().map(function (k) { return k + ': ' + h[k] + '\r\n'; }).join(''); + }; + YetanoXHR.prototype.abort = function () { + var wasActive = this._sent && this.readyState !== 4; + this._token++; + if (this._ctl) { this._ctl.abort(); this._ctl = null; } + if (this._native) { this._native.abort(); this._native = null; } + if (wasActive) { this._sent = false; this._state(4); this._fire('abort'); this._fire('loadend'); } + this.readyState = 0; + }; + YetanoXHR.prototype.send = function (body) { + if (this.readyState !== 1 || this._sent) throw new DOMException('send: invalid state', 'InvalidStateError'); + var self = this, token = this._token; + var local = localURL(this._url); + if (local === null) return this._sendNative(body, false); + if (NATIVE && isAsset(local)) return this._sendNative(body, true, nativeURL(local)); + this._sent = true; + var ctl = new AbortController(); + this._ctl = ctl; + var headers = Object.assign({}, this._reqHeaders); + this._fire('loadstart', 0); + (async function () { + var bytes = null; + if (body != null && self._method !== 'GET' && self._method !== 'HEAD') bytes = await toBytes(body, headers); + return request({ method: self._method, url: local, headers: headers, body: bytes, signal: ctl.signal, timeoutMs: self.timeout > 0 ? self.timeout : undefined }); + })().then(async function (r) { + if (r.streaming) r.body = new Uint8Array(await new Response(r.body).arrayBuffer()); + return r; + }).then(function (r) { + if (token !== self._token) return; // reopened/aborted meanwhile + self._ctl = null; + self.status = r.status; self.statusText = r.statusText; self._respHeaders = r.headers; + self.responseURL = local; + self._state(2); + var type = (self._mime || r.headers['content-type'] || '').split(';')[0].trim(); + var text = null; + function asText() { if (text === null) text = new TextDecoder().decode(r.body); return text; } + switch (self.responseType) { + case 'arraybuffer': self.response = r.body.buffer.slice(r.body.byteOffset, r.body.byteOffset + r.body.byteLength); break; + case 'blob': self.response = new Blob([r.body], { type: type }); break; + case 'json': try { self.response = JSON.parse(asText()); } catch (e) { self.response = null; } break; + case 'document': self.response = new DOMParser().parseFromString(asText(), type === 'text/xml' || type === 'application/xml' ? type : 'text/html'); break; + default: self.responseText = self.response = asText(); + } + self._state(3); + self._fire('progress', r.body.length, r.body.length); + self._sent = false; + self._state(4); + self._fire('load', r.body.length, r.body.length); + self._fire('loadend', r.body.length, r.body.length); + }, function (e) { + if (token !== self._token) return; + self._ctl = null; self._sent = false; + self.status = 0; + self._state(4); + self._fire(e && e.name === 'TimeoutError' ? 'timeout' : (e && e.name === 'AbortError' ? 'abort' : 'error')); + self._fire('loadend'); + }); + }; + YetanoXHR.prototype._sendNative = function (body, asset, url) { + var self = this; + if (!asset && (cfg.external !== 'passthrough' || !OrigXHR)) { + this._sent = true; + setTimeout(function () { + self._sent = false; self.status = 0; self._state(4); + self._fire('error'); self._fire('loadend'); + if (window.console) console.warn(String(externalBlocked(self._url))); + }); + return; + } + var x = new OrigXHR(); + this._native = x; + this._sent = true; + x.open(this._method, url || this._url, true); + Object.keys(this._reqHeaders).forEach(function (k) { x.setRequestHeader(k, self._reqHeaders[k]); }); + x.responseType = this.responseType; x.timeout = this.timeout; x.withCredentials = this.withCredentials; + ['readystatechange', 'loadstart', 'progress', 'load', 'error', 'abort', 'timeout', 'loadend'].forEach(function (t) { + x.addEventListener(t, function () { + if (self._native !== x) return; + self.status = x.status; self.statusText = x.statusText; self.response = x.response; self.responseURL = x.responseURL; + if (x.responseType === '' || x.responseType === 'text') self.responseText = x.responseText; + self._respHeaders = {}; + (x.getAllResponseHeaders() || '').trim().split(/[\r\n]+/).forEach(function (l) { + var i = l.indexOf(':'); if (i > 0) self._respHeaders[l.slice(0, i).trim().toLowerCase()] = l.slice(i + 1).trim(); + }); + if (t === 'readystatechange') { self._state(x.readyState); } else { self._fire(t); } + }); + }); + x.send(body); + }; + window.XMLHttpRequest = YetanoXHR; + + // ---- page console -> host log (diagnostics) --------------------------- + if (cfg.forwardConsole) { + ['log', 'warn', 'error'].forEach(function (lvl) { + var orig = console[lvl]; + console[lvl] = function () { + try { post({ t: 'log', level: lvl, msg: Array.prototype.map.call(arguments, String).join(' ') }); } catch (e) {} + return orig.apply(console, arguments); + }; + }); + window.addEventListener('error', function (e) { post({ t: 'log', level: 'error', msg: 'uncaught: ' + e.message + ' @' + e.filename + ':' + e.lineno }); }); + window.addEventListener('unhandledrejection', function (e) { post({ t: 'log', level: 'error', msg: 'unhandled rejection: ' + (e.reason && e.reason.stack || e.reason) }); }); + } + + // ---- public API ------------------------------------------------------ + async function call(route, payload, opts) { + opts = opts || {}; + var r = await bridgeFetch('/rpc/' + route, { + method: 'POST', headers: { 'content-type': 'application/json' }, + body: JSON.stringify(payload === undefined ? null : payload), + signal: opts.signal, yetanoTimeout: opts.timeoutMs + }); + var text = await r.text(); + if (!r.ok) { var err = new Error(route + ': HTTP ' + r.status + ': ' + text); err.status = r.status; throw err; } + return text ? JSON.parse(text) : null; + } + + window.yetano = Object.freeze({ + __installed: true, + protocol: PROTO, + config: cfg, + transport: NATIVE ? 'native' : 'inline', + bridgeFetch: bridgeFetch, + ready: ready, + fetch: yetanoFetch, + call: call, + pendingCount: function () { return pending.size; }, + stats: function () { return { staleDropped: stats.staleDropped, requests: stats.requests, pending: pending.size, generation: gen }; }, + _post: cfg.selftest ? post : undefined + }); +})(); diff --git a/gui/bridge/native.go b/gui/bridge/native.go new file mode 100644 index 0000000..10f6f46 --- /dev/null +++ b/gui/bridge/native.go @@ -0,0 +1,72 @@ +package bridge + +import ( + "context" + "errors" + "fmt" + "net/http" + "strings" +) + +// NativeWriter is the response side of a native resource request +// (implemented by window.ResourceWriter). +type NativeWriter interface { + Respond(status int, header http.Header) + Write(p []byte) (int, error) + Close(err error) +} + +// ServeNative answers a request the WebView made to the app origin through +// the native resource handler: "/" is the entry document, everything else +// goes through the same router as bridge requests. Stream responses are +// written through as they are produced. +func (r *Router) ServeNative(ctx context.Context, origin, method, rawURL string, header http.Header, body []byte, w NativeWriter) { + if !strings.HasPrefix(rawURL, origin+"/") { + w.Respond(http.StatusForbidden, textHeader()) + w.Write([]byte("not the app origin: " + rawURL)) + return + } + local := rawURL[len(origin):] + path, q, err := ParseLocalURL(local) + if err != nil { + w.Respond(http.StatusBadRequest, textHeader()) + w.Write([]byte(err.Error())) + return + } + if path == "/" { + r.mu.RLock() + entry := r.entry + r.mu.RUnlock() + path = "/assets/" + entry + } + req := &Request{Native: true, Method: strings.ToUpper(method), URL: local, Path: path, Query: q, Header: header, Body: body} + resp, err := r.Serve(ctx, req) + if err != nil { + w.Close(err) + return + } + h := resp.Header + if h == nil { + h = http.Header{} + } + h.Set("Cache-Control", "no-store") + w.Respond(resp.Status, h) + if resp.Stream != nil { + if err := resp.Stream(ctx, w); err != nil && !errors.Is(err, context.Canceled) { + w.Close(fmt.Errorf("%s %s: stream: %w", req.Method, req.Path, err)) + return + } + w.Close(nil) + return + } + if len(resp.Body) > 0 { + w.Write(resp.Body) + } + w.Close(nil) +} + +func textHeader() http.Header { + h := http.Header{} + h.Set("Content-Type", "text/plain; charset=utf-8") + return h +} diff --git a/gui/bridge/router.go b/gui/bridge/router.go new file mode 100644 index 0000000..11d6ca6 --- /dev/null +++ b/gui/bridge/router.go @@ -0,0 +1,265 @@ +package bridge + +import ( + "context" + "errors" + "fmt" + "io" + "io/fs" + "net/http" + "net/url" + "runtime/debug" + "sort" + "strings" + "sync" + + "yetano.dev/yetano/core/gui/assets" + "yetano.dev/yetano/core/gui/document" +) + +// Request is a local request as it arrives from the fetch/XHR adapter or +// the native resource handler. +type Request struct { + Native bool // via the native resource handler (link mode for HTML/CSS) + Method string + URL string // as written by the page ("/rpc/add?x=1", "assets:img/a.png") + Path string // percent-decoded once, without query + Query url.Values + Header http.Header + Body []byte +} + +// Response is an HTTP-like local response. 404/500 are responses, not +// transport errors. A handler either sets Body or Stream. Stream writes the +// body incrementally: the native resource handler delivers every Write to +// the page as it happens; the bridge transport buffers it (MaxBody). +type Response struct { + Status int + Header http.Header + Body []byte + Stream func(ctx context.Context, w io.Writer) error +} + +// HandlerFunc serves one registered route. Returning an error yields a 500 +// response that names the route; a cancelled ctx yields an abort/timeout. +type HandlerFunc func(ctx context.Context, req *Request) (*Response, error) + +// Router maps local requests to the asset resolver and to registered Go +// handlers. Routes are fixed before the document starts (Freeze). +type Router struct { + mu sync.RWMutex + routes map[string]HandlerFunc // "METHOD /path" + frozen bool + res *assets.Resolver + entry string // asset served for "/" by the native handler + native bool // document mode: link (native) or inline (bridge) +} + +// SetDocument sets the entry asset for "/" and whether Go-generated HTML is +// prepared for the native resource handler (link mode) or inlined. +func (r *Router) SetDocument(entry string, native bool) { + r.mu.Lock() + r.entry, r.native = entry, native + r.mu.Unlock() +} + +// NewRouter creates a router that serves GET/HEAD /assets/... and assets:... +// from res. +func NewRouter(res *assets.Resolver) *Router { + return &Router{routes: map[string]HandlerFunc{}, res: res} +} + +// Resolver returns the asset resolver behind /assets/. +func (r *Router) Resolver() *assets.Resolver { return r.res } + +// Handle registers h for an exact method and path. Duplicate registrations +// and registrations after Freeze are errors. +func (r *Router) Handle(method, path string, h HandlerFunc) error { + method = strings.ToUpper(method) + if !strings.HasPrefix(path, "/") || strings.HasPrefix(path, "/assets/") || h == nil { + return fmt.Errorf("bridge: invalid route %s %s", method, path) + } + key := method + " " + path + r.mu.Lock() + defer r.mu.Unlock() + if r.frozen { + return fmt.Errorf("bridge: route %s registered after document start", key) + } + if _, dup := r.routes[key]; dup { + return fmt.Errorf("bridge: duplicate route %s", key) + } + r.routes[key] = h + return nil +} + +// Freeze ends registration. +func (r *Router) Freeze() { + r.mu.Lock() + r.frozen = true + r.mu.Unlock() +} + +// Routes lists registered routes (diagnostics). +func (r *Router) Routes() []string { + r.mu.RLock() + defer r.mu.RUnlock() + out := make([]string, 0, len(r.routes)) + for k := range r.routes { + out = append(out, k) + } + sort.Strings(out) + return out +} + +// ParseLocalURL splits a page-local URL into path and query. It accepts +// "/x" (not "//x") and "assets:x". The path is percent-decoded exactly once. +func ParseLocalURL(raw string) (path string, q url.Values, err error) { + p, rest := assets.SplitRef(raw) + if strings.HasPrefix(rest, "?") { + qs := rest[1:] + if i := strings.IndexByte(qs, '#'); i >= 0 { + qs = qs[:i] + } + if q, err = url.ParseQuery(qs); err != nil { + return "", nil, fmt.Errorf("bad query: %w", err) + } + } + switch { + case strings.HasPrefix(p, assets.PrefixScheme): + p = assets.PrefixSlash + p[len(assets.PrefixScheme):] + case strings.HasPrefix(p, "/") && !strings.HasPrefix(p, "//"): + default: + return "", nil, fmt.Errorf("not a local URL: %q", raw) + } + dec, err := url.PathUnescape(p) + if err != nil { + return "", nil, fmt.Errorf("bad path escape: %w", err) + } + return dec, q, nil +} + +// Serve answers one request. It returns an error only when ctx ended +// (abort, timeout, stale generation, close). +func (r *Router) Serve(ctx context.Context, req *Request) (resp *Response, err error) { + defer func() { + if p := recover(); p != nil { + resp, err = Text(http.StatusInternalServerError, fmt.Sprintf("%s %s: handler panic: %v\n%s", req.Method, req.Path, p, debug.Stack())), nil + } + }() + resp = r.serve(ctx, req) + if cerr := ctx.Err(); cerr != nil { + return nil, context.Cause(ctx) + } + return resp, nil +} + +func (r *Router) serve(ctx context.Context, req *Request) *Response { + if strings.HasPrefix(req.Path, assets.PrefixSlash) { + if req.Method != http.MethodGet && req.Method != http.MethodHead { + return Text(http.StatusMethodNotAllowed, "assets are read-only") + } + name := req.Path[len(assets.PrefixSlash):] + res, err := r.res.Resolve(ctx, name) + switch { + case errors.Is(err, assets.ErrInvalidPath): + return Text(http.StatusBadRequest, err.Error()) + case errors.Is(err, fs.ErrNotExist): + return Text(http.StatusNotFound, err.Error()) + case err != nil: + return Text(http.StatusInternalServerError, err.Error()) + } + h := http.Header{} + h.Set("Content-Type", res.MIME) + h.Set("X-Yetano-Asset-Source", res.Source) + body := res.Bytes + if req.Native { + // Natively loaded HTML/CSS: assets: references become /assets/ + // URLs the WebView can load; nothing is inlined. + var err error + switch assets.BaseMIME(res.MIME) { + case "text/html": + var doc *document.Result + if doc, err = document.Prepare(ctx, r.res, name, body, document.Options{Link: true}); err == nil { + body = doc.HTML + } + case "text/css": + body, err = document.PrepareCSS(ctx, r.res, name, body, document.Options{Link: true}) + } + if err != nil { + return Text(http.StatusInternalServerError, err.Error()) + } + } + if req.Method == http.MethodHead { + h.Set("Content-Length", fmt.Sprint(len(body))) + body = nil + } + return &Response{Status: http.StatusOK, Header: h, Body: body} + } + + r.mu.RLock() + h, ok := r.routes[req.Method+" "+req.Path] + if !ok && req.Method == http.MethodHead { + h, ok = r.routes["GET "+req.Path] + } + known := false + if !ok { + for k := range r.routes { + if strings.HasSuffix(k, " "+req.Path) { + known = true + } + } + } + r.mu.RUnlock() + if !ok { + if known { + return Text(http.StatusMethodNotAllowed, fmt.Sprintf("%s not allowed for %s", req.Method, req.Path)) + } + return Text(http.StatusNotFound, "no route for "+req.Method+" "+req.Path) + } + resp, err := h(ctx, req) + if err != nil { + if ctx.Err() != nil { + return nil + } + return Text(http.StatusInternalServerError, fmt.Sprintf("%s %s: %v", req.Method, req.Path, err)) + } + if resp == nil { + resp = &Response{Status: http.StatusNoContent} + } + if resp.Status < 200 || resp.Status > 599 { + return Text(http.StatusInternalServerError, fmt.Sprintf("%s %s: handler returned invalid status %d", req.Method, req.Path, resp.Status)) + } + if req.Method == http.MethodHead { + resp.Body = nil + } + return resp +} + +// Text builds a text/plain response. +func Text(status int, body string) *Response { + h := http.Header{} + h.Set("Content-Type", "text/plain; charset=utf-8") + return &Response{Status: status, Header: h, Body: []byte(body)} +} + +// JSONBytes builds an application/json response from already-encoded JSON. +func JSONBytes(status int, body []byte) *Response { + h := http.Header{} + h.Set("Content-Type", "application/json") + return &Response{Status: status, Header: h, Body: body} +} + +// HTML prepares Go-generated HTML through the same asset replace as the entry +// document and returns it as a text/html response. +func (r *Router) HTML(ctx context.Context, name string, src []byte) (*Response, error) { + r.mu.RLock() + link := r.native + r.mu.RUnlock() + doc, err := document.Prepare(ctx, r.res, name, src, document.Options{Link: link}) + if err != nil { + return nil, err + } + h := http.Header{} + h.Set("Content-Type", "text/html; charset=utf-8") + return &Response{Status: http.StatusOK, Header: h, Body: doc.HTML}, nil +} diff --git a/gui/bridge/script.go b/gui/bridge/script.go new file mode 100644 index 0000000..63f139d --- /dev/null +++ b/gui/bridge/script.go @@ -0,0 +1,32 @@ +package bridge + +import ( + _ "embed" + "encoding/json" +) + +//go:embed bridge.js +var bridgeJS string + +// PageConfig is exposed to the page as window.__yetano_config (and +// window.yetano.config) before the bridge installs itself. +type PageConfig struct { + External string `json:"external"` // "reject" (default) or "passthrough" + Transport string `json:"transport"` // "native" (scheme handler) or "inline" (data: entry, bridge only) + Origin string `json:"origin,omitempty"` + DefaultTimeoutMs int `json:"defaultTimeoutMs,omitempty"` + HandshakeTimeoutMs int `json:"handshakeTimeoutMs,omitempty"` + ForwardConsole bool `json:"forwardConsole,omitempty"` + Selftest bool `json:"selftest,omitempty"` + Run int `json:"run,omitempty"` + ProtocolOverride int `json:"protocolOverride,omitempty"` // tests only +} + +// InitScript returns the document-start script: config + bridge. +func InitScript(cfg PageConfig) string { + if cfg.External == "" { + cfg.External = "reject" + } + b, _ := json.Marshal(cfg) + return "window.__yetano_config=" + string(b) + ";\n" + bridgeJS +} diff --git a/gui/bridge/session.go b/gui/bridge/session.go new file mode 100644 index 0000000..e0ca02d --- /dev/null +++ b/gui/bridge/session.go @@ -0,0 +1,477 @@ +// Package bridge connects the page and the Go host without any network +// listener: one native binding (__yetano_post) carries JSON messages from +// JS to Go; replies go back through Dispatch+Eval on the UI thread. +// +// Protocol v1 (all messages are JSON objects with a "t" field): +// +// JS -> Go {t:"hello", v, nonce} +// JS -> Go {t:"req", id, gen, method, url, headers, body(base64|null), timeoutMs} +// JS -> Go {t:"abort", id, gen, reason} +// JS -> Go {t:"log", level, msg} +// Go -> JS {t:"ready", v, gen, nonce, session} or {t:"ready", nonce, error} +// Go -> JS {t:"res", id, gen, status, statusText, headers, body(base64)} +// Go -> JS {t:"err", id, gen, code, message} code: abort|timeout|stale|closed|protocol +// +// Every document load sends a new hello and gets a new generation. Calls of +// an older generation are cancelled and their results are dropped, both in Go +// (before Dispatch and again on the UI thread) and in JS. +package bridge + +import ( + "context" + "crypto/rand" + "encoding/base64" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "net/http" + "strings" + "sync" + "sync/atomic" + "time" +) + +// ProtocolVersion is the bridge wire version. +const ProtocolVersion = 1 + +// Binding is the name of the single native binding. +const Binding = "__yetano_post" + +// Cancellation causes reported to handlers via context.Cause. +var ( + ErrAborted = errors.New("request aborted by page") + ErrTimeout = errors.New("request timed out") + ErrStale = errors.New("document generation replaced (reload/navigation)") + ErrClosed = errors.New("session closed") +) + +// Dispatcher is the part of the native window the session needs. Dispatch +// must be safe from any goroutine and run f on the UI thread; Eval is only +// called from inside such an f. +type Dispatcher interface { + Dispatch(f func()) + Eval(js string) +} + +// Options configure a session. +type Options struct { + MaxBody int // max request body (decoded); default 8 MiB + MaxTimeout time.Duration // upper bound for any call; default 60s + CloseWait time.Duration // how long Close waits for handlers; default 5s + Logf func(format string, args ...any) + OnPageLog func(level, msg string) + OnHello func(gen uint64) // called after a new generation started +} + +// Stats are counters for diagnostics and tests. +type Stats struct { + Generation uint64 `json:"generation"` + Hellos uint64 `json:"hellos"` + Requests uint64 `json:"requests"` + Completed uint64 `json:"completed"` + Cancelled uint64 `json:"cancelled"` + DroppedStale uint64 `json:"droppedStale"` + DroppedClosed uint64 `json:"droppedClosed"` + ProtocolErrors uint64 `json:"protocolErrors"` + Pending int `json:"pending"` +} + +type call struct { + gen uint64 + cancel context.CancelCauseFunc +} + +// Session owns the bridge state of one window. +type Session struct { + id string + router *Router + opt Options + + mu sync.Mutex + d Dispatcher + gen uint64 + closed bool + calls map[string]*call + wg sync.WaitGroup + + hellos, requests, completed, cancelled atomic.Uint64 + droppedStale, droppedClosed, protocolErrors atomic.Uint64 +} + +// NewSession creates a session for router. The router is frozen. +func NewSession(router *Router, opt Options) *Session { + if opt.MaxBody == 0 { + opt.MaxBody = 8 << 20 + } + if opt.MaxTimeout == 0 { + opt.MaxTimeout = 60 * time.Second + } + if opt.CloseWait == 0 { + opt.CloseWait = 5 * time.Second + } + if opt.Logf == nil { + opt.Logf = func(string, ...any) {} + } + router.Freeze() + var b [8]byte + _, _ = rand.Read(b[:]) + return &Session{id: hex.EncodeToString(b[:]), router: router, opt: opt, calls: map[string]*call{}} +} + +// Attach sets the dispatcher (the native window). Must happen before the +// first message. +func (s *Session) Attach(d Dispatcher) { + s.mu.Lock() + s.d = d + s.mu.Unlock() +} + +// ID returns the random session id. +func (s *Session) ID() string { return s.id } + +// Stats returns a snapshot of the counters. +func (s *Session) Stats() Stats { + s.mu.Lock() + gen, pending := s.gen, len(s.calls) + s.mu.Unlock() + return Stats{ + Generation: gen, Hellos: s.hellos.Load(), Requests: s.requests.Load(), + Completed: s.completed.Load(), Cancelled: s.cancelled.Load(), + DroppedStale: s.droppedStale.Load(), DroppedClosed: s.droppedClosed.Load(), + ProtocolErrors: s.protocolErrors.Load(), Pending: pending, + } +} + +type inMsg struct { + T string `json:"t"` + V int `json:"v"` + Nonce string `json:"nonce"` + ID string `json:"id"` + Gen uint64 `json:"gen"` + Method string `json:"method"` + URL string `json:"url"` + Headers map[string]string `json:"headers"` + Body *string `json:"body"` + TimeoutMs int64 `json:"timeoutMs"` + Reason string `json:"reason"` + Level string `json:"level"` + Msg string `json:"msg"` +} + +// Post is the native binding target. It only decodes and enqueues; all work +// happens on other goroutines, so the UI thread is never blocked. +func (s *Session) Post(raw json.RawMessage) { + var m inMsg + if err := json.Unmarshal(raw, &m); err != nil { + s.protocolErrors.Add(1) + s.opt.Logf("bridge: undecodable message: %v", err) + return + } + switch m.T { + case "hello": + s.hello(m) + case "req": + s.request(m) + case "abort": + s.abort(m) + case "log": + if s.opt.OnPageLog != nil { + s.opt.OnPageLog(m.Level, m.Msg) + } + default: + s.protocolErrors.Add(1) + s.opt.Logf("bridge: unknown message type %q", m.T) + if m.ID != "" { + s.send(m.Gen, map[string]any{"t": "err", "id": m.ID, "gen": m.Gen, "code": "protocol", "message": "unknown message type " + m.T}) + } + } +} + +func (s *Session) hello(m inMsg) { + s.hellos.Add(1) + if m.V != ProtocolVersion { + s.protocolErrors.Add(1) + s.mu.Lock() + gen := s.gen + s.mu.Unlock() + // Reply on the current generation so the page sees the refusal. + s.sendAny(gen, map[string]any{"t": "ready", "nonce": m.Nonce, "error": fmt.Sprintf("unsupported bridge protocol %d (host speaks %d)", m.V, ProtocolVersion)}) + return + } + s.mu.Lock() + if s.closed { + s.mu.Unlock() + return + } + s.gen++ + gen := s.gen + for id, c := range s.calls { + if c.gen < gen { + c.cancel(ErrStale) + delete(s.calls, id) + } + } + s.mu.Unlock() + s.send(gen, map[string]any{"t": "ready", "v": ProtocolVersion, "gen": gen, "nonce": m.Nonce, "session": s.id}) + if s.opt.OnHello != nil { + s.opt.OnHello(gen) + } +} + +func (s *Session) request(m inMsg) { + s.requests.Add(1) + fail := func(code, msg string) { + s.send(m.Gen, map[string]any{"t": "err", "id": m.ID, "gen": m.Gen, "code": code, "message": msg}) + } + if m.ID == "" { + s.protocolErrors.Add(1) + return + } + method := strings.ToUpper(m.Method) + if method == "" { + method = http.MethodGet + } + path, q, err := ParseLocalURL(m.URL) + if err != nil { + // A bad URL is a response (400), not a transport failure. + s.respond(m.Gen, m.ID, Text(http.StatusBadRequest, err.Error())) + return + } + var body []byte + if m.Body != nil { + if base64.StdEncoding.DecodedLen(len(*m.Body)) > s.opt.MaxBody+3 { + s.respond(m.Gen, m.ID, Text(http.StatusRequestEntityTooLarge, "request body too large")) + return + } + if body, err = base64.StdEncoding.DecodeString(*m.Body); err != nil { + s.protocolErrors.Add(1) + fail("protocol", "request body is not valid base64") + return + } + } + h := http.Header{} + for k, v := range m.Headers { + h.Set(k, v) + } + timeout := s.opt.MaxTimeout + if m.TimeoutMs > 0 && time.Duration(m.TimeoutMs)*time.Millisecond < timeout { + timeout = time.Duration(m.TimeoutMs) * time.Millisecond + } + + s.mu.Lock() + switch { + case s.closed: + s.mu.Unlock() + s.droppedClosed.Add(1) + return + case m.Gen != s.gen: + s.mu.Unlock() + s.droppedStale.Add(1) + return + } + if _, dup := s.calls[m.ID]; dup { + s.mu.Unlock() + s.protocolErrors.Add(1) + fail("protocol", "duplicate request id") + return + } + ctx, cancel := context.WithCancelCause(context.Background()) + ctx, cancelTimeout := context.WithTimeoutCause(ctx, timeout, ErrTimeout) + s.calls[m.ID] = &call{gen: m.Gen, cancel: cancel} + s.wg.Add(1) + s.mu.Unlock() + + req := &Request{Method: method, URL: m.URL, Path: path, Query: q, Header: h, Body: body} + go func() { + defer s.wg.Done() + defer cancelTimeout() + resp, err := s.router.Serve(ctx, req) + if err == nil && resp.Stream != nil { + s.stream(ctx, cancel, m, req, resp) + return + } + s.mu.Lock() + _, live := s.calls[m.ID] + delete(s.calls, m.ID) + s.mu.Unlock() + cancel(nil) + if err != nil { + s.cancelled.Add(1) + code := "abort" + switch { + case errors.Is(err, ErrTimeout): + code = "timeout" + case errors.Is(err, ErrStale): + code = "stale" + case errors.Is(err, ErrClosed): + code = "closed" + } + // A call removed by abort/hello/Close already ended on the + // page side; only a host-side deadline still needs a reply. + if live { + fail(code, err.Error()) + } + return + } + if !live { + s.droppedStale.Add(1) + return + } + s.completed.Add(1) + s.respond(m.Gen, m.ID, resp) + }() +} + +func (s *Session) abort(m inMsg) { + s.mu.Lock() + c, ok := s.calls[m.ID] + if ok && c.gen == m.Gen { + delete(s.calls, m.ID) + } + s.mu.Unlock() + if ok && c.gen == m.Gen { + if m.Reason == "timeout" { + c.cancel(ErrTimeout) + } else { + c.cancel(ErrAborted) + } + } +} + +func (s *Session) respond(gen uint64, id string, r *Response) { + hdr := map[string]string{} + for k, v := range r.Header { + hdr[strings.ToLower(k)] = strings.Join(v, ", ") + } + s.send(gen, map[string]any{ + "t": "res", "id": id, "gen": gen, "status": r.Status, "statusText": http.StatusText(r.Status), + "headers": hdr, "body": base64.StdEncoding.EncodeToString(r.Body), + }) +} + +// send delivers msg to the page if gen is still the current generation and +// the session is open; otherwise the message is dropped and counted. +func (s *Session) send(gen uint64, msg map[string]any) { s.deliver(gen, msg, true) } + +// sendAny delivers without a generation check (protocol refusal). +func (s *Session) sendAny(gen uint64, msg map[string]any) { s.deliver(gen, msg, false) } + +func (s *Session) deliver(gen uint64, msg map[string]any, checkGen bool) { + b, err := json.Marshal(msg) + if err != nil { + s.opt.Logf("bridge: marshal: %v", err) + return + } + // json.Marshal escapes <, >, &, U+2028 and U+2029, so b is a safe JS + // expression. + js := "window.__yetano_recv&&window.__yetano_recv(" + string(b) + ")" + ok := func() bool { + if s.closed { + s.droppedClosed.Add(1) + return false + } + if checkGen && gen != s.gen { + s.droppedStale.Add(1) + return false + } + return true + } + s.mu.Lock() + d := s.d + if !ok() || d == nil { + s.mu.Unlock() + return + } + s.mu.Unlock() + d.Dispatch(func() { + // Re-check on the UI thread: a reload or Close may have happened + // while this closure was queued. + s.mu.Lock() + live := ok() + s.mu.Unlock() + if live { + d.Eval(js) + } + }) +} + +// stream delivers a Stream response as res(stream:true), chunk..., end. +// The call stays registered (abortable, generation-bound) until the end. +func (s *Session) stream(ctx context.Context, cancel context.CancelCauseFunc, m inMsg, req *Request, resp *Response) { + hdr := map[string]string{} + for k, v := range resp.Header { + hdr[strings.ToLower(k)] = strings.Join(v, ", ") + } + s.send(m.Gen, map[string]any{"t": "res", "id": m.ID, "gen": m.Gen, "status": resp.Status, + "statusText": http.StatusText(resp.Status), "headers": hdr, "stream": true}) + serr := resp.Stream(ctx, &chunkWriter{s: s, ctx: ctx, gen: m.Gen, id: m.ID}) + cerr := ctx.Err() + s.mu.Lock() + _, live := s.calls[m.ID] + delete(s.calls, m.ID) + s.mu.Unlock() + cancel(nil) + switch { + case cerr != nil: + s.cancelled.Add(1) + if live { // host-side deadline; page-side ends are already settled + code := "abort" + if errors.Is(context.Cause(ctx), ErrTimeout) { + code = "timeout" + } + s.send(m.Gen, map[string]any{"t": "err", "id": m.ID, "gen": m.Gen, "code": code, "message": context.Cause(ctx).Error()}) + } + case serr != nil: + s.send(m.Gen, map[string]any{"t": "err", "id": m.ID, "gen": m.Gen, "code": "stream", "message": fmt.Sprintf("%s %s: %v", req.Method, req.Path, serr)}) + default: + s.completed.Add(1) + s.send(m.Gen, map[string]any{"t": "end", "id": m.ID, "gen": m.Gen}) + } +} + +// chunkWriter sends every Write as chunk message(s) of at most 192 KiB. +type chunkWriter struct { + s *Session + ctx context.Context + gen uint64 + id string +} + +func (w *chunkWriter) Write(p []byte) (int, error) { + const max = 192 << 10 + for off := 0; off < len(p); off += max { + if err := w.ctx.Err(); err != nil { + return off, context.Cause(w.ctx) + } + end := min(off+max, len(p)) + w.s.send(w.gen, map[string]any{"t": "chunk", "id": w.id, "gen": w.gen, "data": base64.StdEncoding.EncodeToString(p[off:end])}) + } + return len(p), nil +} + +// Close blocks new calls, invalidates the generation, cancels running +// handlers and waits (bounded) for them. It never needs the UI thread, so it +// can be called after the native loop ended and before the window is +// destroyed. Close is idempotent. +func (s *Session) Close() error { + s.mu.Lock() + if s.closed { + s.mu.Unlock() + return nil + } + s.closed = true + for id, c := range s.calls { + c.cancel(ErrClosed) + delete(s.calls, id) + } + s.mu.Unlock() + done := make(chan struct{}) + go func() { s.wg.Wait(); close(done) }() + select { + case <-done: + return nil + case <-time.After(s.opt.CloseWait): + return fmt.Errorf("bridge: handlers still running %s after close (they ignore their context)", s.opt.CloseWait) + } +} diff --git a/gui/bridge/session_test.go b/gui/bridge/session_test.go new file mode 100644 index 0000000..518d21c --- /dev/null +++ b/gui/bridge/session_test.go @@ -0,0 +1,358 @@ +package bridge + +import ( + "context" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "strings" + "sync" + "testing" + "testing/fstest" + "time" + + "yetano.dev/yetano/core/gui/assets" +) + +// fakeUI runs dispatched functions serially on one goroutine (like a UI +// thread) and decodes every Eval into a message. +type fakeUI struct { + q chan func() + msgs chan map[string]any + once sync.Once +} + +func newFakeUI() *fakeUI { + u := &fakeUI{q: make(chan func(), 256), msgs: make(chan map[string]any, 256)} + go func() { + for f := range u.q { + f() + } + }() + return u +} +func (u *fakeUI) Dispatch(f func()) { u.q <- f } +func (u *fakeUI) Eval(js string) { + const p = "window.__yetano_recv&&window.__yetano_recv(" + var m map[string]any + if err := json.Unmarshal([]byte(strings.TrimSuffix(strings.TrimPrefix(js, p), ")")), &m); err != nil { + panic(err) + } + u.msgs <- m +} +func (u *fakeUI) next(t *testing.T) map[string]any { + t.Helper() + select { + case m := <-u.msgs: + return m + case <-time.After(3 * time.Second): + t.Fatal("no message") + return nil + } +} +func (u *fakeUI) none(t *testing.T, d time.Duration) { + t.Helper() + select { + case m := <-u.msgs: + t.Fatalf("unexpected message %v", m) + case <-time.After(d): + } +} + +type harness struct { + s *Session + ui *fakeUI + started chan string + causes chan error +} + +func newHarness(t *testing.T) *harness { + res, _ := assets.NewResolver(assets.NewFSSource("t", fstest.MapFS{"a.wasm": {Data: []byte("\x00asm\x01\x00\x00\x00")}})) + r := NewRouter(res) + h := &harness{ui: newFakeUI(), started: make(chan string, 16), causes: make(chan error, 16)} + must := func(err error) { + if err != nil { + t.Fatal(err) + } + } + must(r.Handle("POST", "/rpc/add", func(_ context.Context, req *Request) (*Response, error) { + var in struct{ A, B int } + json.Unmarshal(req.Body, &in) + return JSONBytes(200, []byte(fmt.Sprintf(`{"result":%d}`, in.A+in.B))), nil + })) + must(r.Handle("POST", "/rpc/block", func(ctx context.Context, req *Request) (*Response, error) { + h.started <- string(req.Body) + <-ctx.Done() + h.causes <- context.Cause(ctx) + return nil, ctx.Err() + })) + must(r.Handle("GET", "/rpc/panic", func(context.Context, *Request) (*Response, error) { panic("boom") })) + if err := r.Handle("POST", "/rpc/add", nil); err == nil { + t.Fatal("nil/duplicate handler accepted") + } + if err := r.Handle("POST", "/rpc/add", func(context.Context, *Request) (*Response, error) { return nil, nil }); err == nil { + t.Fatal("duplicate route accepted") + } + h.s = NewSession(r, Options{CloseWait: time.Second}) + if err := r.Handle("GET", "/late", func(context.Context, *Request) (*Response, error) { return nil, nil }); err == nil { + t.Fatal("route after session start accepted") + } + h.s.Attach(h.ui) + t.Cleanup(func() { h.s.Close() }) + return h +} + +func (h *harness) post(v any) { + b, _ := json.Marshal(v) + h.s.Post(b) +} + +func (h *harness) hello(t *testing.T) uint64 { + h.post(map[string]any{"t": "hello", "v": ProtocolVersion, "nonce": "n"}) + m := h.ui.next(t) + if m["t"] != "ready" || m["nonce"] != "n" { + t.Fatalf("ready: %v", m) + } + return uint64(m["gen"].(float64)) +} + +func (h *harness) req(gen uint64, id, method, url, body string) { + var b *string + if body != "" { + e := base64.StdEncoding.EncodeToString([]byte(body)) + b = &e + } + h.post(map[string]any{"t": "req", "id": id, "gen": gen, "method": method, "url": url, "body": b}) +} + +func body(t *testing.T, m map[string]any) string { + b, err := base64.StdEncoding.DecodeString(m["body"].(string)) + if err != nil { + t.Fatal(err) + } + return string(b) +} + +func TestRoundtripAndResponses(t *testing.T) { + h := newHarness(t) + g := h.hello(t) + h.req(g, "1", "POST", "/rpc/add", `{"a":3,"b":4}`) + m := h.ui.next(t) + if m["t"] != "res" || m["id"] != "1" || m["status"].(float64) != 200 || body(t, m) != `{"result":7}` { + t.Fatalf("%v", m) + } + cases := map[string]float64{"/rpc/nope": 404, "/rpc/panic": 500, "/assets/../x": 400, "/assets/a.wasm": 200, "assets:a.wasm": 200, "//evil/x": 400, "/assets/missing": 404} + i := 10 + for u, want := range cases { + i++ + h.req(g, fmt.Sprint(i), "GET", u, "") + m := h.ui.next(t) + if m["status"].(float64) != want { + t.Errorf("%s: %v", u, m["status"]) + } + if u == "/assets/a.wasm" && m["headers"].(map[string]any)["content-type"] != "application/wasm" { + t.Errorf("wasm mime: %v", m["headers"]) + } + } + h.req(g, "h", "HEAD", "/assets/a.wasm", "") + if m := h.ui.next(t); body(t, m) != "" || m["headers"].(map[string]any)["content-length"] != "8" { + t.Errorf("HEAD: %v", m) + } + h.req(g, "m", "PUT", "/rpc/add", "") + if m := h.ui.next(t); m["status"].(float64) != 405 { + t.Errorf("405: %v", m) + } +} + +func TestProtocolVersionMismatch(t *testing.T) { + h := newHarness(t) + h.post(map[string]any{"t": "hello", "v": 99, "nonce": "x"}) + m := h.ui.next(t) + if m["t"] != "ready" || !strings.Contains(fmt.Sprint(m["error"]), "unsupported bridge protocol 99") { + t.Fatalf("%v", m) + } + if h.s.Stats().Generation != 0 { + t.Error("generation advanced on refused hello") + } +} + +func TestAbortReachesHandler(t *testing.T) { + h := newHarness(t) + g := h.hello(t) + h.req(g, "1", "POST", "/rpc/block", "x") + <-h.started + h.post(map[string]any{"t": "abort", "id": "1", "gen": g}) + if c := <-h.causes; !errors.Is(c, ErrAborted) { + t.Fatalf("cause %v", c) + } + h.ui.none(t, 100*time.Millisecond) // the page already settled the call +} + +func TestStaleGenerationCancelledAndDropped(t *testing.T) { + h := newHarness(t) + g1 := h.hello(t) + h.req(g1, "1", "POST", "/rpc/block", "old") + <-h.started + g2 := h.hello(t) // reload + if g2 != g1+1 { + t.Fatalf("gen %d -> %d", g1, g2) + } + if c := <-h.causes; !errors.Is(c, ErrStale) { + t.Fatalf("cause %v", c) + } + h.ui.none(t, 100*time.Millisecond) + // A request still tagged with the old generation is dropped. + h.req(g1, "2", "POST", "/rpc/add", `{"a":1,"b":1}`) + h.ui.none(t, 100*time.Millisecond) + if h.s.Stats().DroppedStale == 0 { + t.Error("stale request not counted") + } +} + +func TestCloseCancelsAndBlocksDelivery(t *testing.T) { + h := newHarness(t) + g := h.hello(t) + h.req(g, "1", "POST", "/rpc/block", "x") + <-h.started + if err := h.s.Close(); err != nil { + t.Fatal(err) + } + if c := <-h.causes; !errors.Is(c, ErrClosed) { + t.Fatalf("cause %v", c) + } + if err := h.s.Close(); err != nil { + t.Fatal("second close", err) + } + h.req(g, "2", "POST", "/rpc/add", `{"a":1,"b":1}`) + h.ui.none(t, 100*time.Millisecond) + if st := h.s.Stats(); st.Pending != 0 || st.DroppedClosed == 0 { + t.Errorf("%+v", st) + } +} + +func TestDuplicateIDAndBadMessages(t *testing.T) { + h := newHarness(t) + g := h.hello(t) + h.req(g, "1", "POST", "/rpc/block", "x") + <-h.started + h.req(g, "1", "POST", "/rpc/add", `{}`) + if m := h.ui.next(t); m["code"] != "protocol" { + t.Fatalf("%v", m) + } + h.s.Post(json.RawMessage(`"string"`)) + h.s.Post(json.RawMessage(`{"t":"bogus","id":"z","gen":1}`)) + if m := h.ui.next(t); m["code"] != "protocol" { + t.Fatalf("%v", m) + } + if h.s.Stats().ProtocolErrors < 3 { + t.Errorf("%+v", h.s.Stats()) + } +} + +func TestHostTimeout(t *testing.T) { + res, _ := assets.NewResolver(assets.NewFSSource("t", fstest.MapFS{})) + r := NewRouter(res) + r.Handle("GET", "/slow", func(ctx context.Context, _ *Request) (*Response, error) { <-ctx.Done(); return nil, ctx.Err() }) + s := NewSession(r, Options{MaxTimeout: 50 * time.Millisecond}) + ui := newFakeUI() + s.Attach(ui) + defer s.Close() + s.Post(json.RawMessage(`{"t":"hello","v":1,"nonce":"n"}`)) + ui.next(t) + s.Post(json.RawMessage(`{"t":"req","id":"1","gen":1,"method":"GET","url":"/slow"}`)) + if m := ui.next(t); m["t"] != "err" || m["code"] != "timeout" { + t.Fatalf("%v", m) + } +} + +func TestParseLocalURL(t *testing.T) { + p, q, err := ParseLocalURL("assets:img/a.png?x=1#f") + if err != nil || p != "/assets/img/a.png" || q.Get("x") != "1" { + t.Fatal(p, q, err) + } + if p, _, _ := ParseLocalURL("/assets/%252e"); p != "/assets/%2e" { + t.Errorf("decoded more than once: %q", p) + } + for _, bad := range []string{"https://x/y", "//x/y", "rel/path", "/a%zz"} { + if _, _, err := ParseLocalURL(bad); err == nil { + t.Errorf("%q accepted", bad) + } + } +} + +func TestInitScript(t *testing.T) { + js := InitScript(PageConfig{Selftest: true}) + if !strings.HasPrefix(js, `window.__yetano_config={"external":"reject"`) || !strings.Contains(js, "__yetano_post") { + t.Fatal(js[:120]) + } + _ = http.StatusOK +} + +func TestStreamChunksAndAbort(t *testing.T) { + res, _ := assets.NewResolver(assets.NewFSSource("t", fstest.MapFS{})) + r := NewRouter(res) + causes := make(chan error, 1) + r.Handle("GET", "/s", func(context.Context, *Request) (*Response, error) { + return &Response{Status: 200, Stream: func(ctx context.Context, w io.Writer) error { + for i := 0; ; i++ { + if _, err := fmt.Fprintf(w, "c%d", i); err != nil { + causes <- err + return err + } + if i == 2 { + // after three chunks wait for the page to abort + <-ctx.Done() + causes <- context.Cause(ctx) + return ctx.Err() + } + } + }}, nil + }) + r.Handle("GET", "/done", func(context.Context, *Request) (*Response, error) { + return &Response{Status: 201, Stream: func(_ context.Context, w io.Writer) error { + w.Write(make([]byte, 400<<10)) // split into 192 KiB chunks + return nil + }}, nil + }) + s := NewSession(r, Options{}) + ui := newFakeUI() + s.Attach(ui) + defer s.Close() + s.Post(json.RawMessage(`{"t":"hello","v":1,"nonce":"n"}`)) + ui.next(t) + + s.Post(json.RawMessage(`{"t":"req","id":"1","gen":1,"method":"GET","url":"/s"}`)) + if m := ui.next(t); m["t"] != "res" || m["stream"] != true { + t.Fatalf("head: %v", m) + } + for i := 0; i < 3; i++ { + if m := ui.next(t); m["t"] != "chunk" { + t.Fatalf("chunk %d: %v", i, m) + } + } + s.Post(json.RawMessage(`{"t":"abort","id":"1","gen":1}`)) + if c := <-causes; !errors.Is(c, ErrAborted) { + t.Fatalf("cause %v", c) + } + ui.none(t, 100*time.Millisecond) // page already ended the stream: no end/err + + s.Post(json.RawMessage(`{"t":"req","id":"2","gen":1,"method":"GET","url":"/done"}`)) + if m := ui.next(t); m["status"].(float64) != 201 { + t.Fatalf("%v", m) + } + total := 0 + for { + m := ui.next(t) + if m["t"] == "end" { + break + } + b, _ := base64.StdEncoding.DecodeString(m["data"].(string)) + total += len(b) + } + if total != 400<<10 { + t.Fatalf("streamed %d bytes", total) + } +} diff --git a/gui/doc.go b/gui/doc.go new file mode 100644 index 0000000..1ae1a47 --- /dev/null +++ b/gui/doc.go @@ -0,0 +1,23 @@ +// Package gui is the native WebView host shared by Yetano desktop +// programs: a native window with a WebView that shows embedded HTML/CSS/JS +// and routes the page's fetch/XHR to Go handlers -- without any local web +// server, port or localhost listener. +// +// The host lives in four subpackages: +// +// - [yetano.dev/yetano/core/gui/assets]: asset resolver over embed.FS, +// a directory (os.Root), a ZIP file or ZIP bytes; path rules, MIME. +// - [yetano.dev/yetano/core/gui/document]: prepares the entry HTML and +// CSS (link mode: /assets/ URLs, validated; inline mode: data: URLs). +// - [yetano.dev/yetano/core/gui/bridge]: the page script (fetch/XHR +// replacement), protocol v1 with chunked streams, Session, Router and +// ServeNative for the native resource handler. +// - [yetano.dev/yetano/core/gui/window]: the native window: macOS +// (Cocoa + WKWebView, cgo, scheme yetano://app) and Windows (Win32 + +// WebView2, pure Go, https://yetano.invalid). Other platforms return +// window.ErrUnsupported. +// +// This is a separate Go module (yetano.dev/yetano/core/gui, tags gui/vX.Y.Z) +// so the main core module stays free of cgo and WebView dependencies. See +// README.md for wiring, invariants and the platform pitfalls. +package gui diff --git a/gui/document/css.go b/gui/document/css.go new file mode 100644 index 0000000..e218838 --- /dev/null +++ b/gui/document/css.go @@ -0,0 +1,267 @@ +package document + +import ( + "context" + "fmt" + "strings" + + "yetano.dev/yetano/core/gui/assets" +) + +// rewriteCSS replaces url(...) and @import references in css. base is the +// virtual path of the stylesheet ("" for CSS embedded in the entry HTML); +// relative references resolve against it. Comments and strings outside of +// url()/@import are copied untouched. +func (p *preparer) rewriteCSS(ctx context.Context, css, base string) (string, error) { + var out strings.Builder + i := 0 + n := len(css) + for i < n { + c := css[i] + switch { + case c == '/' && i+1 < n && css[i+1] == '*': + end := strings.Index(css[i+2:], "*/") + if end < 0 { + out.WriteString(css[i:]) + return out.String(), nil + } + out.WriteString(css[i : i+2+end+2]) + i += 2 + end + 2 + case c == '"' || c == '\'': + j := skipString(css, i) + out.WriteString(css[i:j]) + i = j + case c == '\\' && i+1 < n: + out.WriteString(css[i : i+2]) + i += 2 + case hasFoldPrefix(css[i:], "url(") && isIdentBoundary(css, i): + ref, end, ok := parseURLToken(css, i+4) + if !ok { + out.WriteByte(c) + i++ + continue + } + repl, err := p.cssRef(ctx, ref, base, false) + if err != nil { + return "", err + } + if repl == strings.TrimSpace(ref) { + out.WriteString(css[i:end]) // not an asset: byte-identical + } else { + out.WriteString("url(" + quoteCSS(repl) + ")") + } + i = end + case c == '@' && hasFoldPrefix(css[i:], "@import") && i+7 < n && !isIdentChar(css[i+7]): + j := i + 7 + for j < n && isSpace(css[j]) { + j++ + } + var ref string + var end int + switch { + case j < n && (css[j] == '"' || css[j] == '\''): + end = skipString(css, j) + ref = unquoteCSS(css[j:end]) + case hasFoldPrefix(css[j:], "url("): + var ok bool + ref, end, ok = parseURLToken(css, j+4) + if !ok { + out.WriteString(css[i:j]) + i = j + continue + } + default: + out.WriteString(css[i:j]) + i = j + continue + } + repl, err := p.cssRef(ctx, ref, base, true) + if err != nil { + return "", err + } + if repl == strings.TrimSpace(ref) { + out.WriteString(css[i:end]) + } else { + out.WriteString("@import url(" + quoteCSS(repl) + ")") + } + i = end + default: + out.WriteByte(c) + i++ + } + } + return out.String(), nil +} + +// cssRef resolves one reference found in CSS. Data URLs, fragments and +// external URLs are left alone. +func (p *preparer) cssRef(ctx context.Context, ref, base string, isImport bool) (string, error) { + ref = strings.TrimSpace(ref) + var name string + var err error + switch { + case ref == "" || strings.HasPrefix(ref, "#") || strings.HasPrefix(ref, "data:"): + return ref, nil + case assets.IsAssetRef(ref): + name, err = assets.FromRef(ref) + case hasScheme(ref) || strings.HasPrefix(ref, "//") || strings.HasPrefix(ref, "/"): + return ref, nil // external or not an asset: untouched + case base != "": + pth, _ := assets.SplitRef(ref) + name, err = assets.Join(base, pth) + if err == nil && p.link { + // The WebView resolves relative URLs itself; only validate. + if _, err := p.resolve(ctx, name, base); err != nil { + return "", err + } + return ref, nil + } + default: + return ref, nil // relative ref in entry-level CSS: not an asset reference + } + if err != nil { + return "", p.fail(base, ref, err) + } + if p.link { + return p.assetDataURL(ctx, name, base) + } + if isImport { + css, err := p.loadCSS(ctx, name) + if err != nil { + return "", err + } + return dataURL("text/css;charset=utf-8", []byte(css)), nil + } + if assets.BaseMIME(mimeOf(name)) == "text/css" { + css, err := p.loadCSS(ctx, name) + if err != nil { + return "", err + } + return dataURL("text/css;charset=utf-8", []byte(css)), nil + } + return p.assetDataURL(ctx, name, base) +} + +// loadCSS loads and rewrites a stylesheet asset, detecting @import cycles. +func (p *preparer) loadCSS(ctx context.Context, name string) (string, error) { + for _, s := range p.cssStack { + if s == name { + return "", fmt.Errorf("css @import cycle: %s -> %s", strings.Join(p.cssStack, " -> "), name) + } + } + res, err := p.resolve(ctx, name, p.current()) + if err != nil { + return "", err + } + if assets.BaseMIME(res.MIME) != "text/css" { + return "", fmt.Errorf("%s: expected text/css, got %s", name, res.MIME) + } + p.cssStack = append(p.cssStack, name) + defer func() { p.cssStack = p.cssStack[:len(p.cssStack)-1] }() + return p.rewriteCSS(ctx, string(res.Bytes), name) +} + +func (p *preparer) current() string { + if len(p.cssStack) == 0 { + return p.entry + } + return p.cssStack[len(p.cssStack)-1] +} + +// parseURLToken parses the inside of url( ... ) starting at i and returns the +// reference and the index after ')'. +func parseURLToken(s string, i int) (string, int, bool) { + n := len(s) + for i < n && isSpace(s[i]) { + i++ + } + if i < n && (s[i] == '"' || s[i] == '\'') { + end := skipString(s, i) + ref := unquoteCSS(s[i:end]) + j := end + for j < n && isSpace(s[j]) { + j++ + } + if j >= n || s[j] != ')' { + return "", 0, false + } + return ref, j + 1, true + } + start := i + for i < n && s[i] != ')' { + if s[i] == '\\' { + i++ + } + i++ + } + if i >= n { + return "", 0, false + } + return strings.TrimSpace(s[start:i]), i + 1, true +} + +func skipString(s string, i int) int { + q := s[i] + j := i + 1 + for j < len(s) { + switch s[j] { + case '\\': + j += 2 + continue + case q: + return j + 1 + case '\n': + return j + } + j++ + } + return len(s) +} + +func unquoteCSS(s string) string { + if len(s) >= 2 && (s[0] == '"' || s[0] == '\'') && s[len(s)-1] == s[0] { + s = s[1 : len(s)-1] + } + // Minimal unescape: "\x" -> "x" (hex escapes are not used in asset paths). + if strings.IndexByte(s, '\\') < 0 { + return s + } + var b strings.Builder + for i := 0; i < len(s); i++ { + if s[i] == '\\' && i+1 < len(s) { + i++ + } + b.WriteByte(s[i]) + } + return b.String() +} + +func quoteCSS(s string) string { + return `"` + strings.NewReplacer(`\`, `\\`, `"`, `\"`, "\n", `\a `).Replace(s) + `"` +} + +func hasFoldPrefix(s, prefix string) bool { + return len(s) >= len(prefix) && strings.EqualFold(s[:len(prefix)], prefix) +} + +func isIdentChar(c byte) bool { + return c == '-' || c == '_' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c >= 0x80 +} + +func isIdentBoundary(s string, i int) bool { return i == 0 || !isIdentChar(s[i-1]) } + +func isSpace(c byte) bool { return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' } + +func hasScheme(ref string) bool { + for i := 0; i < len(ref); i++ { + c := ref[i] + switch { + case c == ':': + return i > 0 + case c >= 'a' && c <= 'z', c >= 'A' && c <= 'Z', i > 0 && (c >= '0' && c <= '9' || c == '+' || c == '-' || c == '.'): + default: + return false + } + } + return false +} diff --git a/gui/document/prepare.go b/gui/document/prepare.go new file mode 100644 index 0000000..fc5e911 --- /dev/null +++ b/gui/document/prepare.go @@ -0,0 +1,295 @@ +// Package document prepares HTML for display: every "/assets/..." and +// "assets:..." reference in HTML attributes,
`) + if strings.Count(out, "data:image/png;base64,") != 3 || strings.Count(out, "data:image/svg+xml;base64,") != 1 { + t.Fatal(out) + } +} + +func TestErrors(t *testing.T) { + r := resolver(testFiles) + for name, in := range map[string]string{ + "missing": ``, + "traversal": ``, + "cycle": ``, + "escape": ``, + } { + if _, err := Prepare(context.Background(), r, "index.html", []byte(in), Options{}); err == nil { + t.Errorf("%s: no error", name) + } else if !strings.Contains(err.Error(), "index.html") { + t.Errorf("%s: error does not name the document: %v", name, err) + } + } + big := `` + if _, err := Prepare(context.Background(), r, "index.html", []byte(strings.Repeat(big, 100)), Options{MaxOutput: 1000}); err == nil { + t.Error("size limit not enforced") + } +} + +func TestFragmentKeepsSemantics(t *testing.T) { + in := `` + out := prep(t, in) + if !strings.HasPrefix(out, "") { + t.Fatal(out) + } +} + +func TestLinkMode(t *testing.T) { + r := resolver(testFiles) + res, err := Prepare(context.Background(), r, "index.html", []byte(`
`), Options{Link: true}) + if err != nil { + t.Fatal(err) + } + want := `
` + if string(res.HTML) != want { + t.Fatalf("got %s\nwant %s", res.HTML, want) + } + css, err := PrepareCSS(context.Background(), r, "css/app.css", []byte(testFiles["css/app.css"]), Options{Link: true}) + if err != nil || string(css) != testFiles["css/app.css"] { + t.Fatalf("relative CSS must stay byte-identical: %s %v", css, err) + } + if _, err := Prepare(context.Background(), r, "index.html", []byte(``), Options{Link: true}); err == nil { + t.Error("missing asset not reported in link mode") + } + if _, err := PrepareCSS(context.Background(), r, "css/escape.css", []byte(testFiles["css/escape.css"]), Options{Link: true}); err == nil { + t.Error("root escape not reported in link mode") + } +} diff --git a/gui/go.mod b/gui/go.mod new file mode 100644 index 0000000..9786ab5 --- /dev/null +++ b/gui/go.mod @@ -0,0 +1,11 @@ +module yetano.dev/yetano/core/gui + +go 1.26.0 + +require ( + github.com/jchv/go-webview2 v0.0.0-20260205173254-56598839c808 + golang.org/x/net v0.59.0 + golang.org/x/sys v0.48.0 +) + +require github.com/jchv/go-winloader v0.0.0-20250406163304-c1995be93bd1 // indirect diff --git a/gui/go.sum b/gui/go.sum new file mode 100644 index 0000000..c8bfa50 --- /dev/null +++ b/gui/go.sum @@ -0,0 +1,10 @@ +github.com/jchv/go-webview2 v0.0.0-20260205173254-56598839c808 h1:ftnsTqIUH57XQEF+PnXX9++nlHCzdkuB5zbWyMMruZo= +github.com/jchv/go-webview2 v0.0.0-20260205173254-56598839c808/go.mod h1:rWifBlzkgrvd7zUqlfq91sWt3473OikgnglnIILx/Jo= +github.com/jchv/go-winloader v0.0.0-20250406163304-c1995be93bd1 h1:njuLRcjAuMKr7kI3D85AXWkw6/+v9PwtV6M6o11sWHQ= +github.com/jchv/go-winloader v0.0.0-20250406163304-c1995be93bd1/go.mod h1:alcuEEnZsY1WQsagKhZDsoPCRoOijYqhZvPwLG0kzVs= +golang.org/x/net v0.59.0 h1:5zfYln+w5XCxwrnMMJPufRgNoXEaGxl0wo5GqPXyues= +golang.org/x/net v0.59.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg= +golang.org/x/sys v0.0.0-20200810151505-1b9f1253b3ed/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210218145245-beda7e5e158e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo= +golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= diff --git a/gui/window/darwin.h b/gui/window/darwin.h new file mode 100644 index 0000000..4a599b6 --- /dev/null +++ b/gui/window/darwin.h @@ -0,0 +1,21 @@ +#ifndef YETANO_WINDOW_DARWIN_H +#define YETANO_WINDOW_DARWIN_H +#include + +void *yt_create(uintptr_t goHandle, const char *title, int width, int height, int debug, const char *scheme); +void yt_add_script(void *h, const char *js); +void yt_navigate(void *h, const char *url); +void yt_eval(void *h, const char *js); +void yt_dispatch(uintptr_t fn); +void yt_run(void); +void yt_stop(void); +void yt_destroy(void *h); +void yt_task_respond(void *h, long tid, int status, const char *headersJSON, const char *url); +void yt_task_data(void *h, long tid, const void *data, int n); +void yt_task_finish(void *h, long tid, const char *err); +void yt_snapshot(void *h, const char *path); +void yt_set_appearance(void *h, int mode); +void yt_accent_color(char *buf, int n); +void yt_set_app_icon(const void *png, int n); + +#endif diff --git a/gui/window/darwin.m b/gui/window/darwin.m new file mode 100644 index 0000000..f9ac7b3 --- /dev/null +++ b/gui/window/darwin.m @@ -0,0 +1,282 @@ +//go:build darwin + +// Native macOS host: NSWindow + WKWebView with +// - a WKScriptMessageHandler "yetano" (page -> Go messages), +// - document-start WKUserScripts, +// - a WKURLSchemeHandler for the "yetano" scheme (native resources, streaming), +// - main-queue dispatch for Go closures. +// Everything here runs on the main thread; calls from Go goroutines are +// marshalled with dispatch_async onto the main queue. +#import +#import +#include "darwin.h" + +// Implemented in Go (window_darwin.go). +extern void ytGoMessage(uintptr_t h, const char *msg); +extern void ytGoSchemeStart(uintptr_t h, long id, const char *method, const char *url, const char *headers, const void *body, int n); +extern void ytGoSchemeStop(uintptr_t h, long id); +extern void ytGoDispatch(uintptr_t fn); +extern void ytGoClosed(uintptr_t h); +extern void ytGoSnapshotDone(uintptr_t h, const char *err); + +@interface YTHost : NSObject +@property (assign) uintptr_t goHandle; +@property (strong) NSWindow *window; +@property (strong) WKWebView *webview; +@property (strong) NSMutableDictionary> *tasks; +@property (assign) long nextTask; +@property (assign) BOOL closed; +@end + +@implementation YTHost + +- (void)userContentController:(WKUserContentController *)ucc didReceiveScriptMessage:(WKScriptMessage *)message { + if (self.closed || ![message.body isKindOfClass:[NSString class]]) return; + ytGoMessage(self.goHandle, [(NSString *)message.body UTF8String]); +} + +- (void)webView:(WKWebView *)webView startURLSchemeTask:(id)task { + long tid = ++self.nextTask; + self.tasks[@(tid)] = task; + NSURLRequest *req = task.request; + NSData *body = req.HTTPBody; + if (!body && req.HTTPBodyStream) { + NSMutableData *buf = [NSMutableData data]; + NSInputStream *s = req.HTTPBodyStream; + [s open]; + uint8_t chunk[65536]; + NSInteger n; + while ((n = [s read:chunk maxLength:sizeof chunk]) > 0) [buf appendBytes:chunk length:(NSUInteger)n]; + [s close]; + body = buf; + } + NSDictionary *hdr = req.allHTTPHeaderFields ?: @{}; + NSData *hj = [NSJSONSerialization dataWithJSONObject:hdr options:0 error:nil]; + NSString *hs = [[NSString alloc] initWithData:hj encoding:NSUTF8StringEncoding]; + ytGoSchemeStart(self.goHandle, tid, [(req.HTTPMethod ?: @"GET") UTF8String], [req.URL.absoluteString UTF8String], + [hs UTF8String], body.bytes, (int)body.length); +} + +- (void)webView:(WKWebView *)webView stopURLSchemeTask:(id)task { + NSNumber *key = nil; + for (NSNumber *k in self.tasks) { + if (self.tasks[k] == task) { key = k; break; } + } + if (!key) return; + [self.tasks removeObjectForKey:key]; + ytGoSchemeStop(self.goHandle, key.longValue); +} + +- (void)windowWillClose:(NSNotification *)n { + if (self.closed) return; + ytGoClosed(self.goHandle); + yt_stop(); +} + +@end + +static NSString *str(const char *s) { return [NSString stringWithUTF8String:s ?: ""]; } + +static void ensureApp(void) { + static BOOL done = NO; + if (done) return; + done = YES; + [NSApplication sharedApplication]; + [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular]; + // Minimal menu: Quit and the Edit actions (copy/paste need them). + NSMenu *bar = [NSMenu new]; + NSMenuItem *appItem = [NSMenuItem new]; + [bar addItem:appItem]; + NSMenu *appMenu = [NSMenu new]; + [appMenu addItemWithTitle:@"Quit" action:@selector(terminate:) keyEquivalent:@"q"]; + appItem.submenu = appMenu; + NSMenuItem *editItem = [NSMenuItem new]; + [bar addItem:editItem]; + NSMenu *edit = [[NSMenu alloc] initWithTitle:@"Edit"]; + [edit addItemWithTitle:@"Cut" action:@selector(cut:) keyEquivalent:@"x"]; + [edit addItemWithTitle:@"Copy" action:@selector(copy:) keyEquivalent:@"c"]; + [edit addItemWithTitle:@"Paste" action:@selector(paste:) keyEquivalent:@"v"]; + [edit addItemWithTitle:@"Select All" action:@selector(selectAll:) keyEquivalent:@"a"]; + editItem.submenu = edit; + NSApp.mainMenu = bar; + [NSApp finishLaunching]; +} + +void *yt_create(uintptr_t goHandle, const char *title, int width, int height, int debug, const char *scheme) { + @autoreleasepool { + ensureApp(); + YTHost *host = [YTHost new]; + host.goHandle = goHandle; + host.tasks = [NSMutableDictionary dictionary]; + + WKWebViewConfiguration *cfg = [WKWebViewConfiguration new]; + [cfg.userContentController addScriptMessageHandler:host name:@"yetano"]; + if (scheme && scheme[0]) [cfg setURLSchemeHandler:host forURLScheme:str(scheme)]; + if (debug) [cfg.preferences setValue:@YES forKey:@"developerExtrasEnabled"]; + + NSRect frame = NSMakeRect(0, 0, width, height); + host.webview = [[WKWebView alloc] initWithFrame:frame configuration:cfg]; + if (@available(macOS 13.3, *)) { if (debug) host.webview.inspectable = YES; } + + host.window = [[NSWindow alloc] initWithContentRect:frame + styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | + NSWindowStyleMaskMiniaturizable | NSWindowStyleMaskResizable + backing:NSBackingStoreBuffered + defer:NO]; + host.window.releasedWhenClosed = NO; + host.window.title = str(title); + host.window.contentView = host.webview; + host.window.delegate = host; + [host.window center]; + [host.window makeKeyAndOrderFront:nil]; + [NSApp activateIgnoringOtherApps:YES]; + return (__bridge_retained void *)host; + } +} + +void yt_add_script(void *h, const char *js) { + YTHost *host = (__bridge YTHost *)h; + WKUserScript *s = [[WKUserScript alloc] initWithSource:str(js) + injectionTime:WKUserScriptInjectionTimeAtDocumentStart + forMainFrameOnly:YES]; + [host.webview.configuration.userContentController addUserScript:s]; +} + +void yt_navigate(void *h, const char *url) { + YTHost *host = (__bridge YTHost *)h; + [host.webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str(url)]]]; +} + +void yt_eval(void *h, const char *js) { + YTHost *host = (__bridge YTHost *)h; + if (host.closed) return; + [host.webview evaluateJavaScript:str(js) completionHandler:nil]; +} + +static void runGo(void *fn) { ytGoDispatch((uintptr_t)fn); } + +void yt_dispatch(uintptr_t fn) { dispatch_async_f(dispatch_get_main_queue(), (void *)fn, runGo); } + +void yt_run(void) { + @autoreleasepool { [NSApp run]; } +} + +void yt_stop(void) { + [NSApp stop:nil]; + // stop: takes effect after the next event; post one. + NSEvent *e = [NSEvent otherEventWithType:NSEventTypeApplicationDefined location:NSZeroPoint modifierFlags:0 + timestamp:0 windowNumber:0 context:nil subtype:0 data1:0 data2:0]; + [NSApp postEvent:e atStart:YES]; +} + +void yt_destroy(void *h) { + YTHost *host = (__bridge_transfer YTHost *)h; // balances __bridge_retained + host.closed = YES; + for (NSNumber *k in host.tasks.allKeys) { + // Remaining tasks are failed so WebKit does not wait forever. + id t = host.tasks[k]; + @try { [t didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCancelled userInfo:nil]]; } @catch (id e) {} + } + [host.tasks removeAllObjects]; + [host.webview stopLoading]; + [host.webview.configuration.userContentController removeScriptMessageHandlerForName:@"yetano"]; + [host.webview.configuration.userContentController removeAllUserScripts]; + host.window.delegate = nil; + [host.window orderOut:nil]; + host.window.contentView = nil; + [host.window close]; + host.webview = nil; + host.window = nil; +} + +// --- scheme task responses (called from Go, any thread) -------------------- + +static void onTask(void *h, long tid, void (^block)(id)) { + YTHost *host = (__bridge YTHost *)h; + dispatch_async(dispatch_get_main_queue(), ^{ + id t = host.tasks[@(tid)]; + if (!t || host.closed) return; // stopped meanwhile: must not be touched + block(t); + }); +} + +void yt_task_respond(void *h, long tid, int status, const char *headersJSON, const char *url) { + NSData *hj = [str(headersJSON) dataUsingEncoding:NSUTF8StringEncoding]; + NSDictionary *hdr = [NSJSONSerialization JSONObjectWithData:hj options:0 error:nil]; + NSURL *u = [NSURL URLWithString:str(url)]; + onTask(h, tid, ^(id t) { + NSHTTPURLResponse *r = [[NSHTTPURLResponse alloc] initWithURL:u statusCode:status HTTPVersion:@"HTTP/1.1" headerFields:hdr]; + [t didReceiveResponse:r]; + }); +} + +void yt_task_data(void *h, long tid, const void *data, int n) { + NSData *d = [NSData dataWithBytes:data length:(NSUInteger)n]; // copied before returning to Go + onTask(h, tid, ^(id t) { [t didReceiveData:d]; }); +} + +void yt_task_finish(void *h, long tid, const char *err) { + NSString *e = err ? str(err) : nil; + YTHost *host = (__bridge YTHost *)h; + onTask(h, tid, ^(id t) { + if (e) { + [t didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorUnknown + userInfo:@{NSLocalizedDescriptionKey : e}]]; + } else { + [t didFinish]; + } + [host.tasks removeObjectForKey:@(tid)]; + }); +} + +// --- snapshot: render the web view into a PNG file (main thread) --------- + +void yt_snapshot(void *h, const char *path) { + YTHost *host = (__bridge YTHost *)h; + NSString *p = str(path); + uintptr_t gh = host.goHandle; + [host.webview takeSnapshotWithConfiguration:nil completionHandler:^(NSImage *img, NSError *error) { + if (!img) { ytGoSnapshotDone(gh, [(error.localizedDescription ?: @"snapshot failed") UTF8String]); return; } + CGImageRef cg = [img CGImageForProposedRect:NULL context:nil hints:nil]; + NSBitmapImageRep *rep = [[NSBitmapImageRep alloc] initWithCGImage:cg]; + NSData *png = [rep representationUsingType:NSBitmapImageFileTypePNG properties:@{}]; + NSError *werr = nil; + if (![png writeToFile:p options:NSDataWritingAtomic error:&werr]) { + ytGoSnapshotDone(gh, [werr.localizedDescription UTF8String]); + return; + } + ytGoSnapshotDone(gh, NULL); + }]; +} + +// --- appearance ------------------------------------------------------------ + +// yt_set_appearance: 0 = follow the system, 1 = light, 2 = dark. Changes the +// title bar and what the page sees as prefers-color-scheme. +void yt_set_appearance(void *h, int mode) { + YTHost *host = (__bridge YTHost *)h; + NSAppearance *a = nil; + if (mode == 1) a = [NSAppearance appearanceNamed:NSAppearanceNameAqua]; + if (mode == 2) a = [NSAppearance appearanceNamed:NSAppearanceNameDarkAqua]; + host.window.appearance = a; +} + +// yt_accent_color writes the user's accent color as "#RRGGBB" into buf. +void yt_accent_color(char *buf, int n) { + @autoreleasepool { + NSColor *c = [[NSColor controlAccentColor] colorUsingColorSpace:[NSColorSpace sRGBColorSpace]]; + if (!c) { buf[0] = 0; return; } + snprintf(buf, (size_t)n, "#%02X%02X%02X", (int)lround(c.redComponent * 255), (int)lround(c.greenComponent * 255), (int)lround(c.blueComponent * 255)); + } +} + +// yt_set_app_icon sets the Dock icon from PNG bytes, unless the process runs +// from an app bundle (which brings its own icon). +void yt_set_app_icon(const void *png, int n) { + @autoreleasepool { + ensureApp(); + if ([[NSBundle mainBundle] bundleIdentifier] != nil) return; + NSImage *img = [[NSImage alloc] initWithData:[NSData dataWithBytes:png length:(NSUInteger)n]]; + if (img) NSApp.applicationIconImage = img; + } +} diff --git a/gui/window/window.go b/gui/window/window.go new file mode 100644 index 0000000..77a1f3f --- /dev/null +++ b/gui/window/window.go @@ -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() + } +} diff --git a/gui/window/window_darwin.go b/gui/window/window_darwin.go new file mode 100644 index 0000000..e7547f3 --- /dev/null +++ b/gui/window/window_darwin.go @@ -0,0 +1,283 @@ +//go:build darwin && cgo + +package window + +/* +#cgo CFLAGS: -x objective-c -fobjc-arc +#cgo LDFLAGS: -framework Cocoa -framework WebKit +#include +#include "darwin.h" +*/ +import "C" + +import ( + "context" + "encoding/json" + "net/http" + "runtime" + "runtime/cgo" + "sync" + "unsafe" +) + +// Cocoa requires the UI on the main thread: keep the main goroutine there. +func init() { runtime.LockOSThread() } + +// Scheme and host of the app origin on macOS. WKURLSchemeHandler cannot +// take over http/https, so the app gets its own scheme. +const darwinScheme = "yetano" + +type darwinBackend struct { + h unsafe.Pointer // retained YTHost + handle cgo.Handle // -> *darwinBackend, given to ObjC + opt Options + tasks taskTable + mu sync.RWMutex // guards h against Destroy while a goroutine calls into ObjC + + snapDone func(error) +} + +// with runs f with the live host pointer, or not at all after Destroy. +func (b *darwinBackend) with(f func(h unsafe.Pointer)) bool { + b.mu.RLock() + defer b.mu.RUnlock() + if b.h == nil { + return false + } + f(b.h) + return true +} + +func newBackend(opt Options) (backend, string, string, error) { + b := &darwinBackend{opt: opt} + b.handle = cgo.NewHandle(b) + title := C.CString(opt.Title) + defer C.free(unsafe.Pointer(title)) + scheme := C.CString("") + if opt.Resource != nil { + C.free(unsafe.Pointer(scheme)) + scheme = C.CString(darwinScheme) + } + defer C.free(unsafe.Pointer(scheme)) + debug := 0 + if opt.Debug { + debug = 1 + } + b.h = C.yt_create(C.uintptr_t(b.handle), title, C.int(opt.Width), C.int(opt.Height), C.int(debug), scheme) + if b.h == nil { + b.handle.Delete() + return nil, "", "", errUnavailable("WKWebView could not be created") + } + b.Init(postShimDarwin) + return b, "cocoa/WKWebView", darwinScheme + "://app", nil +} + +type errUnavailable string + +func (e errUnavailable) Error() string { return "window: " + string(e) } + +func cstr(s string) *C.char { return C.CString(s) } + +func (b *darwinBackend) Init(js string) { + c := cstr(js) + defer C.free(unsafe.Pointer(c)) + C.yt_add_script(b.h, c) +} + +func (b *darwinBackend) Navigate(url string) { + c := cstr(url) + defer C.free(unsafe.Pointer(c)) + C.yt_navigate(b.h, c) +} + +func (b *darwinBackend) Eval(js string) { + c := cstr(js) + defer C.free(unsafe.Pointer(c)) + C.yt_eval(b.h, c) +} + +func (b *darwinBackend) Run() { C.yt_run() } +func (b *darwinBackend) Terminate() { C.yt_stop() } + +func (b *darwinBackend) Dispatch(f func()) { + C.yt_dispatch(C.uintptr_t(cgo.NewHandle(f))) +} + +func (b *darwinBackend) Destroy() { + b.tasks.cancelAll() + b.mu.Lock() + h := b.h + b.h = nil + b.mu.Unlock() + C.yt_destroy(h) + // The handle stays valid: ObjC may still deliver an already queued + // message; the callbacks check b.h. +} + +//export ytGoDispatch +func ytGoDispatch(fn C.uintptr_t) { + h := cgo.Handle(fn) + f := h.Value().(func()) + h.Delete() + f() +} + +//export ytGoMessage +func ytGoMessage(h C.uintptr_t, msg *C.char) { + b := cgo.Handle(h).Value().(*darwinBackend) + if b.opt.OnMessage != nil && b.with(func(unsafe.Pointer) {}) { + b.opt.OnMessage(C.GoString(msg)) + } +} + +// Snapshot renders the page into a PNG file; done runs on the UI thread. +func (b *darwinBackend) Snapshot(path string, done func(error)) { + b.mu.Lock() + b.snapDone = done + b.mu.Unlock() + c := cstr(path) + defer C.free(unsafe.Pointer(c)) + b.with(func(h unsafe.Pointer) { C.yt_snapshot(h, c) }) +} + +// SetAppearance: "light", "dark", or anything else to follow the system. +func (b *darwinBackend) SetAppearance(mode string) { + m := 0 + switch mode { + case "light": + m = 1 + case "dark": + m = 2 + } + b.with(func(h unsafe.Pointer) { C.yt_set_appearance(h, C.int(m)) }) +} + +func setAppIcon(png []byte) { + if len(png) > 0 { + C.yt_set_app_icon(unsafe.Pointer(&png[0]), C.int(len(png))) + } +} + +func accentColor() string { + var buf [16]C.char + C.yt_accent_color(&buf[0], C.int(len(buf))) + return C.GoString(&buf[0]) +} + +//export ytGoSnapshotDone +func ytGoSnapshotDone(h C.uintptr_t, err *C.char) { + b := cgo.Handle(h).Value().(*darwinBackend) + b.mu.Lock() + done := b.snapDone + b.snapDone = nil + b.mu.Unlock() + if done == nil { + return + } + if err != nil { + done(errUnavailable("snapshot: " + C.GoString(err))) + return + } + done(nil) +} + +//export ytGoClosed +func ytGoClosed(h C.uintptr_t) {} + +//export ytGoSchemeStart +func ytGoSchemeStart(h C.uintptr_t, id C.long, method, url, headers *C.char, body unsafe.Pointer, n C.int) { + b := cgo.Handle(h).Value().(*darwinBackend) + req := &ResourceRequest{Method: C.GoString(method), URL: C.GoString(url), Header: http.Header{}} + var hm map[string]string + _ = json.Unmarshal([]byte(C.GoString(headers)), &hm) + for k, v := range hm { + req.Header.Set(k, v) + } + if n > 0 { + req.Body = C.GoBytes(body, n) + } + ctx, cancel := context.WithCancel(context.Background()) + tid := int64(id) + b.tasks.add(tid, cancel) + w := &darwinTask{b: b, id: tid, url: req.URL} + go func() { + defer b.tasks.cancel(tid) + b.opt.Resource(ctx, req, w) + w.Close(nil) + }() +} + +//export ytGoSchemeStop +func ytGoSchemeStop(h C.uintptr_t, id C.long) { + cgo.Handle(h).Value().(*darwinBackend).tasks.cancel(int64(id)) +} + +// darwinTask forwards a response to the WKURLSchemeTask. The ObjC side drops +// calls for tasks that WebKit already stopped. +type darwinTask struct { + b *darwinBackend + id int64 + url string + mu sync.Mutex + responded bool + done bool +} + +func (t *darwinTask) Respond(status int, header http.Header) { + t.mu.Lock() + defer t.mu.Unlock() + if t.responded || t.done { + return + } + t.responded = true + hm := map[string]string{} + for k, v := range header { + if len(v) > 0 { + hm[k] = v[0] + } + } + hj, _ := json.Marshal(hm) + ch, cu := cstr(string(hj)), cstr(t.url) + defer C.free(unsafe.Pointer(ch)) + defer C.free(unsafe.Pointer(cu)) + t.b.with(func(h unsafe.Pointer) { C.yt_task_respond(h, C.long(t.id), C.int(status), ch, cu) }) +} + +func (t *darwinTask) Write(p []byte) (int, error) { + t.mu.Lock() + defer t.mu.Unlock() + if t.done { + return 0, context.Canceled + } + if !t.responded { + t.mu.Unlock() + t.Respond(http.StatusOK, nil) + t.mu.Lock() + } + if len(p) > 0 && !t.b.with(func(h unsafe.Pointer) { C.yt_task_data(h, C.long(t.id), unsafe.Pointer(&p[0]), C.int(len(p))) }) { + return 0, context.Canceled + } + return len(p), nil +} + +func (t *darwinTask) Close(err error) { + t.mu.Lock() + if t.done { + t.mu.Unlock() + return + } + responded := t.responded + t.mu.Unlock() + if !responded && err == nil { + t.Respond(http.StatusNoContent, nil) + } + t.mu.Lock() + defer t.mu.Unlock() + t.done = true + var ce *C.char + if err != nil { + ce = cstr(err.Error()) + defer C.free(unsafe.Pointer(ce)) + } + t.b.with(func(h unsafe.Pointer) { C.yt_task_finish(h, C.long(t.id), ce) }) +} diff --git a/gui/window/window_other.go b/gui/window/window_other.go new file mode 100644 index 0000000..fb0743c --- /dev/null +++ b/gui/window/window_other.go @@ -0,0 +1,9 @@ +//go:build !(darwin && cgo) && !windows + +package window + +func newBackend(Options) (backend, string, string, error) { return nil, "", "", ErrUnsupported } + +func accentColor() string { return "" } + +func setAppIcon([]byte) {} diff --git a/gui/window/window_test.go b/gui/window/window_test.go new file mode 100644 index 0000000..a7da3b8 --- /dev/null +++ b/gui/window/window_test.go @@ -0,0 +1,75 @@ +package window + +import ( + "context" + "testing" +) + +// fakeBackend queues dispatched functions like a real UI loop (run them +// with drain) and records calls. +type fakeBackend struct { + queue []func() + evals []string + destroyed int +} + +func (f *fakeBackend) drain() { + for len(f.queue) > 0 { + g := f.queue[0] + f.queue = f.queue[1:] + g() + } +} + +func (f *fakeBackend) Init(string) {} +func (f *fakeBackend) Navigate(string) {} +func (f *fakeBackend) Run() {} +func (f *fakeBackend) Terminate() {} +func (f *fakeBackend) Dispatch(g func()) { f.queue = append(f.queue, g) } +func (f *fakeBackend) Eval(js string) { f.evals = append(f.evals, js) } +func (f *fakeBackend) Destroy() { f.destroyed++ } + +func TestDispatchAfterDestroyIsDropped(t *testing.T) { + fb := &fakeBackend{} + w := &Window{b: fb, alive: true, name: "fake"} + ran := 0 + w.Dispatch(func() { ran++; w.Eval("a") }) + w.Dispatch(func() { ran++ }) + fb.drain() + w.Dispatch(func() { ran++ }) // queued, Destroy comes first + w.Destroy() + fb.drain() + w.Destroy() // idempotent + w.Dispatch(func() { ran++ }) + w.Eval("b") + if ran != 2 || len(fb.evals) != 1 || fb.destroyed != 1 || w.DroppedDispatches() != 1 || len(fb.queue) != 0 { + t.Fatalf("ran=%d evals=%v destroyed=%d dropped=%d", ran, fb.evals, fb.destroyed, w.DroppedDispatches()) + } +} + +func TestSnapshotUnsupported(t *testing.T) { + w := &Window{b: &fakeBackend{}, alive: true, name: "fake"} + var got error + w.Snapshot("x.png", func(err error) { got = err }) + if got == nil { + t.Fatal("expected an error from a backend without snapshot support") + } + w.SetAppearance("dark") // no-op without support, must not panic +} + +func TestTaskTableCancel(t *testing.T) { + var tt taskTable + ctx1, c1 := context.WithCancel(context.Background()) + ctx2, c2 := context.WithCancel(context.Background()) + tt.add(1, c1) + tt.add(2, c2) + tt.cancel(1) + if ctx1.Err() == nil || ctx2.Err() != nil { + t.Fatal("cancel(1) must cancel only task 1") + } + tt.cancel(1) // unknown id: no-op + tt.cancelAll() + if ctx2.Err() == nil { + t.Fatal("cancelAll must cancel the remaining tasks") + } +} diff --git a/gui/window/window_windows.go b/gui/window/window_windows.go new file mode 100644 index 0000000..a3547a4 --- /dev/null +++ b/gui/window/window_windows.go @@ -0,0 +1,705 @@ +//go:build windows + +package window + +import ( + "context" + "errors" + "fmt" + "net/http" + "runtime" + "sort" + "strings" + "sync" + "sync/atomic" + "syscall" + "time" + "unsafe" + + "github.com/jchv/go-webview2/pkg/edge" + "golang.org/x/sys/windows" + "golang.org/x/sys/windows/registry" +) + +// WebView2 needs every call on the thread that created it (STA, message +// loop). Lock the main goroutine to the main thread before main runs. +func init() { runtime.LockOSThread() } + +// App origin on Windows. WebView2's WebResourceRequested intercepts this +// https URL before any network access; ".invalid" can never resolve, so a +// missed interception cannot reach a real host. Custom schemes would need +// ICoreWebView2EnvironmentOptions4, which pkg/edge does not pass. +const windowsOrigin = "https://yetano.invalid" + +var ( + user32 = windows.NewLazySystemDLL("user32.dll") + kernel32 = windows.NewLazySystemDLL("kernel32.dll") + pRegisterClassEx = user32.NewProc("RegisterClassExW") + pCreateWindowEx = user32.NewProc("CreateWindowExW") + pDefWindowProc = user32.NewProc("DefWindowProcW") + pShowWindow = user32.NewProc("ShowWindow") + pUpdateWindow = user32.NewProc("UpdateWindow") + pSetFocus = user32.NewProc("SetFocus") + pGetMessage = user32.NewProc("GetMessageW") + pPeekMessage = user32.NewProc("PeekMessageW") + pTranslate = user32.NewProc("TranslateMessage") + pDispatch = user32.NewProc("DispatchMessageW") + pPostMessage = user32.NewProc("PostMessageW") + pPostQuit = user32.NewProc("PostQuitMessage") + pDestroyWindow = user32.NewProc("DestroyWindow") + pIsWindow = user32.NewProc("IsWindow") + pLoadCursor = user32.NewProc("LoadCursorW") + pLoadIcon = user32.NewProc("LoadIconW") + pGetSysMetrics = user32.NewProc("GetSystemMetrics") + pGetModuleHandle = kernel32.NewProc("GetModuleHandleW") + dwmapi = windows.NewLazySystemDLL("dwmapi.dll") + pDwmSetAttribute = dwmapi.NewProc("DwmSetWindowAttribute") + pSetWindowPos = user32.NewProc("SetWindowPos") + pGetDpiForSystem = user32.NewProc("GetDpiForSystem") +) + +func setAppIcon([]byte) {} // the icon comes from the .exe resources (RT_GROUP_ICON "APP") + +const ( + wmDestroy = 0x0002 + wmMove = 0x0003 + wmSize = 0x0005 + wmClose = 0x0010 + wmQuit = 0x0012 + wmMoving = 0x0216 + wmApp = 0x8000 + pmRemove = 0x0001 + swShow = 5 + wsOverlapp = 0x00CF0000 +) + +type wndClassEx struct { + cbSize uint32 + style uint32 + lpfnWndProc uintptr + cbClsExtra int32 + cbWndExtra int32 + hInstance uintptr + hIcon uintptr + hCursor uintptr + hbrBackground uintptr + lpszMenuName *uint16 + lpszClassName *uint16 + hIconSm uintptr +} + +type msgT struct { + hwnd uintptr + message uint32 + wParam uintptr + lParam uintptr + time uint32 + ptX int32 + ptY int32 + private uint32 +} + +var ( + classOnce sync.Once + className *uint16 + windowsMu sync.Mutex + byHWND = map[uintptr]*winBackend{} +) + +func registerClass() { + classOnce.Do(func() { + className, _ = windows.UTF16PtrFromString("YetanoWebView") + hinst, _, _ := pGetModuleHandle.Call(0) + cursor, _, _ := pLoadCursor.Call(0, 32512) // IDC_ARROW + // The executable's own icon (gui/winres: RT_GROUP_ICON "APP"), else + // the stock application icon. + appName, _ := windows.UTF16PtrFromString("APP") + icon, _, _ := pLoadIcon.Call(hinst, uintptr(unsafe.Pointer(appName))) + if icon == 0 { + icon, _, _ = pLoadIcon.Call(0, 32512) // IDI_APPLICATION + } + wc := wndClassEx{ + lpfnWndProc: windows.NewCallback(wndproc), hInstance: hinst, hCursor: cursor, + hIcon: icon, hIconSm: icon, lpszClassName: className, hbrBackground: 6, // COLOR_WINDOW+1 + } + wc.cbSize = uint32(unsafe.Sizeof(wc)) + pRegisterClassEx.Call(uintptr(unsafe.Pointer(&wc))) + }) +} + +type winBackend struct { + hwnd uintptr + chromium *edge.Chromium + opt Options + mu sync.Mutex + queue []func() + destroying bool + tasks taskTable + nextID atomic.Int64 +} + +func newBackend(opt Options) (backend, string, string, error) { + // A previous window in this process may still have teardown messages + // (including WM_QUIT) queued. pkg/edge's Embed waits for the controller + // with a GetMessage loop that gives up on WM_QUIT, so drain first. + if n := settle(200 * time.Millisecond); n > 0 && Debugf != nil { + Debugf("window: discarded %d WM_QUIT before creating a window", n) + } + registerClass() + b := &winBackend{opt: opt} + // The manifest declares per-monitor DPI awareness: sizes are physical + // pixels, so scale the requested (96-dpi) size. + if pGetDpiForSystem.Find() == nil { + if dpi, _, _ := pGetDpiForSystem.Call(); dpi > 96 { + opt.Width, opt.Height = opt.Width*int(dpi)/96, opt.Height*int(dpi)/96 + } + } + title, _ := windows.UTF16PtrFromString(opt.Title) + sw, _, _ := pGetSysMetrics.Call(0) // SM_CXSCREEN + sh, _, _ := pGetSysMetrics.Call(1) // SM_CYSCREEN + x, y := (int(sw)-opt.Width)/2, (int(sh)-opt.Height)/2 + hinst, _, _ := pGetModuleHandle.Call(0) + hwnd, _, err := pCreateWindowEx.Call(0, uintptr(unsafe.Pointer(className)), uintptr(unsafe.Pointer(title)), + wsOverlapp, uintptr(x), uintptr(y), uintptr(opt.Width), uintptr(opt.Height), 0, 0, hinst, 0) + if hwnd == 0 { + return nil, "", "", fmt.Errorf("window: CreateWindowEx: %v", err) + } + b.hwnd = hwnd + windowsMu.Lock() + byHWND[hwnd] = b + windowsMu.Unlock() + pShowWindow.Call(hwnd, swShow) + pUpdateWindow.Call(hwnd) + pSetFocus.Call(hwnd) + + c := edge.NewChromium() + c.DataPath = opt.DataPath + c.MessageCallback = func(msg string) { + if opt.OnMessage != nil { + opt.OnMessage(msg) + } + } + if opt.Resource != nil { + c.WebResourceRequestedCallback = b.onResource + } + b.chromium = c + if !c.Embed(hwnd) { + b.Destroy() + return nil, "", "", errors.New("window: WebView2 could not be created (is the Microsoft Edge WebView2 Runtime installed?)") + } + c.Resize() + if s, err := c.GetSettings(); err == nil { + _ = s.PutAreDevToolsEnabled(opt.Debug) + _ = s.PutAreDefaultContextMenusEnabled(opt.Debug) + } + if opt.Resource != nil { + c.AddWebResourceRequestedFilter(windowsOrigin+"/*", edge.COREWEBVIEW2_WEB_RESOURCE_CONTEXT_ALL) + } + b.Init(postShimWindows) + return b, "win32/WebView2", windowsOrigin, nil +} + +func wndproc(hwnd, msg, wp, lp uintptr) uintptr { + windowsMu.Lock() + b := byHWND[hwnd] + windowsMu.Unlock() + if b != nil { + switch msg { + case wmSize: + if b.chromium != nil { + b.chromium.Resize() + } + case wmMove, wmMoving: + if b.chromium != nil { + _ = b.chromium.NotifyParentWindowPositionChanged() + } + case wmApp: + b.runQueue() + return 0 + case wmClose: + pDestroyWindow.Call(hwnd) + return 0 + case wmDestroy: + b.mu.Lock() + programmatic := b.destroying + b.mu.Unlock() + if !programmatic { + pPostQuit.Call(0) // user closed the window: end Run + } + return 0 + } + } + r, _, _ := pDefWindowProc.Call(hwnd, msg, wp, lp) + return r +} + +func (b *winBackend) runQueue() { + b.mu.Lock() + q := b.queue + b.queue = nil + b.mu.Unlock() + for _, f := range q { + f() + } +} + +func (b *winBackend) Init(js string) { b.chromium.Init(js) } +func (b *winBackend) Navigate(url string) { b.chromium.Navigate(url) } +func (b *winBackend) Eval(js string) { b.chromium.Eval(js) } +func (b *winBackend) Terminate() { pPostQuit.Call(0) } + +// Dispatch posts to the window (not the thread), so closures also run while +// a modal loop (move/resize) is active. +func (b *winBackend) Dispatch(f func()) { + b.mu.Lock() + b.queue = append(b.queue, f) + b.mu.Unlock() + pPostMessage.Call(b.hwnd, wmApp, 0, 0) +} + +func (b *winBackend) Run() { + var m msgT + for { + r, _, _ := pGetMessage.Call(uintptr(unsafe.Pointer(&m)), 0, 0, 0) + if int32(r) <= 0 { + return + } + pTranslate.Call(uintptr(unsafe.Pointer(&m))) + pDispatch.Call(uintptr(unsafe.Pointer(&m))) + } +} + +// Destroy destroys the window synchronously (WebView2 is torn down with +// its parent) and pumps the remaining messages. +func (b *winBackend) Destroy() { + b.tasks.cancelAll() + b.mu.Lock() + b.destroying = true + b.mu.Unlock() + if ok, _, _ := pIsWindow.Call(b.hwnd); ok != 0 { + pDestroyWindow.Call(b.hwnd) + } + windowsMu.Lock() + delete(byHWND, b.hwnd) + windowsMu.Unlock() + if n := settle(200 * time.Millisecond); n > 0 && Debugf != nil { + Debugf("window: discarded %d WM_QUIT after destroy", n) + } +} + +// settle pumps this thread's queue for d, dispatching normal messages and +// discarding WM_QUIT. It returns the number of WM_QUIT seen. +func settle(d time.Duration) int { + quits := 0 + end := time.Now().Add(d) + var m msgT + for time.Now().Before(end) { + r, _, _ := pPeekMessage.Call(uintptr(unsafe.Pointer(&m)), 0, 0, 0, pmRemove) + if r == 0 { + time.Sleep(5 * time.Millisecond) + continue + } + if m.message == wmQuit { + quits++ + continue + } + pTranslate.Call(uintptr(unsafe.Pointer(&m))) + pDispatch.Call(uintptr(unsafe.Pointer(&m))) + } + return quits +} + +// ---- appearance --------------------------------------------------------- + +// SetAppearance switches the title bar between light and dark +// (DWMWA_USE_IMMERSIVE_DARK_MODE). "system" follows the "app mode" setting. +func (b *winBackend) SetAppearance(mode string) { + dark := mode == "dark" + if mode != "light" && mode != "dark" { + dark = systemDark() + } + var v int32 + if dark { + v = 1 + } + const dwmwaUseImmersiveDarkMode = 20 + pDwmSetAttribute.Call(b.hwnd, dwmwaUseImmersiveDarkMode, uintptr(unsafe.Pointer(&v)), 4) + // Redraw the non-client area so the change shows immediately. + const swpFlags = 0x0001 | 0x0002 | 0x0004 | 0x0010 | 0x0020 // NOSIZE|NOMOVE|NOZORDER|NOACTIVATE|FRAMECHANGED + pSetWindowPos.Call(b.hwnd, 0, 0, 0, 0, 0, swpFlags) +} + +func systemDark() bool { + k, err := registry.OpenKey(registry.CURRENT_USER, `Software\Microsoft\Windows\CurrentVersion\Themes\Personalize`, registry.QUERY_VALUE) + if err != nil { + return false + } + defer k.Close() + v, _, err := k.GetIntegerValue("AppsUseLightTheme") + return err == nil && v == 0 +} + +// accentColor reads the accent color Windows uses for window chrome +// (HKCU\Software\Microsoft\Windows\DWM\AccentColor, 0xAABBGGRR). +func accentColor() string { + k, err := registry.OpenKey(registry.CURRENT_USER, `Software\Microsoft\Windows\DWM`, registry.QUERY_VALUE) + if err != nil { + return "" + } + defer k.Close() + v, _, err := k.GetIntegerValue("AccentColor") + if err != nil { + return "" + } + return fmt.Sprintf("#%02X%02X%02X", v&0xff, v>>8&0xff, v>>16&0xff) +} + +// ---- raw COM helpers ---------------------------------------------------- + +func comCall(obj unsafe.Pointer, slot int, args ...uintptr) uintptr { + vtbl := *(*unsafe.Pointer)(obj) + fn := *(*uintptr)(unsafe.Add(vtbl, slot*int(unsafe.Sizeof(uintptr(0))))) + r, _, _ := syscall.SyscallN(fn, append([]uintptr{uintptr(obj)}, args...)...) + return r +} + +func comRelease(obj unsafe.Pointer) { + if obj != nil { + comCall(obj, 2) + } +} + +func coString(p *uint16) string { + if p == nil { + return "" + } + s := windows.UTF16PtrToString(p) + windows.CoTaskMemFree(unsafe.Pointer(p)) + return s +} + +// vtable slots, from WebView2.h +const ( + argsPutResponse = 5 + argsGetDeferral = 6 + deferralComplete = 3 + reqGetMethod = 5 + reqGetContent = 7 + reqGetHeaders = 9 + hdrGetIterator = 8 + iterGetCurrent = 3 + iterHasCurrent = 4 + iterMoveNext = 5 + envCreateResponse = 4 + streamRead = 3 +) + +// onResource runs on the UI thread for every request to windowsOrigin. +func (b *winBackend) onResource(req *edge.ICoreWebView2WebResourceRequest, args *edge.ICoreWebView2WebResourceRequestedEventArgs) { + rp, ap := unsafe.Pointer(req), unsafe.Pointer(args) + uri, _ := req.GetUri() + var method *uint16 + comCall(rp, reqGetMethod, uintptr(unsafe.Pointer(&method))) + rr := &ResourceRequest{Method: coString(method), URL: uri, Header: http.Header{}} + + var headers unsafe.Pointer + if comCall(rp, reqGetHeaders, uintptr(unsafe.Pointer(&headers))) == 0 && headers != nil { + var it unsafe.Pointer + if comCall(headers, hdrGetIterator, uintptr(unsafe.Pointer(&it))) == 0 && it != nil { + for { + var has int32 + comCall(it, iterHasCurrent, uintptr(unsafe.Pointer(&has))) + if has == 0 { + break + } + var n, v *uint16 + comCall(it, iterGetCurrent, uintptr(unsafe.Pointer(&n)), uintptr(unsafe.Pointer(&v))) + rr.Header.Add(coString(n), coString(v)) + var more int32 + comCall(it, iterMoveNext, uintptr(unsafe.Pointer(&more))) + } + comRelease(it) + } + comRelease(headers) + } + var content unsafe.Pointer + if comCall(rp, reqGetContent, uintptr(unsafe.Pointer(&content))) == 0 && content != nil { + buf := make([]byte, 64<<10) + for { + var n uint32 + hr := comCall(content, streamRead, uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf)), uintptr(unsafe.Pointer(&n))) + rr.Body = append(rr.Body, buf[:n]...) + if hr != 0 || n == 0 { + break + } + } + comRelease(content) + } + + var deferral unsafe.Pointer + comCall(ap, argsGetDeferral, uintptr(unsafe.Pointer(&deferral))) + comCall(ap, 1) // AddRef: args outlive this callback until the response is set + ctx, cancel := context.WithCancel(context.Background()) + id := b.nextID.Add(1) + b.tasks.add(id, cancel) + t := &winTask{b: b, args: ap, deferral: deferral, stream: newGoStream()} + // WebView2 has no cancel notification for intercepted requests; the + // closest signal is the page dropping the response stream. + t.stream.onDrop = func() { b.tasks.cancel(id) } + go func() { + defer b.tasks.cancel(id) + b.opt.Resource(ctx, rr, t) + t.Close(nil) + }() +} + +// winTask answers one intercepted request. Respond completes the deferral +// with a response whose body is a goStream; Write feeds that stream, so the +// page receives data as it is written. +type winTask struct { + b *winBackend + args unsafe.Pointer + deferral unsafe.Pointer + stream *goStream + mu sync.Mutex + responded bool + closed bool +} + +func (t *winTask) Respond(status int, header http.Header) { + t.mu.Lock() + if t.responded { + t.mu.Unlock() + return + } + t.responded = true + t.mu.Unlock() + var hs []string + for k, v := range header { + for _, x := range v { + hs = append(hs, k+": "+x) + } + } + sort.Strings(hs) + reason := http.StatusText(status) + t.b.Dispatch(func() { + env := unsafe.Pointer(t.b.chromium.Environment()) + r16, _ := windows.UTF16PtrFromString(reason) + h16, _ := windows.UTF16PtrFromString(strings.Join(hs, "\r\n")) + var resp unsafe.Pointer + hr := comCall(env, envCreateResponse, uintptr(t.stream.ptr()), uintptr(status), + uintptr(unsafe.Pointer(r16)), uintptr(unsafe.Pointer(h16)), uintptr(unsafe.Pointer(&resp))) + if hr == 0 && resp != nil { + comCall(t.args, argsPutResponse, uintptr(resp)) + comRelease(resp) + } else if Debugf != nil { + Debugf("window: CreateWebResourceResponse failed: 0x%08x", hr) + } + comCall(t.deferral, deferralComplete) + comRelease(t.deferral) + comRelease(t.args) + t.stream.release() // our own reference; WebView2 holds its own + }) +} + +func (t *winTask) Write(p []byte) (int, error) { + t.mu.Lock() + responded := t.responded + t.mu.Unlock() + if !responded { + t.Respond(http.StatusOK, nil) + } + return t.stream.write(p) +} + +func (t *winTask) Close(err error) { + t.mu.Lock() + if t.closed { + t.mu.Unlock() + return + } + t.closed = true + responded := t.responded + t.mu.Unlock() + if !responded { + if err != nil { + t.Respond(http.StatusBadGateway, nil) + } else { + t.Respond(http.StatusNoContent, nil) + } + } + t.stream.finish() +} + +// ---- goStream: a COM IStream whose Read blocks on Go-written chunks ------- + +type istreamVtbl struct { + QueryInterface, AddRef, Release uintptr + Read, Write, Seek, SetSize, CopyTo, Commit, Revert, Lock, Unlock uintptr + Stat, Clone uintptr +} + +type goStream struct { + vtbl *istreamVtbl // must be first: COM object layout + refs atomic.Int32 + mu sync.Mutex + cond *sync.Cond + buf []byte + eof bool + pos uint64 + pin runtime.Pinner + // onDrop runs when WebView2 released the last reference: the page no + // longer reads the body (finished or aborted). + onDrop func() +} + +var ( + streamVtbl *istreamVtbl + streamsMu sync.Mutex + liveStreams = map[uintptr]*goStream{} + iidIUnknown = windows.GUID{Data1: 0x00000000, Data2: 0x0000, Data3: 0x0000, Data4: [8]byte{0xC0, 0, 0, 0, 0, 0, 0, 0x46}} + iidSeqStrm = windows.GUID{Data1: 0x0c733a30, Data2: 0x2a1c, Data3: 0x11ce, Data4: [8]byte{0xad, 0xe5, 0x00, 0xaa, 0x00, 0x44, 0x77, 0x3d}} + iidIStream = windows.GUID{Data1: 0x0000000c, Data2: 0x0000, Data3: 0x0000, Data4: [8]byte{0xC0, 0, 0, 0, 0, 0, 0, 0x46}} +) + +const ( + sOK = 0 + sFalse = 1 + eNotImpl = 0x80004001 + eNoIface = 0x80004002 + stgInvFunc = 0x80030001 +) + +func initStreamVtbl() { + if streamVtbl != nil { + return + } + notImpl := windows.NewCallback(func(this uintptr) uintptr { return eNotImpl }) + notImpl2 := windows.NewCallback(func(this, a uintptr) uintptr { return eNotImpl }) + notImpl3 := windows.NewCallback(func(this, a, b uintptr) uintptr { return eNotImpl }) + notImpl4 := windows.NewCallback(func(this, a, b, c uintptr) uintptr { return eNotImpl }) + streamVtbl = &istreamVtbl{ + QueryInterface: windows.NewCallback(func(this uintptr, riid *windows.GUID, out *uintptr) uintptr { + if *riid == iidIUnknown || *riid == iidSeqStrm || *riid == iidIStream { + *out = this + lookupStream(this).refs.Add(1) + return sOK + } + *out = 0 + return eNoIface + }), + AddRef: windows.NewCallback(func(this uintptr) uintptr { return uintptr(lookupStream(this).refs.Add(1)) }), + Release: windows.NewCallback(func(this uintptr) uintptr { + s := lookupStream(this) + n := s.refs.Add(-1) + if n == 0 { + s.drop() + } + return uintptr(n) + }), + // WebView2 calls Read on a background thread and reads to EOF before + // the page sees any byte (measured: no incremental delivery, and + // E_PENDING fails the request). Blocking here is therefore fine, + // but it is not a streaming path. + Read: windows.NewCallback(func(this uintptr, pv *byte, cb uint32, pcbRead *uint32) uintptr { + n := lookupStream(this).read(unsafe.Slice(pv, cb)) + if pcbRead != nil { + *pcbRead = uint32(n) + } + if n == 0 { + return sFalse + } + return sOK + }), + Write: notImpl4, + Seek: windows.NewCallback(func(this uintptr, move int64, origin uint32, newPos *uint64) uintptr { + s := lookupStream(this) + if origin == 1 && move == 0 { // STREAM_SEEK_CUR, 0: tell + if newPos != nil { + s.mu.Lock() + *newPos = s.pos + s.mu.Unlock() + } + return sOK + } + return stgInvFunc + }), + SetSize: notImpl2, + CopyTo: notImpl4, + Commit: notImpl2, + Revert: notImpl, + Lock: notImpl4, + Unlock: notImpl4, + Stat: notImpl3, + Clone: notImpl2, + } +} + +func newGoStream() *goStream { + streamsMu.Lock() + initStreamVtbl() + s := &goStream{vtbl: streamVtbl} + s.cond = sync.NewCond(&s.mu) + s.refs.Store(1) // ours, released after the response was handed over + s.pin.Pin(s) + liveStreams[uintptr(unsafe.Pointer(s))] = s + streamsMu.Unlock() + return s +} + +func lookupStream(p uintptr) *goStream { + streamsMu.Lock() + defer streamsMu.Unlock() + return liveStreams[p] +} + +func (s *goStream) ptr() unsafe.Pointer { return unsafe.Pointer(s) } + +func (s *goStream) release() { + if s.refs.Add(-1) == 0 { + s.drop() + } +} + +func (s *goStream) drop() { + s.finish() + if s.onDrop != nil { + go s.onDrop() + } + streamsMu.Lock() + delete(liveStreams, uintptr(unsafe.Pointer(s))) + streamsMu.Unlock() + s.pin.Unpin() +} + +func (s *goStream) write(p []byte) (int, error) { + s.mu.Lock() + defer s.mu.Unlock() + if s.eof { + return 0, context.Canceled + } + s.buf = append(s.buf, p...) + s.cond.Broadcast() + return len(p), nil +} + +func (s *goStream) finish() { + s.mu.Lock() + s.eof = true + s.cond.Broadcast() + s.mu.Unlock() +} + +// read blocks until data or EOF; it returns what is available (at most len +// p), so chunks reach the page as soon as they are written. +func (s *goStream) read(p []byte) int { + s.mu.Lock() + defer s.mu.Unlock() + for len(s.buf) == 0 && !s.eof { + s.cond.Wait() + } + n := copy(p, s.buf) + s.buf = s.buf[n:] + s.pos += uint64(n) + return n +}