Files
magpie/internal/gui/lightweight.go
T
forever 2c31129692 gui: on macOS 26 the main window has a plain title bar's corners (TextEdit's, not Finder's), its traffic lights still in the header (waitingsnow) (#1042)
* gui: on macOS 26 the main window has a plain title bar's corners (TextEdit's, not Finder's), its traffic lights still in the header (waitingsnow)

From macOS 26 a window with a toolbar has larger corners than one with a
plain title bar: 26pt, Finder's, against 16pt for TextEdit or an
Electron app. The main window has an empty toolbar only to inset its
traffic lights into the page's header (Wails' MacTitleBarHiddenInset),
so its corners were a toolbar window's. On macOS 15 a toolbar doesn't
change them (12pt either way, measured on 15.8).

On macOS 26 and later plainTitlebar now takes the toolbar off
(insetLights, titlebar_darwin.go), and MagpieLights keeps the lights and
the title bar's 66pt height where the toolbar had them. AppKit lays the
title bar out again at its own 32pt after a resize or zoom, a new title,
a new appearance and leaving full screen; the lights are put back once
it is done, and AppKit's hover tracking is told where they went. Their
autoresizing mask keeps their distance from the top: AppKit draws a new
system appearance (light or dark, more contrast, less transparency)
before the run loop turns, which drew them 8pt above the window for one
frame. A sheet, such as the folder chooser, still begins below the title
bar (Wails' window delegate gets window:willPositionSheet:usingRect:,
which places this window's sheets only).

A first press while another app is in front still moves the window from
anywhere in the 66pt title bar, as AppKit moved it with the toolbar
(firstPress, a local mouse-down monitor). AppKit's own band is now a
plain title bar's 32pt; below it the page doesn't take a first press, so
the press would only have brought the window forward. A press on a view
that takes a first press (a traffic light, a resize edge) is left alone,
as AppKit leaves it.

The macOS version is asked at run time. go build and go test build the
cgo objects for the Mac's own macOS, where @available(macOS 26.0, *) is
compiled away: a test binary built so on 26.7.1 took the toolbar off on
15.8. An older macOS, the lights on the right (a right-to-left language)
or a title bar not laid out as expected keep the toolbar. Linux and
Windows are unchanged; the GTK 3 comment now says its corners stay
square.

TestMainWindowCorners (new; darwin, run by CI's macOS job) measures the
main window beside a plain and a toolbar window in a process of its own
(runAppKit, so WebKit's data stays out of the real ~/Library): once
shown, after a new title and size and a new system appearance, as AppKit
draws that appearance, a first press 20, 40, 60 and 70pt below the top
while no window is key, and where a sheet begins.
TestMainWindowRightToLeft launches it right to left. Both pass on macOS
26.7.1 (3 runs in a row), 26.6.2 (CI's) and 15.8 Intel, where the
toolbar stays. With each part taken out, they fail:
- the change itself: "corners of 26.00pt; a window with a plain title
  bar has 16.00pt, one with a toolbar 26.00pt";
- putting the lights back: "traffic light 1 at [16 16] (x, y from the
  top left), the toolbar had it at [26 26]";
- the height: "a title bar 32pt tall, the toolbar's was 66pt";
- the mask: "as AppKit draws a new system appearance, traffic light 1
  is at [26 -8]";
- the sheet's place: "a sheet on a short window begins 16pt below its
  top; below the toolbar it began 66pt";
- the press monitor: "a first press 40pt below the top, with another
  app in front, began 0 window drags; with the toolbar it began 1";
- the right-to-left check: "the traffic lights are on the right, and
  the main window's toolbar was taken off";
- the run-time check (@available instead), on 15.8: "a toolbar doesn't
  change the corners on this macOS, yet the main window's was taken
  off".
The presses are sent within the test's own process, and a drag is
counted, not begun; no system setting changes.

The real app on 26.7.1, built from this commit and driven through
Accessibility under a HOME of its own, has 16.25pt corners (26.50pt on
main) and its lights where main has them, through resize, zoom, light
and dark, a new title, full screen, minimise, close and show, a
maximised start, and the window lightweight mode makes again. A real
pointer and a key window's press were not tried. go vet, the three
builds and go test -tags nogui ./... pass.

* gui: where AppKit gives magpie the Mac's earlier design (an SDK before macOS 26's, or UIDesignRequiresCompatibility), the main window keeps its toolbar (waitingsnow)

The main window's toolbar comes off only in the design of macOS 26,
where a toolbar gives a window larger corners. 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 set
UIDesignRequiresCompatibility; the last commit asked only for the macOS
version. A program linked against an earlier SDK gets the earlier design
on macOS 26 too: yetone's test binary (Go 1.26.3, Xcode 26.2) names SDK
11.0, and on 26.2 every window there had 12pt corners, yet the main
window's toolbar was taken off and TestMainWindowCorners failed at every
stage.

designOf26 now reads each at run time: the macOS version (NSProcessInfo),
the key (NSBundle) and the SDK the program names. The SDK is 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 header is read
through _NSGetMachExecuteHeader (crt_externs.h):
dyld_get_program_sdk_version is declared only in dyld's private header,
and it doesn't see the key (27.0 in a bundle that sets it, where AppKit
gives the earlier design). The comment no longer says go build builds
for the Mac's own macOS: the program names 11.0, and it is clang that
compiles the cgo code for the Mac's own macOS (ld: "built for newer
'macOS' version (26.0) than being linked (11.0)"), where
@available(macOS 26.0, *) would be compiled away.

TestMainWindowCorners now runs the windows' program twice, as linked
against the macOS 26 SDK and against macOS 15's (runAppKitSDK; stampSDK
rewrites the SDK in a copy and signs it again), so on macOS 26 it checks
both designs whatever SDK the toolchain names. In the earlier design it
checks that the main window keeps its toolbar. gui-shell.md says which
design gets the change, which SDKs the test runs with, why the key has
no test, and how to run it as for an Intel Mac.

Both subtests and TestMainWindowRightToLeft pass on 26.7.1 (arm64, 3
runs in a row, and amd64 under Rosetta), 26.6.2 (arm64, as CI) and 15.8
(Intel). With each new part taken out, its subtest fails:
- reading the SDK (designOf26 answering yes after the macOS and the
  key): "a toolbar doesn't change the corners in this design, yet the
  main window's was taken off", with macOS 15's SDK;
- 26.0 itself (> for >=): "corners of 26.00pt; a window with a plain
  title bar has 16.00pt, one with a toolbar 26.00pt", with the macOS 26
  SDK;
- reading LC_VERSION_MIN_MACOSX, or 26.0 there, built for amd64: the
  corners message, with the macOS 26 SDK;
- the macOS version, asked with @available instead, built on 26.7.1 for
  amd64 and run on 15.8: the toolbar message, with the macOS 26 SDK.
Taking out the last commit's parts fails the macOS 26 SDK subtest or
TestMainWindowRightToLeft as before.

UIDesignRequiresCompatibility is checked by hand, not in a test: AppKit
reads it from an app bundle's Info.plist, LaunchServices registers each
bundle that runs (and keeps a temporary one after it is deleted), and in
a process run from a bundle a press sent within it began a window drag
in only 3 of 12 runs. On 26.7.1 the test program in a bundle whose
Info.plist sets the key has 12pt corners like every window there, and
keeps its toolbar; in a bundle without the key it has 16pt and no
toolbar, as when run on its own. With the key's check taken out, the
toolbar is taken off although AppKit gives the earlier design. The
bundles were unregistered (lsregister -u) and deleted.

go vet, the three builds, go test -tags nogui ./... and go test
./internal/gui/... pass. The real app wasn't run again.

* ci: run the checks again (waitingsnow)

test (macos-latest) failed in TestRelayKeepsClientAlive (internal/gateway, 1 ping in a 150ms gap), a timing test this PR doesn't touch; it passes on main and 5 times of 5 locally.
2026-10-13 09:55:23 +08:00

378 lines
13 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//go:build !nogui
package gui
import (
"cmp"
"log"
"os"
"runtime"
"sync"
"time"
"github.com/wailsapp/wails/v3/pkg/application"
"github.com/wailsapp/wails/v3/pkg/events"
"github.com/yetone/magpie/internal/omarchy"
"github.com/yetone/magpie/internal/settings"
)
// The windows, h.main and h.panel, are nil while lightweight mode has let
// them go (lightweight_rule.go). Both are read and set on the main thread
// only (application.InvokeSync, which runs at once when already on it), so
// a window is never used after it has gone. h.winMu is held, never on the
// main thread, around what has to reach a window from elsewhere and wait for
// the main thread itself (TintPanel's dispatch_sync), and around letting a
// window go.
// makeMain makes the main window, hidden, on url, with its hooks.
func (h *host) makeMain(url string) *application.WebviewWindow {
z := h.zoom()
// the window opens at the size it was last given, no smaller than its
// page's least at the text size (window_rule.go); maximised again, if it
// was: on Linux as it is made, elsewhere once it is first shown
// (placeMain)
minW, minH := windowMin(z, 0, 0)
width, height := openSize(settings.Load().Window, minW, minH)
state := application.WindowStateNormal
if runtime.GOOS == "linux" && settings.Load().WindowMaximised {
state = application.WindowStateMaximised
}
// Windows' title bar in the page's colour from the first frame; the
// page keeps it so as its theme changes (TintTitleBar)
winOpts, winBg := windowChrome(cmp.Or(os.Getenv("MAGPIE_THEME"), settings.Load().Theme))
w := h.app.Window.NewWithOptions(application.WebviewWindowOptions{
Name: "main",
Title: "magpie",
URL: url,
Width: width,
Height: height,
MinWidth: minW,
MinHeight: minH,
Zoom: z,
Hidden: true,
StartState: state,
Mac: mainMacWindow(),
Windows: winOpts,
BackgroundColour: winBg,
})
// A resize is kept once it settles (settle): the size, or that the
// window is maximised. Nothing is kept of a window not placed and shown
// yet (placeMain: a text size can resize it, unmaximised as yet), one
// let go (0×0), or one full screen or minimised, which keeps what was
// kept before it went so; nor, on Linux, of one hidden by then, since
// X11 drops a hidden window's maximised state.
var resized *time.Timer
w.OnWindowEvent(events.Common.WindowDidResize, func(*application.WindowEvent) {
if resized != nil {
resized.Stop()
}
resized = time.AfterFunc(500*time.Millisecond, func() {
if h.placed.Load() != w || w.IsFullscreen() || w.IsMinimised() || runtime.GOOS == "linux" && !w.IsVisible() {
return
}
wd, ht := w.Size()
if wd == 0 {
return
}
sw, sh := fitScreen(w)
if s := settings.Load(); settle(&s, wd, ht, sw, sh, w.IsMaximised()) {
settings.Save(s)
}
})
})
// Closing the window keeps the tray alive; quitting is a menu action.
// One lightweight mode lets go is closed for good.
w.RegisterHook(events.Common.WindowClosing, func(e *application.WindowEvent) {
if h.gone.Load() == w {
return
}
e.Cancel()
if closeStep(runtime.GOOS, w.IsFullscreen()) == closeLeaveFullscreen {
h.leaveFullscreenThenHide()
return
}
h.hideMain()
})
// Out of full screen, magpie leaves the Dock again if it was there only
// for that (dockOnFullscreen).
w.OnWindowEvent(events.Mac.WindowDidExitFullScreen, func(*application.WindowEvent) {
if h.closing.Swap(false) {
h.hideMain()
return
}
h.dock(settings.Load(), true)
})
return w
}
// makePanel makes the tray panel, at the height it last had, and hangs it
// on the tray icon.
func (h *host) makePanel() *application.WebviewWindow {
z := h.zoom()
po := panelOptions(runtime.GOOS, h.query)
po.Width, po.Height, po.Zoom = h.panelW(), cmp.Or(h.panelHeight, zoomed(panelStart, z)), z
w := h.app.Window.NewWithOptions(po)
if h.tray != nil {
h.tray.AttachWindow(w).WindowOffset(6)
}
// the icon stays lit while the panel is open (the Mac's)
trayOwnClicks()
w.OnWindowEvent(events.Mac.WindowShow, func(*application.WindowEvent) { trayHighlight(true) })
w.OnWindowEvent(events.Mac.WindowHide, func(*application.WindowEvent) { trayHighlight(false) })
// The system's close hides the panel, as Escape does: a title bar's X
// (KWin's, #1283), Alt+F4 or the window manager's close key. Closed, it
// was gone while the tray still opened it, and the icon did nothing
// until magpie restarted. One lightweight mode let go (no longer
// h.panel by then) is closed.
w.RegisterHook(events.Common.WindowClosing, func(e *application.WindowEvent) {
if !application.InvokeSyncWithResult(func() bool { return h.panel == w }) {
return
}
e.Cancel()
w.Hide()
if omarchy.Hyprland() {
go omarchy.StopClicks()
}
})
return w
}
// 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), 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())
}
if w.Name() == "panel" {
nameWindow(w, panelTitle)
ownFrame(w)
} else {
plainTitlebar(w)
}
}
// whenLoaded runs fn on the main thread once w can be shown: at once, but on
// Windows only once its page has come, since Wails shows a WebView2 window
// 3 s after Show whether or not its controller is made (see markReady).
func (h *host) whenLoaded(w *application.WebviewWindow, fn func()) {
if runtime.GOOS != "windows" {
fn()
return
}
// until then it isn't shown by anything else (openMain, togglePanelNow):
// a WebView2 window shown before its page has come is drawn black, and
// on a slow start can crash
if h.loading == nil {
h.loading = map[*application.WebviewWindow]bool{}
}
h.loading[w] = true
var once sync.Once
w.OnWindowEvent(events.Windows.WebViewNavigationCompleted, func(*application.WindowEvent) {
once.Do(func() {
application.InvokeAsync(func() {
delete(h.loading, w)
fn()
})
})
})
}
// lighten looks at the closed windows every lightEvery and lets go of one
// closed long enough while lightweight mode is on (#580).
func (h *host) lighten() {
<-h.ready
var ticks [2]int // the main window's, the panel's
for range time.Tick(lightEvery) {
on := settings.Load().Lightweight
var let []*application.WebviewWindow
h.winMu.Lock()
application.InvokeSync(func() {
for i, wp := range []**application.WebviewWindow{&h.main, &h.panel} {
w := *wp
if w == nil || h.loading[w] {
ticks[i] = 0
continue
}
var release bool
if ticks[i], release = lightStep(on, h.lightShown(w), ticks[i]); !release {
continue
}
ticks[i] = 0
dropWebView(w)
*wp = nil
if i == 0 {
h.gone.Store(w) // its closing hook lets it close
} else if h.tray != nil {
h.tray.AttachWindow(nil) // the untyped nil: no window
}
let = append(let, w)
}
})
h.winMu.Unlock()
for _, w := range let {
log.Printf("lightweight: the %s window's webview let go", w.Name())
w.Close()
}
}
}
// panelWin is the panel, made again if lightweight mode let it go; on the
// main thread. again says it was.
func (h *host) panelWin() (w *application.WebviewWindow, again bool) {
if h.panel == nil {
h.panel = h.makePanel()
h.madeAgain(h.panel)
return h.panel, true
}
return h.panel, false
}
// lightShown says whether lightweight mode keeps w: it is up (windowUp),
// or it is the main window leaving full screen to be closed; on the main
// thread. A window open under another app's was let go as closed, and
// Command-Tab back to magpie found it blank or gone (#1381).
func (h *host) lightShown(w *application.WebviewWindow) bool {
return windowUp(w) || w == h.main && h.closing.Load()
}
// mainShown says whether the main window is up (windowUp), covered or not;
// on the main thread.
func (h *host) mainShown() bool { return h.main != nil && windowUp(h.main) }
// openMain shows the main window on url ("" where it is), making it again
// if lightweight mode let it go; on the main thread.
func (h *host) openMain(url string) {
h.closing.Store(false) // opened again while leaving full screen: it stays
if h.panel != nil {
h.panel.Hide()
}
h.dock(settings.Load(), true)
if h.main == nil {
w := h.makeMain(cmp.Or(url, "/?"+h.query))
h.main = w
h.madeAgain(w)
h.whenLoaded(w, func() {
if h.main == w {
h.placeMain(w)
showHere(w)
}
})
return
}
if url != "" {
h.main.SetURL(url)
}
if h.loading[h.main] {
return // made again, it is shown once its page has come
}
h.placeMain(h.main)
showHere(h.main)
}
// reopenMain answers a click on magpie's Dock icon (#1252). A window that is
// open, on whichever Space, is left there, and magpie is activated as any
// app is: the Mac takes the user to the window's Space. One closed or
// minimised is shown as openMain shows it, on the Space the user is on.
func (h *host) reopenMain() {
if h.main == nil || h.loading[h.main] || !windowOpen(h.main) {
h.openMain("")
return
}
h.closing.Store(false) // reopened while leaving full screen: it stays
if h.panel != nil {
h.panel.Hide()
}
activateApp()
}
// spaceSettle is how long a window just shown keeps moving to the active
// Space: the Mac moves it once the order to the front is committed, after
// Show has returned, and not at all if the flag is gone by then.
const spaceSettle = 500 * time.Millisecond
// showHere shows w and makes it key on the Space the user is on, wherever it
// was last; on the main thread. It moves only while being shown: left on,
// activating magpie in any way (the Dock, Command-Tab) would pull the open
// window off its own Space onto the user's (#1252).
func showHere(w *application.WebviewWindow) {
setMovesToActiveSpace(w, true)
w.Show()
w.Focus()
time.AfterFunc(spaceSettle, func() {
application.InvokeAsync(func() { setMovesToActiveSpace(w, false) })
})
}
// placeMain puts the main window, made and not shown yet, as it was last
// left; on the main thread, before its first Show. On Windows, a size kept
// on a larger screen is fitted to this one's work area and centred: Windows
// doesn't, and the title bar would be out of reach. Then, if it was
// maximised, it is maximised again; on Linux it was made so (StartState),
// since GTK can't be asked about a window not shown yet.
//
// StartState can't do it elsewhere: on the Mac the window is centred after
// it is zoomed, and so isn't zoomed when shown; on Windows it shows the
// window before its page has come. Maximised while hidden, it zooms as it
// appears on the Mac, and Show (SW_SHOW) keeps it so on Windows. Restored,
// it goes back to the size it opened at. Wails' Maximise lets go of the
// window's least size until its own UnMaximise, which a restore from the
// Mac's title bar isn't; the least is put back at once. Before, too: the Mac
// makes a window a point short, under its least when its size is the
// least, and the resize to it then would stop the zoom.
//
// A Mac window larger than its screen is left to the Mac, which shows it
// fitted to the screen, and zoomed: zoomed here as well, it would restore
// to its own size, which the Mac fits to the screen again, so it couldn't
// be restored at all.
func (h *host) placeMain(w *application.WebviewWindow) {
if h.placed.Swap(w) == w || runtime.GOOS == "linux" {
return
}
if w.IsMaximised() {
return
}
wd, ht := w.Size()
sw, sh := h.mainRoom(w)
fw, fh, fitted := fitRoom(wd, ht, sw, sh)
if fitted && runtime.GOOS == "windows" {
w.SetSize(fw, fh)
w.Center()
fitted = false
}
if settings.Load().WindowMaximised && !fitted {
w.EnableSizeConstraints()
w.Maximise()
w.EnableSizeConstraints()
}
}
// mainRoom is the work area of the screen the main window is on, in the
// units of its Size, 0s when unknown: DIPs on Windows, points on the Mac,
// where GetScreen gives it in pixels (Wails' cScreenToScreen; the Screen
// manager's copy is laid out only once the app has finished launching,
// after the window may first be shown).
func (h *host) mainRoom(w *application.WebviewWindow) (int, int) {
switch runtime.GOOS {
case "windows":
return screenRoom(w)
case "darwin":
if s, err := w.GetScreen(); err == nil && s != nil && s.ScaleFactor > 0 {
return int(float32(s.WorkArea.Width) / s.ScaleFactor), int(float32(s.WorkArea.Height) / s.ScaleFactor)
}
}
return 0, 0
}
// fitScreen is the work area the main window is fitted to, in the units of
// its Size: Windows' (DIPs), 0s elsewhere — the Mac fits a window to its
// screen itself, and GTK's window manager does.
func fitScreen(w *application.WebviewWindow) (int, int) {
if runtime.GOOS != "windows" {
return 0, 0
}
return screenRoom(w)
}