gui: on Windows the header is the window's title bar (258a14 on X)

With a wallpaper, Windows' main window had a white native title bar over
the page, cut off from it ("内容区域和标题栏有割裂感"). On Windows the main
window is now frameless (mainFrameless), as the Mac's header already is
the title bar: the page and its wallpaper run to the top edge. Wails v3's
frameless window keeps WS_OVERLAPPEDWINDOW, so the shadow, Windows 11's
rounded corners, snap (Win+arrows, drag to an edge) and Wails' resize
edges stay. The header draws minimise, maximise/restore and close at its
right (#wincap, wincap.js, imported in that window alone), Windows-sized
with Segoe Fluent Icons, in the theme's colour, Close red on hover
(.1s ease); the header's refresh and pin sit left of them and stay
no-drag. A double click on what drags the window maximises or restores
it. The app tells the page when the window is (un)maximised (captionJS),
which swaps the glyph and its tooltip and keeps Wails' resize edges off
while maximised so the corner pixel is Close's. The buttons stay over a
dialog's scrim (wincap.js undoes modalBackground's inert on them). The
Mac, Linux, the tray panel and the web page are unchanged.

TestCoreScriptBudget: +27 on both budgets for the one import line in
app.js, past the 29 bytes of room there were; the rest lives in
wincap.js and app.css.

Run (mote, at this tree on origin/main 256910f17):
- gofmt -l clean; go vet ./internal/gui, GOOS=windows go vet
  ./internal/gui, go test -count=1 ./internal/gui: ok.
- Linux: go vet -tags gtk3 ./internal/gui on WSL magpie-desktop: ok
  (at the tree before the rebase).
- GUI: win-caption (new), brand, header-centre, header-zoom-fit,
  i18n-keys, modal-backdrop, providers-withdrawn, text-size,
  sidebar-overlay-scrollbar, both engines, every language: 125 ok,
  7 red, all red on origin/main too: header-centre webkit (#3479),
  modal-backdrop Linux window/panel (#6663), text-size webkit (#6561).
- A 47-file run of every GUI file the header, modal or Windows path
  reaches (mica, before the rebase): the same reds plus mobile-web
  (no .git in a run copy, #5013) and sidebar-overlay-scrollbar de
  webkit once (#1863, commented).
- Whole GUI suite (mica, load ~99): started at the pre-rebase tree and
  synced to the rebased one mid-run, so it isn't a clean record. Its
  reds in 28+ files match main's: 10 of those files alone on mote give
  the same 121 of 218 red at origin/main 256910f17 and at this tree
  (#6709, commented).
- Windows 11 on xiaomi-gpu, built from this tree, sandbox USERPROFILE,
  port 3461: screenshots light/dark with and without a wallpaper, and
  maximised; double click on the bar maximises and restores, max/restore
  and min buttons work (IsIconic true after min), Win+Left snapped to
  half the screen, Win+Up/Down maximise and restore.

Broken by hand: win-caption is red on the old assets (5 of 5 cases);
without wincap.js's MutationObserver it is red 10 of 10 ("the caption
buttons aren't" inert); #457's +0.5 in fitTop turns header-zoom-fit red.

Not tried: Windows 11's snap-layouts flyout over maximise (it needs
Wails' composition hosting, not shown); dragging the window and its
resize edges with a real mouse (a firewall prompt of another session's
magpie dims the desktop and swallows input; buttons and double click
were driven through CDP instead).
This commit is contained in:
yetone
2026-11-16 03:37:02 +08:00
parent 256910f174
commit dd77094ca2
14 changed files with 396 additions and 42 deletions
+1 -1
View File
@@ -35,7 +35,7 @@ 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`). A hidden macOS window keeps its WKWebView's page marked visible, so `hideWebview` tells the page it is out of sight before `orderOut`; that makes `document.hidden` and `visibilityState` true, stops the page's polling and frame loops, and pauses CSS animations. `showWebview` tells it it is visible again (#4293). 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`). On Windows a hidden window's WebView2 is put on its low memory target (`lowWhileHidden`, [`memtarget_windows.go`](../../internal/gui/memtarget_windows.go): `ICoreWebView2_19::put_MemoryUsageTargetLevel`, on each hide, on a page that comes while hidden, and back to normal on each show), so the panel and the window kept loaded in the tray stop holding what they last drew; the page stays loaded and running, unlike lightweight mode. In the tray the WebView2 processes' private working set went from ~170 MB to 20 to 40 MB, while their commit charge stayed where it was (molamaker11 on X). WKWebView and WebKitGTK have nothing magpie can set for it.
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. Where it was left is kept too, in `settings.WindowAt` (its top left corner across every screen, in the system's coordinates), so after a restart or an update it opens there rather than in the middle (jorbenzhu on Discord). `keepAt` saves it once a move or resize has rested for half a second, unless the window is maximised, full screen, minimised or hidden; `settings.Save` writes through temp and rename, and a settings file that can't be read is left alone. On its first show `placeMain` puts it back (`putBack`): `openAt` takes the screen holding most of the window, moves the window fully onto that screen's work area, and leaves it centred when no screen holds any of it, such as a monitor that is gone, or when the screens or the file can't be read (`TestOpenAt`). Under Wayland a window can't place itself, so nothing is kept or put back there unless GDK_BACKEND is x11 (`keepsPlace`, `TestKeepsPlace`). The pin in the window's title bar, between Refresh and Settings (`#pin`, `renderOnTop`; NovaStudiosss on X, to watch Usage and Routing while working in another app), keeps the window above other apps' windows: `POST /api/window/ontop?on=1` (or `0`) saves `settings.OnTop` (`SetOnTop`, this computer's own, kept through a Settings save) and calls `SetAlwaysOnTop`, and `makeMain` opens the window pinned when it is set. boot.js says whether there is a pin (`pin`, `pinnable` in `ontop.go`) and whether it is pressed (`onTop`) before the first paint. There is none in the panel, in a browser page or `magpie web`, or under Wayland (the same `keepsPlace`: GTK's keep-above does nothing there), and the route refuses there with 400 and saves nothing (`TestPinKeepsWindowOnTop`, `TestPinRefusedWithoutAWindowToPin`, `window-pin.test.cjs`). The tray's panel isn't kept: on the Mac and Windows it opens under the tray icon, and on Linux where the click was.
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 where it doesn't change the corners: in the earlier design, and on macOS 27, which gives a window with a toolbar a plain title bar's 16pt corners (`toolbarRounder` holds the window's radius against a window of its style with no toolbar, never shown); 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.
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 where it doesn't change the corners: in the earlier design, and on macOS 27, which gives a window with a toolbar a plain title bar's 16pt corners (`toolbarRounder` holds the window's radius against a window of its style with no toolbar, never shown); 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. On Windows the main window is frameless (`mainFrameless` in [`mainwindow.go`](../../internal/gui/mainwindow.go)), so a wallpaper or the page's colour runs to its top instead of stopping under a separate strip (258a14 on X). Wails keeps the frame's styles, so it still has its shadow and Windows 11's rounded corners, and snaps with Win+arrows and by dragging to a screen's edge. The page draws the caption buttons at the header's right (`#wincap`, shown by app.css under `html.win` from `layout.js` in the window and not on the web, run by `wincap.js`, which app.js imports in that window alone, Segoe Fluent Icons' glyphs, Close red on hover); they minimise, maximise or restore, and close (hide; the tray stays), and stay over a dialog's scrim (`wincap.js` undoes the `inert` that `modalBackground` sets on them). The header's own tools sit left of them. A double click on anything that drags the window maximises or restores it. The app tells the page whether the window is maximised (`captionJS`, on Wails' runtime ready and on a resize that changes it), which swaps maximise for restore and keeps Wails' resize edges inside the page off while maximised, so the top-right pixel is Close's (`TestCaptionKeepsEdgesOffWhileMaximised`, `win-caption.test.cjs`). Windows 11's snap layouts flyout over maximise isn't shown: it needs Wails' composition hosting (`--wails-non-client-region`), which forwards input by `SendMouseInput` only. The panel keeps its own window as before.
8. On the Mac, Settings › Show in Dock puts magpie in the Dock never (`DockNever`), while the window is open (the default; `DockWindow` records it chosen, for an older magpie that took none for never) or always (`Dock`, which wins). The default was never until ShouguangCao on X found the open window out of Command-Tab, so going back to it to paste a key copied elsewhere took the menu bar; a new install (no settings.json) reads With window, and Hide is a choice of its own (`inDock`, `dockChoice` in app.js, `TestDockFollowsWindowByDefault`, `dock-choice.test.cjs`). A file written before that has no `dockSettled`, and stored Hide as nothing, so a user who chose Hide can't be told from one who never chose: such a file with no Dock choice reads as Hide, and the first save writes it so with `dockSettled` (`settleDock`, `TestOlderSettingsKeepHide`, `TestNewInstallFollowsWindow`). A file nobody can read reads the same way. The page never sends `dockSettled`; the save keeps the file's (`TestSettingsSaveKeepsDockReading`). It is this computer's own, as the Dock choice is (`KeepOwn`). 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).
9. Settings › General › Quick panel shortcut binds a key combination that opens the tray's panel from any app (ben hanks on Discord); none is set by default. The page records the keys and posts them to `POST /api/settings/panel-shortcut`, which checks them (`panelShortcut`: a letter, digit, Space or F1–F20 with Ctrl, Alt/Option or Cmd/Super, or an F key alone, written as Wails' accelerator), has the running app bind them (`onPanelShortcut`, `bindPanelKey` through Wails' `GlobalShortcut`: Carbon's hot keys on the Mac, `RegisterHotKey` on Windows, `XGrabKey` on X11) and saves them only once bound. One the system refuses (on Windows and X11, another app holding it) is not saved and the old one stays bound; one saved but refused as magpie starts is retried after a handed-over magpie exits and else said in the row (`panelKeysJSON.Taken`). A pressed shortcut toggles the panel as a tray click does (`togglePanel`). The Mac's Carbon hot keys don't refuse a combination another app registered too, so there both are taken and magpie can't tell the user. The shortcut is per computer (`KeepOwn`), and the Mac's old process lets go of it as it hands over (`leaveMenuBar`). On Wayland no app may grab keys itself, so the field is off and the row says the command to bind in the desktop's own keyboard settings (`magpie panel`); Wails' GlobalShortcuts portal is not used, since the compositor decides its keys and Hyprland binds none unless configured. From there a not-connected Claude Code's or Codex's opened row switches its account (shuizhuyu on X, [Switch accounts only](providers-accounts.md)).
10. A click on the tray icon opens the quick panel, or the main window when Settings › General › Click the tray icon to says so. The panel opens the main window from one control, on its edge nearest the tray (isaac_bai on Discord): hung below its icon (the Mac's menu bar, a taskbar or bar at the top) it is the header's icon (`#open`, named "Open the main window"); standing above it (Windows' taskbar at the bottom, a bottom panel on Linux) it is the foot's "Open the main window" left of Quit (`#openMain`), and the header has no icon. The two are never shown together (yogurt36 on Discord). Once `togglePanelNow` has placed and shown the panel, `tellPanelSide` reads the panel's bounds and its screen's and sends `magpiePanelOpenAt("foot")` when the panel is nearer the screen's bottom, `"head"` otherwise (`panelOpenAt`; the Mac is always `head`). Under Wayland a window can't read where the compositor put it, and until the app says, layout.js sets `body[data-open-at]` by the system: `foot` on Windows, `head` elsewhere ([`panelside.go`](../../internal/gui/panelside.go), `TestPanelOpensTheWindowFromTheEdgeNearestTheTray`, `panel-open-once.test.cjs`). On Windows a double-click on the icon opens the main window too (isaac_bai on Discord): Wails passes the icon's `WM_LBUTTONDBLCLK` on as `OnDoubleClick`, the panel its first click opened is hidden by `openMain`, and the `WM_LBUTTONUP` that ends the double-click is swallowed once (`trayDouble`, within `trayDoubleRelease`) so it does not open the panel over the window. The Mac's status item calls its action on each mouse-down with no click count, and Linux's StatusNotifierItem has only `Activate`, so there a double-click is two clicks and is left as such (`trayDoubleClicks`, `TestTrayDoubleClickOpensTheWindowOnWindowsOnly`, `TestTrayDoubleClickReleaseSwallowedOnce`; [`traydouble.go`](../../internal/gui/traydouble.go)).
+14 -1
View File
@@ -231,7 +231,20 @@ code { font: var(--code-style, normal) var(--code-weight, 400) 11.5px var(--code
body.window.mac .top { padding-left: calc(96px / var(--zoom, 1)); height: calc(50px / var(--zoom, 1)); padding-top: calc(2px / var(--zoom, 1)); }
body.window.mac .seg { top: calc(50% + 1px / var(--zoom, 1)); } /* 50% centres in the padding box; the 2px top padding puts the flex row a pixel lower */
.brand { display: flex; align-items: center; gap: 6px; font-weight: 600; letter-spacing: .01em; }
body.window:not(.mac):not(.linux):not(.web) .brand { display: none; } /* Windows' title bar above already shows the icon and the name; a browser tab has no title bar of the app's */
/* Windows' window (html.win from layout.js; not the panel, not the web):
the header is the title bar (mainwindow.go mainFrameless), its caption
buttons fixed at its right as Windows places them, the header's own
tools left of them; over a dialog's backdrop too, so the window can
always be closed or moved aside; at Windows' own size whatever the text
size, as the Mac's traffic lights */
.wincap { display: none; }
.win body.window:not(.web) .top { padding-right: calc(146px / var(--zoom, 1)); }
.win body.window:not(.web) .wincap { display: flex; position: fixed; z-index: 40; top: 0; right: 0; height: var(--top-h, 46px); }
.wincap button { width: calc(46px / var(--zoom, 1)); height: 100%; display: grid; place-items: center; padding: 0; border: 0; border-radius: 0; background: transparent; color: var(--fg); font: calc(10px / var(--zoom, 1)) "Segoe Fluent Icons", "Segoe MDL2 Assets", sans-serif; transition: background-color .1s ease, color .1s ease; }
.wincap button:hover { background: color-mix(in srgb, var(--fg) 9%, transparent); }
.wincap button:active { background: color-mix(in srgb, var(--fg) 6%, transparent); color: color-mix(in srgb, var(--fg) 70%, transparent); }
.wincap button[data-cap="close"]:hover { background: #c42b1c; color: #fff; }
.wincap button[data-cap="close"]:active { background: color-mix(in srgb, #c42b1c 90%, transparent); color: rgba(255, 255, 255, .7); }
/* app.js removes these controls later; keep them out of the first paint too. */
body.window :is(#open, #openMain, #quit),
/* one control opens the main window, on the panel's edge nearest the tray
+3
View File
@@ -23636,6 +23636,9 @@ $(".top").addEventListener("dblclick", (e) => {
if (mode === "window") { $("#open").remove(); $("#openMain").remove(); $("#quit").remove(); }
else { $("#nav").remove(); $("#side").remove(); }
if (mode !== "window" || !document.body.classList.contains("linux")) $("#winclose").remove();
// Windows' window (html.win, body.window, not the web): the header is its
// title bar, with the caption buttons wincap.js runs
if ($(".win .window:not(.web)")) import("./wincap.js");
// The title bar's pin keeps the window above other apps' windows, for Usage
// or Routing watched while working elsewhere (NovaStudiosss on X): in the
+12
View File
@@ -2042,6 +2042,9 @@ const I18N = {
"Models: {models}": "模型:{models}",
"No models match “{q}”": "没有和“{q}”匹配的模型",
"Close": "关闭",
"Minimize": "最小化",
"Maximize": "最大化",
"Restore Down": "向下还原",
"Vendors": "供应商",
"the makers' own APIs": "模型厂商的 API",
"Subscriptions": "订阅",
@@ -7372,6 +7375,9 @@ const I18N = {
"Models: {models}": "模型:{models}",
"No models match “{q}”": "沒有和「{q}」匹配的模型",
"Close": "關閉",
"Minimize": "最小化",
"Maximize": "最大化",
"Restore Down": "向下還原",
"Vendors": "供應商",
"the makers' own APIs": "模型廠商的 API",
"Subscriptions": "訂閱",
@@ -12675,6 +12681,9 @@ const I18N = {
"Models: {models}": "モデル:{models}",
"No models match “{q}”": "「{q}」に一致するモデルはありません",
"Close": "閉じる",
"Minimize": "最小化",
"Maximize": "最大化",
"Restore Down": "元に戻す (縮小)",
"Vendors": "ベンダー",
"the makers' own APIs": "メーカー自身の API",
"Subscriptions": "サブスクリプション",
@@ -18009,6 +18018,9 @@ const I18N = {
"Models: {models}": "Modelle: {models}",
"No models match “{q}”": "Keine Modelle passen zu „{q}“",
"Close": "Schließen",
"Minimize": "Minimieren",
"Maximize": "Maximieren",
"Restore Down": "Verkleinern",
"Vendors": "Anbieter",
"the makers' own APIs": "die eigenen APIs der Hersteller",
"Subscriptions": "Abos",
+8
View File
@@ -114,6 +114,14 @@
</button>
</div>
</header>
<!-- Windows: the header is the window's title bar (app.css .wincap), and
these are its minimise, maximise and close, drawn as Windows draws
them (app.js magpieCaption) -->
<div class="wincap" id="wincap" style="--wails-draggable:no-drag">
<button type="button" data-cap="min" data-tt="Minimize" tabindex="-1">&#xE921;</button>
<button type="button" data-cap="max" data-tt="Maximize" tabindex="-1">&#xE922;</button>
<button type="button" data-cap="close" data-tt="Close" tabindex="-1">&#xE8BB;</button>
</div>
<nav class="ptabs" id="ptabs" hidden>
<button type="button" data-ptab="agents"><span data-t>Agents</span><em id="ptabN"></em></button>
+27
View File
@@ -0,0 +1,27 @@
// Windows' caption buttons (258a14 on X): the main window there is
// frameless (mainwindow.go mainFrameless), its header the title bar, and
// these minimise, maximise or restore, and close: hide, the tray stays.
// The app says whether the window is maximised (mainwindow.go captionJS),
// and maximise turns into restore. A double click on what drags the window
// maximises or restores it, as on a title bar. app.js imports this in the
// Windows window alone, so it weighs nothing on the core.
const cap = $("#wincap");
// over a dialog's backdrop too, so the window can always be closed or
// moved aside: what modalBackground makes inert, these undo
new MutationObserver(() => cap.inert = false).observe(cap, { attributeFilter: ["inert"] });
const act = { min: (w) => w.Minimise(), max: (w) => w.ToggleMaximise(), close: (w) => w.Close() };
cap.onclick = (e) => {
const b = e.target.closest("button[data-cap]");
if (b) winRuntime.then((w) => w && act[b.dataset.cap](w.Window));
};
window.magpieCaption = (m) => {
const b = cap.querySelector('[data-cap="max"]');
b.textContent = m ? "\uE923" : "\uE922";
b.dataset.enTitle = m ? "Restore Down" : "Maximize";
b.title = t(b.dataset.enTitle);
};
if (window.magpieMaximised !== undefined) window.magpieCaption(window.magpieMaximised);
document.addEventListener("dblclick", (e) => {
if (e.button !== 0 || !(e.target instanceof Element) || e.target.closest("button, a, input, textarea, select, nav, [contenteditable]")) return;
if (getComputedStyle(e.target).getPropertyValue("--wails-draggable").trim() === "drag") winRuntime.then((w) => w?.Window.ToggleMaximise());
});
File diff suppressed because one or more lines are too long
+16 -2
View File
@@ -8,6 +8,7 @@ import (
"os"
"runtime"
"sync"
"sync/atomic"
"time"
"github.com/wailsapp/wails/v3/pkg/application"
@@ -55,6 +56,7 @@ func (h *host) makeMain(url string) *application.WebviewWindow {
Hidden: true,
StartState: state,
AlwaysOnTop: onTop,
Frameless: mainFrameless(runtime.GOOS),
Mac: mainMacWindow(),
Windows: winOpts,
BackgroundColour: winBg,
@@ -62,8 +64,20 @@ func (h *host) makeMain(url string) *application.WebviewWindow {
h.zoomWhenLoaded(w)
lowWhileHidden(w)
h.mendWebView(w)
if runtime.GOOS == "windows" {
w.OnWindowEvent(events.Common.WindowRuntimeReady, func(*application.WindowEvent) { w.ExecJS(frameOnlyResizeJS) })
if mainFrameless(runtime.GOOS) {
// the page's caption buttons follow the window's maximised state
// (captionJS); a resize that changes it says so, once
var maxed atomic.Bool
w.OnWindowEvent(events.Common.WindowRuntimeReady, func(*application.WindowEvent) {
m := w.IsMaximised()
maxed.Store(m)
w.ExecJS(captionJS(m))
})
w.OnWindowEvent(events.Common.WindowDidResize, func(*application.WindowEvent) {
if m := w.IsMaximised(); maxed.Swap(m) != m {
w.ExecJS(captionJS(m))
}
})
}
// 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
+22 -12
View File
@@ -3,6 +3,7 @@
package gui
import (
"fmt"
"time"
"github.com/wailsapp/wails/v3/pkg/application"
@@ -30,18 +31,27 @@ func mainMacWindow() application.MacWindow {
}
}
// frameOnlyResizeJS leaves resizing the main window on Windows to its own
// frame. Wails' page script arms a resize along every edge inside the page
// (SM_CYSIZEFRAME pixels, its drag.ts) whenever the window is resizable on
// Windows, frame or no frame; meant for a frameless window, in the framed
// main window it made the top of the page, under the title bar, drag the
// window's height too (shangyuan0818 on Discord). Its switch is turned off,
// and kept off: Wails turns it on again once its script is ready, which may
// come before this or after. Linux and the Mac never arm it on a framed
// window.
const frameOnlyResizeJS = `(()=>{const w=window._wails;if(!w||typeof w.setResizable!=="function")return;` +
`if(!w.setResizable.frameOnly){const f=w.setResizable;w.setResizable=()=>f(false);w.setResizable.frameOnly=true}` +
`w.setResizable(false)})();`
// mainFrameless: the main window on Windows has no title bar of its own.
// The page's header is its title bar, as on the Mac, so a wallpaper or the
// page's colour runs to the top of the window instead of under a separate
// strip (258a14 on X); the page draws minimise, maximise and close
// (#wincap). Wails keeps the frame's styles, so the window still snaps,
// casts its shadow and has rounded corners on Windows 11.
func mainFrameless(goos string) bool { return goos == "windows" }
// captionJS tells the page whether the window is maximised, and keeps
// Wails' resize edges inside the page off while it is. A frameless window
// is resized by those edges (SM_CYSIZEFRAME pixels, Wails' drag.ts), which
// Wails arms whenever the window is resizable; maximised, they would take
// the top-right pixel from Close and the top row from the header's drag.
// Wails turns them on again once its script is ready, which may come
// before this or after, so its switch is wrapped once and remembers what
// it was last asked.
func captionJS(maximised bool) string {
return fmt.Sprintf(`(()=>{const m=%t;window.magpieMaximised=m;const w=window._wails;`+
`if(w&&typeof w.setResizable==="function"){if(!w.setResizable.edges){const f=w.setResizable,g=v=>{g.on=v;f(!!v&&!window.magpieMaximised)};g.edges=true;g.on=true;w.setResizable=g}w.setResizable(w.setResizable.on)}`+
`if(typeof window.magpieCaption==="function")window.magpieCaption(m)})();`, maximised)
}
type closeAction int
+41 -14
View File
@@ -3,6 +3,7 @@
package gui
import (
"fmt"
"os"
"os/exec"
"strings"
@@ -141,25 +142,51 @@ func TestClosingHidesShownAccounts(t *testing.T) {
}
}
// shangyuan0818 on Discord: on Windows the top of the page, under the
// title bar, resized the window's height as its frame does. Wails' page
// script arms that edge whenever it is told the window is resizable, which
// Wails says once its script is ready, before or after magpie's hook runs;
// either way, and with the hook run twice, the edge stays off. Its stand-in
// here keeps what each setResizable call said, as drag.ts does.
func TestFrameOnlyResizeStaysOff(t *testing.T) {
// The main window on Windows has no title bar of its own; the page's header
// is its title bar (258a14 on X: a wallpaper stopped under a white strip).
// Linux and the Mac keep theirs.
func TestMainWindowFramelessOnWindowsOnly(t *testing.T) {
for goos, want := range map[string]bool{"windows": true, "darwin": false, "linux": false} {
if got := mainFrameless(goos); got != want {
t.Errorf("mainFrameless(%q) = %v, want %v", goos, got, want)
}
}
src, err := os.ReadFile("lightweight.go")
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(src), "Frameless: mainFrameless(runtime.GOOS),") {
t.Error("makeMain doesn't make the main window by mainFrameless")
}
}
// A frameless window is resized by Wails' edges inside the page, which
// Wails arms once its script is ready, before or after magpie's hook runs.
// Restored, they stay on, so the window can be resized; maximised, they
// stay off whichever came first and however often, so the top-right pixel
// is Close's and the top row drags. The page hears the state each time.
// The stand-in keeps what each setResizable call said, as drag.ts does.
func TestCaptionKeepsEdgesOffWhileMaximised(t *testing.T) {
node, err := exec.LookPath("node")
if err != nil {
t.Fatal("node is needed to run the page's script: ", err)
}
stub := `const said=[];window._wails={setResizable:v=>said.push(v)};`
stub := `const said=[],heard=[];window._wails={setResizable:v=>said.push(v)};window.magpieCaption=m=>heard.push(m);`
ready := `window._wails.setResizable(true);` // what Wails runs once its script is ready
last := `if(said.at(-1)!==false){console.log(JSON.stringify(said));process.exit(1)}`
expect := func(edges, m bool) string {
return fmt.Sprintf(`if(said.at(-1)!==%t||heard.at(-1)!==%t||window.magpieMaximised!==%t){console.log(JSON.stringify({said,heard}));process.exit(1)}`, edges, m, m)
}
max, restored := captionJS(true), captionJS(false)
for name, js := range map[string]string{
"hook after Wails": stub + ready + frameOnlyResizeJS + last,
"hook before Wails": stub + frameOnlyResizeJS + ready + last,
"hook twice": stub + frameOnlyResizeJS + frameOnlyResizeJS + ready + ready + last,
"no runtime": `const window={};` + frameOnlyResizeJS,
"maximised, hook after Wails": stub + ready + max + expect(false, true),
"maximised, hook before Wails": stub + max + ready + expect(false, true),
"maximised, hook twice": stub + max + max + ready + ready + expect(false, true),
"restored, hook after Wails": stub + ready + restored + expect(true, false),
"restored, hook before Wails": stub + restored + ready + expect(true, false),
"restored after maximised": stub + ready + max + restored + expect(true, false),
"maximised after restored": stub + ready + restored + max + expect(false, true),
"Wails says not resizable": stub + restored + `window._wails.setResizable(false);` + restored + expect(false, false),
"no runtime": `const window={};` + max,
} {
script := "const window=globalThis;" + js
if name == "no runtime" {
@@ -167,7 +194,7 @@ func TestFrameOnlyResizeStaysOff(t *testing.T) {
}
out, err := exec.Command(node, "-e", script).CombinedOutput()
if err != nil {
t.Errorf("%s: the page's edge is armed: %v %s", name, err, out)
t.Errorf("%s: %v %s", name, err, out)
}
}
}
+2 -2
View File
@@ -2,7 +2,7 @@
// The header's logo and name: in `magpie web` they're shown whatever the
// machine, since a browser tab has no title bar of the app's to show them
// (they were hidden everywhere but a Mac or Linux window); in the Windows
// window they stay hidden, its title bar already has them.
// window too, whose header is its title bar now (258a14 on X).
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
@@ -33,7 +33,7 @@ const cases = [
{ web: true, platform: "Win32", shown: true },
{ web: true, platform: "MacIntel", shown: true },
{ web: true, platform: "Linux x86_64", shown: true },
{ web: false, platform: "Win32", shown: false },
{ web: false, platform: "Win32", shown: true },
{ web: false, platform: "MacIntel", shown: true },
];
+12 -6
View File
@@ -41,8 +41,10 @@ const settled = (page) => page.evaluate(() => new Promise((r) => requestAnimatio
const header = (page) => page.evaluate(() => {
const top = document.querySelector(".top"), r = top.getBoundingClientRect();
const n = document.querySelector("#nav").getBoundingClientRect(), a = document.querySelector(".actions").getBoundingClientRect();
// the layout's button, shown, is what the tabs sit after
const lead = document.querySelector("#sideToggle"), from = lead.offsetParent ? lead.getBoundingClientRect().right : r.left;
// what the tabs sit after, as fitTop finds it: the brand where it shows
// (Windows' header is its title bar, 258a14 on X), else the layout's button
const lead = [document.querySelector(".brand"), document.querySelector("#sideToggle")].find((e) => e.offsetParent);
const from = lead ? lead.getBoundingClientRect().right : r.left;
return {
cls: top.className, update: !document.querySelector("#update").hidden,
off: n.left + n.width / 2 - innerWidth / 2, left: n.left - from, right: a.left - n.right,
@@ -58,10 +60,12 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
if (errors.length) console.log(errors);
await browser.close();
});
for (const lang of ["zh", "en"]) for (const zoom of [1, 1.1, 1.25]) {
await t.test(`${lang} at ${Math.round(zoom * 100)}%`, async () => {
// Windows, whose header is its title bar with the caption buttons at its
// right (258a14 on X), and Linux, whose header has nothing past its own
for (const platform of ["Win32", "Linux x86_64"]) for (const lang of ["zh", "en"]) for (const zoom of [1, 1.1, 1.25]) {
await t.test(`${platform} ${lang} at ${Math.round(zoom * 100)}%`, async () => {
const ctx = await browser.newContext({ viewport: { width: Math.round(1100 / zoom), height: 600 }, deviceScaleFactor: zoom });
await ctx.addInitScript(() => { Object.defineProperty(Navigator.prototype, "platform", { get: () => "Win32" }); });
await ctx.addInitScript((p) => { Object.defineProperty(Navigator.prototype, "platform", { get: () => p }); }, platform);
const page = await ctx.newPage();
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", server(lang));
@@ -88,7 +92,9 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
// the closer tabs are tried in the middle before the row
if (h.cls.includes("cramped") && !h.cls.includes("inrow")) middle += 1000;
}
assert(middle > 1000, `the closer tabs were never in the middle (${middle})`);
// Windows' caption buttons leave English no width where the closer
// tabs fit in the middle: they go from the middle to the row
if (!(platform === "Win32" && lang === "en")) assert(middle > 1000, `the closer tabs were never in the middle (${middle})`);
assert(inrow > 0, "the narrowest windows never put the tabs in the row");
await ctx.close();
});
+24 -2
View File
@@ -9,7 +9,7 @@
// has no page zoom to set, so it is the device scale factor there. A Windows
// window is swept from 1300 to 700 points at 110 and 125%, with an Update
// pill waiting: a wider window is never drawn in more than a narrower one,
// and with room to spare the header is as at 100%. English and Chinese; no
// and a header with a pixel to spare is as at 100%. English and Chinese; no
// backend, the API is faked here.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
@@ -55,11 +55,28 @@ async function zoomed(engine, zoom, t) {
}
const settled = (page) => page.evaluate(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r))));
// whether the whole header, none of it drawn in, fits with a pixel to spare
// either side of the tabs, the buttons against the padding give or take
// #457's hair; Windows' caption buttons sit in the
// header's right padding (258a14 on X), so no fixed window width says it
const room = (page) => page.evaluate((all) => {
const top = document.querySelector(".top"), was = top.className;
top.classList.remove(...all);
const shown = (s) => { const e = document.querySelector(s); return e && e.offsetParent ? e : null; };
const r = top.getBoundingClientRect(), a = document.querySelector(".actions").getBoundingClientRect();
const n = document.querySelector("#nav").getBoundingClientRect();
const lead = shown("#navBack") || shown(".brand") || shown("#sideToggle");
const left = lead ? lead.getBoundingClientRect().right : r.left + parseFloat(getComputedStyle(top).paddingLeft);
const ok = a.right <= r.right - parseFloat(getComputedStyle(top).paddingRight) + 0.5 && left + 9 <= n.left && n.right + 9 <= a.left;
top.className = was;
return ok;
}, STEPS);
const steps = (page) => page.evaluate((all) => all.filter((c) => document.querySelector(".top").classList.contains(c)).length, STEPS);
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(engine + ": a zoomed header with room is drawn as at 100%", async (t) => {
assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit");
let roomy = 0;
for (const lang of ["zh", "en"]) for (const zoom of [1.1, 1.25]) {
await t.test(`${lang} at ${Math.round(zoom * 100)}%`, async (t) => {
const ctx = await zoomed(engine, zoom, t);
@@ -78,7 +95,11 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
await page.setViewportSize({ width: engine === "webkit" ? Math.round(w / zoom) : w, height: 600 });
await settled(page);
const n = await steps(page), at = `${w}pt: ${await page.evaluate(() => document.querySelector(".top").className)}`;
if (w >= 1200) assert.equal(n, 0, "the header is drawn in with room to spare at " + at);
// beside the sidebar the header has no tabs to fit
if (!await page.evaluate(() => document.body.classList.contains("side-nav")) && await room(page)) {
roomy++;
assert.equal(n, 0, "the header is drawn in with room to spare at " + at);
}
assert(n >= last, "a wider window is drawn in more than a narrower one at " + at);
last = n;
}
@@ -86,5 +107,6 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
assert.deepEqual(errors, []);
});
}
assert(roomy > 0, "no window had room for the whole header");
});
}
+212
View File
@@ -0,0 +1,212 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// 258a14 on X: with a wallpaper, Windows' own white title bar sat over the
// page, cut off from it. The main window on Windows is frameless now
// (mainwindow.go mainFrameless) and its header is the title bar, as on the
// Mac: the page draws minimise, maximise and close at its right (#wincap).
// They sit in the header's height at the window's top-right corner, cover
// none of the header's own tools (search, refresh, pin, Settings), stay
// clicks while the rest of the bar drags, stay reachable over a dialog, and
// call the window's own Minimise, ToggleMaximise and Close. Maximise turns
// into restore when the app says the window is maximised (captionJS). A
// double click on what drags maximises. The Mac, Linux, the panel and a
// browser page show none. No backend: Wails' runtime is a stand-in that
// keeps what it was asked.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const assets = path.resolve(__dirname, "../assets");
function serve(lang, web) {
const settings = { theme: "light", lang, tray: "panel", currency: "usd" };
const relay = { id: "relay", name: "Relay", icon: "generic", host: "relay.test", chat: "https://relay.test/v1",
responses: "", anthropic: "", models: [{ id: "fixture-model", name: "Fixture model", on: true }], agents: [], fallback: [], headers: {},
key: { set: true, masked: "sk-…1234" }, keyList: [], ready: true };
return async (route) => {
const url = new URL(route.request().url());
const json = (data) => route.fulfill({ json: data });
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:${web},pin:true,onTop:false};` });
if (url.pathname === "/wails/runtime.js") {
return route.fulfill({ contentType: "text/javascript", body: "window.__calls = []; const say = (n) => () => { window.__calls.push(n); return Promise.resolve(); };" +
"export const Window = { Minimise: say('Minimise'), ToggleMaximise: say('ToggleMaximise'), Close: say('Close'), IsMaximised: () => Promise.resolve(false) }; window.__runtimeReady = true;" });
}
if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings });
if (url.pathname === "/api/settings") return json(settings);
if (url.pathname === "/api/providers") return json({ providers: [relay], presets: [], excluded: [], gateway: { running: true, window: true } });
if (url.pathname === "/api/usage/quotas") return json([]);
if (url.pathname === "/api/usage") return json({ days: [] });
if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
if (url.pathname === "/api/plugins") return json({ plugins: [] });
if (url.pathname === "/api/library") return json({ dir: "/home/u/.magpie/library", backups: "/home/u/.magpie/backups", home: "/home/u", agents: [],
instructions: { agents: [], sets: [] }, foundServers: [], projects: [], foundSkills: [], skills: [], servers: [] });
if (url.pathname.startsWith("/api/")) return json({});
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); }
};
}
const MAXIMIZE = { en: "Maximize", zh: "最大化", "zh-TW": "最大化", ja: "最大化", de: "Maximieren" };
const RESTORE = { en: "Restore Down", zh: "向下还原", "zh-TW": "向下還原", ja: "元に戻す (縮小)", de: "Verkleinern" };
// every control the bar shows (the header's, and a page's tools pinned in
// it beside the sidebar): where it is, and whether it drags
function barControls(page) {
return page.evaluate(() => {
const top = document.querySelector("header.top").getBoundingClientRect();
return [...document.querySelectorAll("header.top :is(button, input, a, [role=tab]), .pv-head :is(button, input), .lib-head :is(button, input), .pm-head :is(button, input), .set-head :is(button, input, [role=tab])")]
.filter((e) => e.getClientRects().length && getComputedStyle(e).visibility !== "hidden")
.map((e) => {
// a narrow header's tabs scroll in their own box (app.css .packed):
// what is out of it is not there to click
const r = e.getBoundingClientRect(), clip = e.closest("#nav")?.getBoundingClientRect();
const left = clip ? Math.max(r.left, clip.left) : r.left, right = clip ? Math.min(r.right, clip.right) : r.right;
return { e, r, left, right };
})
.filter(({ r, left, right }) => right - left > 4 && r.top < top.bottom && r.bottom > 0)
.map(({ e, r, left, right }) => ({ id: e.id || e.getAttribute("aria-label") || e.className || e.tagName, cls: String(e.className), left, right,
hit: (() => { const h = document.elementFromPoint((left + right) / 2, r.top + r.height / 2); return !!h && (h === e || e.contains(h)); })(),
drag: getComputedStyle(e).getPropertyValue("--wails-draggable").trim() }));
});
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
test(`${engine} ${lang}: Windows' header is the title bar, with its caption buttons`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(async () => { await browser.close(); });
const open = async ({ platform = "Win32", mode = "window", web = false, width = 1100, view = "providers" } = {}) => {
const context = await browser.newContext({ viewport: { width, height: 700 }, reducedMotion: "reduce" });
await context.addInitScript((p) => Object.defineProperty(Navigator.prototype, "platform", { get: () => p }), platform);
const page = await context.newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", serve(lang, web));
await page.goto(`http://magpie.test/?mode=${mode}`);
await page.waitForFunction(() => document.querySelector("header.top"));
if (!web) await page.waitForFunction(() => window.__runtimeReady === true);
if (mode === "window") await page.waitForSelector("#nav button.on");
if (mode === "window" && view !== "agents") {
await page.evaluate((v) => show(v), view);
await page.waitForSelector(`#view-${view}:not([hidden])`);
}
await page.waitForTimeout(300);
return { page, errors, context };
};
for (const width of [1100, 640]) for (const view of ["providers", "library", "plugins", "settings"]) {
const where = `${width}px ${view}`;
const { page, errors, context } = await open({ width, view });
const cap = await page.evaluate(() => {
const c = document.querySelector("#wincap"), top = document.querySelector("header.top").getBoundingClientRect();
if (!c || !c.getClientRects().length) return null;
return { top: top.height, drag: getComputedStyle(c).getPropertyValue("--wails-draggable").trim(),
buttons: [...c.querySelectorAll("button")].map((b) => { const r = b.getBoundingClientRect(); const h = document.elementFromPoint(r.left + r.width / 2, r.top + r.height / 2);
return { cap: b.dataset.cap, left: r.left, right: r.right, top: r.top, bottom: r.bottom, title: b.title, glyph: b.textContent, hit: h === b }; }) };
});
assert.ok(cap, `${where}: the caption buttons show`);
assert.deepEqual(cap.buttons.map((b) => b.cap), ["min", "max", "close"], `${where}: minimise, maximise, close`);
assert.equal(cap.drag, "no-drag", `${where}: the caption buttons are clicks, not the window's drag`);
const [min, , close] = cap.buttons;
assert.ok(Math.abs(close.right - width) < 0.5 && close.top === 0, `${where}: close is at the window's top-right corner: ${JSON.stringify(close)}`);
for (const b of cap.buttons) {
assert.ok(b.hit, `${where}: ${b.cap} is under the pointer, nothing over it`);
assert.ok(b.top === 0 && Math.abs(b.bottom - cap.top) < 0.5, `${where}: ${b.cap} fills the header's height: ${JSON.stringify(b)} in ${cap.top}`);
}
assert.equal(cap.buttons[1].title, MAXIMIZE[lang], `${where}: maximise's tooltip in ${lang}`);
assert.equal(cap.buttons[1].glyph, "");
// the header's own tools are left of the caption buttons and stay clicks
const controls = await barControls(page);
assert.ok(controls.some((c) => c.id === "sync"), `${where}: refresh is in the bar`);
assert.ok(controls.some((c) => c.id === "pin"), `${where}: the pin is in the bar`);
for (const c of controls) {
assert.ok(c.right <= min.left + 0.5, `${where}: ${c.id} runs under the caption buttons: ${JSON.stringify(c)} vs ${min.left}`);
assert.ok(c.hit, `${where}: ${c.id} is covered`);
assert.equal(c.drag, "no-drag", `${where}: ${c.id} drags the window`);
}
// beside the sidebar the page's own tools are in the bar too: the
// search boxes, the Library folder
if (width === 1100) {
const own = { settings: "setQ", library: "lib-more" }[view];
if (own) assert.ok(controls.some((c) => c.id === own || c.cls.split(" ").includes(own)), `${where}: ${own} is in the bar: ${JSON.stringify(controls.map((c) => c.id))}`);
}
// the bar itself drags, between its tools
assert.equal(await page.locator("header.top").evaluate((h) => getComputedStyle(h).getPropertyValue("--wails-draggable").trim()), "drag", `${where}: the header drags`);
// (a header packed as narrow as it goes leaves the brand out, as on
// every system)
if (!(await page.locator(".top.packed").count())) assert.ok(await page.locator(width >= 1024 ? "#side .side-top .brand" : ".top .brand").isVisible(), `${where}: the logo and name show`);
assert.deepEqual(errors, [], where);
await context.close();
}
// the buttons ask the window; maximise becomes restore and back
{
const { page, errors, context } = await open();
for (const cap of ["min", "max", "close"]) await page.locator(`#wincap [data-cap="${cap}"]`).click();
await page.waitForFunction(() => window.__calls.length >= 3);
assert.deepEqual(await page.evaluate(() => window.__calls), ["Minimise", "ToggleMaximise", "Close"]);
await page.evaluate(() => window.magpieCaption(true));
const max = page.locator('#wincap [data-cap="max"]');
assert.equal(await max.textContent(), "", "restore's glyph");
assert.equal(await max.getAttribute("title"), RESTORE[lang], "restore's tooltip");
await page.evaluate(() => window.magpieCaption(false));
assert.equal(await max.textContent(), "", "maximise's glyph again");
assert.equal(await max.getAttribute("title"), MAXIMIZE[lang]);
// a double click on the bar maximises; on a tool it doesn't
await page.evaluate(() => { window.__calls.length = 0; });
const bar = await page.evaluate(() => {
const top = document.querySelector("header.top").getBoundingClientRect();
for (let x = top.right - 160; x > top.left; x -= 4) {
const e = document.elementFromPoint(x, top.top + top.height / 2);
if (e && !e.closest("button, nav, input, a") && getComputedStyle(e).getPropertyValue("--wails-draggable").trim() === "drag") return { x, y: top.top + top.height / 2 };
}
return null;
});
assert.ok(bar, "an empty stretch of the bar");
await page.mouse.dblclick(bar.x, bar.y);
await page.locator("#sync").dblclick();
await page.waitForTimeout(100);
assert.deepEqual(await page.evaluate(() => window.__calls), ["ToggleMaximise"], "only the bar's double click maximises");
// a dialog open: the buttons stay over its scrim, and still close
await page.locator('#providers .row.provider[data-id="relay"]').click();
await page.getByRole("dialog").first().waitFor();
await page.waitForTimeout(400);
assert.ok(await page.evaluate(() => document.querySelector("header.top").inert), "the header is inert behind the dialog");
assert.ok(!(await page.evaluate(() => document.querySelector("#wincap").inert)), "the caption buttons aren't");
await page.evaluate(() => { window.__calls.length = 0; });
const box = await page.locator('#wincap [data-cap="close"]').boundingBox();
assert.ok(await page.evaluate(([x, y]) => document.elementFromPoint(x, y)?.dataset.cap === "close", [box.x + box.width / 2, box.y + box.height / 2]), "close is over the scrim");
await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);
await page.waitForFunction(() => window.__calls.length);
assert.deepEqual(await page.evaluate(() => window.__calls), ["Close"]);
assert.deepEqual(errors, []);
await context.close();
}
// the app may say the window is maximised before app.js is up
{
const context = await browser.newContext({ viewport: { width: 1100, height: 700 } });
await context.addInitScript(() => { Object.defineProperty(Navigator.prototype, "platform", { get: () => "Win32" }); window.magpieMaximised = true; });
const page = await context.newPage();
await page.route("**/*", serve(lang, false));
await page.goto("http://magpie.test/");
await page.waitForSelector("#nav button.on");
assert.equal(await page.locator('#wincap [data-cap="max"]').textContent(), "", "restore's glyph from the first paint");
await context.close();
}
// the Mac and Linux keep their own buttons, the panel and a browser page have none
for (const o of [{ platform: "MacIntel" }, { platform: "Linux x86_64" }, { mode: "panel", width: 440 }, { web: true }]) {
const { page, errors, context } = await open(o);
assert.ok(!(await page.locator("#wincap").isVisible()), `${JSON.stringify(o)}: no caption buttons`);
assert.notEqual(await page.evaluate(() => getComputedStyle(document.querySelector("header.top")).paddingRight), "146px", `${JSON.stringify(o)}: no room kept for them`);
assert.deepEqual(errors, []);
await context.close();
}
});
}
}