From 31dbc347e87ce2e2562f8ad7ed357d4f75f82b8b Mon Sep 17 00:00:00 2001 From: Bjoern Kalkbrenner Date: Sun, 15 Nov 2026 15:19:45 +0100 Subject: [PATCH] gui/window: keep the window frame across starts, take the first click - Options.FrameFile: the window's position, size and maximized state in a small JSON file, read at New (a frame on no connected screen is ignored, the window opens centered), written shortly after every move or resize and at Destroy. macOS: NSWindow frame (the normal frame under a zoomed one), checked against NSScreen visible frames; Windows: Get/SetWindowPlacement, checked with MonitorFromRect. - macOS: the web view is a WKWebView subclass that accepts the first mouse click, so a page in an inactive window reacts to it instead of the click only activating the window (yanks' start dialog). Co-Authored-By: Claude Opus 5.5 --- TODO.md | 12 ++-- gui/README.md | 10 ++- gui/window/darwin.h | 3 +- gui/window/darwin.m | 53 +++++++++++++++- gui/window/frame.go | 116 +++++++++++++++++++++++++++++++++++ gui/window/frame_test.go | 40 ++++++++++++ gui/window/window.go | 23 ++++++- gui/window/window_darwin.go | 19 +++++- gui/window/window_windows.go | 62 ++++++++++++++++++- 9 files changed, 325 insertions(+), 13 deletions(-) create mode 100644 gui/window/frame.go create mode 100644 gui/window/frame_test.go diff --git a/TODO.md b/TODO.md index cc5f560..89b71f3 100644 --- a/TODO.md +++ b/TODO.md @@ -47,11 +47,13 @@ speculatively. `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` (macOS): the web view should accept the first mouse - click in an inactive window (a WKWebView subclass with - `acceptsFirstMouse:` YES) -- today the first click only activates - the window, so a dialog shown at start looks dead (yanks, - 2026-11-14; yanks now waits for the focus before showing it). +- [x] `core/gui` (macOS): the web view accepts the first mouse click in + an inactive window (`YTWebView`, `acceptsFirstMouse:` YES; + `gui/v0.2.0`, 2026-11-15) -- before, the first click only activated + the window, so a dialog shown at start looked dead (yanks). +- [x] `core/gui`: `window.Options.FrameFile` keeps the window's position, + size and maximized state across starts (macOS and Windows; + `gui/v0.2.0`, 2026-11-15). - [ ] `core/gui`: Linux/FreeBSD backend (WebKitGTK) -- see gui/README.md. - [x] `core/tui`: shared TUI kernel (themes, styles, Paint/Outer, ListState, text helpers) as the nested module diff --git a/gui/README.md b/gui/README.md index 5fef3af..ef13d42 100644 --- a/gui/README.md +++ b/gui/README.md @@ -38,7 +38,7 @@ the main module's `vX.Y.Z` tags do not version this one. Never move a tag. | `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`. | +| `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 @@ -70,6 +70,14 @@ 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, diff --git a/gui/window/darwin.h b/gui/window/darwin.h index 4a599b6..901d47a 100644 --- a/gui/window/darwin.h +++ b/gui/window/darwin.h @@ -2,7 +2,8 @@ #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_create(uintptr_t goHandle, const char *title, int width, int height, int debug, const char *scheme, + int hasFrame, int fx, int fy, int fw, int fh, int zoomed); 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); diff --git a/gui/window/darwin.m b/gui/window/darwin.m index f9ac7b3..e0ad01b 100644 --- a/gui/window/darwin.m +++ b/gui/window/darwin.m @@ -18,6 +18,17 @@ 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); +extern void ytGoFrame(uintptr_t h, int x, int y, int w, int hgt, int zoomed); + +// YTWebView takes the first mouse click in an inactive window: without +// it the click only activates the window, so a page (a dialog shown at +// start) looks dead until clicked twice. +@interface YTWebView : WKWebView +@end + +@implementation YTWebView +- (BOOL)acceptsFirstMouse:(NSEvent *)event { return YES; } +@end @interface YTHost : NSObject @property (assign) uintptr_t goHandle; @@ -26,6 +37,7 @@ extern void ytGoSnapshotDone(uintptr_t h, const char *err); @property (strong) NSMutableDictionary> *tasks; @property (assign) long nextTask; @property (assign) BOOL closed; +@property (assign) NSRect normalFrame; // the last frame while not zoomed @end @implementation YTHost @@ -67,7 +79,21 @@ extern void ytGoSnapshotDone(uintptr_t h, const char *err); ytGoSchemeStop(self.goHandle, key.longValue); } +// The frame is reported after every move and resize; while zoomed, the +// normal frame underneath is kept, so un-zooming returns to it. +- (void)reportFrame { + if (self.closed || !self.window) return; + BOOL zoomed = self.window.isZoomed; + if (!zoomed) self.normalFrame = self.window.frame; + NSRect f = self.normalFrame; + if (f.size.width <= 0) return; + ytGoFrame(self.goHandle, (int)f.origin.x, (int)f.origin.y, (int)f.size.width, (int)f.size.height, zoomed ? 1 : 0); +} +- (void)windowDidMove:(NSNotification *)n { [self reportFrame]; } +- (void)windowDidResize:(NSNotification *)n { [self reportFrame]; } + - (void)windowWillClose:(NSNotification *)n { + [self reportFrame]; if (self.closed) return; ytGoClosed(self.goHandle); yt_stop(); @@ -102,7 +128,19 @@ static void ensureApp(void) { [NSApp finishLaunching]; } -void *yt_create(uintptr_t goHandle, const char *title, int width, int height, int debug, const char *scheme) { +// onScreen: at least a 120 x 60 point piece of the frame (with its title +// bar) is on a connected screen -- a frame saved on a display that is +// gone is not restored off screen. +static BOOL onScreen(NSRect f) { + for (NSScreen *s in [NSScreen screens]) { + NSRect i = NSIntersectionRect(f, s.visibleFrame); + if (i.size.width >= 120 && i.size.height >= 60) return YES; + } + return NO; +} + +void *yt_create(uintptr_t goHandle, const char *title, int width, int height, int debug, const char *scheme, + int hasFrame, int fx, int fy, int fw, int fh, int zoomed) { @autoreleasepool { ensureApp(); YTHost *host = [YTHost new]; @@ -115,7 +153,7 @@ void *yt_create(uintptr_t goHandle, const char *title, int width, int height, in if (debug) [cfg.preferences setValue:@YES forKey:@"developerExtrasEnabled"]; NSRect frame = NSMakeRect(0, 0, width, height); - host.webview = [[WKWebView alloc] initWithFrame:frame configuration:cfg]; + host.webview = [[YTWebView alloc] initWithFrame:frame configuration:cfg]; if (@available(macOS 13.3, *)) { if (debug) host.webview.inspectable = YES; } host.window = [[NSWindow alloc] initWithContentRect:frame @@ -126,9 +164,17 @@ void *yt_create(uintptr_t goHandle, const char *title, int width, int height, in host.window.releasedWhenClosed = NO; host.window.title = str(title); host.window.contentView = host.webview; + NSRect saved = NSMakeRect(fx, fy, fw, fh); + BOOL restore = hasFrame && onScreen(saved); + if (restore) { + [host.window setFrame:saved display:NO]; + } else { + [host.window center]; + } + host.normalFrame = host.window.frame; host.window.delegate = host; - [host.window center]; [host.window makeKeyAndOrderFront:nil]; + if (restore && zoomed && !host.window.isZoomed) [host.window zoom:nil]; [NSApp activateIgnoringOtherApps:YES]; return (__bridge_retained void *)host; } @@ -171,6 +217,7 @@ void yt_stop(void) { void yt_destroy(void *h) { YTHost *host = (__bridge_transfer YTHost *)h; // balances __bridge_retained + [host reportFrame]; // a window ended by Terminate, not closed by the user host.closed = YES; for (NSNumber *k in host.tasks.allKeys) { // Remaining tasks are failed so WebKit does not wait forever. diff --git a/gui/window/frame.go b/gui/window/frame.go new file mode 100644 index 0000000..1040ea1 --- /dev/null +++ b/gui/window/frame.go @@ -0,0 +1,116 @@ +package window + +import ( + "encoding/json" + "os" + "path/filepath" + "sync" + "time" +) + +// Frame is a window's position and size in the platform's own screen +// coordinates (macOS: points, origin bottom left; Windows: pixels of the +// virtual screen, origin top left). It is only ever read back on the +// platform that wrote it. Maximized (macOS: zoomed) keeps the normal +// frame underneath, so un-maximizing returns to it. +type Frame struct { + X int `json:"x"` + Y int `json:"y"` + Width int `json:"width"` + Height int `json:"height"` + Maximized bool `json:"maximized,omitempty"` +} + +// minFrame is the smallest frame restored; anything smaller is a broken +// file, not a window someone made. +const minFrame = 200 + +func (f Frame) usable() bool { return f.Width >= minFrame && f.Height >= minFrame } + +// loadFrame reads a frame file written by frameSaver. A missing, +// unreadable or implausible file is no frame: the window opens with its +// default size, centered. +func loadFrame(path string) (Frame, bool) { + if path == "" { + return Frame{}, false + } + data, err := os.ReadFile(path) + if err != nil { + return Frame{}, false + } + var f Frame + if json.Unmarshal(data, &f) != nil || !f.usable() { + return Frame{}, false + } + return f, true +} + +// frameSaver writes the window's frame to its file, a moment after the +// last move or resize (a drag reports many), and once more at Destroy. +type frameSaver struct { + path string + mu sync.Mutex + last Frame + dirty bool + timer *time.Timer +} + +const frameSaveDelay = 400 * time.Millisecond + +func (s *frameSaver) changed(f Frame) { + if s == nil || !f.usable() { + return + } + s.mu.Lock() + defer s.mu.Unlock() + if f == s.last && !s.dirty { + return + } + s.last, s.dirty = f, true + if s.timer == nil { + s.timer = time.AfterFunc(frameSaveDelay, s.flush) + } else { + s.timer.Reset(frameSaveDelay) + } +} + +// flush writes a pending frame (temp file + rename, so a crash never +// leaves half a file). Errors are not fatal: the next start just opens +// with the default frame. +func (s *frameSaver) flush() { + if s == nil { + return + } + s.mu.Lock() + if s.timer != nil { + s.timer.Stop() + } + f, dirty := s.last, s.dirty + s.dirty = false + s.mu.Unlock() + if !dirty { + return + } + data, err := json.Marshal(f) + if err != nil { + return + } + if err := os.MkdirAll(filepath.Dir(s.path), 0o755); err != nil { + debugf("window: frame file: %v", err) + return + } + tmp := s.path + ".tmp" + if err := os.WriteFile(tmp, append(data, '\n'), 0o644); err != nil { + debugf("window: frame file: %v", err) + return + } + if err := os.Rename(tmp, s.path); err != nil { + debugf("window: frame file: %v", err) + } +} + +func debugf(format string, args ...any) { + if Debugf != nil { + Debugf(format, args...) + } +} diff --git a/gui/window/frame_test.go b/gui/window/frame_test.go new file mode 100644 index 0000000..c3a27b8 --- /dev/null +++ b/gui/window/frame_test.go @@ -0,0 +1,40 @@ +package window + +import ( + "os" + "path/filepath" + "testing" +) + +func TestFrameFileRoundTrip(t *testing.T) { + path := filepath.Join(t.TempDir(), "state", "window.json") + if _, ok := loadFrame(path); ok { + t.Fatal("a missing file is a frame") + } + s := &frameSaver{path: path} + s.changed(Frame{X: 10, Y: 20, Width: 300, Height: 200}) + s.changed(Frame{X: 40, Y: 50, Width: 1200, Height: 800, Maximized: true}) // the last one wins + s.flush() + f, ok := loadFrame(path) + if !ok || f != (Frame{X: 40, Y: 50, Width: 1200, Height: 800, Maximized: true}) { + t.Fatalf("loaded %+v, %v", f, ok) + } + if _, err := os.Stat(path + ".tmp"); !os.IsNotExist(err) { + t.Errorf("temp file left behind: %v", err) + } + + // Too small or broken: no frame, the window opens with its default. + for _, data := range []string{`{"x":0,"y":0,"width":50,"height":40}`, `not json`, ``} { + if err := os.WriteFile(path, []byte(data), 0o644); err != nil { + t.Fatal(err) + } + if f, ok := loadFrame(path); ok { + t.Errorf("%q loaded as %+v", data, f) + } + } + s.changed(Frame{Width: 10, Height: 10}) // ignored + s.flush() + if data, _ := os.ReadFile(path); string(data) != "" { + t.Errorf("an unusable frame was written: %q", data) + } +} diff --git a/gui/window/window.go b/gui/window/window.go index 77a1f3f..e1eec32 100644 --- a/gui/window/window.go +++ b/gui/window/window.go @@ -53,6 +53,16 @@ type Options struct { 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 { @@ -67,6 +77,7 @@ type backend interface { // Window is a guarded native WebView window. type Window struct { + frames *frameSaver mu sync.Mutex b backend alive bool @@ -92,11 +103,20 @@ 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}, nil + return &Window{b: b, alive: true, name: name, base: base, frames: frames}, nil } // Backend names the native backend. @@ -156,6 +176,7 @@ func (w *Window) Destroy() { w.alive = false w.mu.Unlock() w.b.Destroy() + w.frames.flush() } // snapshotter is implemented by backends that can render the page to PNG. diff --git a/gui/window/window_darwin.go b/gui/window/window_darwin.go index e7547f3..fd7988b 100644 --- a/gui/window/window_darwin.go +++ b/gui/window/window_darwin.go @@ -63,7 +63,16 @@ func newBackend(opt Options) (backend, string, string, error) { 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) + var has, zoomed C.int + var f Frame + if opt.restore != nil { + has, f = 1, *opt.restore + if f.Maximized { + zoomed = 1 + } + } + b.h = C.yt_create(C.uintptr_t(b.handle), title, C.int(opt.Width), C.int(opt.Height), C.int(debug), scheme, + has, C.int(f.X), C.int(f.Y), C.int(f.Width), C.int(f.Height), zoomed) if b.h == nil { b.handle.Delete() return nil, "", "", errUnavailable("WKWebView could not be created") @@ -122,6 +131,14 @@ func ytGoDispatch(fn C.uintptr_t) { f() } +//export ytGoFrame +func ytGoFrame(h C.uintptr_t, x, y, w, hgt, zoomed C.int) { + b := cgo.Handle(h).Value().(*darwinBackend) + if b.opt.onFrame != nil { + b.opt.onFrame(Frame{X: int(x), Y: int(y), Width: int(w), Height: int(hgt), Maximized: zoomed != 0}) + } +} + //export ytGoMessage func ytGoMessage(h C.uintptr_t, msg *C.char) { b := cgo.Handle(h).Value().(*darwinBackend) diff --git a/gui/window/window_windows.go b/gui/window/window_windows.go index a3547a4..9ccef66 100644 --- a/gui/window/window_windows.go +++ b/gui/window/window_windows.go @@ -56,6 +56,9 @@ var ( pDwmSetAttribute = dwmapi.NewProc("DwmSetWindowAttribute") pSetWindowPos = user32.NewProc("SetWindowPos") pGetDpiForSystem = user32.NewProc("GetDpiForSystem") + pGetPlacement = user32.NewProc("GetWindowPlacement") + pSetPlacement = user32.NewProc("SetWindowPlacement") + pMonitorFromRect = user32.NewProc("MonitorFromRect") ) func setAppIcon([]byte) {} // the icon comes from the .exe resources (RT_GROUP_ICON "APP") @@ -168,7 +171,9 @@ func newBackend(opt Options) (backend, string, string, error) { windowsMu.Lock() byHWND[hwnd] = b windowsMu.Unlock() - pShowWindow.Call(hwnd, swShow) + if f := opt.restore; f == nil || !restorePlacement(hwnd, *f) { + pShowWindow.Call(hwnd, swShow) + } pUpdateWindow.Call(hwnd) pSetFocus.Call(hwnd) @@ -209,14 +214,17 @@ func wndproc(hwnd, msg, wp, lp uintptr) uintptr { if b.chromium != nil { b.chromium.Resize() } + b.reportFrame() case wmMove, wmMoving: if b.chromium != nil { _ = b.chromium.NotifyParentWindowPositionChanged() } + b.reportFrame() case wmApp: b.runQueue() return 0 case wmClose: + b.reportFrame() pDestroyWindow.Call(hwnd) return 0 case wmDestroy: @@ -233,6 +241,57 @@ func wndproc(hwnd, msg, wp, lp uintptr) uintptr { return r } +// windowPlacement is WINDOWPLACEMENT. rcNormalPosition is the restored +// (not maximized) frame in workspace coordinates; Get and Set use the +// same ones, so a saved frame comes back where it was. +type windowPlacement struct { + length uint32 + flags uint32 + showCmd uint32 + ptMinPosition [2]int32 + ptMaxPosition [2]int32 + rcNormalPosition [4]int32 // left, top, right, bottom +} + +const ( + swShowNormal = 1 + swShowMinimized = 2 + swShowMaximized = 3 + wpfRestoreToMaximize = 0x0002 +) + +// reportFrame hands the window's normal frame and maximized state to +// Options.FrameFile's saver. +func (b *winBackend) reportFrame() { + if b.opt.onFrame == nil { + return + } + var wp windowPlacement + wp.length = uint32(unsafe.Sizeof(wp)) + if r, _, _ := pGetPlacement.Call(b.hwnd, uintptr(unsafe.Pointer(&wp))); r == 0 { + return + } + rc := wp.rcNormalPosition + maximized := wp.showCmd == swShowMaximized || (wp.showCmd == swShowMinimized && wp.flags&wpfRestoreToMaximize != 0) + b.opt.onFrame(Frame{X: int(rc[0]), Y: int(rc[1]), Width: int(rc[2] - rc[0]), Height: int(rc[3] - rc[1]), Maximized: maximized}) +} + +// restorePlacement shows the window with a saved frame, when that frame +// is still on a monitor (MONITOR_DEFAULTTONULL); false: show it as new. +func restorePlacement(hwnd uintptr, f Frame) bool { + rc := [4]int32{int32(f.X), int32(f.Y), int32(f.X + f.Width), int32(f.Y + f.Height)} + if m, _, _ := pMonitorFromRect.Call(uintptr(unsafe.Pointer(&rc)), 0); m == 0 { + return false + } + wp := windowPlacement{showCmd: swShowNormal, rcNormalPosition: rc} + if f.Maximized { + wp.showCmd = swShowMaximized + } + wp.length = uint32(unsafe.Sizeof(wp)) + r, _, _ := pSetPlacement.Call(hwnd, uintptr(unsafe.Pointer(&wp))) + return r != 0 +} + func (b *winBackend) runQueue() { b.mu.Lock() q := b.queue @@ -277,6 +336,7 @@ func (b *winBackend) Destroy() { b.destroying = true b.mu.Unlock() if ok, _, _ := pIsWindow.Call(b.hwnd); ok != 0 { + b.reportFrame() // a window ended by Terminate, not closed by the user pDestroyWindow.Call(b.hwnd) } windowsMu.Lock()