diff --git a/internal/gui/api.go b/internal/gui/api.go index cefb45c87..a541eb501 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -12,6 +12,7 @@ import ( "mime" "net/http" "os" + "slices" "strings" "time" @@ -494,7 +495,8 @@ func Handler(w Windows, gw *gateway.Server) http.Handler { if (in.Dock != cur.Dock || in.DockWindow != cur.DockWindow) && onDock != nil { onDock(in) } - if (in.TrayUsage != cur.TrayUsage || in.TrayUsageEvery != cur.TrayUsageEvery) && onTrayUsage != nil { + // the cards the menu bar shows, any of them (TrayUsage is only the first) + if (!slices.Equal(settings.Load().TrayUsages, cur.TrayUsages) || in.TrayUsageEvery != cur.TrayUsageEvery) && onTrayUsage != nil { onTrayUsage() } // the tray menu follows the page's language (#301) diff --git a/internal/gui/app.go b/internal/gui/app.go index 07cd32116..432be1d79 100644 --- a/internal/gui/app.go +++ b/internal/gui/app.go @@ -524,10 +524,18 @@ func (h *host) flap() { if err != nil { break } - h.tray.SetTemplateIcon(b) + h.setBird(b) time.Sleep(30 * time.Millisecond) } - h.tray.SetTemplateIcon(trayIcon) + h.setBird(trayIcon) +} + +// setBird sets a frame of the bird: in the menu bar's image while it shows +// the usage cards (trayImageFrame), else as the tray's icon. +func (h *host) setBird(b []byte) { + if !trayImageFrame(b) { + h.tray.SetTemplateIcon(b) + } } // panelOptions: the tray panel's window, frameless and see-through. On diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 83dbfc302..81d009997 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -5775,24 +5775,43 @@ function closeProtoMenu() { document.removeEventListener("keydown", protoMenu.keys, true); document.removeEventListener("scroll", protoMenu.scroll, true); removeEventListener("resize", closeProtoMenu); + const done = protoMenu.done; protoMenu = null; + done?.(); } +// openProtoMenu picks one of opts, or several when value is a list: each +// ticked or unticked in turn with the menu kept open, choose given the +// ticked ones, in the menu's order, once it closes (and only if they +// changed); "" is none of them and closes it, "\x00" a note to read. function openProtoMenu(anchor, opts, value, choose, head = "Protocol this key speaks", cls = "") { closeProtoMenu(); + const multi = Array.isArray(value); + let picked = multi ? [...value] : null; + const isOn = (v) => !multi ? v === value : v === "" ? !picked.length : picked.includes(v); const box = el("div", "pop proto-menu" + (cls ? " " + cls : "")); box.setAttribute("role", "menu"); box.append(el("div", "pm-head", t(head))); + const tick = (b, o) => { + b.classList.toggle("on", isOn(o.v)); + b.setAttribute("aria-checked", isOn(o.v)); + b.firstChild.replaceChildren(...(isOn(o.v) ? [svg(CHECK, 12, 1.9)] : [])); + }; const items = opts.map((o) => { - const b = el("button", "pm-item" + (o.v === value ? " on" : "")); + const b = el("button", "pm-item"); b.type = "button"; - b.setAttribute("role", "menuitemradio"); - b.setAttribute("aria-checked", o.v === value); - const tick = el("span", "pm-tick"); - if (o.v === value) tick.append(svg(CHECK, 12, 1.9)); + b.setAttribute("role", multi && o.v && o.v !== "\x00" ? "menuitemcheckbox" : "menuitemradio"); const words = el("span", "pm-words"); words.append(el("span", "pm-name", t(o.name)), el("span", "pm-note", t(o.note))); - b.append(tick, words); - b.onclick = (e) => { e.stopPropagation(); closeProtoMenu(); choose(o.v); }; + b.append(el("span", "pm-tick"), words); + tick(b, o); + b.onclick = (e) => { + e.stopPropagation(); + if (!multi) { closeProtoMenu(); choose(o.v); return; } + if (o.v === "\x00") return; + if (!o.v) { picked = []; closeProtoMenu(); return; } + picked = picked.includes(o.v) ? picked.filter((v) => v !== o.v) : [...picked, o.v]; + items.forEach((it, i) => tick(it, opts[i])); + }; b.onmouseenter = () => b.focus({ preventScroll: true }); box.append(b); return b; @@ -5821,7 +5840,11 @@ function openProtoMenu(anchor, opts, value, choose, head = "Protocol this key sp document.addEventListener("keydown", keys, true); document.addEventListener("scroll", scroll, true); addEventListener("resize", closeProtoMenu); - protoMenu = { box, anchor, outside, keys, scroll }; + const done = multi ? () => { + if (picked.length === value.length && picked.every((v) => value.includes(v))) return; + choose(opts.map((o) => o.v).filter((v) => picked.includes(v))); + } : null; + protoMenu = { box, anchor, outside, keys, scroll, done }; (items.find((b) => b.classList.contains("on")) || items[0]).focus({ preventScroll: true }); } @@ -8742,8 +8765,9 @@ function importForm() { // provider, and the account when there is one. const trayCardID = (q) => q.user ? q.provider + "|" + q.user : q.provider; -// renderTrayUsage: the subscription or plan whose windows show beside the -// tray icon. The cards are the Usage page's, asked for when the menu opens. +// renderTrayUsage: the subscriptions and plans whose windows show beside +// the tray icon, side by side. The cards are the Usage page's, asked for +// when the menu opens; any number are ticked in it. function renderTrayUsage(s, keep) { $("#quotaLeftSegs").replaceChildren(segs([[false, t("Used")], [true, t("Left")]], !!s.quotaLeft, (on) => { if (on !== quotaLeft) setQuotaLeft(on); })); @@ -8755,17 +8779,18 @@ function renderTrayUsage(s, keep) { $("#trayUsageRow").hidden = web; if (web) return; const mac = document.body.classList.contains("mac"); - $("#trayUsageSub").textContent = mac ? t("Show a subscription's use beside magpie's icon in the menu bar, refreshed every few minutes") - : t("Show a subscription's use when pointing at magpie's tray icon, refreshed every few minutes"); - const id = s.trayUsage || ""; - const pill = el("button", "proto pick" + (id ? " set" : "")); + $("#trayUsageSub").textContent = mac ? t("Show your subscriptions' use beside magpie's icon in the menu bar, side by side, refreshed every few minutes") + : t("Show your subscriptions' use when pointing at magpie's tray icon, refreshed every few minutes"); + const ids = s.trayUsages || (s.trayUsage ? [s.trayUsage] : []); + const pill = el("button", "proto pick" + (ids.length ? " set" : "")); pill.type = "button"; const paint = () => { - const card = (quotas || []).find((q) => trayCardID(q) === id); - pill.replaceChildren(el("span", "", !id ? t("Off") : card ? card.name : id.split("|")[0]), svg(CHEV, 11, 1.6)); + const card = (quotas || []).find((q) => trayCardID(q) === ids[0]); + pill.replaceChildren(el("span", "", !ids.length ? t("Off") : ids.length > 1 ? t("{n} subscriptions", { n: ids.length }) + : card ? card.name : ids[0].split("|")[0]), svg(CHEV, 11, 1.6)); }; paint(); - if (id && !quotas) loadQuotas().then(paint); + if (ids.length === 1 && !quotas) loadQuotas().then(paint); pill.onclick = async (e) => { e.stopPropagation(); if (pill.classList.contains("open")) return closeProtoMenu(); @@ -8773,13 +8798,16 @@ function renderTrayUsage(s, keep) { const cards = (quotas || []).filter((q) => !q.error && (q.windows?.length || q.balance)); const opts = [{ v: "", name: "Off", note: "" }, ...cards.map((q) => ({ v: trayCardID(q), name: q.name, note: [q.plan, q.user].filter(Boolean).join(" · ") }))]; + // one ticked that isn't there now (signed out, or not answering) stays + // to be unticked + for (const id of ids) if (!opts.some((o) => o.v === id)) opts.push({ v: id, name: id.split("|")[0], note: id.split("|")[1] || "" }); if (!cards.length) opts.push({ v: "\x00", name: "No subscriptions yet", note: "Sign in to one, or add a plan's key, and it shows on the Usage page" }); - openProtoMenu(pill, opts, id, (v) => { if (v !== id && v !== "\x00") savePrefs({ ...keep, trayUsage: v }); }, "Shown beside the icon"); + openProtoMenu(pill, opts, ids, (trayUsages) => savePrefs({ ...keep, trayUsages }), "Shown beside the icon"); }; $("#trayUsagePick").replaceChildren(pill); // how often it is asked for again, and whether it reads as used or left — // the Usage page's choice too (#122) - $("#trayEveryRow").hidden = !id; + $("#trayEveryRow").hidden = !ids.length; $("#trayEverySegs").replaceChildren(segs(TRAY_EVERY.map((m) => [m, t("{n} min", { n: m })]), s.trayUsageEvery || 3, (trayUsageEvery) => savePrefs({ ...keep, trayUsageEvery }))); } @@ -9184,6 +9212,7 @@ function wbCheckinLine(r) { function prefsKeep(s) { return { theme: s.theme, lang: s.lang, tray: s.tray, dock: !!s.dock, dockWindow: !!s.dockWindow, proxy: s.proxy || "", sessionTerminal: s.sessionTerminal || "", + trayUsages: s.trayUsages || [], redact: !!s.redact, redactPersonal: !!s.redactPersonal, redactWords: s.redactWords || [], codexWarmup: s.codexWarmup || "", claudeWarmup: s.claudeWarmup || "", codexWarmAt: s.codexWarmAt || "", claudeWarmAt: s.claudeWarmAt || "", workbuddyCheckin: !!s.workbuddyCheckin, noStats: !!s.noStats, trayUsage: s.trayUsage || "", trayUsageEvery: s.trayUsageEvery || 3, vision: s.vision || "", imageGen: s.imageGen || "", currency: s.currency || "usd" }; diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 62f3414e4..d6664e5fb 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -136,9 +136,10 @@ const I18N = { "Warm up on reset": "窗口重置时预热", "Daily warm-up": "每日定时预热", "Usage in the menu bar": "菜单栏显示用量", - "Show a subscription's use beside magpie's icon in the menu bar, refreshed every few minutes": "在菜单栏 magpie 图标旁显示一个订阅的用量,每隔几分钟刷新", - "Show a subscription's use when pointing at magpie's tray icon, refreshed every few minutes": "鼠标指向托盘里的 magpie 图标时显示一个订阅的用量,每隔几分钟刷新", + "Show your subscriptions' use beside magpie's icon in the menu bar, side by side, refreshed every few minutes": "在菜单栏 magpie 图标旁并排显示所选订阅的用量,每隔几分钟刷新", + "Show your subscriptions' use when pointing at magpie's tray icon, refreshed every few minutes": "鼠标指向托盘里的 magpie 图标时显示所选订阅的用量,每隔几分钟刷新", "Shown beside the icon": "显示在图标旁", + "{n} subscriptions": "{n} 个订阅", "Menu bar refresh": "菜单栏刷新频率", "How often the usage beside the icon is asked for again": "图标旁的用量多久重新获取一次", "Usage shows": "用量显示", diff --git a/internal/gui/tests/README.md b/internal/gui/tests/README.md index b6b9698df..9a8a3fb74 100644 --- a/internal/gui/tests/README.md +++ b/internal/gui/tests/README.md @@ -175,6 +175,14 @@ cny (#212): the Usage page's total converts, the row's tooltip carries the rate, picking it with the settings list scrolled well down moves nothing, and the choice survives a reload — in English and Chinese. +`tray-usages.test.cjs` picks several of the Usage page's cards for the menu +bar in Settings: the menu keeps open as Codex and Claude Code are ticked +beside Copilot, posts nothing till it closes and then the three once, in the +menu's order; the pill reads "3 subscriptions"; a menu opened and closed +unchanged posts nothing; a save of another setting keeps them; Off unticks +them all, closing the menu and the refresh row; no row has a left-border +stripe and no click moves the page; in English and Chinese. + `text-size.test.cjs` checks the Settings page's Text size row (100, 110, 125 and 150%): a pick posts to /api/settings/text-size without scrolling the page, stays picked after a reload (boot.js carries it, and the page's @@ -376,7 +384,7 @@ that draws the latest numbers. The checks run in English and Chinese. With Node.js and Playwright available: ```sh -node --test internal/gui/tests/menu-scroll.test.cjs internal/gui/tests/click-scroll.test.cjs internal/gui/tests/panel-fold.test.cjs internal/gui/tests/panel-routing.test.cjs internal/gui/tests/gateway-fold.test.cjs internal/gui/tests/routing-kind.test.cjs internal/gui/tests/balance-fix.test.cjs internal/gui/tests/cli-update.test.cjs internal/gui/tests/login-import.test.cjs internal/gui/tests/agy-launch.test.cjs internal/gui/tests/currency.test.cjs internal/gui/tests/usage-ledger.test.cjs internal/gui/tests/update-check.test.cjs internal/gui/tests/omarchy.test.cjs internal/gui/tests/brand.test.cjs node --test internal/gui/tests/signin-callback.test.cjs internal/gui/tests/routing-steady.test.cjs internal/gui/tests/old-webkit.test.cjs internal/gui/tests/session-terminal.test.cjs internal/gui/tests/text-size.test.cjs internal/gui/tests/zcode-site.test.cjs internal/gui/tests/rail-tip.test.cjs internal/gui/tests/sync-update.test.cjs internal/gui/tests/plugin-signin.test.cjs internal/gui/tests/plugin-market.test.cjs internal/gui/tests/s3-sync.test.cjs internal/gui/tests/routing-wb-refused.test.cjs internal/gui/tests/market-have.test.cjs internal/gui/tests/sessions-today.test.cjs internal/gui/tests/routing-side-calls.test.cjs internal/gui/tests/import-all-skills.test.cjs internal/gui/tests/routing-flood.test.cjs internal/gui/tests/routing-busy.test.cjs internal/gui/tests/own-skill.test.cjs internal/gui/tests/routing-manual.test.cjs +node --test internal/gui/tests/menu-scroll.test.cjs internal/gui/tests/click-scroll.test.cjs internal/gui/tests/panel-fold.test.cjs internal/gui/tests/panel-routing.test.cjs internal/gui/tests/gateway-fold.test.cjs internal/gui/tests/routing-kind.test.cjs internal/gui/tests/balance-fix.test.cjs internal/gui/tests/cli-update.test.cjs internal/gui/tests/login-import.test.cjs internal/gui/tests/agy-launch.test.cjs internal/gui/tests/currency.test.cjs internal/gui/tests/usage-ledger.test.cjs internal/gui/tests/update-check.test.cjs internal/gui/tests/omarchy.test.cjs internal/gui/tests/brand.test.cjs node --test internal/gui/tests/signin-callback.test.cjs internal/gui/tests/routing-steady.test.cjs internal/gui/tests/old-webkit.test.cjs internal/gui/tests/session-terminal.test.cjs internal/gui/tests/text-size.test.cjs internal/gui/tests/zcode-site.test.cjs internal/gui/tests/rail-tip.test.cjs internal/gui/tests/sync-update.test.cjs internal/gui/tests/plugin-signin.test.cjs internal/gui/tests/plugin-market.test.cjs internal/gui/tests/s3-sync.test.cjs internal/gui/tests/routing-wb-refused.test.cjs internal/gui/tests/market-have.test.cjs internal/gui/tests/sessions-today.test.cjs internal/gui/tests/routing-side-calls.test.cjs internal/gui/tests/import-all-skills.test.cjs internal/gui/tests/routing-flood.test.cjs internal/gui/tests/routing-busy.test.cjs internal/gui/tests/own-skill.test.cjs internal/gui/tests/routing-manual.test.cjs internal/gui/tests/tray-usages.test.cjs ``` If Playwright is installed outside the repository, set `NODE_PATH` to the diff --git a/internal/gui/tests/tray-usages.test.cjs b/internal/gui/tests/tray-usages.test.cjs new file mode 100644 index 000000000..06fb40563 --- /dev/null +++ b/internal/gui/tests/tray-usages.test.cjs @@ -0,0 +1,173 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// Settings → Usage in the menu bar picks any number of the Usage page's +// cards, shown side by side beside the tray icon: the menu keeps open as +// each is ticked or unticked, and posts the ticked ones once, as it closes, +// in the menu's order; Off unticks them all; the pill says how many; a save +// of another setting keeps them; no click moves the page. English and +// Chinese; no backend, the API is faked here. +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"); + +const quotas = [ + { provider: "claude", name: "Claude Code", icon: "claude-color", user: "a@b.c", plan: "Max", + windows: [{ name: "5-hour", used: 42 }, { name: "Weekly", used: 18 }] }, + { provider: "codex", name: "Codex", icon: "codex-color", user: "x@y.z", plan: "Plus", + windows: [{ name: "5-hour", used: 8 }, { name: "Weekly", used: 100 }] }, + { provider: "copilot", name: "Copilot", icon: "githubcopilot", windows: [{ name: "Premium", used: 63 }] }, + { provider: "kimi", name: "Kimi", icon: "kimi", error: "signed out" }, +]; + +function settingsPayload(over) { + return { + theme: "light", lang: "en", tray: "panel", quotaLeft: false, currency: "usd", + dock: false, dockWindow: false, proxy: "", redact: false, redactPersonal: false, redactWords: [], + codexWarmup: "", claudeWarmup: "", codexWarmAt: "", claudeWarmAt: "", workbuddyCheckin: false, noStats: false, + trayUsage: "copilot", trayUsages: ["copilot"], trayUsageEvery: 3, vision: "", imageGen: "", + version: "0.1.400", dir: "~/.config/magpie", gateway: "http://127.0.0.1:3425", + proxyNow: "none", proxySource: "none", login: false, + visionModels: [], imageGenModels: [], workbuddyCheckins: [], lanURLs: [], + fx: { rate: 7.2, at: new Date().toISOString(), stale: false }, + ...over, + }; +} + +// server answers as magpie does: trayUsage kept as the first of trayUsages +function server(lang, posts) { + let cur = settingsPayload({ lang }); + return 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 = {lang:"${lang}",theme:"light",web:false};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" }, fx: cur.fx }); + if (url.pathname === "/api/settings") { + if (req.method() === "POST") { + const body = req.postDataJSON(); + posts.push(body); + cur = { ...cur, ...body, trayUsage: (body.trayUsages || [])[0] || "" }; + } + return json(cur); + } + if (url.pathname === "/api/usage/quotas") return json(quotas); + if (url.pathname === "/api/groups") return json({ groups: [], models: [] }); + 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)]; + await route.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +const view = (page) => page.locator("#view-settings").evaluate((v) => v.scrollTop); + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": several cards in the menu bar", async (t) => { + assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit"); + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + const pages = []; + t.after(async () => { + if (process.env.ARTIFACT_DIR) { + await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true }); + for (const [i, p] of pages.entries()) await p.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-tray-usages-${i}.png`) }); + } + await browser.close(); + }); + + for (const [lang, off, three, two] of [ + ["en", "Off", "3 subscriptions", "2 subscriptions"], + ["zh", "关闭", "3 个订阅", "2 个订阅"], + ]) { + await t.test(lang, async () => { + const errors = [], posts = []; + const context = await browser.newContext({ viewport: { width: 900, height: 420 }, reducedMotion: "reduce" }); + const page = await context.newPage(); + pages.push(page); + page.setDefaultTimeout(5000); + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", server(lang, posts)); + + await page.goto("http://magpie.test/?view=usage"); + await page.locator("#prefs").click(); + const pill = page.locator("#trayUsagePick button"); + await pill.waitFor(); + await page.waitForFunction(() => document.querySelector("#trayUsagePick button").textContent.trim() === "Copilot"); + assert.equal(await page.locator("#trayEveryRow").isVisible(), true, "the refresh row shows with a card picked"); + + // scrolled down with a real wheel, the pill still in sight + await pill.hover(); + for (let i = 0; i < 20 && !(await view(page)); i++) { await page.mouse.wheel(0, 120); await page.waitForTimeout(20); } + await pill.scrollIntoViewIfNeeded(); + const before = await view(page); + assert(before > 0, "the settings list must be scrolled"); + + // the menu: Off, the cards that can show (not the signed-out one), + // each with a box to tick; Copilot ticked + await pill.click(); + const menu = page.locator(".proto-menu"); + await menu.waitFor(); + const items = menu.locator(".pm-item"); + assert.deepEqual((await items.locator(".pm-name").allTextContents()).map((s) => s.trim()), [off, "Claude Code", "Codex", "Copilot"]); + assert.deepEqual(await items.evaluateAll((bs) => bs.map((b) => b.getAttribute("role"))), + ["menuitemradio", "menuitemcheckbox", "menuitemcheckbox", "menuitemcheckbox"]); + const checked = () => items.evaluateAll((bs) => bs.map((b) => b.getAttribute("aria-checked"))); + assert.deepEqual(await checked(), ["false", "false", "false", "true"]); + // no coloured stripe down a ticked row's side + assert.equal(await items.nth(3).evaluate((b) => getComputedStyle(b).borderLeftWidth), "0px"); + + // ticking two more keeps it open and sends nothing yet + await items.nth(2).click(); + await items.nth(1).click(); + assert.equal(await menu.isVisible(), true, "the menu stays open while ticking"); + assert.deepEqual(await checked(), ["false", "true", "true", "true"]); + assert.equal(posts.length, 0, "nothing is saved till the menu closes"); + assert.equal(await view(page), before, "ticking must not scroll the page"); + + // closing it saves them once, in the menu's order + await page.keyboard.press("Escape"); + await page.waitForFunction((s) => document.querySelector("#trayUsagePick button").textContent.trim() === s, three); + assert.equal(posts.length, 1); + assert.deepEqual(posts[0].trayUsages, ["claude|a@b.c", "codex|x@y.z", "copilot"]); + await page.waitForTimeout(300); + assert.equal(await view(page), before, "saving must not scroll the page"); + + // opened and closed with nothing changed: nothing sent + await pill.click(); + await menu.waitFor(); + await pill.click(); + await menu.waitFor({ state: "detached" }); + assert.equal(posts.length, 1, "an unchanged pick sends nothing"); + + // one unticked, then a click elsewhere: the other two + await pill.click(); + await items.nth(3).click(); + await page.locator("#trayUsageRow .name").click(); + await page.waitForFunction((s) => document.querySelector("#trayUsagePick button").textContent.trim() === s, two); + assert.deepEqual(posts.at(-1).trayUsages, ["claude|a@b.c", "codex|x@y.z"]); + + // another setting saved keeps them + const sent = posts.length; + await page.locator("#currencySegs .opt").nth(1).click(); + for (let i = 0; i < 50 && posts.length === sent; i++) await page.waitForTimeout(50); + assert.equal(posts.at(-1).currency, "cny"); + assert.deepEqual(posts.at(-1).trayUsages, ["claude|a@b.c", "codex|x@y.z"], "a save of another setting keeps the cards"); + + // Off unticks them all and closes the menu + await pill.click(); + await items.nth(0).click(); + await menu.waitFor({ state: "detached" }); + await page.waitForFunction((s) => document.querySelector("#trayUsagePick button").textContent.trim() === s, off); + assert.deepEqual(posts.at(-1).trayUsages, []); + assert.equal(await page.locator("#trayEveryRow").isVisible(), false, "no refresh row with none picked"); + await page.waitForTimeout(300); + assert.equal(await view(page), before, "no click moved the page"); + + assert.deepEqual(errors, []); + await context.close(); + }); + } + }); +} diff --git a/internal/gui/trayimage_darwin.go b/internal/gui/trayimage_darwin.go new file mode 100644 index 000000000..3ccda6442 --- /dev/null +++ b/internal/gui/trayimage_darwin.go @@ -0,0 +1,346 @@ +//go:build darwin && cgo + +package gui + +/* +#cgo CFLAGS: -x objective-c +#cgo LDFLAGS: -framework AppKit +#include +#import + +typedef struct { + const void *icon; + int iconLen; + int mono; + const char *letter; + const char *rows; // one or two, a newline between +} mpTrayCell; + +// Metrics, in points: the menu bar is 22 high (24 beside a notch), and a +// cell is a 14pt logo with its two windows beside it, stacked as small +// digits, each window's figures right-aligned over the other's. +static const CGFloat mpLogo = 14, mpLogoGap = 3, mpCellGap = 8, mpBirdGap = 2, mpRowGap = 3.5; + +static NSFont *mpRowFont(int rows) { + if (rows > 1) return [NSFont monospacedDigitSystemFontOfSize:9.5 weight:NSFontWeightSemibold]; + return [NSFont monospacedDigitSystemFontOfSize:11 weight:NSFontWeightMedium]; +} + +// mpCells reads the cells Go sends into dictionaries the drawing keeps. +static NSArray *mpCells(mpTrayCell *cells, int n) { + NSMutableArray *out = [NSMutableArray arrayWithCapacity:n]; + for (int i = 0; i < n; i++) { + NSMutableDictionary *c = [NSMutableDictionary dictionary]; + if (cells[i].icon != NULL && cells[i].iconLen > 0) { + NSImage *im = [[NSImage alloc] initWithData:[NSData dataWithBytes:cells[i].icon length:cells[i].iconLen]]; + // an SVG an older system can't read comes back as nothing, or empty + if (im != nil && im.representations.count > 0) c[@"icon"] = im; + [im release]; + } + c[@"mono"] = @(cells[i].mono != 0); + c[@"letter"] = [NSString stringWithUTF8String:cells[i].letter ? cells[i].letter : ""]; + NSArray *rows = [[NSString stringWithUTF8String:cells[i].rows ? cells[i].rows : ""] componentsSeparatedByString:@"\n"]; + if (rows.count > 2) rows = [rows subarrayWithRange:NSMakeRange(0, 2)]; + c[@"rows"] = rows; + [out addObject:c]; + } + return out; +} + +static CGFloat mpColumn(NSDictionary *c) { + NSArray *rows = c[@"rows"]; + NSDictionary *attrs = @{NSFontAttributeName: mpRowFont((int)rows.count)}; + CGFloat w = 0; + for (NSString *r in rows) w = MAX(w, ceil([r sizeWithAttributes:attrs].width)); + return w; +} + +static CGFloat mpWidth(NSArray *cells, CGFloat h) { + CGFloat w = h + mpBirdGap; + for (NSDictionary *c in cells) w += mpLogo + mpLogoGap + mpColumn(c) + mpCellGap; + return ceil(w - mpCellGap + 1); +} + +// mpTinted draws a black glyph in the text colour of what it is drawn on +// (the menu bar's, light or dark), as a template image is: in a layer of +// its own, so filling it touches nothing drawn before. +static void mpTinted(NSImage *im, NSRect r) { + CGContextRef cg = [[NSGraphicsContext currentContext] CGContext]; + CGContextBeginTransparencyLayerWithRect(cg, NSRectToCGRect(r), NULL); + [im drawInRect:r fromRect:NSZeroRect operation:NSCompositingOperationSourceOver fraction:1 respectFlipped:YES hints:nil]; + [[NSColor labelColor] set]; + NSRectFillUsingOperation(r, NSCompositingOperationSourceIn); + CGContextEndTransparencyLayer(cg); +} + +// mpDraw draws the bird, then each cell, top down (a flipped context). +static void mpDraw(NSArray *cells, NSImage *bird, CGFloat h) { + if (bird != nil) mpTinted(bird, NSMakeRect(0, 0, h, h)); + CGFloat x = h + mpBirdGap; + NSColor *ink = [NSColor labelColor]; + for (NSDictionary *c in cells) { + NSRect logo = NSMakeRect(x, round((h - mpLogo) / 2), mpLogo, mpLogo); + NSImage *icon = c[@"icon"]; + if (icon != nil && [c[@"mono"] boolValue]) { + mpTinted(icon, logo); + } else if (icon != nil) { + [icon drawInRect:logo fromRect:NSZeroRect operation:NSCompositingOperationSourceOver fraction:1 respectFlipped:YES hints:nil]; + } else { + // no logo: the name's first letter in a ring + NSBezierPath *ring = [NSBezierPath bezierPathWithRoundedRect:NSInsetRect(logo, 0.75, 0.75) xRadius:3.5 yRadius:3.5]; + ring.lineWidth = 1.2; + [ink set]; + [ring stroke]; + NSDictionary *a = @{NSFontAttributeName: [NSFont systemFontOfSize:8.5 weight:NSFontWeightBold], NSForegroundColorAttributeName: ink}; + NSString *l = c[@"letter"]; + NSSize s = [l sizeWithAttributes:a]; + [l drawAtPoint:NSMakePoint(NSMidX(logo) - s.width / 2, NSMidY(logo) - s.height / 2) withAttributes:a]; + } + x += mpLogo + mpLogoGap; + NSArray *rows = c[@"rows"]; + NSFont *f = mpRowFont((int)rows.count); + NSDictionary *a = @{NSFontAttributeName: f, NSForegroundColorAttributeName: ink}; + CGFloat col = mpColumn(c); + // the digits (cap height) centred as a block; drawAtPoint takes the + // line's top, its baseline an ascender below + CGFloat cap = f.capHeight; + CGFloat top = (h - (cap * rows.count + mpRowGap * (rows.count - 1))) / 2; + for (NSUInteger i = 0; i < rows.count; i++) { + NSString *r = rows[i]; + CGFloat base = top + cap * (i + 1) + mpRowGap * i; + CGFloat w = [r sizeWithAttributes:a].width; + [r drawAtPoint:NSMakePoint(x + col - w, base - f.ascender) withAttributes:a]; + } + x += col + mpCellGap; + } +} + +// mpImage is the bird and the cells as one image, drawn afresh each time it +// is shown so its colours follow the menu bar's, and sharp at any scale. +static NSImage *mpImage(NSArray *cells, NSImage *bird, CGFloat h) { + NSImage *im = [NSImage imageWithSize:NSMakeSize(mpWidth(cells, h), h) flipped:YES drawingHandler:^BOOL(NSRect r) { + mpDraw(cells, bird, h); + return YES; + }]; + im.cacheMode = NSImageCacheNever; + return im; +} + +static NSStatusBarButton *mpFind(NSView *v) { + if ([v isKindOfClass:[NSStatusBarButton class]]) return (NSStatusBarButton *)v; + for (NSView *s in v.subviews) { + NSStatusBarButton *b = mpFind(s); + if (b != nil) return b; + } + return nil; +} + +// mpButton is magpie's one status item's button, in the status bar's window. +static NSStatusBarButton *mpButton(void) { + for (NSWindow *w in NSApp.windows) { + NSStatusBarButton *b = mpFind(w.contentView); + if (b != nil) return b; + } + return nil; +} + +// What the item shows while the cells are up; the bird changes as it flaps. +static NSArray *mpShown; +static NSImage *mpBird; + +static void mpApply(void) { + NSStatusBarButton *b = mpButton(); + if (b == nil || mpShown == nil) return; + b.title = @""; + b.image = mpImage(mpShown, mpBird, [[NSStatusBar systemStatusBar] thickness]); + b.imagePosition = NSImageOnly; +} + +static NSImage *mpBirdImage(const void *bird, int len) { + NSImage *im = [[NSImage alloc] initWithData:[NSData dataWithBytes:bird length:len]]; + return im; +} + +// mpShow puts the cells up beside the bird; 0 when there is no item to put +// them on. On the main queue after what Wails has queued there (the label +// taken off), so nothing of Wails' lands after it. +// It runs on a Go thread, which has no autorelease pool of its own to +// drain what reading the cells leaves (every few minutes, for good). +static int mpShow(mpTrayCell *cells, int n, const void *bird, int len) { + __block int ok = 0; + @autoreleasepool { + NSArray *cs = [mpCells(cells, n) retain]; + NSImage *bi = mpBirdImage(bird, len); + dispatch_sync(dispatch_get_main_queue(), ^{ + if (mpButton() == nil) return; + [mpShown release]; + [mpBird release]; + mpShown = cs; + mpBird = [bi retain]; + mpApply(); + ok = 1; + }); + if (!ok) [cs release]; + [bi release]; + } + return ok; +} + +// mpFrame is a frame of the bird's flap while the cells are up; 0 when +// they aren't, and the frame is Wails' to set as the icon. +static int mpFrame(const void *bird, int len) { + __block int ok = 0; + @autoreleasepool { + NSImage *bi = mpBirdImage(bird, len); + dispatch_sync(dispatch_get_main_queue(), ^{ + if (mpShown == nil) return; + [mpBird release]; + mpBird = [bi retain]; + mpApply(); + ok = 1; + }); + [bi release]; + } + return ok; +} + +// mpHide forgets the cells; the icon Wails sets next puts the bird back. +static void mpHide(void) { + dispatch_async(dispatch_get_main_queue(), ^{ + [mpShown release]; + mpShown = nil; + }); +} + +// mpPNG draws the image as the menu bar would at scale, light or dark, on +// the bar's colour when bg is set: for tests and previews. +static void *mpPNG(mpTrayCell *cells, int n, const void *bird, int len, CGFloat h, CGFloat scale, int dark, int bg, int *outLen, int *pxW, int *pxH) { + __block void *out = NULL; + @autoreleasepool { + NSArray *cs = mpCells(cells, n); + NSImage *bi = len > 0 ? [mpBirdImage(bird, len) autorelease] : nil; + CGFloat w = mpWidth(cs, h); + NSBitmapImageRep *rep = [[[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL pixelsWide:(NSInteger)ceil(w * scale) pixelsHigh:(NSInteger)ceil(h * scale) + bitsPerSample:8 samplesPerPixel:4 hasAlpha:YES isPlanar:NO colorSpaceName:NSDeviceRGBColorSpace bytesPerRow:0 bitsPerPixel:0] autorelease]; + rep.size = NSMakeSize(w, h); + *pxW = (int)rep.pixelsWide; + *pxH = (int)rep.pixelsHigh; + NSGraphicsContext *g = [NSGraphicsContext graphicsContextWithBitmapImageRep:rep]; + NSAppearance *look = [NSAppearance appearanceNamed:dark ? NSAppearanceNameDarkAqua : NSAppearanceNameAqua]; + [NSGraphicsContext saveGraphicsState]; + [NSGraphicsContext setCurrentContext:g]; + void (^paint)(void) = ^{ + if (bg) { + [(dark ? [NSColor colorWithSRGBRed:0.16 green:0.16 blue:0.17 alpha:1] : [NSColor colorWithSRGBRed:0.93 green:0.93 blue:0.94 alpha:1]) set]; + NSRectFill(NSMakeRect(0, 0, w, h)); + } + [mpImage(cs, bi, h) drawInRect:NSMakeRect(0, 0, w, h)]; + }; + if (@available(macOS 11.0, *)) { + [look performAsCurrentDrawingAppearance:paint]; + } else { + paint(); // the system's own look, light or dark as it is + } + [g flushGraphics]; + [NSGraphicsContext restoreGraphicsState]; + NSData *png = [rep representationUsingType:NSBitmapImageFileTypePNG properties:@{}]; + *outLen = (int)png.length; + out = malloc(png.length); + memcpy(out, png.bytes, png.length); + } + return out; +} +*/ +import "C" + +import ( + "strings" + "unsafe" +) + +// The Mac's menu bar draws the cards as one image beside the bird (see +// trayusage.go): drawn by AppKit, as the bar's own text is, in its colour +// light or dark and sharp at any scale. Wails sizes an icon it is given to +// a square, so the image is set on the status item's button here; the +// bird's flap goes through it while it is up (trayImageFrame). + +// withCells hands the cells to C for the length of f. +func withCells(cells []trayCell, f func(*C.mpTrayCell, C.int)) { + if len(cells) == 0 { + f(nil, 0) + return + } + cs := (*[1 << 16]C.mpTrayCell)(C.malloc(C.size_t(len(cells)) * C.size_t(unsafe.Sizeof(C.mpTrayCell{}))))[:len(cells):len(cells)] + var owned []unsafe.Pointer + for i, c := range cells { + cs[i] = C.mpTrayCell{letter: C.CString(c.Letter), rows: C.CString(strings.Join(c.Rows, "\n"))} + owned = append(owned, unsafe.Pointer(cs[i].letter), unsafe.Pointer(cs[i].rows)) + if len(c.Icon) > 0 { + cs[i].icon, cs[i].iconLen = C.CBytes(c.Icon), C.int(len(c.Icon)) + owned = append(owned, cs[i].icon) + } + if c.Mono { + cs[i].mono = 1 + } + } + defer func() { + for _, p := range owned { + C.free(p) + } + C.free(unsafe.Pointer(&cs[0])) + }() + f(&cs[0], C.int(len(cells))) +} + +func cBytes(b []byte) (unsafe.Pointer, C.int) { + if len(b) == 0 { + return nil, 0 + } + return C.CBytes(b), C.int(len(b)) +} + +// trayImageShow puts the cells up beside the bird; false when the item +// can't be found, and the text is to be shown instead. +func trayImageShow(cells []trayCell, bird []byte) bool { + ok := false + b, n := cBytes(bird) + defer C.free(b) + withCells(cells, func(cs *C.mpTrayCell, count C.int) { ok = C.mpShow(cs, count, b, n) != 0 }) + return ok +} + +// trayImageFrame sets a frame of the bird's flap while the cells are up; +// false when they aren't, for Wails to set it as the icon. +func trayImageFrame(bird []byte) bool { + b, n := cBytes(bird) + defer C.free(b) + return C.mpFrame(b, n) != 0 +} + +// trayImageHide takes the cells down; the icon set next is the bird alone. +func trayImageHide() { C.mpHide() } + +// trayImagePNG is the image as the menu bar h points high draws it at +// scale (2 for a Retina screen), light or dark, on the bar's colour when +// bg; with its size in pixels. +func trayImagePNG(cells []trayCell, bird []byte, h, scale float64, dark, bg bool) (png []byte, w, ht int) { + b, n := cBytes(bird) + defer C.free(b) + withCells(cells, func(cs *C.mpTrayCell, count C.int) { + var size, pw, ph C.int + p := C.mpPNG(cs, count, b, n, C.CGFloat(h), C.CGFloat(scale), cBool(dark), cBool(bg), &size, &pw, &ph) + if p != nil { + png = C.GoBytes(p, size) + C.free(p) + } + w, ht = int(pw), int(ph) + }) + return png, w, ht +} + +func cBool(b bool) C.int { + if b { + return 1 + } + return 0 +} diff --git a/internal/gui/trayimage_darwin_test.go b/internal/gui/trayimage_darwin_test.go new file mode 100644 index 000000000..57ed73b3f --- /dev/null +++ b/internal/gui/trayimage_darwin_test.go @@ -0,0 +1,101 @@ +//go:build darwin && cgo + +package gui + +import ( + "bytes" + "fmt" + "image" + "image/png" + "os" + "path/filepath" + "testing" + "time" +) + +// The menu bar's image: the bird, then a cell for each card side by side, +// drawn at twice the points for a Retina screen, in the bar's text colour +// light or dark. MAGPIE_TRAY_PREVIEW= writes each as a PNG to look at. +func TestTrayImage(t *testing.T) { + bird, err := os.ReadFile("tray.png") + if err != nil { + t.Fatal(err) + } + cells, _, _ := trayUsageView(trayCards(), time.Now(), false) + out := os.Getenv("MAGPIE_TRAY_PREVIEW") + widths := map[bool][]int{} + for _, dark := range []bool{false, true} { + for n := 0; n <= 3; n++ { + b, w, h := trayImagePNG(cells[:n], bird, 22, 2, dark, false) + img, err := png.Decode(bytes.NewReader(b)) + if err != nil { + t.Fatalf("%d cells: %v", n, err) + } + if h != 44 || img.Bounds().Dx() != w || img.Bounds().Dy() != h { + t.Fatalf("%d cells: %dx%d px, image %v", n, w, h, img.Bounds()) + } + widths[dark] = append(widths[dark], w) + // the bird and each cell's digits are there, in the bar's text + // colour: dark on the light bar, light on the dark one + ink := inkIn(img, image.Rect(0, 0, 44, 44), dark) + if ink < 40 { + t.Errorf("%d cells, dark %v: the bird has %d px of ink", n, dark, ink) + } + // and the last card's, in what it adds to the width + if n > 0 { + if ink := inkIn(img, image.Rect(widths[dark][n-1], 0, w, h), dark); ink < 60 { + t.Errorf("%d cells, dark %v: the last cell has %d px of ink", n, dark, ink) + } + } + if out != "" { + bg, _, _ := trayImagePNG(cells[:n], bird, 22, 2, dark, true) + name := fmt.Sprintf("tray-%d-%s.png", n, map[bool]string{false: "light", true: "dark"}[dark]) + if err := os.WriteFile(filepath.Join(out, name), bg, 0o644); err != nil { + t.Fatal(err) + } + } + } + } + // each card widens it, by no more than a modest cell + for dark, ws := range widths { + if ws[0] > 52 { + t.Errorf("dark %v: the bird alone is %d px", dark, ws[0]) + } + for i := 1; i < len(ws); i++ { + if d := ws[i] - ws[i-1]; d < 40 || d > 110 { + t.Errorf("dark %v: cell %d widens it by %d px", dark, i, d) + } + } + } + if widths[false][3] != widths[true][3] { + t.Errorf("light %d px, dark %d px", widths[false][3], widths[true][3]) + } + + // a logo that can't be read, or none, is the name's letter in a ring + b, _, _ := trayImagePNG([]trayCell{{Icon: []byte("not a picture"), Letter: "Z", Rows: []string{"5%", "7%"}}, {Letter: "Q", Rows: []string{"$3"}}}, bird, 22, 2, false, false) + img, err := png.Decode(bytes.NewReader(b)) + if err != nil { + t.Fatal(err) + } + if ink := inkIn(img, image.Rect(48, 8, 48+28, 36), false); ink < 40 { + t.Errorf("no letter where the logo can't be read: %d px", ink) + } +} + +// inkIn counts the pixels in r drawn in the bar's text colour. +func inkIn(img image.Image, r image.Rectangle, dark bool) int { + n := 0 + for y := r.Min.Y; y < r.Max.Y && y < img.Bounds().Max.Y; y++ { + for x := r.Min.X; x < r.Max.X && x < img.Bounds().Max.X; x++ { + c, g, b, a := img.At(x, y).RGBA() + if a < 0x8000 { + continue + } + lum := (c + g + b) / 3 * 0xffff / max(a, 1) + if dark && lum > 0xc000 || !dark && lum < 0x4000 { + n++ + } + } + } + return n +} diff --git a/internal/gui/trayimage_other.go b/internal/gui/trayimage_other.go new file mode 100644 index 000000000..4f23a0703 --- /dev/null +++ b/internal/gui/trayimage_other.go @@ -0,0 +1,12 @@ +//go:build !darwin || !cgo + +package gui + +// Only the Mac's menu bar draws the cards as an image (trayimage_darwin.go); +// other trays show the text. + +func trayImageShow([]trayCell, []byte) bool { return false } + +func trayImageFrame([]byte) bool { return false } + +func trayImageHide() {} diff --git a/internal/gui/trayusage.go b/internal/gui/trayusage.go index 468fb2dd7..715ed25e3 100644 --- a/internal/gui/trayusage.go +++ b/internal/gui/trayusage.go @@ -5,6 +5,7 @@ import ( "context" "fmt" "math" + "regexp" "slices" "strings" "time" @@ -13,10 +14,12 @@ import ( "github.com/yetone/magpie/internal/settings" ) -// Settings → Usage in the menu bar: one subscription's or plan's windows -// beside the tray icon ("42% · 18%"), for keeping an eye on them without -// opening magpie. The Mac's menu bar shows the text; Windows' tray has no -// room for any, and gets it in the icon's tooltip only. +// Settings → Usage in the menu bar: the windows of the subscriptions and +// plans ticked there, beside the tray icon, for keeping an eye on them +// without opening magpie. The Mac's menu bar draws each as its logo with +// its two windows stacked, "42%" over "18%", side by side (trayimage); a +// tray elsewhere gets them as text ("42% · 18% | 10% · 5%"), Windows' in +// the icon's tooltip only, having no room for any. // trayUsageEvery is how often the text is brought up to date, as Settings // says (every 3 minutes unless told otherwise). The vendors are asked no @@ -121,19 +124,167 @@ func until(d time.Duration) string { return fmt.Sprintf("%dm", max(mins, 1)) } -// trayUsageCard is the card settings.TrayUsage names, among the Usage -// page's (cached as there); false when it is off or gone. -func trayUsageCard(ctx context.Context) (provider.SubscriptionQuota, bool) { - id := settings.Load().TrayUsage - if id == "" { - return provider.SubscriptionQuota{}, false +// trayUsageCards are the cards settings.TrayUsages names, in its order, +// among the Usage page's (cached as there); one gone is left out. +func trayUsageCards(ctx context.Context, ids []string) []provider.SubscriptionQuota { + if len(ids) == 0 { + return nil } - cards := provider.Quotas(ctx) - i := slices.IndexFunc(cards, func(q provider.SubscriptionQuota) bool { return trayCardID(q) == id }) - if i < 0 { - return provider.SubscriptionQuota{}, false + return trayPick(provider.Quotas(ctx), ids) +} + +func trayPick(cards []provider.SubscriptionQuota, ids []string) []provider.SubscriptionQuota { + var out []provider.SubscriptionQuota + for _, id := range ids { + if i := slices.IndexFunc(cards, func(q provider.SubscriptionQuota) bool { return trayCardID(q) == id }); i >= 0 { + out = append(out, cards[i]) + } } - return cards[i], true + return out +} + +// trayCell is a card as the Mac's menu bar draws it: its logo, and its +// label's parts stacked, the shortest window over the longer ("42%" over +// "18%"), or its balance alone. +type trayCell struct { + Icon []byte // the logo as the Usage page has it (SVG or PNG); nil for none + Mono bool // a black glyph, drawn in the menu bar's text colour + Letter string // drawn in its place when there is no logo, or it can't be read + Rows []string +} + +// trayUsageView is what the tray shows for the cards: a cell for each +// that has a label; the labels as one line of text, " | " between cards, +// for a tray that shows text and not the cells; and the tooltip spelling +// each out. +func trayUsageView(cards []provider.SubscriptionQuota, now time.Time, left bool) (cells []trayCell, label, tip string) { + var labels, tips []string + for _, q := range cards { + l, t := trayUsageText(q, now, left) + if t != "" { + tips = append(tips, t) + } + if l == "" { + continue + } + labels = append(labels, l) + c := trayCell{Rows: strings.Split(l, " · ")} + for i, r := range c.Rows { + c.Rows[i] = trayRow(r) + } + c.Icon, c.Mono = trayIconFile(q.Icon) + if r := []rune(strings.TrimSpace(q.Name)); len(r) > 0 { + c.Letter = strings.ToUpper(string(r[0])) + } + cells = append(cells, c) + } + return cells, strings.Join(labels, " | "), strings.Join(tips, "\n\n") +} + +// trayRow is a cell's row cut to fit the menu bar: a balance is a few +// figures ("¥12345.67"), but one read from a plan's own page can be any +// text, and the whole of it is in the tooltip. +func trayRow(r string) string { + if rs := []rune(r); len(rs) > trayRowMax { + return strings.TrimSpace(string(rs[:trayRowMax-1])) + "…" + } + return r +} + +const trayRowMax = 10 + +// trayIconFile is a card's logo among the page's icons, as its icon() has +// it: a "-color" one and the PNGs in their own colours, the others a black +// glyph (a mask there); nil when there is no such file (a picture the user +// gave their own provider isn't one). +func trayIconFile(name string) (b []byte, mono bool) { + if name == "" || strings.ContainsAny(name, `/\:`) { + return nil, false + } + if b, err := assets.ReadFile("assets/icons/" + name + ".png"); err == nil { + return b, false + } + b, err := assets.ReadFile("assets/icons/" + name + ".svg") + if err != nil { + return nil, false + } + return svgArcFlags(b), !strings.HasSuffix(name, "-color") +} + +var svgPathData = regexp.MustCompile(`\sd="([^"]*[aA][^"]*)"`) + +// svgArcFlags spaces out the flags of a path's arcs ("a4.5 4.5 0 004.5 0", +// the flags run into the number after them), which browsers read and the +// Mac's own SVG drawing doesn't: it draws a line for such an arc, and +// Codex's logo comes out a blot. +func svgArcFlags(svg []byte) []byte { + return svgPathData.ReplaceAllFunc(svg, func(m []byte) []byte { + d := string(svgPathData.FindSubmatch(m)[1]) + var out []string + cmd, arg := byte(0), 0 + for i := 0; i < len(d); { + c := d[i] + switch { + case c == ' ' || c == ',' || c == '\t' || c == '\n' || c == '\r': + i++ + case c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z': + if c == 'e' || c == 'E' { // not a command: a number's exponent, never alone + return m + } + cmd, arg = c, 0 + out = append(out, string(c)) + i++ + case (cmd == 'a' || cmd == 'A') && (arg%7 == 3 || arg%7 == 4): + if c != '0' && c != '1' { + return m + } + out = append(out, string(c)) + arg++ + i++ + default: + j := svgNumber(d, i) + if j == i { + return m + } + out = append(out, d[i:j]) + arg++ + i = j + } + } + return []byte(` d="` + strings.Join(out, " ") + `"`) + }) +} + +// svgNumber is where the number at d[i:] ends: a sign, digits with at most +// one point, an exponent. +func svgNumber(d string, i int) int { + j := i + if j < len(d) && (d[j] == '-' || d[j] == '+') { + j++ + } + digits, point := 0, false + for j < len(d) && (d[j] >= '0' && d[j] <= '9' || d[j] == '.' && !point) { + if d[j] == '.' { + point = true + } else { + digits++ + } + j++ + } + if digits == 0 { + return i + } + if j < len(d) && (d[j] == 'e' || d[j] == 'E') { + k := j + 1 + if k < len(d) && (d[k] == '-' || d[k] == '+') { + k++ + } + if k < len(d) && d[k] >= '0' && d[k] <= '9' { + for j = k; j < len(d) && d[j] >= '0' && d[j] <= '9'; j++ { + } + } + } + return j } // onTrayUsage brings the tray's text up to date at once, when the Settings diff --git a/internal/gui/trayusage_cells_test.go b/internal/gui/trayusage_cells_test.go new file mode 100644 index 000000000..159625b1f --- /dev/null +++ b/internal/gui/trayusage_cells_test.go @@ -0,0 +1,137 @@ +package gui + +import ( + "slices" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// trayCards are three cards as the Usage page has them: Claude and Codex +// with a 5-hour and a weekly window, and a plan with a balance. +func trayCards() []provider.SubscriptionQuota { + week, five := 7*24*time.Hour, 5*time.Hour + return []provider.SubscriptionQuota{ + {Provider: "claude", Name: "Claude Code", Icon: "claude-color", User: "a@b.c", Windows: []provider.QuotaWindow{ + {Name: "Weekly", Used: 17.6, Span: week}, {Name: "5-hour", Used: 42.2, Span: five}}}, + {Provider: "codex", Name: "Codex", Icon: "codex-color", User: "x@y.z", Windows: []provider.QuotaWindow{ + {Name: "5-hour", Used: 8, Span: five}, {Name: "Weekly", Used: 100, Span: week}}}, + {Provider: "copilot", Name: "Copilot", Icon: "githubcopilot", Windows: []provider.QuotaWindow{ + {Name: "Premium", Used: 63}}}, + {Provider: "deepseek", Name: "DeepSeek", Icon: "deepseek-color", Balance: "¥12.30"}, + } +} + +func TestTrayUsageCells(t *testing.T) { + now := time.Date(2026, 9, 30, 12, 0, 0, 0, time.UTC) + cards := trayCards() + + // the ticked ones in the order ticked; one no longer there is left out + picked := trayPick(cards, []string{"codex|x@y.z", "gone|who", "claude|a@b.c"}) + if len(picked) != 2 || picked[0].Provider != "codex" || picked[1].Provider != "claude" { + t.Fatalf("picked %+v", picked) + } + if got := trayPick(cards, nil); got != nil { + t.Fatalf("none ticked: %+v", got) + } + if got := trayPick(cards, []string{"claude"}); got != nil { + t.Fatalf("the vendor without the account: %+v", got) + } + + for _, tc := range []struct { + ids []string + rows [][]string + label string + }{ + {nil, nil, ""}, + {[]string{"claude|a@b.c"}, [][]string{{"42%", "18%"}}, "42% · 18%"}, + {[]string{"claude|a@b.c", "codex|x@y.z"}, [][]string{{"42%", "18%"}, {"8%", "100%"}}, "42% · 18% | 8% · 100%"}, + {[]string{"claude|a@b.c", "codex|x@y.z", "copilot", "deepseek"}, + [][]string{{"42%", "18%"}, {"8%", "100%"}, {"63%"}, {"¥12.30"}}, "42% · 18% | 8% · 100% | 63% | ¥12.30"}, + } { + cells, label, tip := trayUsageView(trayPick(cards, tc.ids), now, false) + if label != tc.label { + t.Errorf("%v: label %q, want %q", tc.ids, label, tc.label) + } + if len(cells) != len(tc.rows) { + t.Fatalf("%v: %d cells, want %d", tc.ids, len(cells), len(tc.rows)) + } + for i, c := range cells { + if !slices.Equal(c.Rows, tc.rows[i]) { + t.Errorf("%v: cell %d rows %q, want %q", tc.ids, i, c.Rows, tc.rows[i]) + } + } + if n := strings.Count(tip, "\n\n"); len(tc.ids) > 0 && n != len(tc.ids)-1 { + t.Errorf("%v: tip has %d cards apart:\n%s", tc.ids, n+1, tip) + } + } + + // each cell with its logo as the page draws it: its own colours, or a + // black glyph to tint; the name's letter always there to fall back on + cells, _, _ := trayUsageView(cards, now, false) + for i, want := range []struct { + mono bool + letter string + svg bool + }{{false, "C", true}, {false, "C", true}, {true, "C", true}, {false, "D", true}} { + c := cells[i] + if len(c.Icon) == 0 || c.Mono != want.mono || c.Letter != want.letter || strings.Contains(string(c.Icon[:min(len(c.Icon), 200)]), "`: ``, + ``: ``, + // no arc: as it was + ``: ``, + // what isn't a path's data is left alone + ``: ``, + } { + if got := string(svgArcFlags([]byte(in))); got != want { + t.Errorf("%s\n got %s\nwant %s", in, got, want) + } + } + // as Codex's logo is handed to the menu bar + b, _ := trayIconFile("codex-color") + if !strings.Contains(string(b), "A 4.496 4.496 0 0 0 0 4.496") { + t.Errorf("codex's logo not spaced out: %.300s", b) + } +} diff --git a/internal/gui/trayusage_tray.go b/internal/gui/trayusage_tray.go index 4af996ff4..e5744c48b 100644 --- a/internal/gui/trayusage_tray.go +++ b/internal/gui/trayusage_tray.go @@ -5,14 +5,15 @@ package gui import ( "context" "runtime" + "strings" "time" "github.com/yetone/magpie/internal/provider" "github.com/yetone/magpie/internal/settings" ) -// watchTrayUsage keeps the tray's text up to date, and plain "magpie" in -// the tooltip while it is off. +// watchTrayUsage keeps the tray's cards up to date, and plain "magpie" in +// the tooltip while there are none. func (h *host) watchTrayUsage() { wake := make(chan struct{}, 1) onTrayUsage = func() { @@ -26,28 +27,50 @@ func (h *host) watchTrayUsage() { provider.OnSubscriptionUsage = onTrayUsage go func() { <-h.ready // the tray is made once the app runs - shown := "" + shown, drawn := "", false for { ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) - label, tip := "", "magpie" - if q, ok := trayUsageCard(ctx); ok { - if label, tip = trayUsageText(q, time.Now(), settings.Load().QuotaLeft); tip == "" { - tip = "magpie" - } - } + s := settings.Load() + cells, label, tip := trayUsageView(trayUsageCards(ctx, s.TrayUsages), time.Now(), s.QuotaLeft) cancel() - if label != "" && runtime.GOOS == "darwin" { - // the menu bar sets the text hard against the icon - label = "\u2009" + label + if tip == "" { + tip = "magpie" } - if label+"\x00"+tip != shown { - shown = label + "\x00" + tip - h.tray.SetLabel(label) + if runtime.GOOS != "darwin" { + cells = nil + } else if label != "" { + // the menu bar sets the text hard against the icon + label = " " + label + } + // what is shown, to set it again only when it changes + now := label + "\x00" + tip + for _, c := range cells { + now += "\x00" + c.Letter + strings.Join(c.Rows, "\x01") + } + if now != shown { + shown = now + // the Mac's cells as an image, the text where it can't be + if len(cells) > 0 { + h.tray.SetLabel("") + if trayImageShow(cells, trayIcon) { + drawn = true + } else { + h.tray.SetLabel(label) + shown = "" // and try again next time + } + } else { + if drawn { + drawn = false + trayImageHide() + h.tray.SetTemplateIcon(trayIcon) + } + h.tray.SetLabel(label) + } h.tray.SetTooltip(tip) } // the first answer can take a while; look again soon after it next := trayUsageEvery() - if label == "" && settings.Load().TrayUsage != "" { + if label == "" && len(s.TrayUsages) > 0 { next = 20 * time.Second } select { diff --git a/internal/settings/settings.go b/internal/settings/settings.go index 6f7640577..cc97eae59 100644 --- a/internal/settings/settings.go +++ b/internal/settings/settings.go @@ -94,8 +94,13 @@ type Settings struct { // gateway's /v1/images/generations when a request names no model): a // model's id, "off", or empty for one magpie picks (gateway.drawer). ImageGen string `json:"imageGen,omitempty"` - // TrayUsage is the subscription or plan whose windows are shown beside - // the tray icon, by its provider and account ("claude|a@b.c"); "" none. + // TrayUsages are the subscriptions and plans whose windows are shown + // beside the tray icon, in the order shown, each by its provider and + // account ("claude|a@b.c"); none when empty. + TrayUsages []string `json:"trayUsages,omitempty"` + // TrayUsage is TrayUsages' first, all a magpie before them read: a file + // with it and no TrayUsages shows that one, and it is kept written for + // an older magpie to go on showing it. TrayUsage string `json:"trayUsage,omitempty"` // TrayUsageEvery is how often, in minutes, that text is brought up to // date; 0 is every 3 (one of TrayEvery). @@ -400,6 +405,11 @@ func Save(s Settings) error { } s.RedactRules = rules s.AgentOrder, s.AgentsHidden, s.AgentsShown = ids(s.AgentOrder), ids(s.AgentsHidden), ids(s.AgentsShown) + s.TrayUsages = ids(s.TrayUsages) + s.TrayUsage = "" + if len(s.TrayUsages) > 0 { + s.TrayUsage = s.TrayUsages[0] + } if err := os.MkdirAll(Dir(), 0o755); err != nil { return err } @@ -435,6 +445,11 @@ func (s Settings) normal() Settings { if s.TextSize == 0 { s.TextSize = 100 } + // one card, as a magpie before TrayUsages kept it; an empty list + // sent on purpose (all of them turned off) stays empty + if s.TrayUsages == nil && s.TrayUsage != "" { + s.TrayUsages = []string{s.TrayUsage} + } // a time of day as 06:00 whichever way it came (6:00, 06:00:00) for _, at := range []*string{&s.CodexWarmAt, &s.ClaudeWarmAt} { *at = strings.TrimSpace(*at) diff --git a/internal/settings/trayusages_test.go b/internal/settings/trayusages_test.go new file mode 100644 index 000000000..01c639314 --- /dev/null +++ b/internal/settings/trayusages_test.go @@ -0,0 +1,59 @@ +package settings + +import ( + "os" + "slices" + "strings" + "testing" +) + +// The menu bar shows several cards (TrayUsages); a settings file from before +// them, with the one TrayUsage, shows that one, and TrayUsage is kept as the +// first for an older magpie. +func TestTrayUsagesMigrate(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + if err := os.MkdirAll(Dir(), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(Path(), []byte(`{"trayUsage":"claude|a@b.c","trayUsageEvery":5}`), 0o644); err != nil { + t.Fatal(err) + } + s := Load() + if !slices.Equal(s.TrayUsages, []string{"claude|a@b.c"}) || s.TrayUsage != "claude|a@b.c" { + t.Fatalf("old file: %q %q", s.TrayUsages, s.TrayUsage) + } + // saved as it was read, then with more: TrayUsage follows the first + if err := Save(s); err != nil { + t.Fatal(err) + } + if s = Load(); !slices.Equal(s.TrayUsages, []string{"claude|a@b.c"}) { + t.Fatalf("saved as read: %q", s.TrayUsages) + } + s.TrayUsages = []string{" codex|x@y.z ", "claude|a@b.c", "codex|x@y.z", ""} + if err := Save(s); err != nil { + t.Fatal(err) + } + b, _ := os.ReadFile(Path()) + s = Load() + if !slices.Equal(s.TrayUsages, []string{"codex|x@y.z", "claude|a@b.c"}) || s.TrayUsage != "codex|x@y.z" { + t.Fatalf("several: %q %q\n%s", s.TrayUsages, s.TrayUsage, b) + } + if !strings.Contains(string(b), `"trayUsage": "codex|x@y.z"`) { + t.Fatalf("first not kept for an older magpie:\n%s", b) + } + // all turned off, though the page still sends the first it was drawn with + s.TrayUsages = []string{} + if err := Save(s); err != nil { + t.Fatal(err) + } + if s = Load(); len(s.TrayUsages) != 0 || s.TrayUsage != "" { + t.Fatalf("off: %q %q", s.TrayUsages, s.TrayUsage) + } + // and none of either is none + if err := Save(Settings{}); err != nil { + t.Fatal(err) + } + if s = Load(); s.TrayUsages != nil || s.TrayUsage != "" { + t.Fatalf("none: %q %q", s.TrayUsages, s.TrayUsage) + } +}