Files
core/gui/README.md
T

166 lines
8.8 KiB
Markdown
Raw Normal View History

# 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, FrameFile})`, `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).
`FrameFile` (since `gui/v0.2.0`) keeps the window's position, size and
maximized state across starts: a small JSON file the program places in
its `core/paths` state directory. It is read at `New` -- a frame that is
on no connected screen any more is ignored and the window opens
centered -- and written shortly after every move or resize and at
`Destroy`. The coordinates are the platform's own (macOS: points from
the bottom left; Windows: `WINDOWPLACEMENT`'s normal position).
## 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/<pkg>` with
`yetano.dev/yetano/core/gui/<pkg>` (`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.