tray: Windows shows a card's number in its icon (Benjaminliang_1 on X)

Windows' notification area shows no text beside an icon, so with a card
in the tray the icon itself is now the first card's figure: the first
row of the first card whose first row is a percentage, used or left as
Allowance display has it, its digits alone (trayIconFigure). It is drawn
in Segoe UI Semibold (Go's bold if the font can't be read) at
SM_CXSMICON, white on a dark taskbar, near black on a light one, as tall
as fits, centred by its ink, three digits narrowed into the square
(trayNumberIcon). It is drawn again when the figure, the icon size or
the taskbar theme changes (SystemThemeChanged wakes the loop); the
tooltip still lists every card. A balance or magpie's totals are
skipped; with no such card, or no cards at all, the icon is the bird as
before. Settings > Usage > Tray icon number (settings.TrayNoNumber,
Windows only, on by default, kept per computer) keeps the bird when off;
Menu bar windows is now shown on Windows too, since it picks the row
the number comes from. The number row sits after Menu bar cost, so the
bird > pace > cost order the other tests pin holds. Linux and the Mac
are unchanged. New words in zh, zh-TW, ja and de. app.js stays in the
core budget with one comment shortened, no raise.

Run at this commit on origin/main ec104b862 (traywindows.js merged with
94f6f6092's trayExtra pills; its "not on Windows" note dropped), mote:
gofmt -l empty; go vet and GOOS=windows go vet of gui and settings ok;
go test -count=1 -timeout 45m ./internal/settings ./internal/davsync
ok; ./internal/gui red only on TestMainWindowCorners (#3949),
TestCoreScriptBudget ok. GUI tray-windows, tray-cost, quota-pace,
i18n-keys, tray-bird, tray-logos, tray-usages, quit-ask: 140 pass,
0 fail. win-run on xiaomi-gpu: TestTrayNumberIcon and
TestTrayIconFigure ok. At c0477aa72 the same GUI set once had
quota-pace webkit "On moved the page" (439 !== 120), a late wheel
(#4784); green twice after, and quota-pace alone 3 of 3 green there
and on c0477aa72 itself.

Run before on the same change over origin/main 9d08993c8, mote:
- gofmt -l on gui/settings/davsync: empty; go vet ./internal/gui
  ./internal/settings and GOOS=windows go vet: ok.
- go test -count=1 -timeout 45m ./internal/gui ./internal/settings
  ./internal/davsync: settings ok, davsync ok; gui red only on
  TestMainWindowCorners/macOS_26_SDK (#3949) and TestCoreScriptBudget
  (5 bytes over after the rebase), which is green after the comment
  trim, rerun with TestTrayNumberIcon and TestTrayIconFigure: ok.
- GUI (both engines): tray-windows, tray-cost, quota-pace: 56 pass,
  0 fail. Earlier at this tree: tray-bird, tray-logos, tray-usages,
  i18n-keys green; quota-pace webkit de 420 red once, from a late wheel
  scroll (#4784), green on the rerun; segs-press-redraw red on
  searchAllRow, the same on a clean origin/main 9d08993c8 copy (#4566).
- A 184-file GUI run (the files touching Settings, the tray or i18n,
  before the rebase) under mote load 40-90: 3095 pass, 224 fail. My
  files' reds there (tray-cost: the number row was between pace and
  cost) are fixed above. The rest are in files this change doesn't
  reach (account-alias, model chips, menu-input-scroll, mobile-web,
  omarchy, plugin-github, key-replace, context-map and others; #4600
  lists several). Each was not compared on main one by one.
Windows (win-run on xiaomi-gpu, real Segoe UI): TestTrayNumberIcon and
TestTrayIconFigure ok.
Real Windows 11 run: a production build in a portable sandbox (own
data\, USERPROFILE/APPDATA/LOCALAPPDATA redirected, gateway on a free
port, a fake remote magpie serving one Claude card). The dark taskbar
showed a white "42", then a narrowed "100" when the card read 100%,
and the bird with trayNoNumber set. Only my processes, tasks and
NotifyIconSettings entry were removed afterwards.

Broken by hand: trayIconFigure always "" turns TestTrayIconFigure red
(6 cases); the dark and light colours swapped turn TestTrayNumberIcon
red; the old advance-width centring turns it red too.

Not tried: a light taskbar on the real box (it would change the user's
theme; covered by the test only), hovering the tooltip (screen locked),
other DPIs on real hardware, Windows on ARM64. Linux's code is
unchanged and was not run.
This commit is contained in:
yetone
2026-11-01 21:31:55 +08:00
parent 2b52302dcb
commit da275848b6
14 changed files with 450 additions and 21 deletions
+3 -3
View File
@@ -487,9 +487,9 @@ covers it in both engines, every language and a narrow window.
- The requests magpie makes by itself (a routing classifier's, a web search's, an image description's) are told apart from the agents' on the Usage page (#1839): magpie's row among the agents and its rows in the ledger carry a "magpie's own" mark (`ownBadge`), an account's, key's or model's row adds "{n} by magpie itself" from the summary's `own`, and an account's card says how many of the period's requests were magpie's own (`ownLine`, drawn again once the summary comes after the allowances). See `own-requests.test.cjs` and `TestSummaryCountsMagpiesOwnCallsApart`.
- Opening the allowances is asking to see them (#1588, `quotasOpened` in `app.js`): the Usage page from the nav or its Overview tab picked, the window brought back to the front on the Overview, the tray panel's Allowances tab picked or the panel brought up on it, and a menu bar cell clicked each load `usage/quotas?asked=1`, as Refresh now does. An asked read makes the backend read every account again (`AskClaudeUsage`), so an opening within 30s (`QUOTAS_OPEN_GAP`) of the last asked read sends an ordinary read instead, which joins one on its way; Refresh now always asks. A panel page loaded while it is put away (hidden, or without focus) doesn't ask. The timed refresh is unchanged and never asks. See `allowance-open-read.test.cjs`.
- The menu bar can show magpie's own totals beside the allowances (#1984): `usage:today` and `usage:7d` in `settings.TrayUsages`, offered after the cards in the same picker. `trayUsageCards` sums them with `usage.QueryPage(p, Filter{}, 0, 1).Sum` (the Requests tab's and the panel's cached ledger sum, gateway and session-file calls together) and asks no vendor when only totals are picked; `trayTotalCard` makes every token (in, out and cache, as `allTokens`), marked `Σ` so it doesn't read as the input, over the cost in Settings' currency, `+` when some calls had no price, the cost row left out when none had one. The Mac draws them as plain cells, the bird beside them saying whose. A click opens the Requests tab at the period (`quotaView`, `?tab=requests&period=`) or the panel's Usage tab (`panelUseFocus`). No 3-day total: the Usage page has no such window. See `TestTrayTotals` and `tray-totals.test.cjs`. Settings › *Menu bar cost* (`settings.TrayNoCost`, on by default, on every OS, per computer through `KeepOwn`) turned off leaves the money out (BussanQ on Discord): `trayMoney` drops the total's cost and its count of unpriced calls before `trayTotalCard` and the no-card tooltip `trayIdleTip` see it, so the cards, their tooltip and the idle tooltip say the tokens and requests alone. A relay's or subscription's balance card is money itself and stays. See `TestTrayNoCost` and `tray-cost.test.cjs`.
- The tray's icon is the bird alone where the bar's other icons are glyphs: the Mac's menu bar takes `tray.png` as a template image, and a Linux bar (StatusNotifierItem `IconPixmap`) gets the same silhouette in one colour on transparency (`trayIconFor`, `linuxTrayIcon` in [`trayglyph.go`](../../internal/gui/trayglyph.go)), so a bar that tints its icons by their alpha tints the bird, not a tile (ylorn on Discord). A bar that doesn't tint shows it light, or dark when the portal's `org.freedesktop.appearance` `color-scheme` prefers light (`traySchemeLight`), and it is drawn again when that changes (`watchTrayScheme`). No `IconName` is set: a host that found a `-symbolic` name and drew it untinted would show a black bird on a dark bar, with no pixmap to fall back on. Windows' tray keeps the app's coloured icon. With no cards in the menu bar the tooltip is magpie over today's total (`trayIdleTip`: every token, split into input, output and cache as the today card's tooltip is, then the cost and the requests), brought up to date with the cards' refresh; the tray's menu stays Open, the version and Quit. Wails sets the tooltip only on Windows: on Linux `setTrayTip` sets the StatusNotifierItem's `ToolTip` and sends `NewToolTip` ([`traytip_linux.go`](../../internal/gui/traytip_linux.go)), and on the Mac it is the status item's button's `toolTip` (`trayTipNative` in [`trayimage_darwin.go`](../../internal/gui/trayimage_darwin.go); NextCommit on Discord: no hover there showed anything). See `TestTrayIconPerOS`, `TestTrayIdleTip` and `TestMacTrayTipIsSet`.
- A window's Pace is a number on its card's reset line (fflake33 on Discord): the share used less the share of the window gone by, in points, "Pace +12%" over an even pace and "−8%" under it, turned with the meter when it shows what is left, amber while more is used than an even pace would have (`quotaPace`, `paceLine`). The window's start is the gateway's, `startsAt` from `provider.WithWindowStarts` (its reset less its span, `QuotaWindow.Bounds`); a window whose span isn't known, with no limit, or a past cycle has none. Settings › *Menu bar pace* (`settings.TrayPace`, off by default, hidden on Windows, whose tray shows no text) puts the same number beside each figure in the menu bar and in its tooltip (`trayPace`, `QuotaWindow.Pace`). See `TestWindowPace`, `TestTrayUsagePace` and `quota-pace.test.cjs`.
- Settings › *Menu bar windows* (`settings.TrayWindows`, StrikingRaw on X) picks which of a subscription's windows its menu bar card shows, keyed by provider id (every account of it, the in-use `|*` card too) and by window kind, not position: `trayWindowKind` names a window by its span ("5h", "1d", "7d", "month", "15m"), by `name:` its name when the span isn't known. Unset shows every window, as before; a pick none of whose kinds the card still has shows every window again (`trayShownKinds`), never an empty card. Only the bar's rows and the Linux label are filtered; the tooltip still says every window. One row draws in the menu bar's own font (13pt regular), two stacked rows in 10pt regular, both with digits of one width (`mpRowFont`, `TestTrayRowFont`; qingnianxiaozhe on X found the old 9.5pt semibold and 11pt medium heavier than Surge's and iStat Menus' figures beside them). The GUI learns the kinds from `trayKind` on `/api/usage/quotas` (`withTrayKinds`; model and aside windows get none). The row lists a pill per ticked subscription with two or more kinds, opening the app's menu (All windows, then each kind), hidden on Windows; its code is in `traywindows.js`, imported when Settings draws ticked cards. Per computer through `KeepOwn`. See `TestTrayWindowsPicked`, `TestTrayWindowsKept` and `tray-windows.test.cjs`.
- The tray's icon is the bird alone where the bar's other icons are glyphs: the Mac's menu bar takes `tray.png` as a template image, and a Linux bar (StatusNotifierItem `IconPixmap`) gets the same silhouette in one colour on transparency (`trayIconFor`, `linuxTrayIcon` in [`trayglyph.go`](../../internal/gui/trayglyph.go)), so a bar that tints its icons by their alpha tints the bird, not a tile (ylorn on Discord). A bar that doesn't tint shows it light, or dark when the portal's `org.freedesktop.appearance` `color-scheme` prefers light (`traySchemeLight`), and it is drawn again when that changes (`watchTrayScheme`). No `IconName` is set: a host that found a `-symbolic` name and drew it untinted would show a black bird on a dark bar, with no pixmap to fall back on. Windows' tray keeps the app's coloured icon, unless a card is in the menu bar: Windows' notification area shows no text beside an icon, so the icon itself is the first card's figure (Benjaminliang_1 on X; `trayIconFigure`, `trayNumberIcon` in [`traynumber.go`](../../internal/gui/traynumber.go)). It is the first row of the first card whose first row is a percentage, used or left as Allowance display has it, through *Menu bar windows*' pick, its digits alone, drawn in Segoe UI Semibold (Go's bold where the font can't be read) at `SM_CXSMICON`, white on a dark taskbar and near black on a light one, as tall as fits with a pixel above and below, centred by its ink, and three digits narrowed into the square. A balance or magpie's totals are skipped for the next card; with none the icon is the bird. It is drawn again when the figure, the icon size or the taskbar's theme changes (`SystemThemeChanged` wakes the loop); the tooltip still says every card. Settings › *Tray icon number* (`settings.TrayNoNumber`, Windows' alone, on by default) keeps the bird when off. One icon is set for the current theme, not a light and a dark one: Wails' Windows tray shares one handle between them. Linux keeps its label and tooltip; the Mac its cells. See `TestTrayIconFigure`, `TestTrayNumberIcon` and `tray-windows.test.cjs`. With no cards in the menu bar the tooltip is magpie over today's total (`trayIdleTip`: every token, split into input, output and cache as the today card's tooltip is, then the cost and the requests), brought up to date with the cards' refresh; the tray's menu stays Open, the version and Quit. Wails sets the tooltip only on Windows: on Linux `setTrayTip` sets the StatusNotifierItem's `ToolTip` and sends `NewToolTip` ([`traytip_linux.go`](../../internal/gui/traytip_linux.go)), and on the Mac it is the status item's button's `toolTip` (`trayTipNative` in [`trayimage_darwin.go`](../../internal/gui/trayimage_darwin.go); NextCommit on Discord: no hover there showed anything). See `TestTrayIconPerOS`, `TestTrayIdleTip` and `TestMacTrayTipIsSet`.
- A window's Pace is a number on its card's reset line (fflake33 on Discord): the share used less the share of the window gone by, in points, "Pace +12%" over an even pace and "−8%" under it, turned with the meter when it shows what is left, amber while more is used than an even pace would have (`quotaPace`, `paceLine`). The window's start is the gateway's, `startsAt` from `provider.WithWindowStarts` (its reset less its span, `QuotaWindow.Bounds`); a window whose span isn't known, with no limit, or a past cycle has none. Settings › *Menu bar pace* (`settings.TrayPace`, off by default, hidden on Windows, whose tray shows no text but the first card's figure as its icon) puts the same number beside each figure in the menu bar and in its tooltip (`trayPace`, `QuotaWindow.Pace`). See `TestWindowPace`, `TestTrayUsagePace` and `quota-pace.test.cjs`.
- Settings › *Menu bar windows* (`settings.TrayWindows`, StrikingRaw on X) picks which of a subscription's windows its menu bar card shows, keyed by provider id (every account of it, the in-use `|*` card too) and by window kind, not position: `trayWindowKind` names a window by its span ("5h", "1d", "7d", "month", "15m"), by `name:` its name when the span isn't known. Unset shows every window, as before; a pick none of whose kinds the card still has shows every window again (`trayShownKinds`), never an empty card. Only the bar's rows, the Linux label and Windows' icon figure are filtered; the tooltip still says every window. One row draws in the menu bar's own font (13pt regular), two stacked rows in 10pt regular, both with digits of one width (`mpRowFont`, `TestTrayRowFont`; qingnianxiaozhe on X found the old 9.5pt semibold and 11pt medium heavier than Surge's and iStat Menus' figures beside them). The GUI learns the kinds from `trayKind` on `/api/usage/quotas` (`withTrayKinds`; model and aside windows get none). The row lists a pill per ticked subscription with two or more kinds, opening the app's menu (All windows, then each kind), shown on Windows too, where the first card's pick decides the tray icon's figure; its code is in `traywindows.js`, imported when Settings draws ticked cards. Per computer through `KeepOwn`. See `TestTrayWindowsPicked`, `TestTrayWindowsKept` and `tray-windows.test.cjs`.
- In Usage → Allowances, Trends → Cycle offers each account's own recorded cycle menu beside its curve (`quotaCurve`, `quotaRecordedCycles` in [`app.js`](../../internal/gui/assets/app.js)). The longest window (usually weekly) owns the menu; shorter windows are drawn over the selected dates with their own reset breaks. `/api/usage/quotas/history?days=45` supplies all retained readings, including remote cards. Completed cycles come from observed boundaries, not seven-day arithmetic; an early reset ends the previous cycle at the vendor's new start if it fits between readings, otherwise at the first new reading. Each menu option gives its observed duration, so an early reset is not labelled as a full seven days. The selected meters, plot, legend, tooltip and dashed pace use that cycle's last readings, never today's percentages. A window without a reading in the selected interval says so instead of showing a current value. A local account's past cycle asks `/api/usage/quotas/history/holds?provider=&user=&from=&to=` once per selection (`quotaCycleHoldsOf`), which asks no vendor (#2009, NorethSea): `HistoricalWindowHolds` in [`window_holds_history.go`](../../internal/usage/window_holds_history.go) reckons each window's whole at its own last reading in that cycle, from the request log up to that reading, so the 5-hour figure is the cycle's last 5-hour window, never its short windows added up. Its tooltip names that window's start and the reading's time. It shows "Loading…" until the answer comes. A window it can't reckon says "not enough data" with the reason, as a current card does; a reply that comes after another cycle was picked is dropped, and a card's Refresh or an asked read reckons again. Historical meters show the cycle end and sampling time; current account actions, balances and policies are left out until returning to the current view. Accounts are independent, and a selection survives card refreshes in the same page. Trends → 2 days temporarily shows recent readings; Off removes the curves; the tray always shows its current cycle. See `quota-curve.test.cjs` and the [history limits and reset inference](providers-accounts.md#constraints-and-failure-behavior).
- The Usage page's cards are packed into columns, never all stretched to a row's height (`packUsage`, #860): each card in that order goes to the leftmost column that ends highest, on 1px grid rows, so short cards stack beside a tall one. The last card in each column then reaches down to where the tallest column ends (a `min-height`, cleared before the cards are measured again), so cards side by side in one row are as tall as each other and a stack ends with the tall card beside it (ikunbots on X); content stays at each card's top. The page's order (DOM, dragging, Alt+arrows) stays `UsageOrder`. The column count is the most 260px columns that fit, or one fewer when that leaves much less empty room; it is chosen again only when the cards change or the width fits another number of columns, so a card opened or folded stays where it is, even as the scrollbar comes in. See `usage-pack.test.cjs`.
- The Providers page has a search box over its list (#1614, `findProviders` in [`app.js`](../../internal/gui/assets/app.js)): the words typed keep the rows, on and off, whose text or data say them all: name, id, preset, addresses, every model's id and name, the account's user and plan and each login's, account names and key names. The Turned off fold stays open while searching; Escape or clearing the box shows every row and the fold as it was. A row that is on reorders by dragging its logo, Alt+↑/↓, Alt+Shift+↑/↓ (top, bottom) or its right-click menu (`openProviderMenu`: Move to top, Move up, Move down, Move to bottom). While searching, a step or a drop moves it among the rows shown (it takes the place of the row it passes, `stepProvider`, `shownToOn`) and the hidden ones keep their order; Move to top and Move to bottom go to the ends of the whole list. Every move saves the whole order through `POST /api/providers/arrange`. See `provider-find.test.cjs` and `provider-order.test.cjs`.
+2 -2
View File
@@ -191,7 +191,7 @@ func TestSync(t *testing.T) {
a, b := newComputer(t), newComputer(t)
a.use(t)
provider.Save(provider.Provider{ID: "deepseek", Name: "DeepSeek", Chat: "https://api.deepseek.com/v1", Key: "k1"})
settings.Save(settings.Settings{Theme: "dark", Proxy: "http://127.0.0.1:7890", Window: []int{900, 700}, TrayUsages: []string{"claude|a@b.c"}, TrayUsageEvery: 5, TrayNoLogos: true, TrayNoBird: true, TrayPace: true, TrayNoCost: true, TrayWindows: map[string][]string{"claude": {"5h"}}})
settings.Save(settings.Settings{Theme: "dark", Proxy: "http://127.0.0.1:7890", Window: []int{900, 700}, TrayUsages: []string{"claude|a@b.c"}, TrayUsageEvery: 5, TrayNoLogos: true, TrayNoBird: true, TrayNoNumber: true, TrayPace: true, TrayNoCost: true, TrayWindows: map[string][]string{"claude": {"5h"}}})
profile.Save("work", profile.Profile{Fields: map[string]string{"claude.model": "x"}})
same := cfg
same.Passphrase = cfg.Password
@@ -236,7 +236,7 @@ func TestSync(t *testing.T) {
}
// nor does a's menu bar: what shows beside the icon is b's own (yoooo
// on Discord)
if s := settings.Load(); len(s.TrayUsages) != 0 || s.TrayUsage != "" || s.TrayUsageEvery == 5 || s.TrayNoLogos || s.TrayNoBird || s.TrayPace || s.TrayNoCost || s.TrayWindows != nil {
if s := settings.Load(); len(s.TrayUsages) != 0 || s.TrayUsage != "" || s.TrayUsageEvery == 5 || s.TrayNoLogos || s.TrayNoBird || s.TrayNoNumber || s.TrayPace || s.TrayNoCost || s.TrayWindows != nil {
t.Fatalf("b's menu bar: %+v", s)
}
if ps, _ := profile.Load(); len(ps) != 1 {
+3 -2
View File
@@ -1380,11 +1380,12 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
onDock(in)
}
// the cards the menu bar shows, any of them (TrayUsage is only the first),
// how often, with their logos or not, beside the bird or not, and
// how often, with their logos or not, beside the bird or not, as
// Windows' icon or not, and
// with their Pace numbers or not, with magpie's totals' cost or not, and
// which of each subscription's windows
if (!slices.Equal(settings.Load().TrayUsages, cur.TrayUsages) || in.TrayUsageEvery != cur.TrayUsageEvery ||
in.TrayNoLogos != cur.TrayNoLogos || in.TrayNoBird != cur.TrayNoBird || in.TrayPace != cur.TrayPace ||
in.TrayNoLogos != cur.TrayNoLogos || in.TrayNoBird != cur.TrayNoBird || in.TrayNoNumber != cur.TrayNoNumber || in.TrayPace != cur.TrayPace ||
in.TrayNoCost != cur.TrayNoCost || !maps.EqualFunc(in.TrayWindows, cur.TrayWindows, slices.Equal)) && onTrayUsage != nil {
onTrayUsage()
}
+3 -3
View File
@@ -20636,8 +20636,8 @@ function renderTrayUsage(s, keep) {
$("#trayPaceRow").hidden = !ids.length || document.documentElement.classList.contains("win");
$("#trayPaceSegs").replaceChildren(segs([["off", t("Off")], ["on", t("On")]], s.trayPace ? "on" : "off",
(v) => savePrefs({ ...keep, trayPace: v === "on" })));
// which windows a card shows
if (!ids.length) $("#trayWindowsRow").hidden = true;
// a card's windows
if (!ids.length) $("#trayWindowsRow").hidden = $("#trayNumberRow").hidden = true;
else import("./traywindows.js").then(() => trayWindowsRow(s, keep, ids, mac), () => {});
// and the cost beside magpie's own totals, in their cards and the
// tooltip, which every OS shows with or without cards (BussanQ)
@@ -22652,7 +22652,7 @@ function prefsKeep(s) {
codexWarmAts: warmTimes(s.codexWarmAts, s.codexWarmAt), claudeWarmAts: warmTimes(s.claudeWarmAts, s.claudeWarmAt), workbuddyCheckin: !!s.workbuddyCheckin, traeCheckin: !!s.traeCheckin, minimaxCheckin: !!s.minimaxCheckin, qoderCheckin: !!s.qoderCheckin, noStats: !!s.noStats, noUsageStats: !!s.noUsageStats, signInLinkOnly: !!s.signInLinkOnly,
memberModel: !!s.memberModel, noLoopGuard: !!s.noLoopGuard, claudeLeanPrompt: !!s.claudeLeanPrompt, claudePrintMode: !!s.claudePrintMode, refusalRetries: s.refusalRetries ?? null,
noUpdatePill: !!s.noUpdatePill, noAutoUpdate: !!s.noAutoUpdate, updateEvery: s.updateEvery || 360, autoRestart: !!s.autoRestart, noAutoDownload: !!s.noAutoDownload, updateChannel: s.updateChannel || "",
trayUsage: s.trayUsage || "", trayUsageEvery: s.trayUsageEvery || 3, trayNoLogos: !!s.trayNoLogos, trayNoBird: !!s.trayNoBird, trayPace: !!s.trayPace, trayNoCost: !!s.trayNoCost, trayWindows: s.trayWindows || {}, vision: s.vision || "", visionEffort: s.visionEffort || "", searcherEffort: s.searcherEffort || "", imageGen: s.imageGen || "", imageTimeout: s.imageTimeout || 0, classifyTimeout: s.classifyTimeout || 0, searcher: s.searcher || "", searchFirst: s.searchFirst || "", currency: s.currency || "usd",
trayUsage: s.trayUsage || "", trayUsageEvery: s.trayUsageEvery || 3, trayNoLogos: !!s.trayNoLogos, trayNoBird: !!s.trayNoBird, trayNoNumber: !!s.trayNoNumber, trayPace: !!s.trayPace, trayNoCost: !!s.trayNoCost, trayWindows: s.trayWindows || {}, vision: s.vision || "", visionEffort: s.visionEffort || "", searcherEffort: s.searcherEffort || "", imageGen: s.imageGen || "", imageTimeout: s.imageTimeout || 0, classifyTimeout: s.classifyTimeout || 0, searcher: s.searcher || "", searchFirst: s.searchFirst || "", currency: s.currency || "usd",
chineseUnits: !!s.chineseUnits, usageAlert: s.usageAlert || 0, balanceAlert: s.balanceAlert || 0, resetReminder: s.resetReminder || 0,
turnDoneAlert: s.turnDoneAlert || 0, maskAlert: !!s.maskAlert };
}
+8
View File
@@ -1082,6 +1082,8 @@ const I18N = {
"Shown in the menu bar": "显示在菜单栏",
"Show your subscriptions' allowances, or the tokens and cost of today or the last 7 days, beside magpie's icon in the menu bar, side by side, refreshed every few minutes": "在菜单栏 magpie 图标旁并排显示所选订阅的额度,或今天、最近 7 天的 token 数和费用,每隔几分钟刷新",
"Show your subscriptions' allowances, or the tokens and cost of today or the last 7 days, when pointing at magpie's tray icon, refreshed every few minutes": "鼠标指向托盘里的 magpie 图标时显示所选订阅的额度,或今天、最近 7 天的 token 数和费用,每隔几分钟刷新",
"Tray icon number": "托盘图标数字",
"The first allowance's figure as magpie's tray icon, used or left as Allowance display has it, every one when pointing at it; off, magpie's icon": "把第一个额度的数字作为托盘里的 magpie 图标,已用或剩余按「额度显示」的设置;鼠标指向时显示全部额度;关闭后显示 magpie 图标",
"{n} shown": "已选 {n} 项",
"Tokens and cost today": "今天的 token 数和费用",
"Tokens and cost, last 7 days": "最近 7 天的 token 数和费用",
@@ -5450,6 +5452,8 @@ const I18N = {
"Shown in the menu bar": "顯示在選單列",
"Show your subscriptions' allowances, or the tokens and cost of today or the last 7 days, beside magpie's icon in the menu bar, side by side, refreshed every few minutes": "在選單列 magpie 圖示旁並排顯示所選訂閱的額度,或今天、最近 7 天的 token 數和費用,每隔幾分鐘重新整理",
"Show your subscriptions' allowances, or the tokens and cost of today or the last 7 days, when pointing at magpie's tray icon, refreshed every few minutes": "滑鼠指向托盤裡的 magpie 圖示時顯示所選訂閱的額度,或今天、最近 7 天的 token 數和費用,每隔幾分鐘重新整理",
"Tray icon number": "托盤圖示數字",
"The first allowance's figure as magpie's tray icon, used or left as Allowance display has it, every one when pointing at it; off, magpie's icon": "把第一個額度的數字作為托盤裡的 magpie 圖示,已用或剩餘依「額度顯示」的設定;滑鼠指向時顯示全部額度;關閉後顯示 magpie 圖示",
"{n} shown": "已選 {n} 項",
"Tokens and cost today": "今天的 token 數和費用",
"Tokens and cost, last 7 days": "最近 7 天的 token 數和費用",
@@ -9789,6 +9793,8 @@ const I18N = {
"Shown in the menu bar": "メニューバーに表示",
"Show your subscriptions' allowances, or the tokens and cost of today or the last 7 days, beside magpie's icon in the menu bar, side by side, refreshed every few minutes": "メニューバーの magpie アイコンの横に、サブスクリプションの利用枠、または今日・直近 7 日間のトークン数と費用を並べて表示します(数分ごとに更新)",
"Show your subscriptions' allowances, or the tokens and cost of today or the last 7 days, when pointing at magpie's tray icon, refreshed every few minutes": "トレイの magpie アイコンにポインタを合わせると、サブスクリプションの利用枠、または今日・直近 7 日間のトークン数と費用を表示します(数分ごとに更新)",
"Tray icon number": "トレイアイコンの数値",
"The first allowance's figure as magpie's tray icon, used or left as Allowance display has it, every one when pointing at it; off, magpie's icon": "最初の利用枠の数値を magpie のトレイアイコンとして表示します。使用済みか残りかは「利用枠の表示」に従い、ポインタを合わせるとすべての利用枠を表示します。オフにすると magpie のアイコンになります",
"{n} shown": "{n} 件を表示",
"Tokens and cost today": "今日のトークン数と費用",
"Tokens and cost, last 7 days": "直近 7 日間のトークン数と費用",
@@ -14143,6 +14149,8 @@ const I18N = {
"Shown in the menu bar": "In der Menüleiste angezeigt",
"Show your subscriptions' allowances, or the tokens and cost of today or the last 7 days, beside magpie's icon in the menu bar, side by side, refreshed every few minutes": "Kontingente Ihrer Abos oder Tokens und Kosten von heute bzw. den letzten 7 Tagen nebeneinander neben dem magpie-Symbol in der Menüleiste anzeigen, alle paar Minuten aktualisiert",
"Show your subscriptions' allowances, or the tokens and cost of today or the last 7 days, when pointing at magpie's tray icon, refreshed every few minutes": "Kontingente Ihrer Abos oder Tokens und Kosten von heute bzw. den letzten 7 Tagen beim Zeigen auf das magpie-Tray-Symbol anzeigen, alle paar Minuten aktualisiert",
"Tray icon number": "Zahl im Tray-Symbol",
"The first allowance's figure as magpie's tray icon, used or left as Allowance display has it, every one when pointing at it; off, magpie's icon": "Der Wert des ersten Kontingents als magpie-Tray-Symbol, verbraucht oder übrig wie in der Kontingentanzeige eingestellt, alle beim Zeigen darauf; aus: das magpie-Symbol",
"{n} shown": "{n} angezeigt",
"Tokens and cost today": "Tokens und Kosten heute",
"Tokens and cost, last 7 days": "Tokens und Kosten, letzte 7 Tage",
+4
View File
@@ -284,6 +284,10 @@
<div class="who"><div class="name" data-t>Menu bar cost</div><div class="sub" data-t>What magpie's requests cost, beside their tokens in the menu bar and its tooltip; off, the tokens alone</div></div>
<div id="trayCostSegs"></div>
</div>
<div class="row pref" id="trayNumberRow" hidden>
<div class="who"><div class="name" data-t>Tray icon number</div><div class="sub" data-t>The first allowance's figure as magpie's tray icon, used or left as Allowance display has it, every one when pointing at it; off, magpie's icon</div></div>
<div id="trayNumberSegs"></div>
</div>
<div class="row pref">
<div class="who"><div class="name" data-t>Allowance display</div><div class="sub" data-t>How much of each window is used, or how much is left, on the Usage page, the panel and the menu bar</div></div>
<div id="quotaLeftSegs"></div>
+10 -4
View File
@@ -1,20 +1,26 @@
// Settings › Menu bar windows. app.js imports this only when the menu bar
// Settings › Menu bar windows, and Windows' Tray icon number. app.js imports this only when the menu bar
// shows a card (renderTrayUsage), so it weighs nothing on the core.
// which of a subscription's windows its menu bar card shows, by kind
// (settings.TrayWindows, StrikingRaw on X): a pill each for those ticked
// with two or more, every window unless some are picked; not on Windows,
// whose tooltip says them all. A window the card shows only when picked
// with two or more, every window unless some are picked. A window the card shows only when picked
// (trayExtra: money aside, one model's, Cursor's Grok Bot, CrazyJal on X)
// is offered too; its usual windows ticked alone are no pick at all.
window.trayWindowsRow = function trayWindowsRow(s, keep, ids, mac) {
// Windows' tray shows no text: the first card's figure is its icon, or
// the bird (Benjaminliang_1 on X)
$("#trayNumberRow").hidden = !document.documentElement.classList.contains("win");
$("#trayNumberSegs").replaceChildren(segs([["off", t("Off")], ["on", t("On")]], s.trayNoNumber ? "off" : "on",
(v) => savePrefs({ ...keep, trayNoNumber: v === "off" })));
const pick = s.trayWindows || {}, box = $("#trayWindowsPick"), subs = [];
for (const pid of new Set(ids.filter((id) => !id.startsWith("usage:")).map((id) => id.split("|")[0]))) {
const ws = [], q = (quotas || []).find((q) => q.provider === pid);
for (const w of q?.windows || []) if (w.trayKind && !ws.some((x) => x.v === w.trayKind)) ws.push({ v: w.trayKind, name: w.name, note: "", extra: !!w.trayExtra });
if (ws.length > 1) subs.push([pid, q.name, ws]);
}
$("#trayWindowsRow").hidden = !subs.length || !mac && document.documentElement.classList.contains("win");
// Windows' tray icon draws the first one's figure (traynumber.go), so
// which window it is matters there too
$("#trayWindowsRow").hidden = !subs.length;
if (!quotas && ids.some((id) => !id.startsWith("usage:"))) loadQuotas().then(() => box.isConnected && trayWindowsRow(s, keep, ids, mac));
box.replaceChildren(...subs.map(([pid, name, ws]) => {
const on = (pick[pid] || []).filter((k) => ws.some((w) => w.v === k)), b = el("button", "proto pick" + (on.length ? " set" : ""));
+52 -4
View File
@@ -5,9 +5,12 @@
// window unless some are picked. The pick is saved by provider, kept when
// another setting is saved, and All windows takes it back. A window the
// card shows only when picked (trayExtra: Opus, Cursor's Grok Bot,
// CrazyJal on X) is offered too, and can be picked alone. Hidden on
// Windows, whose tray shows the tooltip alone, and with no card of two
// windows. Every language; narrow too. No backend, the API is faked here.
// CrazyJal on X) is offered too, and can be picked alone. Hidden with no
// card of two windows; shown on Windows too, whose tray icon draws the
// first card's figure. Settings → Tray icon number (settings.TrayNoNumber,
// Benjaminliang_1 on X) is Windows' alone: on, the icon is that figure;
// off, magpie's bird. Every language; narrow too. No backend, the API is
// faked here.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
@@ -181,10 +184,55 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
});
await t.test("hidden where it changes nothing", async () => {
for (const opt of [{ platform: "Win32" }, { over: { trayUsages: ["copilot", "usage:today"], trayUsage: "copilot" } }, { over: { trayUsages: [], trayUsage: "" } }]) {
for (const opt of [{ over: { trayUsages: ["copilot", "usage:today"], trayUsage: "copilot" } }, { over: { trayUsages: [], trayUsage: "" } }, { platform: "Win32", over: { trayUsages: [], trayUsage: "" } }]) {
const { context, page } = await open(browser, "en", [], opt);
await page.waitForTimeout(300);
assert.equal(await page.locator("#trayWindowsRow").isVisible(), false, JSON.stringify(opt));
assert.equal(await page.locator("#trayNumberRow").isVisible(), false, JSON.stringify(opt));
await context.close();
}
});
const NUMBER = { en: ["Tray icon number", "Off", "On"], zh: ["托盘图标数字", "关闭", "开启"], "zh-TW": ["托盤圖示數字", "關閉", "開啟"], ja: ["トレイアイコンの数値", "オフ", "オン"], de: ["Zahl im Tray-Symbol", "Aus", "An"] };
for (const [lang] of LANGS) {
await t.test("Windows: " + lang, async () => {
const posts = [];
const { context, page, errors } = await open(browser, lang, posts, { platform: "Win32", over: { trayWindows: { claude: ["7d"] } } });
// which window is the icon's figure matters on Windows too
await page.locator("#trayWindowsRow").waitFor();
const row = page.locator("#trayNumberRow");
await row.waitFor();
const [name, off, on] = NUMBER[lang];
assert.equal(await row.locator(".name").textContent(), name);
const segs = row.locator("#trayNumberSegs button");
assert.deepEqual((await segs.allTextContents()).map((s) => s.trim()), [off, on]);
// on unless turned off: nothing changes for the user till then
assert.equal(await segs.nth(1).getAttribute("aria-pressed"), "true");
await segs.nth(0).click();
for (let i = 0; i < 100 && !posts.length; i++) await page.waitForTimeout(20);
assert.equal(posts.length, 1);
assert.equal(posts[0].trayNoNumber, true);
assert.deepEqual(posts[0].trayWindows, { claude: ["7d"] }, "the pick is kept");
// another setting saved keeps it off
await page.waitForFunction(() => document.querySelector("#trayNumberSegs button")?.getAttribute("aria-pressed") === "true");
await page.locator("#trayWindowsPick button").click();
await page.locator(".proto-menu .pm-item").first().click();
await page.keyboard.press("Escape");
for (let i = 0; i < 100 && posts.length < 2; i++) await page.waitForTimeout(20);
assert.equal(posts.at(-1).trayNoNumber, true);
// the Mac's menu bar rows are not Windows'
for (const id of ["#trayLogosRow", "#trayBirdRow", "#trayPaceRow"]) assert.equal(await page.locator(id).isVisible(), false, id);
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true, "no sideways scroll");
assert.deepEqual(errors, []);
await context.close();
});
}
await t.test("Tray icon number is Windows' alone", async () => {
for (const platform of ["MacIntel", "Linux x86_64"]) {
const { context, page } = await open(browser, "en", [], { platform });
await page.locator("#trayWindowsRow").waitFor();
assert.equal(await page.locator("#trayNumberRow").isVisible(), false, platform);
await context.close();
}
});
+171
View File
@@ -0,0 +1,171 @@
//go:build !nogui
package gui
import (
"bytes"
"image"
"image/color"
"image/png"
"math"
"strings"
"sync"
xdraw "golang.org/x/image/draw"
"golang.org/x/image/font"
"golang.org/x/image/font/gofont/gobold"
"golang.org/x/image/font/opentype"
"golang.org/x/image/math/fixed"
)
// Windows' notification area shows icons alone, never text beside them,
// so the Mac's menu bar cells can't be shown there (Benjaminliang_1 on X:
// "windows 能不能支持一下显示"). Instead the tray icon itself becomes the
// first card's figure, its digits alone ("42" for 42% used, or left as
// Settings has it), in the taskbar's own text colour on transparency, as
// a battery or a clock in that row is; the tooltip spells out every card.
// A card with no percentage (a balance, magpie's totals) can't be read in
// so small a square: the next card's is drawn, and with none the icon
// stays the bird. Settings › Tray icon number (settings.TrayNoNumber)
// keeps the bird.
// trayIconFigure is the figure goos's tray icon is drawn as for the
// cells: Windows' alone, unless Settings keeps the bird (noNumber).
func trayIconFigure(goos string, noNumber bool, cells []trayCell) string {
if goos != "windows" || noNumber {
return ""
}
return trayFigure(cells)
}
// trayFigure is the figure Windows' tray icon draws for the cells: the
// first row of the first cell whose first row is a percentage, its digits
// alone ("42% +3%" is "42"); "" when no cell has one.
func trayFigure(cells []trayCell) string {
for _, c := range cells {
if len(c.Rows) == 0 {
continue
}
r, _, _ := strings.Cut(strings.TrimSpace(c.Rows[0]), " ")
n, ok := strings.CutSuffix(r, "%")
if ok && n != "" && len(n) <= 3 && strings.Trim(n, "0123456789") == "" {
return n
}
}
return ""
}
// Taskbar text colours: white on a dark taskbar, near black on a light
// one, as linuxTrayIcon's glyph is.
func trayNumberColour(dark bool) color.NRGBA {
if dark {
return trayGlyphLight
}
return trayGlyphDark
}
var (
trayFontOnce sync.Once
trayFontFace *opentype.Font
)
// trayNumberFont is the system's UI font (trayNumberFontFile: Segoe UI's
// semibold on Windows), or Go's bold where it can't be read.
func trayNumberFont() *opentype.Font {
trayFontOnce.Do(func() {
if b := trayNumberFontFile(); b != nil {
if f, err := opentype.Parse(b); err == nil {
trayFontFace = f
return
}
}
trayFontFace, _ = opentype.Parse(gobold.TTF)
})
return trayFontFace
}
// trayNumberIcon is fig drawn as a size×size tray icon (PNG) for a dark
// or light taskbar: the digits as tall as fits with a little room above
// and below, centred; three of them ("100") are narrowed to fit the
// square rather than drawn smaller. nil when it can't be drawn.
func trayNumberIcon(fig string, size int, dark bool) []byte {
f := trayNumberFont()
if f == nil || fig == "" || size < 8 {
return nil
}
face := func(em float64) font.Face {
fc, err := opentype.NewFace(f, &opentype.FaceOptions{Size: em, DPI: 72, Hinting: font.HintingFull})
if err != nil {
return nil
}
return fc
}
// the digits' height at 100px, to size them to the square
probe := face(100)
if probe == nil {
return nil
}
b, _ := font.BoundString(probe, "0123456789")
probe.Close()
ratio := float64(b.Max.Y-b.Min.Y) / 64 / 100
if ratio <= 0 {
return nil
}
em := math.Round(float64(size)*0.72) / ratio
fc := face(em)
if fc == nil {
return nil
}
w := float64(font.MeasureString(fc, fig)) / 64
// narrowed no more than to 2/3 of its width; smaller beyond that
if most := float64(size) * 1.5; w > most {
fc.Close()
em *= most / w
if fc = face(em); fc == nil {
return nil
}
w = float64(font.MeasureString(fc, fig)) / 64
}
defer fc.Close()
db, _ := font.BoundString(fc, "0123456789")
top, bottom := float64(db.Min.Y)/64, float64(db.Max.Y)/64
baseline := math.Round((float64(size)-(bottom-top))/2 - top)
text := image.NewNRGBA(image.Rect(0, 0, int(math.Ceil(w))+4, size))
d := font.Drawer{Dst: text, Src: image.NewUniform(trayNumberColour(dark)), Face: fc,
Dot: fixed.Point26_6{X: fixed.I(2), Y: fixed.I(int(baseline))}}
d.DrawString(fig)
// centred by its ink, not its advance, whose side bearings differ
ink := inkColumns(text)
if ink.Empty() {
return nil
}
out := image.NewNRGBA(image.Rect(0, 0, size, size))
if iw := ink.Dx(); iw <= size {
xdraw.Copy(out, image.Pt((size-iw)/2, 0), text, ink, xdraw.Over, nil)
} else {
xdraw.CatmullRom.Scale(out, out.Bounds(), text, ink, xdraw.Over, nil)
}
var buf bytes.Buffer
if png.Encode(&buf, out) != nil {
return nil
}
return buf.Bytes()
}
// inkColumns is img's full height between its first and last columns
// with any ink.
func inkColumns(img *image.NRGBA) image.Rectangle {
b := img.Bounds()
x0, x1 := b.Max.X, b.Min.X
for y := b.Min.Y; y < b.Max.Y; y++ {
for x := b.Min.X; x < b.Max.X; x++ {
if img.NRGBAAt(x, y).A > 0 {
x0, x1 = min(x0, x), max(x1, x+1)
}
}
}
if x0 >= x1 {
return image.Rectangle{}
}
return image.Rect(x0, b.Min.Y, x1, b.Max.Y)
}
+8
View File
@@ -0,0 +1,8 @@
//go:build !windows && !nogui
package gui
// Only Windows' tray draws a card's figure as its icon (traynumber.go).
func trayIconSize() int { return 0 }
func trayTaskbarDark() bool { return false }
func trayNumberFontFile() []byte { return nil }
+110
View File
@@ -0,0 +1,110 @@
//go:build !nogui
package gui
import (
"bytes"
"image"
"image/color"
"image/png"
"testing"
"time"
)
// Windows' tray icon is the first card's figure (Benjaminliang_1 on X),
// the percentage as the Mac's menu bar shows it, used or left; the
// next card's when the first has none; the bird with no cards, off
// Windows, or with Settings › Tray icon number off.
func TestTrayIconFigure(t *testing.T) {
now := time.Date(2026, 9, 30, 12, 0, 0, 0, time.UTC)
cards := trayCards()
view := func(ids []string, left bool, pick map[string][]string) []trayCell {
cells, _, _ := trayCardsView(trayPick(cards, ids, now), now, left, false, pick)
return cells
}
for _, tc := range []struct {
name string
goos string
noNumber bool
cells []trayCell
want string
}{
{"the first card's first window", "windows", false, view([]string{"claude|a@b.c", "codex|x@y.z"}, false, nil), "42"},
{"what is left, as Settings has it", "windows", false, view([]string{"claude|a@b.c"}, true, nil), "58"},
{"the window picked for the menu bar", "windows", false, view([]string{"claude|a@b.c"}, false, map[string][]string{"claude": {"7d"}}), "18"},
{"a full window", "windows", false, view([]string{"codex|x@y.z"}, false, map[string][]string{"codex": {"7d"}}), "100"},
{"a balance first: the next card's", "windows", false, view([]string{"deepseek", "copilot"}, false, nil), "63"},
{"a balance alone: the bird", "windows", false, view([]string{"deepseek"}, false, nil), ""},
{"no cards: the bird", "windows", false, view(nil, false, nil), ""},
{"turned off: the bird", "windows", true, view([]string{"claude|a@b.c"}, false, nil), ""},
{"the Mac draws its cells", "darwin", false, view([]string{"claude|a@b.c"}, false, nil), ""},
{"Linux shows the label", "linux", false, view([]string{"claude|a@b.c"}, false, nil), ""},
{"with Pace beside it", "windows", false, []trayCell{{Rows: []string{"42% +3%"}}}, "42"},
{"a balance's own text", "windows", false, []trayCell{{Rows: []string{"1234%x"}}, {Rows: []string{"Σ1.2M"}}}, ""},
} {
if got := trayIconFigure(tc.goos, tc.noNumber, tc.cells); got != tc.want {
t.Errorf("%s: %q, want %q", tc.name, got, tc.want)
}
}
}
// The figure is drawn at the size Windows asks for, in the taskbar's text
// colour on transparency, as tall as fits with room above and below, and
// "100" narrowed into the square, not cut.
func TestTrayNumberIcon(t *testing.T) {
// off by more than the rounding of a half-covered pixel
far := func(a, b uint8) bool { d := int(a) - int(b); return d < -4 || d > 4 }
for _, size := range []int{16, 20, 24, 32} {
for _, dark := range []bool{true, false} {
for _, fig := range []string{"7", "42", "100"} {
b := trayNumberIcon(fig, size, dark)
img, err := png.Decode(bytes.NewReader(b))
if err != nil {
t.Fatalf("%s at %d: %v", fig, size, err)
}
if img.Bounds() != image.Rect(0, 0, size, size) {
t.Fatalf("%s at %d: %v", fig, size, img.Bounds())
}
want := trayNumberColour(dark)
// white on a dark taskbar, near black on a light one
if lum := int(want.R) + int(want.G) + int(want.B); dark != (lum > 3*200) || !dark && lum > 3*64 || want.A != 0xff {
t.Fatalf("dark=%v: drawn in %v", dark, want)
}
ink := image.Rectangle{}
for y := range size {
for x := range size {
c := color.NRGBAModel.Convert(img.At(x, y)).(color.NRGBA)
if c.A < 0x80 {
continue
}
if far(c.R, want.R) || far(c.G, want.G) || far(c.B, want.B) {
t.Fatalf("%s at %d dark=%v: (%d,%d) is %v, want %v", fig, size, dark, x, y, c, want)
}
ink = ink.Union(image.Rect(x, y, x+1, y+1))
}
}
if ink.Empty() {
t.Fatalf("%s at %d: nothing drawn", fig, size)
}
// legible: the digits most of the square's height, a pixel
// or more clear of its top and bottom
if h := ink.Dy(); h < size*6/10 || ink.Min.Y < 1 || ink.Max.Y > size-1 {
t.Errorf("%s at %d: ink %v", fig, size, ink)
}
// centred, and three digits fill the width without leaving it
if d := ink.Min.X - (size - ink.Max.X); d < -2 || d > 2 {
t.Errorf("%s at %d: off centre, ink %v", fig, size, ink)
}
if fig == "100" && ink.Dx() < size*8/10 {
t.Errorf("100 at %d: %d wide", size, ink.Dx())
}
}
}
}
if bytes.Equal(trayNumberIcon("42", 16, true), trayNumberIcon("17", 16, true)) {
t.Fatal("42 and 17 drawn alike")
}
if trayNumberIcon("", 16, true) != nil || trayNumberIcon("42", 0, true) != nil {
t.Fatal("drawn with no figure or no size")
}
}
+36
View File
@@ -0,0 +1,36 @@
//go:build windows && !nogui
package gui
import (
"os"
"path/filepath"
"github.com/wailsapp/wails/v3/pkg/w32"
)
// trayIconSize is the size Windows draws a tray icon at, in pixels at the
// display's scale (16 at 100%, 20 at 125%, 24 at 150%, 32 at 200%): Wails
// makes the icon at this size from the PNG it is given, so one drawn at it
// stays sharp.
func trayIconSize() int { return w32.GetSystemMetrics(w32.SM_CXSMICON) }
// trayTaskbarDark says whether the taskbar is dark: Windows' "default
// Windows mode" (SystemUsesLightTheme), which the taskbar follows and the
// apps' own mode doesn't change.
func trayTaskbarDark() bool { return w32.IsSystemCurrentlyDarkMode() }
// trayNumberFontFile is Segoe UI Semibold, Windows' own UI face, or its
// bold; nil when neither can be read.
func trayNumberFontFile() []byte {
dir := os.Getenv("WINDIR")
if dir == "" {
dir = `C:\Windows`
}
for _, n := range []string{"seguisb.ttf", "segoeuib.ttf"} {
if b, err := os.ReadFile(filepath.Join(dir, "Fonts", n)); err == nil {
return b
}
}
return nil
}
+35 -2
View File
@@ -4,11 +4,13 @@ package gui
import (
"context"
"fmt"
"runtime"
"strings"
"time"
"github.com/wailsapp/wails/v3/pkg/application"
"github.com/wailsapp/wails/v3/pkg/events"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
@@ -31,13 +33,17 @@ func (h *host) watchTrayUsage() {
// another account answering, or the agent switched to another: a card
// following the account in use reads it at once (#1516)
provider.OnServedMoved(onTrayUsage)
// the taskbar turned dark or light: the figure in its colour
if runtime.GOOS == "windows" {
h.app.Event.OnApplicationEvent(events.Windows.SystemThemeChanged, func(*application.ApplicationEvent) { onTrayUsage() })
}
// Schedule native cell clicks on the application thread after startup.
onTrayCellClick = func(id string) {
h.whenReady(func() { application.InvokeAsync(func() { h.trayCellClick(id) }) })
}
go func() {
<-h.ready // the tray is made once the app runs
shown, drawn := "", false
shown, drawn, numbered := "", false, false
for {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
s := settings.Load()
@@ -50,6 +56,13 @@ func (h *host) watchTrayUsage() {
currency, rate := trayCurrency()
tip = trayIdleTip(trayMoney(trayTotalSum(usage.Today), s.TrayNoCost), currency, rate)
}
// Windows' tray shows no text: the first card's figure is its
// icon instead (traynumber.go), drawn for the taskbar's size and
// colour
fig, figKey := trayIconFigure(runtime.GOOS, s.TrayNoNumber, cells), ""
if fig != "" {
figKey = fmt.Sprint(fig, "@", trayIconSize(), trayTaskbarDark())
}
if runtime.GOOS != "darwin" {
cells = nil
} else if label != "" {
@@ -57,7 +70,7 @@ func (h *host) watchTrayUsage() {
label = " " + label
}
// what is shown, to set it again only when it changes
now := label + "\x00" + tip
now := label + "\x00" + tip + "\x00" + figKey
for _, c := range cells {
now += "\x00" + c.Letter + strings.Join(c.Rows, "\x01")
if c.Plain {
@@ -77,6 +90,9 @@ func (h *host) watchTrayUsage() {
}
h.tray.SetLabel(label)
}
if runtime.GOOS == "windows" {
numbered = h.setTrayNumber(fig, numbered)
}
h.tray.SetTooltip(tip)
// Wails' is a no-op on Linux; until the tray is up, again next time
if !setTrayTip(h.tray, tip) {
@@ -110,6 +126,23 @@ func (h *host) watchTrayUsage() {
}()
}
// setTrayNumber makes Windows' tray icon fig (trayNumberIcon), or the
// app's icon again when there is none and it was one (numbered); it says
// whether the icon is a figure now. Wails sets one icon for a dark and a
// light taskbar alike, so it is drawn again when the taskbar's changes.
func (h *host) setTrayNumber(fig string, numbered bool) bool {
if fig != "" {
if icon := trayNumberIcon(fig, trayIconSize(), trayTaskbarDark()); icon != nil {
h.tray.SetIcon(icon)
return true
}
}
if numbered {
h.tray.SetIcon(winTrayIcon)
}
return false
}
// trayCellClick opens the allowance represented by the clicked image cell.
// A visible panel closes on the next click, as clicking the bird does.
func (h *host) trayCellClick(id string) {
+5 -1
View File
@@ -537,6 +537,10 @@ type Settings struct {
// cards are there, the cards alone (KevinXC on Discord); a click on one
// still opens the panel, and with no cards the bird is shown.
TrayNoBird bool `json:"trayNoBird,omitempty"`
// TrayNoNumber keeps magpie's icon in Windows' tray while cards are
// picked; off by default, the icon is the first card's figure
// (Benjaminliang_1 on X), as Windows' tray shows no text beside it.
TrayNoNumber bool `json:"trayNoNumber,omitempty"`
// TrayPace puts each window's Pace number beside its figure in the
// menu bar ("42% +12%"), as the Usage page's cards have it (fflake33
// on Discord); off by default, as it widens every card.
@@ -1320,7 +1324,7 @@ func (s *Settings) KeepOwn(cur Settings) {
s.WindowMaximised, s.KeepAwake, s.KeepAwakeDisplay = cur.WindowMaximised, cur.KeepAwake, cur.KeepAwakeDisplay
s.WindowAt = cur.WindowAt
s.TrayUsages, s.TrayUsage, s.TrayUsageEvery, s.TrayNoLogos, s.TrayNoBird, s.TrayPace, s.TrayNoCost = cur.TrayUsages, cur.TrayUsage, cur.TrayUsageEvery, cur.TrayNoLogos, cur.TrayNoBird, cur.TrayPace, cur.TrayNoCost
s.TrayWindows = cur.TrayWindows
s.TrayWindows, s.TrayNoNumber = cur.TrayWindows, cur.TrayNoNumber
s.GatewayMode = cur.GatewayMode
s.NoWSLAgents = cur.NoWSLAgents
s.QuotaReads = cur.QuotaReads