diff --git a/docs/subsystems/gui-shell.md b/docs/subsystems/gui-shell.md index 200656422..d8c7e97e5 100644 --- a/docs/subsystems/gui-shell.md +++ b/docs/subsystems/gui-shell.md @@ -268,10 +268,25 @@ it neither changes nor takes the app's `settings.UIFont`/`CodeFont`. A tab's `/api/fonts` is the server's families (none in a nogui build such as Docker or `magpie-cli`, and none when reading them fails, never an error) plus `commonFamilies` in `internal/gui/fonts.go`, in regular and bold. -The tab keeps those it draws (`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. When none is -kept, the rows still offer System default. Until 10-28 the rows were +The tab keeps those it draws (`webFonts.drawn` in `webfonts.js`: 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. When +none is kept, the rows still offer System default. + +Those are the server's names, so fonts installed only on the browser's +computer were missing (Norcleeh again, magpie in Docker). `webfonts.js`, +which only a tab loads (app.js `loadFonts` imports it; the app's windows never +need it, and it is outside the core script budget), adds them: where the +Local Font Access API is (Chromium on https or localhost), +`queryLocalFonts()` is called in the press that opens a family menu, once +a page, and at load when the `local-fonts` permission is already given; +its style names ("SemiBold Condensed Italic") become weight, slope and +width. Elsewhere (Safari, Firefox, a plain-http LAN address, a refused +permission) the menu's search also takes a typed family: "Use “name”" is +offered when the canvas probe says this browser draws it, and greyed out +when not. A chosen family the server doesn't list stays in the tab's list +on later loads while the browser draws it, so `desktopFonts.available` +keeps applying it. Until 10-28 the rows were gated on a boot `fonts` flag, so a nogui server had none, and what "flashed and vanished" on a refresh was Text size: the rows a tab never shows (Text size, the tray click, Open at login, the menu bar's diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 0b7e71940..581785016 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -2695,6 +2695,9 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; } .proto-menu .pm-head { padding: 6px 8px 5px; font-size: 11px; color: var(--muted); } .proto-menu .pm-item { display: flex; align-items: flex-start; gap: 7px; width: 100%; padding: 6px 8px 7px; border: 0; border-radius: 7px; background: none; color: var(--fg); font: inherit; text-align: left; cursor: default; outline: none; } .proto-menu .pm-item:hover, .proto-menu .pm-item:focus { background: var(--pill); } +/* a font typed in a browser tab that it can't draw (webfonts.js) */ +.proto-menu .pm-item:disabled { background: none; } +.proto-menu .pm-item:disabled .pm-name { color: var(--muted); } .proto-menu .pm-tick { width: 14px; height: 16px; flex: none; display: grid; place-items: center; color: var(--fg); } /* a menu of actions, where nothing is or can be ticked, keeps no room for a tick: its items line up with its heading */ diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 670ff3db8..4a225c91e 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -18885,9 +18885,10 @@ async function loadFonts(refresh = false) { if (fontFlight || (fontList !== null && !refresh)) return fontFlight; fontListError = false; fontFlight = api("fonts" + (refresh ? "?refresh=1" : "")) - .then((list) => { + .then(async (list) => { if (!Array.isArray(list)) throw new Error("invalid font collection"); - window.desktopFonts.catalogue(fontList = web ? window.desktopFonts.here(list) : list); + // a browser tab's own fonts: only a tab loads webfonts.js + window.desktopFonts.catalogue(fontList = web ? await import("./webfonts.js").then(() => webFonts.list(list)) : list); window.desktopFonts.apply(fontChoices(prefs || window.bootPrefs)); }) .catch(() => { fontListError = true; }) @@ -18939,9 +18940,10 @@ function renderFonts(s) { paint(style, chosen?.name || t("System default"), "Font style"); style.disabled = !family?.styles.length; row.querySelector(".font-preview").textContent = t("Aa 0123 · 中文"); - pill.onclick = (e) => { + pill.onclick = async (e) => { e.stopPropagation(); if (pill.classList.contains("open")) return closeProtoMenu(); + if (web) await window.webFonts?.ask(); const options = [{ v: "", name: t("System default"), note: "", literalName: true }, ...(fontList || []).map((f) => ({ v: "family:" + f.name, name: f.name, note: "", literalName: true })), { v: "refresh", name: t("Refresh fonts"), note: fontListError ? t("Couldn't read installed fonts") : "", literalName: true, always: true }]; @@ -18951,6 +18953,7 @@ function renderFonts(s) { const next = fontList.find((f) => "family:" + f.name === v); if (next?.styles.length) chooseFont(key, closestFont(next.styles, chosen)); }, label, "sess-menu font-menu", "right", false, "Search fonts…"); + if (web) window.webFonts?.typing(key); }; style.onclick = (e) => { e.stopPropagation(); diff --git a/internal/gui/assets/fonts.js b/internal/gui/assets/fonts.js index d357b7920..236ab751c 100644 --- a/internal/gui/assets/fonts.js +++ b/internal/gui/assets/fonts.js @@ -2,9 +2,9 @@ // Keep --font and --code as the platform/theme fallbacks: an explicit // 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). +// families it draws (webfonts.js). window.desktopFonts = (() => { - let catalogue = null, held = null, ctx; + let catalogue = null, held = null; const web = window.bootPrefs?.web, KEY = "magpie.fonts"; const own = () => { try { return JSON.parse(localStorage[KEY]); } catch { return held; } }; function keep(key, v) { @@ -12,11 +12,6 @@ window.desktopFonts = (() => { 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) + " ") + '"'; @@ -42,6 +37,6 @@ window.desktopFonts = (() => { // a wider font widens the tabs too: the header is fitted again (kiwiflysky on X) window.fitTop?.(); } - return { apply, available, same, own, keep, here, catalogue: (list) => { catalogue = list; } }; + return { apply, available, same, own, keep, quoted, catalogue: (list) => { catalogue = list; } }; })(); window.desktopFonts.apply(window.bootPrefs); diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 2b45bc132..75c1029e8 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -278,6 +278,9 @@ const I18N = { "System default": "系统默认", "Search fonts…": "搜索字体…", "Refresh fonts": "刷新字体列表", + "Search or type a font name…": "搜索或输入字体名称…", + "Use “{name}”": "使用“{name}”", + "This browser can't find this font": "这个浏览器找不到这款字体", "Couldn't read installed fonts": "无法读取已安装字体", "Font unavailable; using system default": "字体不可用,暂用系统默认", "Aa 0123 · 中文": "Aa 0123 · 中文", @@ -4341,6 +4344,9 @@ const I18N = { "System default": "系統預設", "Search fonts…": "搜尋字型…", "Refresh fonts": "重新整理字型列表", + "Search or type a font name…": "搜尋或輸入字型名稱…", + "Use “{name}”": "使用「{name}」", + "This browser can't find this font": "這個瀏覽器找不到這款字型", "Couldn't read installed fonts": "無法讀取已安裝字型", "Font unavailable; using system default": "字型不可用,暫用系統預設", "Aa 0123 · 中文": "Aa 0123 · 中文", @@ -8349,6 +8355,9 @@ const I18N = { "System default": "システムの既定", "Search fonts…": "フォントを検索…", "Refresh fonts": "フォント一覧を更新", + "Search or type a font name…": "フォント名を検索または入力…", + "Use “{name}”": "「{name}」を使用", + "This browser can't find this font": "このブラウザではこのフォントが見つかりません", "Couldn't read installed fonts": "インストール済みフォントを読み取れませんでした", "Font unavailable; using system default": "フォントを利用できないため、システムの既定を使用中", "Aa 0123 · 中文": "Aa 0123 · 日本語", @@ -12379,6 +12388,9 @@ const I18N = { "System default": "Systemstandard", "Search fonts…": "Schriften suchen…", "Refresh fonts": "Schriftliste aktualisieren", + "Search or type a font name…": "Schrift suchen oder Namen eingeben…", + "Use “{name}”": "„{name}“ verwenden", + "This browser can't find this font": "Dieser Browser findet diese Schrift nicht", "Couldn't read installed fonts": "Installierte Schriften konnten nicht gelesen werden", "Font unavailable; using system default": "Schrift nicht verfügbar; Systemstandard wird verwendet", "Aa 0123 · 中文": "Aa 0123 · 中文", diff --git a/internal/gui/assets/webfonts.js b/internal/gui/assets/webfonts.js new file mode 100644 index 000000000..0eacc3f9c --- /dev/null +++ b/internal/gui/assets/webfonts.js @@ -0,0 +1,117 @@ +// A browser tab's fonts: the ones on the computer the browser runs on, +// which may not be the one magpie runs on (Norcleeh on Discord: magpie in +// Docker, its web GUI listed the container's fonts, never his own). Only +// a tab loads this (app.js loadFonts imports it); the app's windows list the +// installed fonts magpie reads itself. +// +// A tab's list is the server's families it draws, plus: +// - its computer's own, from the Local Font Access API (Chromium, on +// https or localhost), asked the first time the family menu is opened, +// since it needs a press and asks the user's permission once; read at +// once when that permission is already given; +// - the families chosen in this tab (kept in localStorage by fonts.js); +// - any family typed into the menu's search that this browser draws, for +// Safari, Firefox, a plain-http address or a refused permission. +// "Draws" is a canvas probe: text in the family measures apart from +// monospace's or serif's. +window.webFonts = (() => { + let ctx, local = null, asked = false, base = []; + const extra = [], seen = new Map(); + const quoted = window.desktopFonts.quoted; + function drawn(name) { + if (!seen.has(name)) { + ctx ||= document.createElement("canvas").getContext("2d"); + const w = (f) => (ctx.font = "72px " + f, ctx.measureText("mmmlli WwQ@ 0123 中文").width); + seen.set(name, !!name && ["monospace", "serif"].some((b) => w(quoted(name) + "," + b) !== w(b))); + } + return seen.get(name); + } + const face = (family, name = "Regular", weight = 400, style = "normal", stretch = 100) => ({ family, name, weight, style, stretch }); + const regular = (family) => [face(family), face(family, "Bold", 700)]; + const same = window.desktopFonts.same; + // a face's CSS traits from the style name the system gives it + // ("SemiBold Condensed Italic") + const first = (rules, s, d) => (rules.find(([re]) => re.test(s)) || [, d])[1]; + const WEIGHTS = [[/thin|hairline/, 100], [/(extra|ultra)-?light/, 200], [/light/, 300], [/(semi|demi)-?bold/, 600], + [/(extra|ultra)-?bold/, 800], [/black|heavy/, 900], [/medium/, 500], [/bold/, 700]]; + const STRETCHES = [[/ultra-?condensed/, 50], [/extra-?condensed/, 62.5], [/semi-?condensed/, 87.5], [/condensed|narrow/, 75], + [/semi-?expanded/, 112.5], [/extra-?expanded/, 150], [/ultra-?expanded/, 200], [/expanded|wide/, 125]]; + function group(data) { + const fams = new Map(); + for (const d of data) { + if (!d.family) continue; + const s = String(d.style || "").toLowerCase().replace(/\s+/g, ""); + const f = face(d.family, d.style || "Regular", first(WEIGHTS, s, 400), /italic/.test(s) ? "italic" : /oblique/.test(s) ? "oblique" : "normal", first(STRETCHES, s, 100)); + const styles = fams.get(d.family) || []; + if (!styles.some((o) => o.weight === f.weight && o.style === f.style && o.stretch === f.stretch)) styles.push(f); + fams.set(d.family, styles); + } + return [...fams].map(([name, styles]) => ({ name, styles: styles.sort((a, b) => a.weight - b.weight || (a.style > b.style) - (a.style < b.style) || a.stretch - b.stretch) })); + } + function merge() { + const out = new Map(); + for (const f of [...base, ...(local || []), ...extra]) out.set(f.name, f); + const own = window.desktopFonts.own() || {}; + for (const c of [own.uiFont, own.codeFont]) { + if (typeof c?.family !== "string" || !drawn(c.family)) continue; + const f = out.get(c.family) || { name: c.family, styles: regular(c.family) }; + out.set(c.family, f.styles.some((s) => same(s, c)) ? f : { ...f, styles: [...f.styles, c] }); + } + return [...out.values()].sort((a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase())); + } + // called in the press that opens the menu: queryLocalFonts needs it + async function read() { + local = group(await window.queryLocalFonts()); + } + // list: the tab's families, from the server's (/api/fonts) + async function list(server) { + base = server.filter((f) => drawn(f.name)); + if (!asked && window.queryLocalFonts) try { + if ((await navigator.permissions.query({ name: "local-fonts" })).state === "granted") await read(), asked = true; + } catch {} + return merge(); + } + // ask: the first time a family menu opens where the browser can tell + // this computer's fonts, they join the list (app.js fontList) + const catalogue = () => window.desktopFonts.catalogue(fontList = merge()); + function ask() { + if (asked || !window.queryLocalFonts) return; + asked = true; // a refusal isn't asked again on this page + return read().then(catalogue, () => {}); + } + // typing: the open family menu's search also takes a family the list + // lacks; it is offered when this browser draws it, and chosen for key + function typing(key) { + const box = protoMenu?.box, q = box?.querySelector(".sc-q"); + if (!q) return; + q.placeholder = t("Search or type a font name…"); + q.setAttribute("aria-label", q.placeholder); + const b = el("button", "pm-item typed-font"), words = el("span", "pm-words"), name = el("span", "pm-name"), note = el("span", "pm-note"); + b.type = "button"; + b.hidden = true; + words.append(name, note); + b.append(el("span", "pm-tick"), words); + box.lastChild.before(b); // above Refresh fonts + hoverFocus(b); + let family = ""; + q.addEventListener("input", () => { + family = q.value.trim(); + const low = family.toLowerCase(), ok = drawn(family); + b.hidden = !family || (fontList || []).some((f) => f.name.toLowerCase() === low); + b.disabled = !ok; + name.textContent = t("Use “{name}”", { name: family }); + note.textContent = ok ? "" : t("This browser can't find this font"); + }); + // Enter takes it when no listed family matched (app.js took that one) + q.addEventListener("keydown", (e) => { if (e.key === "Enter" && !e.defaultPrevented && !b.hidden && !b.disabled) b.click(); }); + b.onclick = (e) => { + e.stopPropagation(); + closeProtoMenu(); + const styles = regular(family); + extra.push({ name: family, styles }); + catalogue(); + chooseFont(key, styles[0]); + }; + } + return { list, ask, typing, drawn }; +})(); diff --git a/internal/gui/tests/fonts.test.cjs b/internal/gui/tests/fonts.test.cjs index 6b72677ca..045edfeab 100644 --- a/internal/gui/tests/fonts.test.cjs +++ b/internal/gui/tests/fonts.test.cjs @@ -65,6 +65,7 @@ async function open(browser, lang = "en", options = {}) { }; requestAnimationFrame(look); }); + if (options.init) await page.addInitScript(options.init, options.arg); await watchSettingsReads(page); await page.goto("http://magpie.test/?view=settings&tab=general"); await settingsDrawn(page); // rows found are the ones that stay (#1659) @@ -366,6 +367,110 @@ for (const [engine, runtime] of engines) { } finally { await browser.close(); } }); + // Norcleeh (magpie in Docker, its web GUI): the tab listed the server's + // fonts, the container's, never the ones on his own computer. Where the + // browser has the Local Font Access API, the press that opens a family + // menu asks for them, once; they are offered with their real styles. + // queryLocalFonts is stubbed in both engines (a real one needs a press, + // a permission prompt and a secure origin). + const ownFonts = [ + { family: "Norcleeh Sans", fullName: "Norcleeh Sans Regular", postscriptName: "NorcleehSans-Regular", style: "Regular" }, + { family: "Norcleeh Sans", fullName: "Norcleeh Sans Bold Italic", postscriptName: "NorcleehSans-BoldItalic", style: "Bold Italic" }, + { family: "Norcleeh Sans", fullName: "Norcleeh Sans SemiBold Condensed", postscriptName: "NorcleehSans-SemiBoldCond", style: "SemiBold Condensed" }, + { family: "Norcleeh Mono", fullName: "Norcleeh Mono Regular", postscriptName: "NorcleehMono-Regular", style: "Regular" }, + ]; + const localFonts = (fonts) => { + window.__asked = []; + navigator.permissions.query = async () => ({ state: "prompt" }); + window.queryLocalFonts = async () => { + window.__asked.push(navigator.userActivation ? navigator.userActivation.isActive : "unknown"); + return fonts; + }; + }; + for (const lang of ["en", "zh"]) for (const width of [1000, 440]) test(`${engine} ${lang} ${width}px: a browser tab lists the fonts of the computer it runs on`, async () => { + const browser = await runtime.launch(); + try { + const { page, api, errors, close } = await open(browser, lang, { web: true, viewport: { width, height: 820 }, list: [], init: localFonts, arg: ownFonts }); + assert.deepEqual(await page.evaluate(() => window.__asked), [], "nothing is asked before the menu opens (it needs a press)"); + await page.locator("#uiFontRow .font-family").click(); + await page.locator(".font-menu").waitFor(); + const asked = await page.evaluate(() => window.__asked); + assert.equal(asked.length, 1, "the press that opens the menu asks once"); + if (engine === "chromium") assert.equal(asked[0], true, "asked within the press"); + const names = await page.locator(".font-menu .pm-item:not([hidden]) .pm-name").allTextContents(); + assert(names.includes("Norcleeh Sans") && names.includes("Norcleeh Mono"), "this computer's families are offered: " + names); + const box = await page.locator(".font-menu").boundingBox(); + assert(box.x >= 0 && box.x + box.width <= width, "the menu fits the window: " + JSON.stringify(box)); + await page.locator(".font-menu .sc-q").fill("Norcleeh Sans"); + await page.locator(".font-menu .pm-item").filter({ has: page.locator(".pm-name", { hasText: "Norcleeh Sans" }) }).first().click(); + assert.match((await css(page, "body")).family, /^"?Norcleeh Sans/); + await page.locator("#uiFontRow .font-style").click(); + const styles = await page.locator(".font-menu .pm-item .pm-name").allTextContents(); + assert.deepEqual(styles, ["Regular", "SemiBold Condensed", "Bold Italic"], "its real styles, by weight"); + await page.keyboard.press("Escape"); + await style(page, "uiFontRow", "SemiBold Condensed"); + const look = await css(page, "body"); + assert.equal(look.weight, "600"); + assert.equal(look.stretch, "75%"); + await style(page, "uiFontRow", "Bold Italic"); + assert.equal((await css(page, "body")).style, "italic"); + await page.locator("#codeFontRow .font-family").click(); + await page.locator(".font-menu").waitFor(); + assert.equal((await page.evaluate(() => window.__asked)).length, 1, "asked once a page"); + await page.keyboard.press("Escape"); + 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(await page.locator("select").count(), 0); + assert.deepEqual(errors, []); + await close(); + } finally { await browser.close(); } + }); + + // Where there is no such API (Safari, Firefox, a plain-http address) or + // the user refused it, a family is typed into the menu's search: it is + // taken when this browser draws it, and kept across a reload though the + // server has no such font. + for (const lang of ["en", "zh"]) for (const [how, width] of [["missing", 1000], ["refused", 440]]) test(`${engine} ${lang} ${width}px: a browser tab takes a typed font when the API is ${how}`, async () => { + const browser = await runtime.launch(); + try { + const init = how === "missing" ? () => { delete window.queryLocalFonts; } + : () => { window.queryLocalFonts = async () => { throw new DOMException("refused", "NotAllowedError"); }; }; + const { page, api, errors, close } = await open(browser, lang, { web: true, viewport: { width, height: 820 }, list: [], init }); + const real = await page.evaluate(() => ["Georgia", "Courier New", "Times New Roman", "DejaVu Serif", "Liberation Serif"].find(n => { + const ctx = document.createElement("canvas").getContext("2d"), w = f => (ctx.font = "72px " + f, ctx.measureText("mmmlli WwQ@ 0123").width); + return ["monospace", "serif"].some(b => w(`"${n}",${b}`) !== w(b)); + })); + assert(real, "the test machine draws one of the families tried"); + await page.locator("#uiFontRow .font-family").click(); + const q = page.locator(".font-menu .sc-q"); + assert.equal(await q.getAttribute("placeholder"), lang === "zh" ? "搜索或输入字体名称…" : "Search or type a font name…"); + await q.fill("No Such Family Here"); + const typed = page.locator(".font-menu .typed-font"); + assert.equal(await typed.isVisible(), true, "a typed family is answered"); + assert.equal(await typed.isDisabled(), true, "one this browser doesn't draw can't be chosen"); + assert.equal(await typed.locator(".pm-note").textContent(), lang === "zh" ? "这个浏览器找不到这款字体" : "This browser can't find this font"); + await q.fill(real); + assert.equal(await typed.isDisabled(), false); + assert.equal(await typed.locator(".pm-name").textContent(), lang === "zh" ? `使用“${real}”` : `Use “${real}”`); + await q.press("Enter"); + await page.locator(".font-menu").waitFor({ state: "detached" }); + assert.match((await css(page, "body")).family, new RegExp("^\"?" + real)); + assert.equal(await page.locator("#uiFontRow .font-family span").textContent(), real); + await style(page, "uiFontRow", "Bold"); + assert.equal((await css(page, "body")).weight, "700"); + 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"); + 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("^\"?" + real), "kept across a reload, though the server lists no such font"); + assert.equal((await css(page, "body")).weight, "700"); + assert.equal(await page.locator("#uiFontRow .font-family span").textContent(), real); + assert.equal(await page.locator("#uiFontRow .font-note").isVisible(), false, "not called unavailable"); + assert.equal(await page.locator("select").count(), 0); + assert.deepEqual(errors, []); + await close(); + } finally { await browser.close(); } + }); + test(`${engine}: native notifications update the other webview without another save`, async () => { const browser = await runtime.launch(); try {