Files

319 lines
9.4 KiB
Go
Raw Permalink Normal View History

// 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
// FrameFile, if set, keeps the window's position and size across
// starts: read at New (a frame that is no longer on any screen is
// ignored), written a moment after every move or resize and at
// Destroy. A small JSON file (Frame); the program picks the path,
// e.g. in its state directory.
FrameFile string
// Set by New for the backend.
restore *Frame // the frame to open with, nil: default, centered
onFrame func(Frame) // the backend reports a moved or resized window
}
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 {
frames *frameSaver
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
}
var frames *frameSaver
if opt.FrameFile != "" {
frames = &frameSaver{path: opt.FrameFile}
if f, ok := loadFrame(opt.FrameFile); ok {
opt.restore = &f
frames.last = f
}
opt.onFrame = frames.changed
}
b, name, base, err := newBackend(opt)
if err != nil {
return nil, err
}
return &Window{b: b, alive: true, name: name, base: base, frames: frames}, 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()
w.frames.flush()
}
// 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() }
// FileDialog describes a native open or save dialog.
type FileDialog struct {
Save bool // a save dialog; otherwise open one existing file
Title string // the prompt; "" for the system's
Directory string // the folder to start in; "" for the system's choice
Name string // save: the suggested file name
Extensions []string // allowed extensions without the dot ("pdf"); empty: any file
}
// ErrDialogOpen: a file dialog of this window is already open.
var ErrDialogOpen = errors.New("window: a file dialog is already open")
// fileDialoger is implemented by backends with native file dialogs.
type fileDialoger interface {
FileDialog(d FileDialog, done func(path string, err error))
}
// ShowFileDialog shows a native open or save dialog for the window (UI
// thread; one at a time). done runs on the UI thread with the chosen
// path, or "" and a nil error when the user cancelled. A save dialog
// has asked about replacing an existing file already; nothing is read
// or written here -- that is the program's choice.
func (w *Window) ShowFileDialog(d FileDialog, done func(path string, err error)) {
f, ok := w.b.(fileDialoger)
if !ok {
done("", errors.New("window: file dialogs not supported by "+w.name))
return
}
f.FileDialog(d, done)
}
// ChooseFile shows a file dialog from any goroutine and waits for the
// user: the chosen path, or "" and nil when cancelled. ctx ending (the
// request was dropped) stops the wait, not the dialog.
func (w *Window) ChooseFile(ctx context.Context, d FileDialog) (string, error) {
type result struct {
path string
err error
}
ch := make(chan result, 1)
w.mu.Lock()
alive := w.alive
w.mu.Unlock()
if !alive {
return "", errors.New("window: destroyed")
}
w.Dispatch(func() {
w.ShowFileDialog(d, func(p string, err error) { ch <- result{p, err} })
})
select {
case r := <-ch:
return r.path, r.err
case <-ctx.Done():
return "", ctx.Err()
}
}
// 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()
}
}