diff --git a/docs/subsystems/gui-shell.md b/docs/subsystems/gui-shell.md index d736c723b..62bc7cfd3 100644 --- a/docs/subsystems/gui-shell.md +++ b/docs/subsystems/gui-shell.md @@ -27,7 +27,8 @@ three. 4. The page reads `GET /api/state` and writes through `POST` routes. Each write answers with the new state, built under `held`. 5. Closing the window hides it. On the Mac a full-screen window first leaves full screen (`closeStep`). The system's close on the panel (a title bar's X, Alt+F4, a window manager's close key) hides it as Escape does, so the tray icon opens it again; a panel lightweight mode let go, no longer `h.panel`, closes (`makePanel`, `TestPanelCloseHidesIt`). Lightweight mode lets go only of a window closed this way: one covered by another app's window, minimised, or open as magpie was hidden is still open (`windowUp`, not Wails' `IsVisible`, which is the occlusion state), and so is it for the Dock while the window is open and for a restart (#1381, `TestCoveredWindowStaysUp`). On the Mac the tray icon and a usage cell close an open panel by the same test (`windowOpen` in `togglePanelNow` and `trayCellClick`, not Wails' `ToggleWindow`), so under a window over the whole screen, such as a remote-desktop server's privacy curtain, the icon still closes the panel instead of showing it again (#1661, `TestTrayCellClickReleasedPanel`). 6. The window opens as it was last left. Its settled size and whether it was maximised are kept in `settings.Window` and `settings.WindowMaximised` (`settle`; per machine, see `KeepOwn`). A maximised window keeps the size it restores to. `makeMain` opens it at that size (`openSize`). On its first show, `placeMain` maximises it again on the Mac and Windows (on Windows once the page has come). On Linux, `makeMain` makes it maximised with `StartState`. On Windows a size larger than the screen's work area is fitted and centred (`fitRoom`), and the larger size stays kept. The window's position is not kept. -7. On the Mac, Settings › Show in Dock puts magpie in the Dock never (the default: out of the Dock, and so out of Command-Tab), while the window is open (`DockWindow`) or always (`Dock`); a full-screen window joins it whatever the setting (`inDock`, `dockOnFullscreen`). `openMain` joins before it shows the window (`setDock` runs on the main thread at once). An app activated out of the Dock (the quick panel's focus) that then joins it stays last in Command-Tab's order though it is in front, so joining to the front activates magpie by way of the Dock (`dockStep`, `activateAgain`; #1381, `TestDockStep`, `TestDockJoinLeadsCommandTab`). It does so without asking NSApp whether magpie is active: the Mac makes it the front app at once, and NSApp says so only once the main thread has taken that in, after the join on a busy Mac (#1651). +7. The page's header is the window's title bar. `plainTitlebar` sets it up once the app has started, and again on a window lightweight mode made again (`madeAgain`). On Linux it hides GTK's title bar and keeps the shadow and the resize edges; GTK 3 leaves the corners square. On the Mac the traffic lights are inset into the header (`MacTitleBarHiddenInset`). In the design of macOS 26 a window with a toolbar has larger corners than one with a plain title bar, so `insetLights` ([`titlebar_darwin.go`](../../internal/gui/titlebar_darwin.go)) takes the toolbar off, and `MagpieLights` keeps the lights and the title bar's height where the toolbar had them: after a resize, a new title, light or dark, more contrast or less transparency, and leaving full screen. A sheet, such as the folder chooser, still begins below the title bar. A first press while another app is in front still moves the window from anywhere in that title bar (`firstPress`), as AppKit moved it with the toolbar; AppKit itself now does so only in a plain title bar's top 32pt. AppKit gives a program that design from macOS 26 when the program is linked against the macOS 26 SDK or a later one and its Info.plist doesn't ask for the earlier design (`UIDesignRequiresCompatibility`); `designOf26` reads each at run time, as the SDK depends on the toolchain that built magpie. The toolbar stays in the earlier design, where it doesn't change the corners, with the lights on the right (a right-to-left language), or when the title bar isn't laid out as expected; this is decided once, when the window is set up. In full screen the title bar is AppKit's own. Windows keeps its own title bar. +8. On the Mac, Settings › Show in Dock puts magpie in the Dock never (the default: out of the Dock, and so out of Command-Tab), while the window is open (`DockWindow`) or always (`Dock`); a full-screen window joins it whatever the setting (`inDock`, `dockOnFullscreen`). `openMain` joins before it shows the window (`setDock` runs on the main thread at once). An app activated out of the Dock (the quick panel's focus) that then joins it stays last in Command-Tab's order though it is in front, so joining to the front activates magpie by way of the Dock (`dockStep`, `activateAgain`; #1381, `TestDockStep`, `TestDockJoinLeadsCommandTab`). It does so without asking NSApp whether magpie is active: the Mac makes it the front app at once, and NSApp says so only once the main thread has taken that in, after the join on a busy Mac (#1651). ## Constraints and failure behavior @@ -237,6 +238,7 @@ retry after a failed read. See `TestRecentCallBodiesOnDemand` and - A new user's Agents page (the window's first page and the panel's Agents tab) has a *Get started* card above the agents in the welcome's place (wangye1644294 on X, `guideCard` in [`app.js`](../../internal/gui/assets/app.js)). Its three steps are: add a model source; connect an agent, where the agents magpie found that can be connected are named and each is connected in one click (`agents/connect`); and, optional, a routing group, with the most harmless starter template that can be made from the user's models (`provider.Templates`, Never stuck first) added in one click through `POST /api/groups/template`. Every tick comes from the state: the models magpie serves (`served` in `/api/state`, groups left out), an agent wired, or a group that isn't automatic. None comes from the card having been seen. The card goes once the first two steps are done. Its close button saves `settings.GuideHidden` through `POST /api/settings/guide`, so the panel, the window and a reload agree, and the Settings save keeps it. See `getting-started.test.cjs`. - Every page of the window keeps to one width, at most 1200px of content centred, with a 16px gutter in a narrow window (`padding: max(16px, calc(50% - 600px))` on each `#view-…`, #860). Routing, Usage and Sessions are in that rule too (面条 on Discord), so a large screen doesn't stretch them edge to edge while the others sit in the middle; their columns follow the room they get (`byWidth`). See `page-width.test.cjs`. - The page must work in Chromium (Windows' WebView2) and WebKit (macOS, and WebKitGTK on Linux). GUI tests run in both engines. +- In the design of macOS 26 the main window has the corners of a window with a plain title bar, and its lights stay where the toolbar had them. `TestMainWindowCorners` ([`titlebar_darwin_test.go`](../../internal/gui/titlebar_darwin_test.go)) measures this in a process of its own, with package `windowshape`: after a new title and size and a new system appearance, as AppKit draws that appearance, where a first press with another app in front begins a window drag, and where a sheet begins. It runs that process as linked against the macOS 26 SDK and against macOS 15's, whatever SDK the toolchain has (`runAppKitSDK` and `stampSDK` give the copy it runs that SDK, and sign it again). In the earlier design, on an older macOS or with macOS 15's SDK, it checks that the window keeps its toolbar; `TestMainWindowRightToLeft` checks that it keeps it with the lights on the right. Both run in CI's macOS job. No test covers `UIDesignRequiresCompatibility`: AppKit reads it from an app bundle's Info.plist, LaunchServices registers each bundle that runs, and a press sent within a process run from one doesn't always begin a window drag. - On Linux the panel is frameless and the main window has a hidden title bar (`plainTitlebar`). GTK 3 asks KDE's Wayland session (KWin's decoration protocol) for a frame drawn by KWin on any window without client-side decorations, an undecorated one too, so `ownFrame` tells KWin the panel draws its own on each realize (#1283). GTK 4 builds ask for none themselves. With no KWin title bar, and with a Wayland window placed by the compositor rather than by the icon, the panel's header is its drag handle on Linux, as the window's is (`--wails-draggable` in `app.js`; `panel-drag-linux.test.cjs`); on the Mac and Windows the panel isn't dragged (#1430). - On Linux the panel is a solid window, as the main window is, and its page paints `--bg` whole (`panelOptions`, `body.linux.panel` in `app.css`). The Mac's and Windows' panels stay translucent. A see-through panel is an RGBA, app-paintable GTK window under a transparent webview, and on KDE Plasma 6 its page, painted at 93%, left a fainter copy of the old scroll position as it scrolled (Wayland and XWayland, compositing mode on or off) while the main window never did (#1803, `TestPanelSolidOnLinux`, `panel-linux-opaque.test.cjs`). Xvfb with picom on WebKitGTK 2.54 doesn't show the ghost either way, so the fix rests on the reporter's machine. - A Wayland window can't place itself, so under Hyprland and niri the compositor is asked to put the panel under the bar. Under Hyprland `placePanel` gives it a window rule at the cursor (`omarchy.PlacePanel`) and closes it on a click outside (`omarchy.ReportClicks`). The rule names the monitor under the cursor and moves the panel to x, y from that monitor's corner (`omarchy.PanelAt`): Hyprland adds the window's monitor's place to a `move`, so a position across the whole layout put the panel off a monitor not at 0,0 (#1785, `TestPanelAtMonitorOffScreenOrigin`). The cursor and the clients' places that `omarchy.ClickedOutside` compares are both across the layout. niri (`omarchy.Niri`, `NIRI_SOCKET` set) takes no rules at runtime and doesn't report the cursor. There `omarchy.NiriPanel` watches niri's event stream and moves the panel each time it opens: the window of magpie's pid titled `panelTitle`, moved with `MoveFloatingWindow` (after `MoveWindowToFloating` if it was tiled). It goes 6 px under the working area's top, centred on the x the tray host passed to `Activate(x, y)`. Wails keeps that x in its Linux tray (`trayClick`, `TestTrayClickIsWails`), and it is taken across the bar, since that's all a Wayland bar knows. With no click (`magpie panel`), or with one off the output, it goes top right. Wails' `HideOnFocusLost` closes it, since a click on another window takes niri's focus. It still opens in the middle and slides up, and a bar at the bottom or the side isn't accounted for (#1670). @@ -279,6 +281,8 @@ model, folder and search filters. See `sessions-empty-range.test.cjs`. ```sh go test -tags nogui ./internal/gui +go test -run TestMainWindow ./internal/gui +GOARCH=amd64 CGO_ENABLED=1 go test -run TestMainWindow ./internal/gui # as for an Intel Mac go test -run TestWebView2 ./internal/gui # on Windows: Wails' runtime lookup, missing and present go test -v ./internal/fonts # native discovery on each desktop OS make test-ui # every internal/gui/tests/*.test.cjs, Chromium and WebKit @@ -289,3 +293,12 @@ BROWSER=webkit node --test internal/gui/tests/click-scroll.test.cjs webkit`). Set `NODE_PATH` when Playwright is installed outside the repo. The Test workflow in CI does not run this suite, so a GUI change must run it locally and report the result. See [`tests/README.md`](../../internal/gui/tests/README.md). + +`TestMainWindowCorners` and `TestMainWindowRightToLeft` run on a Mac with a +desktop session, as CI's macOS job has, and show a few windows for some +seconds. On macOS 26 they check both designs, whatever SDK the toolchain +links against. CI builds them for arm64. Built for amd64 (under Rosetta on +Apple silicon), they check a program that names its SDK in +`LC_VERSION_MIN_MACOSX`, as go test links one for an Intel Mac. Their +presses are sent within the test's own process, and no system setting +changes. diff --git a/internal/gui/app.go b/internal/gui/app.go index 92216ed46..2a356772d 100644 --- a/internal/gui/app.go +++ b/internal/gui/app.go @@ -510,7 +510,7 @@ func Run(version string, showMain bool, link string) error { h.main.OnWindowEvent(events.Windows.WebViewNavigationCompleted, func(*application.WindowEvent) { markReady() }) } else { h.app.Event.OnApplicationEvent(events.Common.ApplicationStarted, func(*application.ApplicationEvent) { - plainTitlebar(h.main) // Linux: the page's header is the title bar + plainTitlebar(h.main) // Linux: the page's header is the title bar; the Mac: a plain one's corners nameWindow(h.panel, panelTitle) ownFrame(h.panel) // KDE: no title bar of KWin's on it (#1283) markReady() diff --git a/internal/gui/appkit_darwin_test.go b/internal/gui/appkit_darwin_test.go index 6517d5ed3..e81842533 100644 --- a/internal/gui/appkit_darwin_test.go +++ b/internal/gui/appkit_darwin_test.go @@ -3,7 +3,9 @@ package gui import ( + "bytes" "context" + "debug/macho" "errors" "fmt" "io/fs" @@ -21,6 +23,15 @@ import ( // account's home, not HOME, so CFFIXED_USER_HOME gives it a temporary home, // and the test fails when such a folder is left in the real ~/Library. func runAppKit(t *testing.T, timeout time.Duration, env []string, args ...string) ([]byte, error) { + t.Helper() + return runAppKitSDK(t, 0, timeout, env, args...) +} + +// runAppKitSDK is runAppKit with the program naming sdk (major<<16 | +// minor<<8) as the macOS SDK it was linked against, or the one it was, for +// 0. AppKit gives a program the design of the SDK it names, so a test sees +// each design whatever SDK the toolchain has. +func runAppKitSDK(t *testing.T, sdk uint32, timeout time.Duration, env []string, args ...string) ([]byte, error) { t.Helper() self, err := os.Executable() if err != nil { @@ -28,7 +39,9 @@ func runAppKit(t *testing.T, timeout time.Duration, env []string, args ...string } name := fmt.Sprintf("%s-%d", filepath.Base(self), time.Now().UnixNano()) bin := filepath.Join(t.TempDir(), name) - if err := os.Link(self, bin); err != nil { + if sdk != 0 { + stampSDK(t, self, bin, sdk) + } else if err := os.Link(self, bin); err != nil { b, err := os.ReadFile(self) if err != nil { t.Fatal(err) @@ -63,3 +76,42 @@ func runAppKit(t *testing.T, timeout time.Duration, env []string, args ...string } return out, err } + +// stampSDK writes to dst a copy of the program src that names sdk as the +// macOS SDK it was linked against, and signs it again, as an arm64 Mac runs +// only a program whose signature matches it. +func stampSDK(t *testing.T, src, dst string, sdk uint32) { + t.Helper() + b, err := os.ReadFile(src) + if err != nil { + t.Fatal(err) + } + f, err := macho.NewFile(bytes.NewReader(b)) + if err != nil { + t.Fatal(err) + } + // The load commands follow the header (32 bytes in a 64-bit program). + // The SDK is the fifth word of LC_BUILD_VERSION, or the fourth of + // LC_VERSION_MIN_MACOSX, which a program has instead when it runs on + // macOS 10.13, as go test links one for an Intel Mac. + sdkAt := map[uint32]int{0x32: 16, 0x24: 12} // LC_BUILD_VERSION, LC_VERSION_MIN_MACOSX + at, off := -1, 32 + for _, l := range f.Loads { + raw := l.Raw() + if n, ok := sdkAt[f.ByteOrder.Uint32(raw)]; ok { + at = off + n + break + } + off += len(raw) + } + if f.Magic != macho.Magic64 || at < 0 { + t.Fatalf("%s isn't a 64-bit program that names its SDK", src) + } + f.ByteOrder.PutUint32(b[at:], sdk) + if err := os.WriteFile(dst, b, 0o755); err != nil { + t.Fatal(err) + } + if out, err := exec.Command("codesign", "--sign", "-", "--force", dst).CombinedOutput(); err != nil { + t.Fatalf("signing the program again: %v\n%s", err, out) + } +} diff --git a/internal/gui/lightweight.go b/internal/gui/lightweight.go index aec1e2c38..cd63a2fb8 100644 --- a/internal/gui/lightweight.go +++ b/internal/gui/lightweight.go @@ -139,9 +139,9 @@ func (h *host) makePanel() *application.WebviewWindow { } // madeAgain gives a window made again after lightweight mode let it go -// what the start gave the -// first: the Mac's text size (Windows' and Linux's took it with the -// options), Linux's title bar or the panel's name for Hyprland. +// what the start gave the first: the Mac's text size (Windows' and +// Linux's took it with the options), the main window's title bar +// (plainTitlebar) or the panel's name for Hyprland. func (h *host) madeAgain(w *application.WebviewWindow) { if runtime.GOOS == "darwin" && h.zoom() != 1 { setPageZoom(w, h.zoom()) diff --git a/internal/gui/mainwindow.go b/internal/gui/mainwindow.go index 8e5a1dbad..de1a8e0da 100644 --- a/internal/gui/mainwindow.go +++ b/internal/gui/mainwindow.go @@ -21,7 +21,9 @@ import ( func mainMacWindow() application.MacWindow { return application.MacWindow{ // no InvisibleTitleBarHeight: that strip drags from anywhere in - // it, tabs included; the header marks what drags instead + // it, tabs included; the header marks what drags instead. On + // macOS 26 and later its toolbar is taken off once it has placed + // the traffic lights (plainTitlebar) TitleBar: application.MacTitleBarHiddenInset, CollectionBehavior: application.MacWindowCollectionBehaviorMoveToActiveSpace | application.MacWindowCollectionBehaviorFullScreenPrimary, diff --git a/internal/gui/titlebar_darwin.go b/internal/gui/titlebar_darwin.go new file mode 100644 index 000000000..e9ac71458 --- /dev/null +++ b/internal/gui/titlebar_darwin.go @@ -0,0 +1,218 @@ +//go:build !nogui + +package gui + +/* +#cgo CFLAGS: -x objective-c +#cgo LDFLAGS: -framework Cocoa +#import +#import +#import +#import + +static const NSWindowButton lightKinds[3] = {NSWindowCloseButton, NSWindowMiniaturizeButton, NSWindowZoomButton}; + +// MagpieLights keeps a window's traffic lights where its toolbar had put +// them, once the toolbar is gone. AppKit lays the title bar out again +// whenever it changes (a resize or zoom, leaving full screen, a new title or +// appearance), with its own height for the title bar and its own place for +// the lights. Each time, they're put back once AppKit is done: at once after +// a resize, whose animation draws its frames before the run loop turns, else +// as the run loop turns. While AppKit lays them out they can't be: it +// ignores a move of the light it is placing. When the system's appearance +// changes (light or dark, more contrast or less transparency), and at times +// on the way into full screen, AppKit draws the title bar at its own height +// before the run loop turns: the lights keep their distance from its top, +// not its bottom, which would draw them above the window. +@interface MagpieLights : NSObject { +@public + NSWindow *win; // not held: the window holds this; nil once it closes + CGFloat height; // the title bar's, as the toolbar had it + CGFloat x[3], top[3]; + BOOL busy, pending; +} +@end + +@implementation MagpieLights +- (void)apply { + if (busy || win == nil || (win.styleMask & NSWindowStyleMaskFullScreen)) return; + NSView *bar = [win standardWindowButton:NSWindowCloseButton].superview, *box = bar.superview, *frame = box.superview; + if (frame == nil) return; + busy = YES; + BOOL moved = NO; + NSRect f = box.frame; + NSRect want = NSMakeRect(f.origin.x, frame.isFlipped ? 0 : NSHeight(frame.bounds) - height, f.size.width, height); + if (!NSEqualRects(f, want)) { + box.frame = want; + moved = YES; + } + for (int i = 0; i < 3; i++) { + NSButton *b = [win standardWindowButton:lightKinds[i]]; + if (b.superview != bar) continue; + NSAutoresizingMaskOptions keepTop = bar.isFlipped ? NSViewMaxYMargin : NSViewMinYMargin; + if (b.autoresizingMask != keepTop) b.autoresizingMask = keepTop; + NSPoint o = NSMakePoint(x[i], bar.isFlipped ? top[i] : NSHeight(bar.bounds) - top[i] - NSHeight(b.frame)); + if (!NSEqualPoints(b.frame.origin, o)) { + [b setFrameOrigin:o]; + moved = YES; + } + } + // AppKit follows the mouse over the lights, to show their symbols, where + // it laid them out; it looks again where they are as when a live resize + // ends (and during one, it will then). + if (moved && !frame.inLiveResize) [frame viewDidEndLiveResize]; + busy = NO; +} + +- (void)later { + if (pending) return; + pending = YES; + CFRunLoopPerformBlock(CFRunLoopGetMain(), kCFRunLoopCommonModes, ^{ + pending = NO; + [self apply]; + }); + CFRunLoopWakeUp(CFRunLoopGetMain()); +} +- (void)changed:(NSNotification *)n { + if (!busy) [self later]; +} +- (void)resized:(NSNotification *)n { + [self apply]; + [self later]; +} +- (void)closing:(NSNotification *)n { + [[NSNotificationCenter defaultCenter] removeObserver:self]; + win = nil; +} +- (void)dealloc { + [[NSNotificationCenter defaultCenter] removeObserver:self]; + [super dealloc]; +} +@end + +static char lightsKey; + +// A sheet, such as the folder chooser, begins below the title bar, as it +// began below the toolbar. With neither, AppKit lets it rise to the window's +// top, over the header: macOS 26 centres a sheet, so in a short window. +static NSRect sheetBelowTitlebar(id self, SEL _cmd, NSWindow *w, NSWindow *sheet, NSRect r) { + MagpieLights *l = objc_getAssociatedObject(w, &lightsKey); + if (l != nil && l->win != nil && !(w.styleMask & NSWindowStyleMaskFullScreen)) r.origin.y = NSHeight(w.frame) - l->height; + return r; +} + +// A first press on the window while it isn't the key one (another app's is +// in front) moves it from anywhere in the title bar the toolbar had, as +// AppKit moved it then. AppKit now does so only in its own, a plain title +// bar's top 32pt, and the page doesn't take a first press: below that, the +// press would only bring the window forward. As AppKit does, a press on a +// view that takes it (a traffic light, an edge that resizes) is left alone. +static NSEvent *firstPress(NSEvent *e) { + NSWindow *w = e.window; + MagpieLights *l = w == nil ? nil : objc_getAssociatedObject(w, &lightsKey); + if (l == nil || l->win == nil || w.isKeyWindow || !w.isMovable || e.clickCount != 1 || (w.styleMask & NSWindowStyleMaskFullScreen)) return e; + NSView *frame = w.contentView.superview; + NSPoint p = e.locationInWindow; + // The content layout rect begins below AppKit's title bar. + if (frame == nil || !NSPointInRect(p, w.contentLayoutRect) || NSHeight(frame.bounds) - p.y >= l->height) return e; + NSView *hit = [frame hitTest:p]; + if (hit == nil || [hit acceptsFirstMouse:e]) return e; + [w performWindowDragWithEvent:e]; + return e; +} + +// Whether AppKit gives this program the design of macOS 26, where a toolbar +// gives a window larger corners: from macOS 26, for a program linked against +// the macOS 26 SDK or a later one, unless its Info.plist asks for the earlier +// design (UIDesignRequiresCompatibility). Each is read at run time. The SDK is +// the one the program names, which depends on the toolchain that linked it: +// in LC_BUILD_VERSION, or in LC_VERSION_MIN_MACOSX in a program that runs on +// macOS 10.13, as go build links one for an Intel Mac. The macOS version +// isn't asked with @available(macOS 26.0, *): without make's flags, clang +// compiles this code for the Mac's own macOS, though the program is linked to +// run on earlier ones too, and on a Mac with macOS 26 the check would be +// compiled away. +static BOOL designOf26(void) { + if (![NSProcessInfo.processInfo isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion){26, 0, 0}]) return NO; + id compat = [NSBundle.mainBundle objectForInfoDictionaryKey:@"UIDesignRequiresCompatibility"]; + if ([compat respondsToSelector:@selector(boolValue)] && [compat boolValue]) return NO; + const struct mach_header_64 *h = _NSGetMachExecuteHeader(); + const struct load_command *c = (const struct load_command *)(h + 1); + for (uint32_t i = 0; i < h->ncmds; i++, c = (const struct load_command *)((const char *)c + c->cmdsize)) { + if (c->cmd == LC_BUILD_VERSION) return ((const struct build_version_command *)c)->sdk >= 0x1A0000; // 26.0 + if (c->cmd == LC_VERSION_MIN_MACOSX) return ((const struct version_min_command *)c)->sdk >= 0x1A0000; + } + return NO; +} + +// The Mac's title bar with no toolbar (the design of macOS 26). The main +// window has an empty toolbar only to inset the traffic lights into the +// page's header (MacTitleBarHiddenInset), and in that design a window with a +// toolbar has the larger corners of one: the size of Finder's, where every +// other window with a plain title bar has smaller ones (TextEdit's, and an +// Electron app's that insets its lights by moving them). The toolbar is +// taken off, and the lights are kept where it had them, so the header still +// fits them. The window is left as it was in the earlier design, where a +// toolbar doesn't change the corners (see designOf26), with its lights on +// the right (a right-to-left language), or with a title bar not laid out as +// expected. +static void insetLights(void *p) { + if (!designOf26()) return; + NSWindow *w = (NSWindow *)p; + if (w.toolbar == nil || objc_getAssociatedObject(w, &lightsKey) != nil) return; + if (w.windowTitlebarLayoutDirection == NSUserInterfaceLayoutDirectionRightToLeft) return; + NSView *bar = [w standardWindowButton:NSWindowCloseButton].superview, *box = bar.superview, *frame = box.superview; + if (frame == nil) return; + [frame layoutSubtreeIfNeeded]; + MagpieLights *l = [[[MagpieLights alloc] init] autorelease]; + l->win = w; + l->height = NSHeight(box.frame); + NSView *views[5] = {box, bar}; + for (int i = 0; i < 3; i++) { + NSButton *b = [w standardWindowButton:lightKinds[i]]; + if (b == nil || b.superview != bar) return; + l->x[i] = b.frame.origin.x; + l->top[i] = bar.isFlipped ? NSMinY(b.frame) : NSHeight(bar.bounds) - NSMaxY(b.frame); + views[2 + i] = b; + } + objc_setAssociatedObject(w, &lightsKey, l, OBJC_ASSOCIATION_RETAIN); + NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; + for (int i = 0; i < 5; i++) { + views[i].postsFrameChangedNotifications = YES; + [nc addObserver:l selector:@selector(changed:) name:NSViewFrameDidChangeNotification object:views[i]]; + } + [nc addObserver:l selector:@selector(resized:) name:NSWindowDidResizeNotification object:w]; + [nc addObserver:l selector:@selector(closing:) name:NSWindowWillCloseNotification object:w]; + static BOOL watchingPresses; + if (!watchingPresses) { + watchingPresses = YES; + [NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskLeftMouseDown handler:^NSEvent *(NSEvent *e) { return firstPress(e); }]; + } + // Wails' window delegate leaves sheets to AppKit; it's taught to place + // this window's (a window without the helper keeps AppKit's place). + SEL s = @selector(window:willPositionSheet:usingRect:); + id d = w.delegate; + if (d != nil && ![d respondsToSelector:s]) + class_addMethod([d class], s, (IMP)sheetBelowTitlebar, protocol_getMethodDescription(@protocol(NSWindowDelegate), s, NO, YES).types); + w.toolbar = nil; + [l apply]; +} +*/ +import "C" + +import "github.com/wailsapp/wails/v3/pkg/application" + +// plainTitlebar gives the main window, in the design of macOS 26, the +// corners of a window with a plain title bar (see insetLights); the traffic +// lights stay inset into the page's header. +func plainTitlebar(w *application.WebviewWindow) { + application.InvokeSync(func() { + if p := w.NativeWindow(); p != nil { + C.insetLights(p) + } + }) +} + +func nameWindow(*application.WebviewWindow, string) {} + +func ownFrame(*application.WebviewWindow) {} diff --git a/internal/gui/titlebar_darwin_test.go b/internal/gui/titlebar_darwin_test.go new file mode 100644 index 000000000..179fe585b --- /dev/null +++ b/internal/gui/titlebar_darwin_test.go @@ -0,0 +1,277 @@ +//go:build darwin && cgo && !nogui + +package gui + +import ( + "bytes" + "encoding/json" + "fmt" + "math" + "net/http" + "os" + "testing" + "time" + "unsafe" + + "github.com/wailsapp/wails/v3/pkg/application" + "github.com/wailsapp/wails/v3/pkg/events" + + "github.com/yetone/magpie/internal/gui/windowshape" +) + +// titlebarRun is what the separate process measured: the main window, one +// with a plain title bar and one with the toolbar (the main window's as it +// was), at each stage, the main window and the toolbar one as AppKit draws +// a new system appearance, how many window drags a first press Y points +// below the top of each began, and how far below the top a sheet on each +// begins. +type titlebarRun struct { + Stages []struct { + Name string + Main, Plain, Toolbar windowshape.Shape + } + Drawn struct{ Main, Toolbar windowshape.Shape } + Presses []struct { + Y float64 + Main, Plain, Toolbar int + } + Sheet struct{ Main, Plain, Toolbar float64 } +} + +const titlebarMark = "titlebar run: " + +// The macOS SDKs a test runs the windows' program as linked against +// (runAppKitSDK): AppKit gives one linked against macOS 26's or a later one +// the design of macOS 26. +const ( + sdkMacOS15 uint32 = 15 << 16 + sdkMacOS26 uint32 = 26 << 16 +) + +// The main window has the corners of a window with a plain title bar +// (TextEdit's, an Electron app's), not a toolbar's: in the design of macOS +// 26 one with a toolbar has larger ones. Its traffic lights, its title bar's +// height and where a sheet on it begins stay where the toolbar had them, +// also after a new title and size and a new system appearance. The lights +// are in place as AppKit draws that appearance, too. A first press while +// another app is in front moves it from where it did with the toolbar. In +// the earlier design, where a toolbar doesn't change the corners (an older +// macOS, or a program linked against an earlier SDK than macOS 26's), the +// window keeps its toolbar. The windows' program is run as linked against +// each SDK, whatever the toolchain has, in a process of its own that runs +// AppKit on its main thread. +func TestMainWindowCorners(t *testing.T) { + for _, sdk := range []struct { + name string + v uint32 + }{{"macOS 26 SDK", sdkMacOS26}, {"macOS 15 SDK", sdkMacOS15}} { + t.Run(sdk.name, func(t *testing.T) { checkMainWindowCorners(t, sdk.v) }) + } +} + +func checkMainWindowCorners(t *testing.T, sdk uint32) { + var run titlebarRun + measureWindows(t, sdk, "corners", &run) + near := func(a, b float64) bool { return math.Abs(a-b) < 0.5 } + for _, s := range run.Stages { + t.Logf("%s: corners %.2fpt (plain %.2f, toolbar %.2f), lights %v (toolbar %v), title bar %.0fpt (toolbar %.0f), toolbar kept %v", s.Name, + s.Main.Radius, s.Plain.Radius, s.Toolbar.Radius, s.Main.Lights, s.Toolbar.Lights, s.Main.Titlebar, s.Toolbar.Titlebar, s.Main.Toolbar) + if s.Plain.Radius < 0 { + t.Errorf("%s: AppKit doesn't tell a window's corner radius", s.Name) + } else if !near(s.Main.Radius, s.Plain.Radius) { + t.Errorf("%s: corners of %.2fpt; a window with a plain title bar has %.2fpt, one with a toolbar %.2fpt", + s.Name, s.Main.Radius, s.Plain.Radius, s.Toolbar.Radius) + } + for l := range 3 { + if m, tb := s.Main.Lights[l], s.Toolbar.Lights[l]; !near(m[0], tb[0]) || !near(m[1], tb[1]) { + t.Errorf("%s: traffic light %d at %v (x, y from the top left), the toolbar had it at %v", s.Name, l+1, m, tb) + } + } + if !near(s.Main.Titlebar, s.Toolbar.Titlebar) { + t.Errorf("%s: a title bar %.0fpt tall, the toolbar's was %.0fpt", s.Name, s.Main.Titlebar, s.Toolbar.Titlebar) + } + // Where a toolbar doesn't change the corners (the earlier design), + // the main window is left as it was + if near(s.Plain.Radius, s.Toolbar.Radius) && !s.Main.Toolbar { + t.Errorf("%s: a toolbar doesn't change the corners in this design, yet the main window's was taken off", s.Name) + } + } + if len(run.Stages) != 3 { + t.Errorf("measured %d stages, want 3", len(run.Stages)) + } + t.Logf("as AppKit draws a new system appearance: lights %v (toolbar %v), title bar %.0fpt", run.Drawn.Main.Lights, + run.Drawn.Toolbar.Lights, run.Drawn.Main.Titlebar) + for l := range 3 { + if m, tb := run.Drawn.Main.Lights[l], run.Drawn.Toolbar.Lights[l]; !near(m[0], tb[0]) || !near(m[1], tb[1]) { + t.Errorf("as AppKit draws a new system appearance, traffic light %d is at %v (x, y from the top left); the toolbar had it at %v", + l+1, m, tb) + } + } + for _, p := range run.Presses { + t.Logf("a first press %.0fpt below the top, another app in front: %d window drags (plain %d, toolbar %d)", p.Y, p.Main, p.Plain, p.Toolbar) + if p.Main < 0 || p.Plain < 0 || p.Toolbar < 0 { + t.Errorf("a window was the key one, so a press as when another app is in front couldn't be tried") + } else if p.Main != p.Toolbar { + t.Errorf("a first press %.0fpt below the top, with another app in front, began %d window drags; with the toolbar it began %d (with a plain title bar: %d)", + p.Y, p.Main, p.Toolbar, p.Plain) + } + } + // AppKit moves each of them from the top of its title bar: a press there + // that moved none didn't arrive + if len(run.Presses) != 4 || run.Presses[0].Plain != 1 || run.Presses[0].Toolbar != 1 { + t.Errorf("a first press near the top didn't begin a window drag, or not each was tried: %+v", run.Presses) + } + t.Logf("a sheet begins %.0fpt below the top (plain %.0f, toolbar %.0f)", run.Sheet.Main, run.Sheet.Plain, run.Sheet.Toolbar) + if !near(run.Sheet.Main, run.Sheet.Toolbar) { + t.Errorf("a sheet on a short window begins %.0fpt below its top; below the toolbar it began %.0fpt (with a plain title bar: %.0fpt)", + run.Sheet.Main, run.Sheet.Toolbar, run.Sheet.Plain) + } +} + +// With its traffic lights on the right, as in a right-to-left language, +// the main window keeps its toolbar, also in the design of macOS 26: the +// lights are kept in place from the left. +func TestMainWindowRightToLeft(t *testing.T) { + var s windowshape.Shape + // as Xcode launches an app in its right-to-left pseudolanguage + measureWindows(t, sdkMacOS26, "right to left", &s, + "-AppleTextDirection", "YES", "-NSForceRightToLeftWritingDirection", "YES") + t.Logf("lights %v (x, y from the top left), toolbar kept %v", s.Lights, s.Toolbar) + if s.Lights[0][0] < s.Lights[2][0] { + t.Fatalf("launched right to left, the traffic lights are on the left: %v", s.Lights) + } + if !s.Toolbar { + t.Errorf("the traffic lights are on the right, and the main window's toolbar was taken off") + } +} + +// measureWindows measures the windows in mode in a process of its own, run +// as linked against the macOS SDK sdk (runAppKitSDK), with args for AppKit, +// and decodes what it measured into v. +func measureWindows(t *testing.T, sdk uint32, mode string, v any, args ...string) { + t.Helper() + out, err := runAppKitSDK(t, sdk, 40*time.Second, []string{"MAGPIE_TEST_TITLEBAR=" + mode}, args...) + i := bytes.LastIndex(out, []byte(titlebarMark)) + if err != nil || i < 0 { + t.Fatalf("measuring the windows: %v\n%s", err, out) + } + line, _, _ := bytes.Cut(out[i+len(titlebarMark):], []byte("\n")) + if err := json.Unmarshal(line, v); err != nil { + t.Fatalf("%v: %s", err, line) + } +} + +// The process measureWindows runs: the arguments go to AppKit, as the +// test's own flags are never parsed. +func init() { + mode := os.Getenv("MAGPIE_TEST_TITLEBAR") + if mode == "" { + return + } + app := application.New(application.Options{ + Name: "magpie title bar regression", + Mac: application.MacOptions{ActivationPolicy: application.ActivationPolicyProhibited}, + Assets: application.AssetOptions{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/html") + fmt.Fprint(w, ``) + })}, + }) + h := &host{app: app} + main := h.makeMain("/") + if mode == "right to left" { + app.Event.OnApplicationEvent(events.Common.ApplicationStarted, func(*application.ApplicationEvent) { + plainTitlebar(main) + go func() { + application.InvokeSync(func() { main.SetSize(900, 600); main.Show() }) + time.Sleep(time.Second) + var s windowshape.Shape + application.InvokeSync(func() { s = windowshape.Of(main.NativeWindow()) }) + measured(app, s) + }() + }) + runAndExit(app) + } + ref := func(tb application.MacTitleBar) *application.WebviewWindow { + m := mainMacWindow() + m.TitleBar = tb + return app.Window.NewWithOptions(application.WebviewWindowOptions{URL: "/", Width: 900, Height: 600, Hidden: true, Mac: m}) + } + wins := []*application.WebviewWindow{main, ref(application.MacTitleBarHidden), ref(application.MacTitleBarHiddenInset)} + started := make(chan struct{}) + app.Event.OnApplicationEvent(events.Common.ApplicationStarted, func(*application.ApplicationEvent) { + plainTitlebar(main) // as Run does, before the window is first shown + close(started) + }) + each := func(f func(i int, w *application.WebviewWindow)) { + application.InvokeSync(func() { + for i, w := range wins { + f(i, w) + } + }) + } + go func() { + <-started + var run titlebarRun + measure := func(name string) { + time.Sleep(time.Second) + var s [3]windowshape.Shape + each(func(i int, w *application.WebviewWindow) { s[i] = windowshape.Of(w.NativeWindow()) }) + run.Stages = append(run.Stages, struct { + Name string + Main, Plain, Toolbar windowshape.Shape + }{name, s[0], s[1], s[2]}) + } + each(func(_ int, w *application.WebviewWindow) { w.SetSize(900, 600); w.Show() }) + measure("shown") + each(func(_ int, w *application.WebviewWindow) { w.SetTitle("magpie, renamed"); w.SetSize(1000, 680) }) + measure("a new title and size") + // AppKit draws a new system appearance before the run loop turns: + // the windows are measured at once, and again once it has + application.InvokeSync(func() { + windowshape.FlipIncreaseContrast() + run.Drawn.Main, run.Drawn.Toolbar = windowshape.Of(main.NativeWindow()), windowshape.Of(wins[2].NativeWindow()) + }) + measure("a new system appearance") + // The app may not activate, so the windows are never the key one + for _, y := range []float64{20, 40, 60, 70} { + var d [3]int + each(func(i int, w *application.WebviewWindow) { d[i] = windowshape.FirstPress(w.NativeWindow(), 200, y) }) + run.Presses = append(run.Presses, struct { + Y float64 + Main, Plain, Toolbar int + }{y, d[0], d[1], d[2]}) + } + // macOS 26 centres a sheet, no higher than where it may begin: in a + // short window, that's where it is + each(func(_ int, w *application.WebviewWindow) { w.SetSize(900, 480) }) + time.Sleep(time.Second) + var sheets [3]unsafe.Pointer + each(func(i int, w *application.WebviewWindow) { sheets[i] = windowshape.BeginSheet(w.NativeWindow(), 448) }) + time.Sleep(1500 * time.Millisecond) + var tops [3]float64 + each(func(i int, w *application.WebviewWindow) { + tops[i] = windowshape.SheetTop(w.NativeWindow(), sheets[i]) + windowshape.EndSheet(w.NativeWindow(), sheets[i]) + }) + run.Sheet.Main, run.Sheet.Plain, run.Sheet.Toolbar = tops[0], tops[1], tops[2] + measured(app, run) + }() + runAndExit(app) +} + +// measured prints what was measured, for measureWindows, and quits. +func measured(app *application.App, v any) { + b, err := json.Marshal(v) + if err != nil { + panic(err) + } + fmt.Println(titlebarMark + string(b)) + app.Quit() +} + +func runAndExit(app *application.App) { + if err := app.Run(); err != nil { + panic(err) + } + os.Exit(0) +} diff --git a/internal/gui/titlebar_gtk3.go b/internal/gui/titlebar_gtk3.go index 0d9711902..4c04f3107 100644 --- a/internal/gui/titlebar_gtk3.go +++ b/internal/gui/titlebar_gtk3.go @@ -49,8 +49,9 @@ import ( // header of its own. GNOME draws one over it, the name and a close button // stacked on the tabs; frameless, the window would lose its shadow, rounded // corners and the edges it is resized by. A hidden widget as its titlebar -// keeps all those and shows no bar: the page's header drags it, and has the -// close button. +// keeps the shadow and the edges and shows no bar: the page's header drags +// it, and has the close button. The corners stay square: GTK 3 rounds only +// a title bar it draws, and doesn't clip the page to the window's corners. func plainTitlebar(w *application.WebviewWindow) { application.InvokeSync(func() { if p := w.NativeWindow(); p != nil { diff --git a/internal/gui/titlebar_other.go b/internal/gui/titlebar_other.go index f4665c53d..858264278 100644 --- a/internal/gui/titlebar_other.go +++ b/internal/gui/titlebar_other.go @@ -1,11 +1,10 @@ -//go:build (!linux || !cgo) && !nogui +//go:build !darwin && (!linux || !cgo) && !nogui package gui import "github.com/wailsapp/wails/v3/pkg/application" -// plainTitlebar: macOS insets the traffic lights into the page's header -// (MacTitleBarHiddenInset) and Windows keeps its own title bar. +// plainTitlebar: Windows keeps its own title bar. func plainTitlebar(*application.WebviewWindow) {} func nameWindow(*application.WebviewWindow, string) {} diff --git a/internal/gui/windowshape/doc.go b/internal/gui/windowshape/doc.go new file mode 100644 index 000000000..d0b8b242b --- /dev/null +++ b/internal/gui/windowshape/doc.go @@ -0,0 +1,8 @@ +// Package windowshape measures a Mac window for the GUI's tests: the +// radius of its corners, where its traffic lights are, whether it has a +// toolbar, where a sheet on it begins and whether a first press on it +// begins a window drag. It can also flip Increase contrast for its own +// process (on where the system has it off, off where it is on), to give +// the windows a new system appearance. It sends no event to the system and +// changes no setting. Only tests import it. +package windowshape diff --git a/internal/gui/windowshape/windowshape_darwin.go b/internal/gui/windowshape/windowshape_darwin.go new file mode 100644 index 000000000..03a3f3867 --- /dev/null +++ b/internal/gui/windowshape/windowshape_darwin.go @@ -0,0 +1,139 @@ +//go:build cgo + +package windowshape + +/* +#cgo CFLAGS: -x objective-c +#cgo LDFLAGS: -framework Cocoa +#import +#import +#import + +// AppKit's own: no public API gives a window's corner radius. +static double cornerRadius(void *p) { + SEL s = sel_registerName("_cornerRadius"); + if (![(id)p respondsToSelector:s]) return -1; + return ((CGFloat (*)(id, SEL))objc_msgSend)((id)p, s); +} + +static int hasToolbar(void *p) { return ((NSWindow *)p).toolbar != nil; } + +static void lights(void *p, double *out) { + NSWindow *w = (NSWindow *)p; + NSWindowButton kinds[3] = {NSWindowCloseButton, NSWindowMiniaturizeButton, NSWindowZoomButton}; + for (int i = 0; i < 3; i++) { + NSButton *b = [w standardWindowButton:kinds[i]]; + NSRect r = [b convertRect:b.bounds toView:nil]; + out[2 * i] = NSMidX(r); + out[2 * i + 1] = NSHeight(w.frame) - NSMidY(r); + } + out[6] = NSHeight([w standardWindowButton:NSWindowCloseButton].superview.superview.frame); +} + +static void *beginSheet(void *p, double h) { + NSWindow *s = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 400, h) styleMask:NSWindowStyleMaskTitled + backing:NSBackingStoreBuffered defer:NO]; + [(NSWindow *)p beginSheet:s completionHandler:nil]; + return s; +} + +static double sheetTop(void *p, void *s) { + return NSMaxY(((NSWindow *)p).frame) - NSMaxY(((NSWindow *)s).frame); +} + +static void endSheet(void *p, void *s) { + [(NSWindow *)p endSheet:(NSWindow *)s]; + [(NSWindow *)s release]; +} + +static BOOL moreContrast; +static BOOL increaseContrast(id self, SEL _cmd) { return moreContrast; } + +static void flipIncreaseContrast(void) { + static BOOL answered; + if (!answered) { + moreContrast = NSWorkspace.sharedWorkspace.accessibilityDisplayShouldIncreaseContrast; + method_setImplementation(class_getInstanceMethod([NSWorkspace class], @selector(accessibilityDisplayShouldIncreaseContrast)), + (IMP)increaseContrast); + answered = YES; + } + moreContrast = !moreContrast; + [NSWorkspace.sharedWorkspace.notificationCenter postNotificationName:NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification + object:NSWorkspace.sharedWorkspace]; +} + +static int drags; +static void countDrag(id self, SEL _cmd, NSEvent *e) { drags++; } + +static NSEvent *press(NSWindow *w, NSEventType t, NSPoint at) { + return [NSEvent mouseEventWithType:t location:at modifierFlags:0 timestamp:NSProcessInfo.processInfo.systemUptime + windowNumber:w.windowNumber context:nil eventNumber:0 clickCount:1 pressure:t == NSEventTypeLeftMouseDown]; +} + +static int firstPress(void *p, double x, double y) { + NSWindow *w = (NSWindow *)p; + if (w.isKeyWindow) return -1; + NSPoint at = NSMakePoint(x, NSHeight(w.frame) - y); + Method m = class_getInstanceMethod([w class], @selector(performWindowDragWithEvent:)); + IMP drag = method_setImplementation(m, (IMP)countDrag); + drags = 0; + // The release is queued first: a loop the press begins (a resize) takes + // it and ends. + [NSApp postEvent:press(w, NSEventTypeLeftMouseUp, at) atStart:NO]; + [NSApp sendEvent:press(w, NSEventTypeLeftMouseDown, at)]; + NSEvent *up = [NSApp nextEventMatchingMask:NSEventMaskLeftMouseUp untilDate:[NSDate distantPast] inMode:NSDefaultRunLoopMode dequeue:YES]; + if (up != nil) [NSApp sendEvent:up]; + method_setImplementation(m, drag); + return drags; +} +*/ +import "C" + +import "unsafe" + +// Shape is how a window's frame looks, in points. +type Shape struct { + Radius float64 // of its corners; -1 when AppKit doesn't say + Lights [3][2]float64 // each traffic light's middle: x from the window's left, y from its top + Titlebar float64 // the title bar's height + Toolbar bool // whether it has a toolbar +} + +// Of measures the NSWindow w. Call it on the main thread. +func Of(w unsafe.Pointer) Shape { + var out [7]C.double + C.lights(w, &out[0]) + s := Shape{Radius: float64(C.cornerRadius(w)), Titlebar: float64(out[6]), Toolbar: C.hasToolbar(w) != 0} + for i := range 3 { + s.Lights[i] = [2]float64{float64(out[2*i]), float64(out[2*i+1])} + } + return s +} + +// BeginSheet shows a sheet height points tall on w. Call it on the main +// thread, and EndSheet once done. +func BeginSheet(w unsafe.Pointer, height float64) unsafe.Pointer { + return C.beginSheet(w, C.double(height)) +} + +// SheetTop is how far below w's top its sheet begins. +func SheetTop(w, sheet unsafe.Pointer) float64 { return float64(C.sheetTop(w, sheet)) } + +// EndSheet takes the sheet off w. +func EndSheet(w, sheet unsafe.Pointer) { C.endSheet(w, sheet) } + +// FirstPress presses w once, and lets go, x points from its left and y from +// its top, as a press comes while another app is in front: w isn't the key +// window. The press is sent within this process, as AppKit sends the window +// server's, and tells how many window drags it began (counted, not begun), +// or -1 if w is the key window. Call it on the main thread. +func FirstPress(w unsafe.Pointer, x, y float64) int { + return int(C.firstPress(w, C.double(x), C.double(y))) +} + +// FlipIncreaseContrast turns Increase contrast, for this process alone, to +// the opposite of what System Settings has, and back on the next call: +// AppKit is told the display options changed, and finds the setting +// changed, so every window that follows the system takes a new +// appearance. Call it on the main thread. +func FlipIncreaseContrast() { C.flipIncreaseContrast() }