From 833f51adcf4d880c8fd8683f71873bb16e86d74b Mon Sep 17 00:00:00 2001 From: yetone Date: Wed, 28 Oct 2026 08:00:54 +0800 Subject: [PATCH] gui: a browser tab has the font rows too, with its own choice Norcleeh on Discord: magpie opened in a browser had no font setting in Settings > General, while the app does. The rows were hidden on purpose: /api/fonts answered 404 to a browser page and boot sent it no choice, since the list is the fonts of the computer magpie runs on and the tab can be on another one. Now a browser tab (magpie web, or the app's page in a browser) has both rows wherever magpie can read its fonts (boot's fonts; a nogui build can't, and keeps them hidden). Its list is /api/fonts less the families this browser doesn't draw (fonts.js here(): text in the family measures apart from monospace's or serif's on a canvas), so another computer's fonts and Safari's user-installed ones aren't offered. The choice is the browser's own, in localStorage (magpie.fonts), applied by fonts.js before the first paint; it neither changes nor takes the app's settings.UIFont/CodeFont, and a settings save from a browser still keeps the app's. Run on mote at this tree (on b90e81da1), also GOOS=linux (nogui) and GOOS=windows go vet ./internal/gui/..., go build, gofmt -l: - fonts.test.cjs, font-cascade.test.cjs, win-fonts.test.cjs, i18n-keys and the 42 drag/arrange GUI files, Chromium and WebKit, en and zh (and ja/de where a file has them). The reds are 32 subtests in 4 files that fail the same on origin/main b90e81da1 run alone (and one from a stray path in the run command): i18n-keys "a plugin's words are its own" (#3897), routing-rule-drag webkit de (#3789), segs-press-redraw webkit (#3922), usage-agents-hide (#3414). - go test -tags nogui ./internal/gui (TestCoreScriptBudget and TestFontSettingsAPIAndBoot included) ok; go test ./internal/gui -run Font (cgo, CoreText) ok. - Real use: magpie built on mote, `magpie web` in a sandbox HOME, real /api/fonts (204 families). Chromium offered 204, WebKit 179; Georgia picked in each, the body drew it and kept it across a reload, and no settings.json was written. Broken by hand: fontsOn = !web (rows hidden as before): the new test red in all four engine/language cases; here() returning the list unfiltered: red with "a family this browser doesn't draw isn't offered". Not tried: a browser on a different computer from magpie (the canvas filter is what covers it, checked with a family the test machine lacks), Firefox, the Windows and Linux apps' pages in a browser. Budget: not raised; the previous commit's 1,097 bytes cover it. --- docs/subsystems/gui-shell.md | 12 ++++++++- internal/gui/api.go | 6 ++++- internal/gui/assets/app.js | 13 ++++----- internal/gui/assets/fonts.js | 22 ++++++++++++--- internal/gui/fonts.go | 12 +++++---- internal/gui/fonts_test.go | 11 +++++--- internal/gui/tests/README.md | 3 ++- internal/gui/tests/fonts.test.cjs | 45 +++++++++++++++++++++++++++++-- 8 files changed, 101 insertions(+), 23 deletions(-) diff --git a/docs/subsystems/gui-shell.md b/docs/subsystems/gui-shell.md index 579176ed3..52867a467 100644 --- a/docs/subsystems/gui-shell.md +++ b/docs/subsystems/gui-shell.md @@ -258,7 +258,17 @@ CoreText on macOS and Fontconfig on Linux. Discovery is lazy, cached in the handler, and refreshed by the menu. It returns names and CSS traits, never font files or paths. A failed refresh answers 503 and preserves the previous collection; an empty successful collection is distinct from failure. -`magpie web` and `nogui` do not expose this desktop catalogue. +A `nogui` build can't read the catalogue and answers 404. + +A browser tab (`magpie web`, or the app's page opened in a browser) has the +same rows when boot says `fonts` (Norcleeh on Discord). Its choice is the +browser's own, kept in `localStorage` under `magpie.fonts` and applied by +`fonts.js` before the first paint: the tab can be on another computer, so +it neither changes nor takes the app's `settings.UIFont`/`CodeFont`. Its +list is `/api/fonts` less the families the browser doesn't draw +(`desktopFonts.here`: text in the family measures apart from a generic +family's on a canvas), so another computer's fonts, and Safari's +user-installed ones, aren't offered. In a nogui build the rows stay hidden. `settings.UIFont` and `settings.CodeFont` keep the family, style name, OpenType weight, CSS slope and width percentage. A missing choice keeps the diff --git a/internal/gui/api.go b/internal/gui/api.go index 434b42cec..fb92d11aa 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -855,8 +855,12 @@ func Handler(w Windows, gw *gateway.Server) http.Handler { if s.Colorblind { boot["colorblind"] = true } + // a browser tab keeps its own font choice (fonts.js) and is told + // whether there is a list to choose from if !isWeb(w) { boot["uiFont"], boot["codeFont"] = s.UIFont, s.CodeFont + } else if fonts.Available { + boot["fonts"] = true } // and whether it is a gateway's page alone (gatewaymode.go), so the // pages left out never show @@ -902,7 +906,7 @@ func Handler(w Windows, gw *gateway.Server) http.Handler { writeJSON(rw, nil) }) omarchyRoutes(mux, w) - fontRoutes(mux, isWeb(w) || !fonts.Available, fonts.List) + fontRoutes(mux, !fonts.Available, fonts.List) mux.HandleFunc("GET /api/state", func(rw http.ResponseWriter, r *http.Request) { // the panel and its model picker load from here: an account still // without its vendor's list (one whose try at start-up failed) is diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 21540e058..c77040a6f 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -18862,7 +18862,9 @@ if (!web) addEventListener("keydown", (e) => { // keep the family/style controls usable while the shared save queue drains. let fontList = null, fontListError = false, fontFlight = null, fontRevision = 0; const fontDrafts = {}; +const fontsOn = !web || window.bootPrefs?.fonts; function fontChoices(s) { + if (web) return { ...s, ...window.desktopFonts.own() }; return { ...s, ...Object.fromEntries(Object.entries(fontDrafts).map(([k, d]) => [k, d.value])) }; } // The native host notifies both existing webviews after a successful save. @@ -18876,13 +18878,12 @@ window.receiveFonts = (s) => { if (prefs && view === "settings") renderFonts(prefs); }; async function loadFonts(refresh = false) { - if (web || fontFlight || (fontList !== null && !refresh)) return fontFlight; + if (!fontsOn || fontFlight || (fontList !== null && !refresh)) return fontFlight; fontListError = false; fontFlight = api("fonts" + (refresh ? "?refresh=1" : "")) .then((list) => { if (!Array.isArray(list)) throw new Error("invalid font collection"); - fontList = list; - window.desktopFonts.catalogue(list); + window.desktopFonts.catalogue(fontList = web ? window.desktopFonts.here(list) : list); window.desktopFonts.apply(fontChoices(prefs || window.bootPrefs)); }) .catch(() => { fontListError = true; }) @@ -18891,6 +18892,7 @@ async function loadFonts(refresh = false) { return fontFlight; } function chooseFont(key, value) { + if (web) return window.desktopFonts.keep(key, value), renderFonts(prefs); const revision = ++fontRevision; fontDrafts[key] = { value, revision }; window.desktopFonts.apply(fontChoices(prefs)); @@ -18914,8 +18916,7 @@ function renderFonts(s) { const current = fontChoices(s); for (const [key, id, label] of [["uiFont", "uiFontRow", "Interface font"], ["codeFont", "codeFontRow", "Code font"]]) { const row = $("#" + id); - row.hidden = web; - if (web) continue; + if (row.hidden = !fontsOn) continue; const chosen = current[key], family = fontList?.find((f) => f.name === chosen?.family); const missing = chosen && !window.desktopFonts.available(chosen); const note = row.querySelector(".font-note"); @@ -19058,7 +19059,7 @@ function renderLoginAllow(s) { async function loadSettings() { const since = prefsWrites; - if (!web && fontList === null && !fontListError) loadFonts(); + if (fontsOn && fontList === null && !fontListError) loadFonts(); if (window.bootPrefs?.omarchy && !barIcon) api("omarchy/widget").then((b) => { barIcon = b; renderBarIcon(); }).catch(() => {}); const s = await api("settings"); if (!prefsSettled(since) && prefs) return; // the save draws the page when it's in diff --git a/internal/gui/assets/fonts.js b/internal/gui/assets/fonts.js index 9fa601076..d357b7920 100644 --- a/internal/gui/assets/fonts.js +++ b/internal/gui/assets/fonts.js @@ -1,8 +1,22 @@ // Installed font choices reach both webviews before their first paint. // Keep --font and --code as the platform/theme fallbacks: an explicit -// choice is a separate variable, including on Omarchy's body. +// choice is a separate variable, including on Omarchy's body. A browser +// tab's choice is its own (it may be on another computer), from the +// families it draws (here). window.desktopFonts = (() => { - let catalogue = null; + let catalogue = null, held = null, ctx; + const web = window.bootPrefs?.web, KEY = "magpie.fonts"; + const own = () => { try { return JSON.parse(localStorage[KEY]); } catch { return held; } }; + function keep(key, v) { + held = { ...own(), [key]: v }; + try { localStorage[KEY] = JSON.stringify(held); } catch {} + apply(); + } + function here(list) { + ctx ||= document.createElement("canvas").getContext("2d"); + const w = (f) => (ctx.font = "72px " + f, ctx.measureText("mmmlli WwQ@ 0123 中文").width), bases = ["monospace", "serif"]; + return list.filter((f) => bases.some((b) => w(quoted(f.name) + "," + b) !== w(b))); + } const same = (a, b) => !!a && !!b && ["family", "name", "weight", "style", "stretch"].every((k) => a[k] === b[k]); const available = (face) => !face || catalogue === null || catalogue.some((f) => f.styles.some((s) => same(s, face))); const quoted = (s) => '"' + s.replace(/[\\"\x00-\x1f\x7f]/g, (c) => "\\" + c.charCodeAt(0).toString(16) + " ") + '"'; @@ -10,7 +24,7 @@ window.desktopFonts = (() => { const root = document.documentElement; let active = false; for (const [key, prefix, fallback] of [["uiFont", "ui", "font"], ["codeFont", "code", "code"]]) { - const f = !window.bootPrefs?.web && s?.[key]; + const f = (web ? own() : s)?.[key]; const valid = f && typeof f.family === "string" && f.family && ["normal", "italic", "oblique"].includes(f.style) && Number.isFinite(f.weight) && f.weight >= 1 && f.weight <= 1000 && Number.isFinite(f.stretch) && f.stretch >= 0; const values = valid && available(f) ? { @@ -28,6 +42,6 @@ window.desktopFonts = (() => { // a wider font widens the tabs too: the header is fitted again (kiwiflysky on X) window.fitTop?.(); } - return { apply, available, same, catalogue: (list) => { catalogue = list; } }; + return { apply, available, same, own, keep, here, catalogue: (list) => { catalogue = list; } }; })(); window.desktopFonts.apply(window.bootPrefs); diff --git a/internal/gui/fonts.go b/internal/gui/fonts.go index 65aa32a62..7ea5ed6e6 100644 --- a/internal/gui/fonts.go +++ b/internal/gui/fonts.go @@ -21,14 +21,16 @@ func fontSettingsJS(s settings.Settings) string { return "window.receiveFonts?.(" + string(b) + ");" } -// Font discovery belongs to the desktop, never to a remote browser's -// server. A failed refresh leaves the last successful collection intact. -func fontRoutes(mux *http.ServeMux, web bool, discover func() ([]fonts.Family, error)) { +// The fonts installed on the computer magpie runs on, for its windows and +// for a browser tab (which keeps the families it draws itself, fonts.js); +// off where they can't be read (a nogui build). A failed refresh leaves +// the last successful collection intact. +func fontRoutes(mux *http.ServeMux, off bool, discover func() ([]fonts.Family, error)) { var mu sync.Mutex var cached []fonts.Family mux.HandleFunc("GET /api/fonts", func(rw http.ResponseWriter, r *http.Request) { - if web { - http.Error(rw, "installed fonts are available only in the desktop app", http.StatusNotFound) + if off { + http.Error(rw, "installed fonts can't be read by this magpie", http.StatusNotFound) return } mu.Lock() diff --git a/internal/gui/fonts_test.go b/internal/gui/fonts_test.go index 0bc7bc146..d92949f55 100644 --- a/internal/gui/fonts_test.go +++ b/internal/gui/fonts_test.go @@ -58,11 +58,11 @@ func TestFontDiscoveryCacheAndFailure(t *testing.T) { t.Fatalf("refresh did not re-read fonts: %d", calls) } web := http.NewServeMux() - fontRoutes(web, true, func() ([]fonts.Family, error) { t.Fatal("browser enumerated server fonts"); return nil, nil }) + fontRoutes(web, true, func() ([]fonts.Family, error) { t.Fatal("fonts read where they can't be"); return nil, nil }) r = httptest.NewRecorder() web.ServeHTTP(r, httptest.NewRequest("GET", "/api/fonts", nil)) if r.Code != 404 { - t.Fatalf("web font discovery returned %d", r.Code) + t.Fatalf("font discovery turned off returned %d", r.Code) } } @@ -110,9 +110,14 @@ func TestFontSettingsAPIAndBoot(t *testing.T) { if !reflect.DeepEqual(settings.Load().UIFont, face) { t.Fatal("browser save replaced a desktop font") } - if _, ok := boot(web)["uiFont"]; ok { + webBoot := boot(web) + if _, ok := webBoot["uiFont"]; ok { t.Fatal("browser received a desktop font override") } + // a browser tab is offered the font list wherever magpie can read one + if _, ok := webBoot["fonts"]; ok != fonts.Available { + t.Fatalf("browser boot fonts = %v, want %v", ok, fonts.Available) + } post(h, map[string]any{"uiFont": map[string]any{"family": "bad", "name": "Regular", "weight": 1001}}, 400) if !reflect.DeepEqual(settings.Load().UIFont, face) { t.Fatal("invalid choice replaced the saved font") diff --git a/internal/gui/tests/README.md b/internal/gui/tests/README.md index 39f51e4cc..02a7cb5ff 100644 --- a/internal/gui/tests/README.md +++ b/internal/gui/tests/README.md @@ -21,7 +21,8 @@ five languages on Chromium and WebKit. family/style fixtures: independent traits, literal names, search and keyboard selection, rapid queued saves and rollback, reload, unavailable faces, discovery failure and refresh, empty collections, platform fallback, -Omarchy precedence and browser-mode isolation. It checks narrow windows and +Omarchy precedence, and a browser tab's own choice (kept in the browser, +from the families it draws, never the app's). It checks narrow windows and no scroll on click in Chromium and WebKit, in English and Chinese. `ARTIFACT_DIR` retains screenshots; `MAGPIE_FONT_ASSETS` can point to an older asset directory to verify that the test fails on the missing picker. diff --git a/internal/gui/tests/fonts.test.cjs b/internal/gui/tests/fonts.test.cjs index 86ea16f85..ea53de1e9 100644 --- a/internal/gui/tests/fonts.test.cjs +++ b/internal/gui/tests/fonts.test.cjs @@ -26,7 +26,7 @@ async function open(browser, lang = "en", options = {}) { await page.route("**/*", async route => { const req = route.request(), url = new URL(req.url()); const json = data => route.fulfill({ json: data }); - if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs=${JSON.stringify({ ...api.cur, web: !!options.web, ...(options.omarchy ? { omarchy: { mode: "dark", stamp: "one", name: "Test theme", vars: { "--font": '"Theme Font", sans-serif', "--code": '"Theme Mono", monospace' } } } : {}) })};` }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs=${JSON.stringify({ ...api.cur, web: !!options.web, ...(options.fonts ? { fonts: true } : {}), ...(options.omarchy ? { omarchy: { mode: "dark", stamp: "one", name: "Test theme", vars: { "--font": '"Theme Font", sans-serif', "--code": '"Theme Mono", monospace' } } } : {}) })};` }); if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); if (url.pathname === "/api/fonts") { api.reads++; @@ -60,7 +60,7 @@ async function open(browser, lang = "en", options = {}) { // A real assertion, also usable against the original assets, rather than // a timeout or a compile error as the negative-control result. assert.equal(await page.locator("#uiFontRow").count(), 1, "Settings must offer an interface font picker"); - if (!options.web) await page.waitForFunction(() => fontList !== null || fontListError); + if (!options.web || options.fonts) await page.waitForFunction(() => fontList !== null || fontListError); await page.evaluate(async () => { await document.fonts.ready; await Promise.all(document.getAnimations().map(a => a.finished.catch(() => {}))); @@ -272,6 +272,7 @@ for (const [engine, runtime] of engines) { assert.match((await css(page, "body")).family, /Theme Font/); assert.match((await css(page, "#codeFontRow .font-preview")).family, /Consolas/); assert.deepEqual(errors, []); + // a magpie that can't read its fonts (nogui) offers none to a browser const web = await open(browser, "en", { web: true, settings: { uiFont: harmony[1] } }); assert.equal(await web.page.locator("#uiFontRow").isVisible(), false); assert.equal(web.api.reads, 0); @@ -280,6 +281,46 @@ for (const [engine, runtime] of engines) { } finally { await browser.close(); } }); + // Norcleeh on Discord: a browser tab had no font rows. It has them now, + // with the families this browser draws, and its choice is its own. + for (const lang of ["en", "zh"]) test(`${engine} ${lang}: a browser tab picks its own font from the ones it draws`, async () => { + const browser = await runtime.launch(); + try { + const real = ["Georgia", "Courier New", "DejaVu Serif", "Liberation Serif"]; + const list = [{ name: "No Such Family Here", styles: [face("No Such Family Here")] }, ...real.map(n => ({ name: n, styles: [face(n), face(n, "Bold", 700)] }))]; + const { page, api, errors } = await open(browser, lang, { web: true, fonts: true, settings: { uiFont: harmony[1] } }); + api.fonts = list; + assert.equal(await page.locator("#uiFontRow").isVisible(), true, "a browser tab offers the interface font"); + assert.equal(await page.locator("#codeFontRow").isVisible(), true, "and the code font"); + assert.doesNotMatch((await css(page, "body")).family, /HarmonyOS/, "the app's own choice stays the app's"); + await page.locator("#uiFontRow .font-family").click(); + await page.locator(".font-menu .pm-item").last().click(); // Refresh fonts + await page.waitForFunction(() => !fontFlight); + const shown = await page.evaluate(() => fontList.map(f => f.name)); + assert(!shown.includes("No Such Family Here"), "a family this browser doesn't draw isn't offered: " + shown); + const pick = shown[0]; + assert(real.includes(pick), "an installed family is offered: " + shown); + await family(page, "uiFontRow", pick); + await style(page, "uiFontRow", "Bold"); + assert.match((await css(page, "body")).family, new RegExp("^\"?" + pick)); + assert.equal((await css(page, "body")).weight, "700"); + await family(page, "codeFontRow", pick); + assert.match((await css(page, "#codeFontRow .font-preview")).family, new RegExp("^\"?" + pick)); + assert.equal(api.posts.filter(p => "uiFont" in p || "codeFont" in p).length, 0, "the browser's choice isn't sent as the app's"); + assert.equal(api.cur.uiFont.family, harmony[1].family); + await page.reload(); + await page.locator("#uiFontRow .font-family").waitFor(); + await page.waitForFunction(() => fontList !== null && !fontFlight); + assert.match((await css(page, "body")).family, new RegExp("^\"?" + pick), "kept across a reload"); + assert.equal((await css(page, "body")).weight, "700"); + assert.equal(await page.locator("#uiFontRow .font-family span").textContent(), pick); + await reset(page, "uiFontRow"); + assert.doesNotMatch((await css(page, "body")).family, new RegExp(pick)); + assert.match((await css(page, "#codeFontRow .font-preview")).family, new RegExp("^\"?" + pick)); + assert.deepEqual(errors, []); + } finally { await browser.close(); } + }); + test(`${engine}: native notifications update the other webview without another save`, async () => { const browser = await runtime.launch(); try {