diff --git a/gui_off.go b/gui_off.go index e403f7f0c..f0ed1e3f8 100644 --- a/gui_off.go +++ b/gui_off.go @@ -7,3 +7,5 @@ import "errors" const hasGUI = false func runGUI(bool, string) error { return errors.New("this build has no GUI; run `magpie tui`") } + +func runPanel() error { return runGUI(false, "") } diff --git a/gui_on.go b/gui_on.go index dc327e025..f63dc04ac 100644 --- a/gui_on.go +++ b/gui_on.go @@ -15,3 +15,11 @@ func runGUI(showMain bool, link string) error { proc.UserPath() return gui.Run(version, showMain, link) } + +// runPanel starts the app with its quick panel open, or toggles the panel +// of the one already running. +func runPanel() error { + proc.UserPath() + gui.OpenPanel = true + return gui.Run(version, false, "") +} diff --git a/internal/gui/api.go b/internal/gui/api.go index 3bb9f2941..3653773b4 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -267,11 +267,26 @@ func Handler(w Windows, gw *gateway.Server) http.Handler { s := settings.Load() // and the text size, which the Mac's header measures against the // traffic lights - b, _ := json.Marshal(map[string]any{"lang": s.Lang, "theme": s.Theme, "textSize": s.TextSize, "web": isWeb(w)}) + boot := map[string]any{"lang": s.Lang, "theme": s.Theme, "textSize": s.TextSize, "web": isWeb(w)} + // on Omarchy the page takes its theme's look before it paints + if th, ok := omarchyTheme(); ok { + boot["omarchy"] = th + } + b, _ := json.Marshal(boot) rw.Header().Set("Content-Type", "text/javascript; charset=utf-8") rw.Header().Set("Cache-Control", "no-store") rw.Write(append(append([]byte("window.bootPrefs = "), b...), ";\n"...)) }) + // the Omarchy theme as it is now, asked again every few seconds so a + // theme picked in Omarchy's menu reaches the page at once; null off Omarchy + mux.HandleFunc("GET /api/omarchy", func(rw http.ResponseWriter, r *http.Request) { + if th, ok := omarchyTheme(); ok { + writeJSON(rw, th) + return + } + writeJSON(rw, nil) + }) + omarchyRoutes(mux, w) mux.HandleFunc("GET /api/state", func(rw http.ResponseWriter, r *http.Request) { writeJSON(rw, state()) }) diff --git a/internal/gui/app.go b/internal/gui/app.go index c84fb3e81..040d29287 100644 --- a/internal/gui/app.go +++ b/internal/gui/app.go @@ -20,6 +20,7 @@ import ( "github.com/wailsapp/wails/v3/pkg/events" "github.com/yetone/magpie/internal/library" + "github.com/yetone/magpie/internal/omarchy" "github.com/yetone/magpie/internal/settings" "github.com/yetone/magpie/internal/shortcut" "github.com/yetone/magpie/internal/stats" @@ -72,6 +73,8 @@ type host struct { panelHeight int // the panel's, in points panelPage int // what its page last asked for, in CSS pixels textSize atomic.Int64 // Settings' text size, in percent (settings.TextSizes) + hyprRoom int // how tall it may grow under Hyprland's bar; 0 elsewhere + clicks sync.Once // Hyprland's clicks heard, to close the panel on one outside it glides atomic.Int64 // the newest panel glide; older ones stop query string // what the windows' URLs carry (a forced theme) @@ -125,6 +128,10 @@ func (h *host) ChooseFolder(title string) (string, error) { SetTitle(title).AttachToWindow(h.main).PromptForSingleSelection() } +// panelTitle names the panel for Hyprland's rule, which places it (the +// main window is "magpie") +const panelTitle = "magpie panel" + // FitPanel grows or shrinks the panel to its content and keeps it anchored // under the tray icon; a shown panel glides there when g says how. height // is the page's, in its CSS pixels: at a larger text size the panel is @@ -155,6 +162,9 @@ func (h *host) panelW() int { return zoomed(panelWidth, h.zoom()) } // panelRoom is how tall the panel can be on its screen: the work area, // less the gap under the menu bar (or over the taskbar) and a little air. func (h *host) panelRoom() int { + if h.hyprRoom > 0 { // under Hyprland's bar, down to the work area's foot + return h.hyprRoom + } if _, rh := screenRoom(h.panel); rh > 0 { return rh - 16 } @@ -358,6 +368,11 @@ func Run(version string, showMain bool, link string) error { }() h.tray = h.app.SystemTray.New() + if runtime.GOOS == "linux" { + // set before the tray starts, it is the item's id too, which + // Omarchy's bar pins it by (Wails calls it "Wails" otherwise) + h.tray.SetLabel("magpie") + } h.tray.SetTooltip("magpie") if runtime.GOOS == "darwin" { h.tray.SetTemplateIcon(trayIcon) @@ -377,7 +392,7 @@ func Run(version string, showMain bool, link string) error { h.ShowMain("") return } - h.tray.ToggleWindow() + h.togglePanel() }) // Wails shows a Windows webview 3s after Show whether or not WebView2 @@ -389,6 +404,7 @@ func Run(version string, showMain bool, link string) error { } else { h.app.Event.OnApplicationEvent(events.Common.ApplicationStarted, func(*application.ApplicationEvent) { plainTitlebar(h.main) // Linux: the page's header is the title bar + nameWindow(h.panel, panelTitle) markReady() }) } @@ -401,6 +417,9 @@ func Run(version string, showMain bool, link string) error { if showMain { h.whenReady(func() { h.ShowMain("") }) } + if OpenPanel { + h.whenReady(func() { application.InvokeAsync(h.togglePanel) }) + } if link != "" { h.Import(link) } @@ -439,6 +458,8 @@ func singleInstance(h *host) *application.SingleInstanceOptions { case ImportLink(args) != "": h.Import(ImportLink(args)) case len(args) == 1 && args[0] == "tray": + case len(args) == 1 && args[0] == "panel": + h.whenReady(func() { application.InvokeAsync(h.togglePanel) }) default: h.whenReady(func() { h.ShowMain("") }) } @@ -508,3 +529,59 @@ func panelOptions(goos, theme string) application.WebviewWindowOptions { } return o } + +// OpenPanel has Run open the quick panel once it starts, as `magpie panel` +// does; a second `magpie panel` toggles it in the running one. Omarchy's bar +// icon runs it (see omarchy.AddWidget). +var OpenPanel bool + +// togglePanel opens the quick panel by the tray icon, or closes it. +func (h *host) togglePanel() { + if omarchy.Hyprland() { + if h.panel.IsVisible() { + h.hidePanel() + return + } + h.placePanel() + } + h.tray.ToggleWindow() +} + +// placePanel puts the panel, about to open, under Hyprland's bar at the +// click, the way Omarchy's own drop-downs sit: a Wayland window can't place +// itself, so Hyprland is given a rule for it (see omarchy.PlacePanel). +func (h *host) placePanel() { + x, y, room, ok := omarchy.PanelAt(h.panelW()) + if !ok { + return + } + if err := omarchy.PlacePanel(panelTitle, x, y); err != nil { + log.Println("hyprland:", err) + return + } + h.hyprRoom = room + h.clicks.Do(func() { + go omarchy.WatchClicks(func() { + switch { + case !h.panel.IsVisible(): // Escape closed it + omarchy.StopClicks() + case omarchy.ClickedOutside(panelTitle): + application.InvokeAsync(h.hidePanel) + } + }) + }) + if err := omarchy.ReportClicks(); err != nil { + log.Println("hyprland:", err) + } + if _, ht := h.panel.Size(); ht > room && room >= panelMin { + h.panelHeight = room + h.panel.SetSize(h.panelW(), room) + } +} + +// hidePanel closes the panel on Hyprland, where it has no focus-lost to +// close on (see omarchy.ReportClicks). +func (h *host) hidePanel() { + h.panel.Hide() + go omarchy.StopClicks() +} diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index ccce4f54b..8859973fa 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -7540,8 +7540,20 @@ function applyPrefs(s, rate) { return was !== locale; } +// Omarchy's bar: magpie's icon there as a widget of its own (Settings → Bar +// icon), offered only in the app on Omarchy +let barIcon = null; +function renderBarIcon() { + $("#barIconRow").hidden = !barIcon?.available; + if (!barIcon?.available) return; + $("#barIconSegs").replaceChildren(segs([["off", t("Off")], ["on", t("On")]], barIcon.on ? "on" : "off", (v) => + api("omarchy/widget", { on: v === "on" }).then((b) => { barIcon = b; renderBarIcon(); }) + .catch((e) => { status(t(e.message), "err"); renderBarIcon(); }))); +} + async function loadSettings() { const since = prefsWrites; + if (window.bootPrefs?.omarchy && !barIcon) api("omarchy/widget").then((b) => { barIcon = b; renderBarIcon(); }).catch(() => {}); const s = await api("settings"); if (!prefsSettled(since) && prefs) return; // the save draws the page when it's in prefs = s; @@ -7638,6 +7650,7 @@ function renderSettings() { $("#dockSegs").replaceChildren(segs([["off", t("Hide")], ["window", t("With window")], ["on", t("Show")]], s.dock ? "on" : s.dockWindow ? "window" : "off", (v) => savePrefs({ ...keep, dock: v === "on", dockWindow: v === "window" }))); renderSessionTerminal(s, keep); + renderBarIcon(); // the system's record, set on its own, not with the other choices $("#loginSegs").replaceChildren(segs([["off", t("Off")], ["on", t("On")]], s.login ? "on" : "off", (v) => writingPrefs(api("settings/login", { on: v === "on" })).then((ns) => { prefs = ns; renderSettings(); }).catch((e) => { status(t(e.message), "err"); renderSettings(); }))); diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index ff81f13c1..280d7a18b 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -72,6 +72,8 @@ const I18N = { "Don't remind me": "不再提示", "Hide this line; Add a provider still offers it back": "收起这行提示;之后仍可在「添加供应商」里加回来", "Tray icon": "托盘图标", + "Bar icon": "状态栏图标", + "magpie’s icon beside Omarchy’s own in the bar; right-click opens the window": "把 magpie 图标放进 Omarchy 状态栏,与系统图标并排;右键打开窗口", "Dock": "程序坞", "Open at login": "开机自启", "Start magpie in the tray when you log in, so agents find the gateway from the start": "登录系统时在托盘里启动 magpie,各个 Agent 一开始就能连上网关", @@ -974,6 +976,7 @@ const I18N = { "Unavailable app ({id})": "应用不可用({id})", "Appearance": "外观", "Light or dark, or whatever the system is showing": "浅色、深色,或跟随系统", + "Follows the Omarchy theme, as picked in Omarchy's menu": "跟随 Omarchy 主题,在 Omarchy 菜单里切换", "Language": "语言", "Applies at once, no restart": "立即生效,无需重启", "Text size": "文字大小", diff --git a/internal/gui/assets/index.html b/internal/gui/assets/index.html index 0b5fd1b02..9590cb311 100644 --- a/internal/gui/assets/index.html +++ b/internal/gui/assets/index.html @@ -5,9 +5,11 @@ magpie + +
@@ -158,8 +160,8 @@
Preferences
-
Appearance
Light or dark, or whatever the system is showing
-
+
Appearance
Light or dark, or whatever the system is showing
Follows the Omarchy theme, as picked in Omarchy's menu
+
Language
Applies at once, no restart
@@ -173,6 +175,10 @@
Tray icon
What clicking magpie’s icon in the menu bar or tray opens
+
Usage in the menu bar
diff --git a/internal/gui/assets/omarchy.css b/internal/gui/assets/omarchy.css new file mode 100644 index 000000000..40c25a90c --- /dev/null +++ b/internal/gui/assets/omarchy.css @@ -0,0 +1,66 @@ +/* Omarchy: magpie drawn in Omarchy's own design language, only on Omarchy. + omarchy.js puts the class on and the theme's colours, font, border + and rounding (from ~/.local/state/omarchy/current/theme and Hyprland) in + the variables; everything here is scoped under html.omarchy, so no other + system sees any of it. Omarchy's shell draws flat: no shadows, no blur, no + rounding (Hyprland's decoration:rounding, 0 by default), popups framed by + the window border's colour, uppercase letter-spaced labels, and a row + picked out by a faint fill with its text in the accent. */ + +/* what only Omarchy shows, and what it hides: the Appearance setting follows + Omarchy's theme instead of offering light and dark */ +.om-only { display: none !important; } +html.omarchy .om-hide { display: none !important; } +html.omarchy .om-only { display: revert !important; } +html.omarchy .om-theme-name { color: var(--accent); font-size: 12px; white-space: nowrap; } + +html.omarchy, html.omarchy body { font-family: var(--font); font-size: var(--om-size); } +html.omarchy body { -webkit-font-smoothing: antialiased; } + +/* square, or rounded as far as Hyprland rounds its windows; what spins or + draws a dial stays round, as does a slider.s knob; a status dot goes square, like Omarchy.s workspace marks */ +html.omarchy *, html.omarchy *::before, html.omarchy *::after { border-radius: var(--om-radius) !important; } +html.omarchy :is(.pq-dial, .pq-dial b, .sk-ring, .si-spin, .mk-spin, .signing .spinner, .eslide .knob, .effort-ticks i), +html.omarchy input[type="range"]::-webkit-slider-thumb { border-radius: 50% !important; } + +/* no shadows or frosted glass: surfaces are the theme's background */ +html.omarchy * { -webkit-backdrop-filter: none !important; backdrop-filter: none !important; } +html.omarchy :is(.pop, .modal .dialog, .status.lift, body.panel .profiles.open, .list, body.panel .list, .seg > .thumb) { box-shadow: none; } +html.omarchy body.panel { background: var(--bg); border: var(--om-border) solid var(--om-edge); } + +/* popups, menus and dialogs: framed by the window border's colour */ +html.omarchy :is(.pop, body.panel .profiles.open, .status.lift) { background: var(--pop-bg); border: var(--om-border) solid var(--om-edge) !important; } +html.omarchy .modal { background: color-mix(in srgb, var(--bg) 55%, transparent); } +html.omarchy .modal .dialog { background: var(--bg); border: var(--om-border) solid var(--om-edge); } + +/* labels as Omarchy's shell sets its headings: uppercase, spaced out */ +html.omarchy :is(.label, .pop li.group, .kpi span, .editor .ehead + * .k) { letter-spacing: .12em; text-transform: uppercase; font-weight: 500; } +html.omarchy .brand { letter-spacing: 0; font-weight: 700; } + +/* the tabs: no track, the chosen one a faint square with its text in the accent */ +html.omarchy .seg { background: transparent; } +html.omarchy .seg > .thumb { background: var(--om-sel); } +html.omarchy :is(.seg button.on, .ptabs button.on, .opt.on) { color: var(--accent); } +html.omarchy :is(.segs, .ptabs) { background: transparent; } +html.omarchy :is(.segs, .ptabs) > .thumb { background: var(--om-sel); box-shadow: inset 0 0 0 1px var(--om-sel-line); } + +/* lists: a hairline frame, rows picked out by a faint fill */ +html.omarchy .list { border: 1px solid var(--line); background: transparent; } +html.omarchy .row:hover { background: var(--om-hover); } + +/* controls: Omarchy's buttons are a faint fill under a thin edge */ +html.omarchy .field, html.omarchy body.panel .field, html.omarchy body.panel .field:hover { background: var(--om-hover); box-shadow: inset 0 0 0 1px var(--om-hover-line); } +html.omarchy .field:hover { background: var(--om-sel); } +html.omarchy .field.open, html.omarchy body.panel .field.open { box-shadow: inset 0 0 0 1px var(--accent); } +html.omarchy .icon:hover { background: var(--om-sel); color: var(--accent); } +html.omarchy .text.primary { background: var(--accent); color: var(--accent-fg); } + +/* a menu's row under the cursor or keys: the fill and the accent, like Walker's */ +html.omarchy :is(.pop li.sel, .pop li:hover:not(.group), .row-menu .rm-item:not(:disabled):is(:hover, :focus)) { background: var(--om-sel); color: var(--accent); } +html.omarchy :is(.pop li.sel, .pop li:hover) :is(.v, .n) { color: inherit; } + +/* Linux's close button: square like the rest */ +html.omarchy .icon.winclose { background: transparent; } +html.omarchy .icon.winclose:hover { background: var(--red-soft); color: var(--red); } + +html.omarchy ::selection { background: var(--om-sel); color: var(--accent); } diff --git a/internal/gui/assets/omarchy.js b/internal/gui/assets/omarchy.js new file mode 100644 index 000000000..cdfe7e650 --- /dev/null +++ b/internal/gui/assets/omarchy.js @@ -0,0 +1,46 @@ +// On Omarchy (omarchy.org) magpie's windows take the look of Omarchy's own +// panels: the current theme's palette and font, square corners and the +// active border's colour (omarchy.css, under html.omarchy). The theme comes +// with boot.js before the first paint and is asked again every few seconds +// while the page shows, so one picked in Omarchy's menu is taken at once. +// Everywhere else nothing here does anything. +(() => { + const root = document.documentElement; + let stamp = ""; + let style = null; + function apply(th) { + if (!th || !th.vars) return; + root.classList.add("omarchy"); + root.dataset.omarchyMode = th.mode || "dark"; + if (th.stamp === stamp) return; + stamp = th.stamp; + const decls = Object.entries(th.vars).map(([k, v]) => `${k}: ${v} !important;`).join(" "); + if (!style) { + style = document.createElement("style"); + style.id = "omarchy-theme"; + document.head.append(style); + } + // on the root and the body both, so neither the light/dark palettes nor + // the panel's own tints (set on the body) win over the theme + style.textContent = `:root.omarchy, :root.omarchy body { ${decls} color-scheme: ${th.mode === "light" ? "light" : "dark"}; }`; + for (const e of document.querySelectorAll(".om-theme-name")) e.textContent = th.name || ""; + window.omarchyTheme = th; + window.dispatchEvent(new CustomEvent("omarchy-theme", { detail: th })); + } + const boot = window.bootPrefs && window.bootPrefs.omarchy; + if (!boot) return; + apply(boot); + // the settings' theme name is drawn after this script runs + document.addEventListener("DOMContentLoaded", () => { for (const e of document.querySelectorAll(".om-theme-name")) e.textContent = th().name || ""; }); + const th = () => window.omarchyTheme || boot; + async function poll() { + if (document.visibilityState === "visible") { + try { + const r = await fetch("/api/omarchy", { cache: "no-store" }); + if (r.ok) apply(await r.json()); + } catch {} + } + setTimeout(poll, 2500); + } + setTimeout(poll, 2500); +})(); diff --git a/internal/gui/omarchy.go b/internal/gui/omarchy.go new file mode 100644 index 000000000..6b1fa9047 --- /dev/null +++ b/internal/gui/omarchy.go @@ -0,0 +1,72 @@ +package gui + +import ( + "encoding/json" + "log" + "net/http" + "os" + + "github.com/yetone/magpie/internal/omarchy" +) + +// onOmarchy is whether magpie runs on Omarchy, asked once: its windows then +// take Omarchy's look and its bar's place instead of the tray's. +var onOmarchy = omarchy.Detect() + +// omarchyTheme is the Omarchy theme the page draws with, when on Omarchy. +func omarchyTheme() (omarchy.Theme, bool) { + if !onOmarchy { + return omarchy.Theme{}, false + } + return omarchy.Current() +} + +// barIcon is whether magpie can put its icon in Omarchy's bar (the desktop +// app on Omarchy's Hyprland; not a browser's page), and whether it has. +func barIcon(w Windows) map[string]bool { + ok := onOmarchy && !isWeb(w) && omarchy.Hyprland() + return map[string]bool{"available": ok, "on": ok && omarchy.WidgetOn()} +} + +// omarchyRoutes are Settings' Bar icon: magpie's icon in Omarchy's bar +// beside its own, opening the quick panel, instead of in the tray's drawer. +func omarchyRoutes(mux *http.ServeMux, w Windows) { + mux.HandleFunc("GET /api/omarchy/widget", func(rw http.ResponseWriter, r *http.Request) { + writeJSON(rw, barIcon(w)) + }) + mux.HandleFunc("POST /api/omarchy/widget", func(rw http.ResponseWriter, r *http.Request) { + var in struct{ On bool } + if err := json.NewDecoder(r.Body).Decode(&in); err != nil { + fail(rw, err) + return + } + if !barIcon(w)["available"] { + http.Error(rw, "Omarchy's bar isn't here", http.StatusConflict) + return + } + var err error + if in.On { + var exe string + if exe, err = os.Executable(); err == nil { + err = omarchy.AddWidget(exe) + } + } else { + err = omarchy.RemoveWidget() + } + if err != nil { + fail(rw, err) + return + } + writeJSON(rw, barIcon(w)) + }) + // a widget put in by an older magpie, or one elsewhere, runs this one + if barIcon(w)["on"] { + go func() { + if exe, err := os.Executable(); err == nil { + if err := omarchy.KeepWidget(exe); err != nil { + log.Println("omarchy bar icon:", err) + } + } + }() + } +} diff --git a/internal/gui/tests/README.md b/internal/gui/tests/README.md index 4db994dcf..c01c57fd9 100644 --- a/internal/gui/tests/README.md +++ b/internal/gui/tests/README.md @@ -208,10 +208,17 @@ new model at once, in the window and in the tray panel's opened row and its line, the page left where it was; the answer keeps it and says so; a refused pick puts the old model back with the reason; in English and Chinese. +`omarchy.test.cjs` holds Omarchy's look to Omarchy: with no Omarchy theme in +boot.js the page has no omarchy class or theme style, shows the Appearance +choices and no Bar icon row, and asks nothing of /api/omarchy; with one, the +theme's background, square corners and its name in place of the choices, and +Settings → Bar icon, whose On and Off each post and move nothing, hidden when +the app says Omarchy's bar isn't there; 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 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 +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 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 ``` If Playwright is installed outside the repository, set `NODE_PATH` to the diff --git a/internal/gui/tests/old-webkit.test.cjs b/internal/gui/tests/old-webkit.test.cjs index c66045d4b..c3ccd4487 100644 --- a/internal/gui/tests/old-webkit.test.cjs +++ b/internal/gui/tests/old-webkit.test.cjs @@ -132,9 +132,12 @@ test("no built-in newer than Safari 15.0 unless compat.js fills it in", async () test("compat.js is the first of the page's own scripts", async () => { const html = await read("index.html"); - const srcs = [...html.matchAll(/ m[1]).filter((s) => s !== "boot.js"); + // boot.js and omarchy.js run in the head, before the first paint: + // omarchy.js does nothing off Omarchy, whose WebKitGTK is a current one + const all = [...html.matchAll(/ m[1]); + const srcs = all.filter((s) => s !== "boot.js" && s !== "omarchy.js"); assert.equal(srcs[0], "compat.js", "loaded first: " + srcs.join(", ")); - for (const f of await scripts()) assert(srcs.includes(f), f + " is not loaded by index.html"); + for (const f of await scripts()) assert(all.includes(f), f + " is not loaded by index.html"); }); test("the styles hold up in Safari 15.0", async () => { diff --git a/internal/gui/tests/omarchy.test.cjs b/internal/gui/tests/omarchy.test.cjs new file mode 100644 index 000000000..6ab831a0d --- /dev/null +++ b/internal/gui/tests/omarchy.test.cjs @@ -0,0 +1,159 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// Omarchy's look (omarchy.css, omarchy.js) and Settings → Bar icon: with no +// Omarchy theme in boot.js the page is as it always was (no class, no theme +// style, the Appearance choices, no Bar icon row, nothing asked of +// /api/omarchy); with one, the theme's colours and square corners, its name +// where the Appearance choices were, and the Bar icon row when the app says +// the bar is there, whose On and Off post and move nothing. 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 theme = { + name: "tokyo-night", mode: "dark", stamp: "1", + vars: { + "--bg": "#1a1b26", "--fg": "#a9b1d6", "--accent": "#7aa2f7", "--accent-fg": "#1a1b26", "--line": "#3b3d4d", + "--pop-bg": "#1a1b26", "--font": "monospace", "--om-edge": "#7aa2f7", "--om-border": "2px", "--om-radius": "0px", + "--om-size": "13px", "--om-hover": "rgba(169, 177, 214, 0.04)", "--om-hover-line": "rgba(169, 177, 214, 0.25)", + "--om-sel": "rgba(122, 162, 247, 0.12)", "--om-sel-line": "rgba(122, 162, 247, 0.25)", + }, +}; + +function settingsPayload(lang) { + return { + theme: "system", lang, 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: "", 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 }, + }; +} + +// om: the theme boot.js hands over, or none; bar: what /api/omarchy/widget says +function server(lang, om, bar, asked, posted) { + return async (route) => { + const req = route.request(), url = new URL(req.url()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") { + const boot = { lang, theme: "system", web: false, ...(om ? { omarchy: om } : {}) }; + return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = ${JSON.stringify(boot)};` }); + } + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname.startsWith("/api/omarchy")) asked.push(req.method() + " " + url.pathname); + if (url.pathname === "/api/omarchy") return json(om || null); + if (url.pathname === "/api/omarchy/widget") { + if (req.method() === "POST") { + posted.push(req.postDataJSON()); + bar.on = req.postDataJSON().on; + } + return json(bar); + } + if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "system" } }); + if (url.pathname === "/api/settings") return json(settingsPayload(lang)); + 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 + ": Omarchy's look and Bar icon, only on Omarchy", 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}-omarchy-${i}.png`) }); + } + await browser.close(); + }); + + for (const [lang, barName, on, off] of [["en", "Bar icon", "On", "Off"], ["zh", "状态栏图标", "开启", "关闭"]]) { + await t.test(lang + ": elsewhere nothing changes", async () => { + const errors = [], asked = [], posted = []; + 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, null, { available: true, on: false }, asked, posted)); + await page.goto("http://magpie.test/"); + await page.locator("#prefs").click(); + await page.locator("#themeSegs .opt").first().waitFor(); + assert.equal(await page.evaluate(() => document.documentElement.classList.contains("omarchy")), false); + assert.equal(await page.locator("#omarchy-theme").count(), 0, "no theme style"); + assert(await page.locator("#themeSegs").isVisible(), "the Appearance choices show"); + assert.equal(await page.locator(".om-theme-name").isVisible(), false); + assert.equal(await page.locator("#barIconRow").isVisible(), false, "no Bar icon row"); + await page.waitForTimeout(3000); // past omarchy.js's poll + assert.deepEqual(asked, [], "nothing is asked of /api/omarchy"); + assert.deepEqual(errors, []); + await context.close(); + }); + + await t.test(lang + ": on Omarchy", async () => { + const errors = [], asked = [], posted = []; + 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, theme, { available: true, on: false }, asked, posted)); + await page.goto("http://magpie.test/"); + assert.equal(await page.evaluate(() => document.documentElement.classList.contains("omarchy")), true); + assert.equal(await page.evaluate(() => getComputedStyle(document.body).backgroundColor), "rgb(26, 27, 38)", "the theme's background"); + await page.locator("#prefs").click(); + await page.locator("#barIconSegs .opt").first().waitFor(); + assert.equal((await page.locator(".om-theme-name").textContent()).trim(), "tokyo-night"); + assert.equal(await page.locator("#themeSegs").isVisible(), false, "the theme is Omarchy's to pick"); + assert.equal(await page.locator("#langSegs .opt").first().evaluate((b) => getComputedStyle(b).borderTopLeftRadius), "0px", "square"); + assert.equal((await page.locator("#barIconRow .name").textContent()).trim(), barName); + + // On, then Off: each posted, the pick drawn, the page not moved + const segs = page.locator("#barIconSegs .opt"); + assert.deepEqual(await segs.allTextContents(), [off, on]); + assert.equal(await segs.nth(0).evaluate((b) => b.classList.contains("on")), true, "off to start"); + const before = await view(page); + await segs.nth(1).click(); + await page.locator("#barIconSegs .opt.on", { hasText: on }).waitFor(); + await segs.nth(0).click(); + await page.locator("#barIconSegs .opt.on", { hasText: off }).waitFor(); + assert.deepEqual(posted, [{ on: true }, { on: false }]); + await page.waitForTimeout(300); + assert.equal(await view(page), before, "a pick moves nothing"); + assert.deepEqual(errors, []); + await context.close(); + }); + + await t.test(lang + ": Omarchy without its bar (a browser's page)", async () => { + const errors = [], asked = [], posted = []; + const context = await browser.newContext({ viewport: { width: 900, height: 420 }, reducedMotion: "reduce" }); + const page = await context.newPage(); + page.setDefaultTimeout(5000); + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", server(lang, theme, { available: false, on: false }, asked, posted)); + await page.goto("http://magpie.test/"); + await page.locator("#prefs").click(); + await page.locator("#langSegs .opt").first().waitFor(); + await page.waitForTimeout(300); + assert(asked.includes("GET /api/omarchy/widget")); + assert.equal(await page.locator("#barIconRow").isVisible(), false); + assert.deepEqual(errors, []); + await context.close(); + }); + } + }); +} diff --git a/internal/gui/titlebar_gtk3.go b/internal/gui/titlebar_gtk3.go index 6a8c567f1..beb6da5a3 100644 --- a/internal/gui/titlebar_gtk3.go +++ b/internal/gui/titlebar_gtk3.go @@ -5,16 +5,25 @@ package gui /* #cgo pkg-config: gtk+-3.0 #include +#include static void plain_titlebar(void *w) { GtkWidget *bar = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0); gtk_widget_set_no_show_all(bar, TRUE); // kept hidden when the window shows all it holds gtk_window_set_titlebar(GTK_WINDOW(w), bar); } + +static void name_window(void *w, char *title) { + gtk_window_set_title(GTK_WINDOW(w), title); +} */ import "C" -import "github.com/wailsapp/wails/v3/pkg/application" +import ( + "unsafe" + + "github.com/wailsapp/wails/v3/pkg/application" +) // plainTitlebar takes the system's title bar off a window whose page has a // header of its own. GNOME draws one over it, the name and a close button @@ -29,3 +38,15 @@ func plainTitlebar(w *application.WebviewWindow) { } }) } + +// nameWindow gives a frameless window a title, which Wails leaves unset on +// one; Hyprland tells the panel from the main window by it. +func nameWindow(w *application.WebviewWindow, title string) { + application.InvokeSync(func() { + if p := w.NativeWindow(); p != nil { + t := C.CString(title) + C.name_window(p, t) + C.free(unsafe.Pointer(t)) + } + }) +} diff --git a/internal/gui/titlebar_gtk4.go b/internal/gui/titlebar_gtk4.go index 25c6a1987..b62ac2520 100644 --- a/internal/gui/titlebar_gtk4.go +++ b/internal/gui/titlebar_gtk4.go @@ -5,16 +5,25 @@ package gui /* #cgo pkg-config: gtk4 #include +#include static void plain_titlebar(void *w) { GtkWidget *bar = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0); gtk_widget_set_visible(bar, FALSE); gtk_window_set_titlebar(GTK_WINDOW(w), bar); } + +static void name_window(void *w, char *title) { + gtk_window_set_title(GTK_WINDOW(w), title); +} */ import "C" -import "github.com/wailsapp/wails/v3/pkg/application" +import ( + "unsafe" + + "github.com/wailsapp/wails/v3/pkg/application" +) // plainTitlebar takes the system's title bar off a window whose page has a // header of its own. GNOME draws one over it, the name and a close button @@ -29,3 +38,15 @@ func plainTitlebar(w *application.WebviewWindow) { } }) } + +// nameWindow gives a frameless window a title, which Wails leaves unset on +// one; Hyprland tells the panel from the main window by it. +func nameWindow(w *application.WebviewWindow, title string) { + application.InvokeSync(func() { + if p := w.NativeWindow(); p != nil { + t := C.CString(title) + C.name_window(p, t) + C.free(unsafe.Pointer(t)) + } + }) +} diff --git a/internal/gui/titlebar_other.go b/internal/gui/titlebar_other.go index f12aaba3d..ebfb853f5 100644 --- a/internal/gui/titlebar_other.go +++ b/internal/gui/titlebar_other.go @@ -7,3 +7,5 @@ import "github.com/wailsapp/wails/v3/pkg/application" // plainTitlebar: macOS insets the traffic lights into the page's header // (MacTitleBarHiddenInset) and Windows keeps its own title bar. func plainTitlebar(*application.WebviewWindow) {} + +func nameWindow(*application.WebviewWindow, string) {} diff --git a/internal/omarchy/hypr.go b/internal/omarchy/hypr.go new file mode 100644 index 000000000..b2b813add --- /dev/null +++ b/internal/omarchy/hypr.go @@ -0,0 +1,187 @@ +package omarchy + +import ( + "bufio" + "context" + "encoding/json" + "fmt" + "net" + "os" + "path/filepath" + "runtime" + "strconv" + "time" + + "github.com/yetone/magpie/internal/proc" +) + +// Hyprland is whether magpie runs under Hyprland, Omarchy's compositor or +// anyone else's. A Wayland window can't place itself there, so a tray panel +// that asks to go under its icon opens wherever Hyprland floats it (the +// middle of the screen), framed and dimmed like any other window. +func Hyprland() bool { + return runtime.GOOS == "linux" && os.Getenv("HYPRLAND_INSTANCE_SIGNATURE") != "" +} + +// PanelGap is how far a drop-down panel keeps from the bar and the screen's +// edge, as Omarchy's own popups do. +const PanelGap = 6 + +type hyprMonitor struct { + X, Y int + Width, Height int + Scale float64 + Transform int + Reserved [4]int // left, top, right, bottom +} + +// size is the monitor's size in layout coordinates, the ones windows and +// the cursor are placed in. +func (m hyprMonitor) size() (w, h int) { + s := m.Scale + if s <= 0 { + s = 1 + } + w, h = int(float64(m.Width)/s+.5), int(float64(m.Height)/s+.5) + if m.Transform%2 == 1 { // turned 90° or 270° + w, h = h, w + } + return w, h +} + +// PanelAt is where a drop-down panel width wide goes: under the bar, its +// middle at the cursor (which has just clicked the icon it drops from), +// kept PanelGap inside the monitor the cursor is on. maxH is the room it has +// down to the bottom of that monitor's work area. +func PanelAt(width int) (x, y, maxH int, ok bool) { + var cur struct{ X, Y int } + var mons []hyprMonitor + if hyprJSON("cursorpos", &cur) != nil || hyprJSON("monitors", &mons) != nil { + return 0, 0, 0, false + } + return panelAt(width, cur.X, cur.Y, mons) +} + +func panelAt(width, cx, cy int, mons []hyprMonitor) (x, y, maxH int, ok bool) { + for _, m := range mons { + w, h := m.size() + if cx < m.X || cx >= m.X+w || cy < m.Y || cy >= m.Y+h { + continue + } + left, right := m.X+m.Reserved[0]+PanelGap, m.X+w-m.Reserved[2]-PanelGap + x = max(left, min(right-width, cx-width/2)) + y = m.Y + m.Reserved[1] + PanelGap + return x, y, m.Y + h - m.Reserved[3] - PanelGap - y, true + } + return 0, 0, 0, false +} + +// PlacePanel gives the window titled title a rule of its own (replacing +// the last one, by name): floating, pinned to every workspace, at x, y, with +// no border and fully opaque — the page draws its own frame, in the border's +// colour. It is asked each time the panel opens, as where it goes follows +// the click, and a config reload drops rules made this way. +func PlacePanel(title string, x, y int) error { + lua := fmt.Sprintf(`hl.window_rule({ name = "magpie-panel", match = { title = %s }, tag = "-default-opacity", float = true, pin = true, border_size = 0, no_shadow = true, opacity = "1 1", no_anim = true, move = { %d, %d } })`, + strconv.Quote("^"+regexpQuote(title)+"$"), x, y) + return hyprctl("eval", lua) +} + +// Clicks are how the panel closes on a click outside it, as Omarchy's own +// drop-downs do. Losing focus can't say so here: Omarchy has focus follow +// the mouse, so the pointer merely passing over another window takes it, +// and Hyprland tells a program nothing of clicks on others. While the panel +// is open, a left-click bind that lets the click through (non_consuming) +// announces each one on Hyprland's event socket, and WatchClicks hears it. +const clickEvent = "magpie-click" + +// ReportClicks has Hyprland announce every left click, until StopClicks. +func ReportClicks() error { + return hyprctl("eval", `if magpie_click then magpie_click:remove() end magpie_click = hl.bind("mouse:272", function() hl.dispatch(hl.dsp.event("`+clickEvent+`")) end, { non_consuming = true })`) +} + +// StopClicks takes the bind away again. +func StopClicks() error { + return hyprctl("eval", `if magpie_click then magpie_click:remove() magpie_click = nil end`) +} + +// WatchClicks calls click on each click ReportClicks announces, for as long +// as magpie runs, reconnecting when Hyprland restarts. +func WatchClicks(click func()) { + sock := filepath.Join(os.Getenv("XDG_RUNTIME_DIR"), "hypr", os.Getenv("HYPRLAND_INSTANCE_SIGNATURE"), ".socket2.sock") + for { + if c, err := net.Dial("unix", sock); err == nil { + sc := bufio.NewScanner(c) + for sc.Scan() { + if sc.Text() == "custom>>"+clickEvent { + click() + } + } + c.Close() + } + time.Sleep(2 * time.Second) + } +} + +// ClickedOutside is whether the pointer, which has just clicked, is off the +// window titled title and below the bar: a click on the bar is left to the +// icon it lands on, so the panel's own icon toggles it rather than closing +// and reopening it. +func ClickedOutside(title string) bool { + var cur struct{ X, Y int } + var clients []struct { + Title string + At [2]int + Size [2]int + } + if hyprJSON("cursorpos", &cur) != nil || hyprJSON("clients", &clients) != nil { + return false + } + for _, w := range clients { + if w.Title == title { + return outside(cur.X, cur.Y, w.At, w.Size) + } + } + return false +} + +func outside(x, y int, at, size [2]int) bool { + if y < at[1]-PanelGap { // the bar + return false + } + return x < at[0] || x >= at[0]+size[0] || y < at[1] || y >= at[1]+size[1] +} + +func regexpQuote(s string) string { + var b []byte + for i := 0; i < len(s); i++ { + if c := s[i]; (c < 'a' || c > 'z') && (c < 'A' || c > 'Z') && (c < '0' || c > '9') && c != ' ' && c != '-' && c != '_' { + b = append(b, '\\') + } + b = append(b, s[i]) + } + return string(b) +} + +func hyprJSON(what string, v any) error { + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + out, err := proc.CommandContext(ctx, "hyprctl", "-j", what).Output() + if err != nil { + return err + } + return json.Unmarshal(out, v) +} + +func hyprctl(args ...string) error { + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + out, err := proc.CommandContext(ctx, "hyprctl", args...).CombinedOutput() + if err != nil { + return fmt.Errorf("hyprctl %s: %v: %s", args[0], err, out) + } + if s := string(out); s != "ok" && s != "ok\n" && s != "" { + return fmt.Errorf("hyprctl %s: %s", args[0], s) + } + return nil +} diff --git a/internal/omarchy/hypr_test.go b/internal/omarchy/hypr_test.go new file mode 100644 index 000000000..dcea39a08 --- /dev/null +++ b/internal/omarchy/hypr_test.go @@ -0,0 +1,61 @@ +package omarchy + +import "testing" + +func TestPanelAt(t *testing.T) { + // 2528x960 at 1.6 is 1580x600 in layout coordinates; Omarchy's bar + // takes 26 at the top. A second monitor to its right, turned, at 1. + mons := []hyprMonitor{ + {Width: 2528, Height: 960, Scale: 1.6, Reserved: [4]int{0, 26, 0, 0}}, + {X: 1580, Width: 1920, Height: 1080, Scale: 1, Transform: 1}, + } + for _, c := range []struct { + name string + cx, cy int + x, y, room int + ok bool + }{ + {"middle", 800, 10, 580, 32, 562, true}, + {"right edge", 1570, 10, 1580 - 6 - 440, 32, 562, true}, + {"left edge", 20, 10, 6, 32, 562, true}, + {"turned monitor", 1700, 1500, 1586, 6, 1920 - 12, true}, + {"off every monitor", -5, 10, 0, 0, 0, false}, + } { + x, y, room, ok := panelAt(440, c.cx, c.cy, mons) + if x != c.x || y != c.y || room != c.room || ok != c.ok { + t.Errorf("%s: %d,%d room %d %v; want %d,%d room %d %v", c.name, x, y, room, ok, c.x, c.y, c.room, c.ok) + } + } +} + +func TestRegexpQuote(t *testing.T) { + for in, want := range map[string]string{ + "magpie panel": "magpie panel", + "a.b(c)": `a\.b\(c\)`, + "x+y*": `x\+y\*`, + } { + if got := regexpQuote(in); got != want { + t.Errorf("regexpQuote(%q) = %q, want %q", in, got, want) + } + } +} + +func TestOutside(t *testing.T) { + at, size := [2]int{1134, 32}, [2]int{440, 520} + for _, c := range []struct { + name string + x, y int + want bool + }{ + {"on the panel", 1300, 300, false}, + {"on its top-left corner", 1134, 32, false}, + {"left of it", 900, 300, true}, + {"under it", 1300, 560, true}, + {"on the bar", 1400, 10, false}, + {"in the gap under the bar", 900, 28, true}, + } { + if got := outside(c.x, c.y, at, size); got != c.want { + t.Errorf("%s: %v, want %v", c.name, got, c.want) + } + } +} diff --git a/internal/omarchy/omarchy.go b/internal/omarchy/omarchy.go new file mode 100644 index 000000000..77c9a7132 --- /dev/null +++ b/internal/omarchy/omarchy.go @@ -0,0 +1,437 @@ +// Package omarchy is what magpie knows of Omarchy (omarchy.org), the +// Hyprland desktop: whether it runs on one, and the look its current theme +// gives every surface, so magpie's windows can take that look there and +// nowhere else. +// +// Omarchy (4.x) keeps the current theme under +// ~/.local/state/omarchy/current/theme: colors.toml, the palette every app's +// theme is made from, and shell.toml, the tokens its own shell draws with +// (controls, popups, menus). The font is omarchy-font-current's, the corners +// Hyprland's decoration:rounding (0 unless changed) and the border its +// general:border_size in the colour of the active window's. +package omarchy + +import ( + "bufio" + "bytes" + "context" + "fmt" + "os" + "path/filepath" + "runtime" + "strconv" + "strings" + "sync" + "time" + + "github.com/yetone/magpie/internal/proc" +) + +// Detect reports whether magpie runs on Omarchy. MAGPIE_OMARCHY=1 says it +// does (with MAGPIE_OMARCHY_THEME the theme's folder), =0 that it doesn't. +func Detect() bool { + switch os.Getenv("MAGPIE_OMARCHY") { + case "1": + return true + case "0": + return false + } + if runtime.GOOS != "linux" || ThemeDir() == "" { + return false + } + if os.Getenv("OMARCHY_PATH") != "" { + return true + } + home, _ := os.UserHomeDir() + for _, d := range []string{"/usr/share/omarchy", filepath.Join(home, ".local", "share", "omarchy")} { + if fi, err := os.Stat(d); err == nil && fi.IsDir() { + return true + } + } + return false +} + +// ThemeDir is the current theme's folder, or "" when there is none. +func ThemeDir() string { + if d := os.Getenv("MAGPIE_OMARCHY_THEME"); d != "" { + return d + } + home, _ := os.UserHomeDir() + state := os.Getenv("XDG_STATE_HOME") + if state == "" { + state = filepath.Join(home, ".local", "state") + } + for _, d := range []string{ + filepath.Join(state, "omarchy", "current", "theme"), + filepath.Join(home, ".config", "omarchy", "current", "theme"), // before 4.0 + } { + if _, err := os.Stat(filepath.Join(d, "colors.toml")); err == nil { + return d + } + } + return "" +} + +// Theme is the current theme as magpie draws with it. +type Theme struct { + Name string `json:"name"` // tokyo-night + Mode string `json:"mode"` // dark or light + Stamp string `json:"stamp"` // changes when any of it does + Vars map[string]string `json:"vars"` // CSS custom properties +} + +// Parse reads a TOML file's key = value lines, a section's keys as +// "section.key": the little of TOML the theme files use (strings, numbers, +// booleans, comments). +func Parse(b []byte) map[string]string { + out := map[string]string{} + section := "" + sc := bufio.NewScanner(bytes.NewReader(b)) + for sc.Scan() { + line := strings.TrimSpace(sc.Text()) + if line == "" || line[0] == '#' { + continue + } + if line[0] == '[' { + section = strings.Trim(line, "[] ") + continue + } + k, v, ok := strings.Cut(line, "=") + if !ok { + continue + } + k, v = strings.TrimSpace(k), strings.TrimSpace(v) + if strings.HasPrefix(v, `"`) { + if end := strings.Index(v[1:], `"`); end >= 0 { + v = v[1 : end+1] + } + } else if i := strings.Index(v, "#"); i >= 0 { + v = strings.TrimSpace(v[:i]) + } + if section != "" { + k = section + "." + k + } + out[k] = v + } + return out +} + +// color is an RGBA colour, each part 0..1. +type color struct{ r, g, b, a float64 } + +// parseColor reads #rgb, #rrggbb, #rrggbbaa, Hyprland's rgb(rrggbb) and +// rgba(rrggbbaa), and CSS's rgb(r, g, b) and rgba(r, g, b, a). A gradient +// ("rgba(…) rgba(…) 45deg") is read as its first colour. +func parseColor(s string) (color, bool) { + s = strings.TrimSpace(strings.ToLower(s)) + if f := strings.Fields(s); len(f) > 1 && !strings.Contains(s, ",") { + s = f[0] + } + hex := func(h string) (color, bool) { + switch len(h) { + case 3: + h = string([]byte{h[0], h[0], h[1], h[1], h[2], h[2]}) + case 6: + case 8: + default: + return color{}, false + } + n, err := strconv.ParseUint(h, 16, 32) + if err != nil { + return color{}, false + } + if len(h) == 6 { + n = n<<8 | 0xff + } + return color{float64(n>>24&0xff) / 255, float64(n>>16&0xff) / 255, float64(n>>8&0xff) / 255, float64(n&0xff) / 255}, true + } + switch { + case strings.HasPrefix(s, "#"): + return hex(s[1:]) + case strings.HasPrefix(s, "rgb"): + open, end := strings.Index(s, "("), strings.LastIndex(s, ")") + if open < 0 || end < open { + return color{}, false + } + in := strings.TrimSpace(s[open+1 : end]) + if !strings.Contains(in, ",") { + return hex(in) + } + parts := strings.Split(in, ",") + if len(parts) < 3 { + return color{}, false + } + var v [4]float64 + v[3] = 1 + for i, p := range parts[:min(len(parts), 4)] { + f, err := strconv.ParseFloat(strings.TrimSpace(p), 64) + if err != nil { + return color{}, false + } + if i < 3 { + f /= 255 + } + v[i] = f + } + return color{v[0], v[1], v[2], v[3]}, true + } + return color{}, false +} + +func (c color) css() string { + to := func(f float64) int { return int(max(0, min(255, f*255+0.5))) } + if c.a >= 0.999 { + return fmt.Sprintf("#%02x%02x%02x", to(c.r), to(c.g), to(c.b)) + } + return fmt.Sprintf("rgba(%d, %d, %d, %s)", to(c.r), to(c.g), to(c.b), strconv.FormatFloat(max(0, min(1, c.a)), 'f', 3, 64)) +} + +// over is c at alpha a laid over the opaque bg, as one opaque colour. +func (c color) over(bg color, a float64) color { + return color{bg.r + (c.r-bg.r)*a, bg.g + (c.g-bg.g)*a, bg.b + (c.b-bg.b)*a, 1} +} + +func (c color) alpha(a float64) color { c.a = a; return c } + +// luminance is c's relative luminance, to tell a light theme from a dark one +// that doesn't say. +func (c color) luminance() float64 { return 0.2126*c.r + 0.7152*c.g + 0.0722*c.b } + +// Vars turns the theme's palette (colors.toml) and shell tokens +// (shell.toml) into magpie's CSS custom properties, the rest given: the +// font's family, the corners' radius and the border's width. +func Vars(colors, shell map[string]string, font string, rounding, border int) (map[string]string, string) { + get := func(m map[string]string, fallback color, keys ...string) color { + for _, k := range keys { + v := m[k] + // a shell token may name another: "hyprland.active-border" + for range 3 { + if ref, ok := shell[v]; ok { + v = ref + } + } + if c, ok := parseColor(v); ok { + return c + } + } + return fallback + } + num := func(k string, fallback float64) float64 { + if f, err := strconv.ParseFloat(shell[k], 64); err == nil { + return f + } + return fallback + } + black := color{0, 0, 0, 1} + bg := get(shell, get(colors, color{0.102, 0.106, 0.149, 1}, "background"), "popups.background") + bg.a = 1 + fg := get(shell, get(colors, color{0.663, 0.694, 0.839, 1}, "foreground"), "popups.text") + mode := strings.ToLower(colors["mode"]) + if mode != "light" && mode != "dark" { + mode = "dark" + if bg.luminance() > 0.5 { + mode = "light" + } + } + dim := get(colors, fg.over(bg, 0.55), "dark_foreground") + if mode == "light" { + dim = get(colors, fg.over(bg, 0.6), "muted", "dark_foreground") + } + accent := get(shell, get(colors, color{0.478, 0.635, 0.969, 1}, "accent", "blue"), "menu.selected-text") + bright := get(colors, fg, "bright_foreground") + red := get(colors, color{0.969, 0.463, 0.557, 1}, "red") + green := get(colors, color{0.62, 0.808, 0.416, 1}, "green") + yellow := get(colors, color{0.878, 0.686, 0.408, 1}, "yellow") + orange := get(colors, yellow, "orange") + cyan := get(colors, color{0.267, 0.616, 0.671, 1}, "cyan") + blue := get(colors, accent, "blue") + magenta := get(colors, color{0.678, 0.557, 0.902, 1}, "magenta") + edge := get(shell, accent, "popups.border", "hyprland.active-border") + selFg := get(shell, fg, "menu.selected-background") + selA := num("menu.selected-background-alpha", 0.08) + fillA := num("controls.normal-fill-alpha", 0.04) + hoverA := num("controls.hover-cursor-fill-alpha", 0.08) + ctlBorderA := num("controls.normal-border-alpha", 0.4) + pressA := num("controls.pressed-fill-alpha", 0.22) + selectedA := num("controls.selected-fill-alpha", 0.18) + size := num("font.base-size", 12) + soft := func(c color) string { return c.over(bg, 0.16).css() } + shadow := black.alpha(0.35) + if mode == "light" { + shadow = black.alpha(0.12) + } + invert := "1" + if mode == "light" { + invert = "0" + } + if font == "" { + font = "JetBrainsMono Nerd Font" + } + family := fmt.Sprintf("%q, \"JetBrainsMono Nerd Font\", \"JetBrains Mono\", ui-monospace, monospace", font) + v := map[string]string{ + "--bg": bg.css(), + "--card": fg.over(bg, fillA).css(), + "--card-2": fg.over(bg, fillA/2).css(), + "--pill": fg.over(bg, fillA).css(), + "--pill-hover": fg.over(bg, hoverA).css(), + "--pill-line": fg.alpha(ctlBorderA).css(), + "--pill-shadow": "none", + "--card-edge": "none", + "--seg-track": "transparent", + "--seg-thumb": fg.over(bg, selectedA).css(), + "--seg-edge": "none", + "--line": fg.over(bg, 0.16).css(), + "--line-2": fg.over(bg, 0.1).css(), + "--fg": fg.css(), + "--fg-2": fg.css(), + "--fg-hi": bright.css(), + "--muted": dim.css(), + "--faint": fg.over(bg, 0.38).css(), + "--accent": accent.css(), + "--accent-soft": accent.over(bg, 0.14).css(), + "--accent-fg": bg.css(), + "--sel": selFg.over(bg, selA).css(), + "--press": fg.over(bg, pressA).css(), + "--green": green.css(), + "--green-soft": soft(green), + "--red": red.css(), + "--red-soft": soft(red), + "--amber": yellow.css(), + "--amber-soft": soft(yellow), + "--drift": red.css(), + "--drift-soft": soft(red), + "--pop-bg": bg.css(), + "--shadow": "0 8px 24px " + shadow.css(), + "--skel": fg.over(bg, 0.06).css(), + "--skel-hi": fg.over(bg, 0.12).css(), + "--font": family, + "--code": family, + "--logo-invert": invert, + "--tk-s": green.css(), "--tk-k": magenta.css(), "--tk-f": blue.css(), + "--tk-n": orange.css(), "--tk-v": cyan.css(), "--tk-o": magenta.css(), "--tk-c": dim.css(), + "--om-edge": edge.css(), + "--om-border": strconv.Itoa(max(border, 1)) + "px", + "--om-radius": strconv.Itoa(max(rounding, 0)) + "px", + "--om-size": strconv.FormatFloat(size, 'f', -1, 64) + "px", + "--om-hover": fg.alpha(hoverA).css(), + "--om-hover-line": fg.alpha(num("controls.hover-cursor-border-alpha", 0.25)).css(), + "--om-sel": selFg.alpha(selA).css(), + "--om-sel-line": get(shell, fg, "menu.selected-border").alpha(num("menu.selected-border-alpha", 0.25)).css(), + "--om-cyan": cyan.css(), + "--om-magenta": magenta.css(), + "--om-orange": orange.css(), + } + return v, mode +} + +var ( + mu sync.Mutex + cached Theme + seen string // the files' stamp cached was read at + asked time.Time +) + +// watched are the files whose change changes the look: the theme's, the +// font's (omarchy-font-set writes fontconfig's) and Hyprland's config. +func watched(dir string) []string { + home, _ := os.UserHomeDir() + cfg := os.Getenv("XDG_CONFIG_HOME") + if cfg == "" { + cfg = filepath.Join(home, ".config") + } + files := []string{ + filepath.Join(dir, "colors.toml"), + filepath.Join(dir, "shell.toml"), + filepath.Join(filepath.Dir(dir), "theme.name"), + filepath.Join(cfg, "fontconfig", "fonts.conf"), + } + hypr, _ := filepath.Glob(filepath.Join(cfg, "hypr", "*")) + return append(files, hypr...) +} + +func stampOf(files []string) string { + var b strings.Builder + for _, f := range files { + if fi, err := os.Stat(f); err == nil { + fmt.Fprintf(&b, "%s:%d:%d;", filepath.Base(f), fi.ModTime().UnixNano(), fi.Size()) + } + } + return b.String() +} + +// Current is the theme as it is now: read again only when one of its files +// has changed, and those looked at no more than once a second. +func Current() (Theme, bool) { + dir := ThemeDir() + if dir == "" { + return Theme{}, false + } + mu.Lock() + defer mu.Unlock() + if !asked.IsZero() && time.Since(asked) < time.Second && cached.Stamp != "" { + return cached, true + } + asked = time.Now() + stamp := stampOf(watched(dir)) + if stamp == seen && cached.Stamp != "" { + return cached, true + } + colors, _ := os.ReadFile(filepath.Join(dir, "colors.toml")) + shell, _ := os.ReadFile(filepath.Join(dir, "shell.toml")) + name, _ := os.ReadFile(filepath.Join(filepath.Dir(dir), "theme.name")) + font := fontName() + rounding, border := hyprInt("decoration:rounding", 0), hyprInt("general:border_size", 2) + vars, mode := Vars(Parse(colors), Parse(shell), font, rounding, border) + seen = stamp + cached = Theme{ + Name: strings.TrimSpace(string(name)), Mode: mode, Vars: vars, + Stamp: fmt.Sprintf("%x", fnv(stamp+font+strconv.Itoa(rounding)+strconv.Itoa(border))), + } + return cached, true +} + +func fnv(s string) uint64 { + h := uint64(14695981039346656037) + for i := 0; i < len(s); i++ { + h ^= uint64(s[i]) + h *= 1099511628211 + } + return h +} + +// fontName is the font Omarchy sets for everything, as omarchy-font-current +// says. +func fontName() string { + if f := os.Getenv("MAGPIE_OMARCHY_FONT"); f != "" { + return f + } + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + out, err := proc.CommandContext(ctx, "omarchy-font-current").Output() + if err != nil { + return "" + } + return strings.TrimSpace(string(out)) +} + +// hyprInt is one of Hyprland's integer options ("int: 0"), or fallback when +// Hyprland doesn't answer. +func hyprInt(option string, fallback int) int { + if os.Getenv("HYPRLAND_INSTANCE_SIGNATURE") == "" { + return fallback + } + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + out, err := proc.CommandContext(ctx, "hyprctl", "getoption", option).Output() + if err != nil { + return fallback + } + for _, line := range strings.Split(string(out), "\n") { + if v, ok := strings.CutPrefix(strings.TrimSpace(line), "int:"); ok { + if n, err := strconv.Atoi(strings.TrimSpace(v)); err == nil { + return n + } + } + } + return fallback +} diff --git a/internal/omarchy/omarchy_test.go b/internal/omarchy/omarchy_test.go new file mode 100644 index 000000000..55876dcdf --- /dev/null +++ b/internal/omarchy/omarchy_test.go @@ -0,0 +1,145 @@ +package omarchy + +import ( + "os" + "path/filepath" + "testing" +) + +const tokyoColors = `mode = "dark" + +accent = "#7aa2f7" +selection = "#292e42" +muted = "#414868" + +background = "#1a1b26" +foreground = "#a9b1d6" +dark_foreground = "#565f89" +bright_foreground = "#c0caf5" +red = "#f7768e" +yellow = "#e0af68" +green = "#9ece6a" +` + +const tokyoShell = `# comment +[hyprland] +active-border = "#7aa2f7" +active-border-foreground = "#a9b1d6" + +[controls] +normal-fill-alpha = 0.04 # inline +hover-cursor-fill-alpha = 0.08 + +[font] +base-size = 12 + +[popups] +background = "#1a1b26" +text = "#a9b1d6" +border = "hyprland.active-border" + +[menu] +selected-background = "#a9b1d6" +selected-background-alpha = 0.08 +selected-text = "#7aa2f7" +` + +func TestParse(t *testing.T) { + m := Parse([]byte(tokyoShell)) + for k, want := range map[string]string{ + "hyprland.active-border": "#7aa2f7", + "controls.normal-fill-alpha": "0.04", + "font.base-size": "12", + "popups.border": "hyprland.active-border", + } { + if m[k] != want { + t.Errorf("%s = %q, want %q", k, m[k], want) + } + } +} + +func TestParseColor(t *testing.T) { + for in, want := range map[string]string{ + "#7aa2f7": "#7aa2f7", + "#fff": "#ffffff", + "rgb(7aa2f7)": "#7aa2f7", + "rgba(7aa2f780)": "rgba(122, 162, 247, 0.502)", + "rgba(33ccffee) rgba(00ff99ee) 45deg": "rgba(51, 204, 255, 0.933)", + "rgba(10, 20, 30, 0.5)": "rgba(10, 20, 30, 0.500)", + } { + c, ok := parseColor(in) + if !ok || c.css() != want { + t.Errorf("parseColor(%q) = %q %v, want %q", in, c.css(), ok, want) + } + } + if _, ok := parseColor("hyprland.active-border"); ok { + t.Error("a token's name read as a colour") + } +} + +func TestVars(t *testing.T) { + v, mode := Vars(Parse([]byte(tokyoColors)), Parse([]byte(tokyoShell)), "JetBrainsMono Nerd Font", 0, 2) + if mode != "dark" { + t.Errorf("mode %q", mode) + } + for k, want := range map[string]string{ + "--bg": "#1a1b26", + "--fg": "#a9b1d6", + "--accent": "#7aa2f7", + "--muted": "#565f89", + "--red": "#f7768e", + "--om-edge": "#7aa2f7", // popups.border names the Hyprland border + "--om-radius": "0px", + "--om-border": "2px", + "--om-size": "12px", + "--logo-invert": "1", + "--om-sel": "rgba(169, 177, 214, 0.080)", + "--card": "#20212d", // the foreground at 4% over the background + } { + if v[k] != want { + t.Errorf("%s = %q, want %q", k, v[k], want) + } + } + if want := `"JetBrainsMono Nerd Font", "JetBrainsMono Nerd Font", "JetBrains Mono", ui-monospace, monospace`; v["--font"] != want { + t.Errorf("--font = %s", v["--font"]) + } + + // a light theme that doesn't say so is told by its background + v, mode = Vars(map[string]string{"background": "#f5f5f5", "foreground": "#222222"}, nil, "", 8, 1) + if mode != "light" || v["--logo-invert"] != "0" || v["--om-radius"] != "8px" { + t.Errorf("light: %s %s %s", mode, v["--logo-invert"], v["--om-radius"]) + } +} + +func TestCurrent(t *testing.T) { + dir := filepath.Join(t.TempDir(), "current", "theme") + os.MkdirAll(dir, 0o755) + os.WriteFile(filepath.Join(dir, "colors.toml"), []byte(tokyoColors), 0o644) + os.WriteFile(filepath.Join(dir, "shell.toml"), []byte(tokyoShell), 0o644) + os.WriteFile(filepath.Join(filepath.Dir(dir), "theme.name"), []byte("tokyo-night\n"), 0o644) + t.Setenv("MAGPIE_OMARCHY", "1") + t.Setenv("MAGPIE_OMARCHY_THEME", dir) + t.Setenv("MAGPIE_OMARCHY_FONT", "Iosevka") + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + if !Detect() { + t.Fatal("not detected") + } + th, ok := Current() + if !ok || th.Name != "tokyo-night" || th.Vars["--bg"] != "#1a1b26" || th.Stamp == "" { + t.Fatalf("%v %+v", ok, th) + } + // a new theme is read within a second or so + os.WriteFile(filepath.Join(dir, "shell.toml"), []byte("[font]\nbase-size = 13\n"), 0o644) + os.WriteFile(filepath.Join(dir, "colors.toml"), []byte("mode = \"light\"\nbackground = \"#fafafa\"\nforeground = \"#111111\"\n"), 0o644) + mu.Lock() + asked = asked.Add(-2e9) + mu.Unlock() + th2, _ := Current() + if th2.Stamp == th.Stamp || th2.Mode != "light" || th2.Vars["--bg"] != "#fafafa" { + t.Fatalf("not read again: %+v", th2) + } + t.Setenv("MAGPIE_OMARCHY", "0") + if Detect() { + t.Error("MAGPIE_OMARCHY=0 detected") + } +} diff --git a/internal/omarchy/widget.go b/internal/omarchy/widget.go new file mode 100644 index 000000000..a52c779be --- /dev/null +++ b/internal/omarchy/widget.go @@ -0,0 +1,120 @@ +package omarchy + +import ( + "bytes" + "context" + "embed" + "fmt" + "os" + "path/filepath" + "strconv" + "strings" + "time" + + "github.com/yetone/magpie/internal/proc" +) + +// The bar widget: magpie's icon in Omarchy's own bar, where Omarchy's +// widgets are, rather than in the tray's drawer, which Omarchy keeps tray +// icons behind until each is pinned. It is a third-party Omarchy plugin, +// put in by hand the way Omarchy's shell README says (the files under +// ~/.config/omarchy/plugins//, then rescanPlugins and plugin enable), +// and only when the user asks for it in Settings. +const WidgetID = "usemagpie.magpie" + +//go:embed widget +var widgetFiles embed.FS + +func widgetDir() string { + cfg := os.Getenv("XDG_CONFIG_HOME") + if cfg == "" { + home, _ := os.UserHomeDir() + cfg = filepath.Join(home, ".config") + } + return filepath.Join(cfg, "omarchy", "plugins", WidgetID) +} + +// WidgetOn is whether the widget has been put in. +func WidgetOn() bool { + _, err := os.Stat(filepath.Join(widgetDir(), "manifest.json")) + return err == nil +} + +// AddWidget puts the widget in Omarchy's bar, running exe (magpie) when +// clicked, or brings it up to date. +func AddWidget(exe string) error { + dir := widgetDir() + if err := os.MkdirAll(dir, 0o755); err != nil { + return err + } + files, err := widget(exe) + if err != nil { + return err + } + for name, b := range files { + if err := os.WriteFile(filepath.Join(dir, name), b, 0o644); err != nil { + return err + } + } + if err := run("omarchy-shell", "shell", "rescanPlugins"); err != nil { + return err + } + // enabling again is what has the shell load files it already had + _ = run("omarchy", "plugin", "disable", WidgetID) + return run("omarchy", "plugin", "enable", WidgetID) +} + +// KeepWidget brings a widget that is in the bar up to date with this magpie, +// which may have moved or been updated since it was put in. +func KeepWidget(exe string) error { + if !WidgetOn() { + return nil + } + files, err := widget(exe) + if err != nil { + return err + } + for name, b := range files { + if old, err := os.ReadFile(filepath.Join(widgetDir(), name)); err != nil || !bytes.Equal(old, b) { + return AddWidget(exe) + } + } + return nil +} + +// widget is the widget's files, running exe. +func widget(exe string) (map[string][]byte, error) { + files := map[string][]byte{} + for _, name := range []string{"manifest.json", "Widget.qml"} { + b, err := widgetFiles.ReadFile("widget/" + name) + if err != nil { + return nil, err + } + if name == "Widget.qml" { + // a QML string, quoted as JSON is + b = []byte(strings.Replace(string(b), `"__MAGPIE__"`, strconv.Quote(exe), 1)) + } + files[name] = b + } + return files, nil +} + +// RemoveWidget takes it out of the bar again. +func RemoveWidget() error { + _ = run("omarchy", "plugin", "disable", WidgetID) + if err := os.RemoveAll(widgetDir()); err != nil { + return err + } + return run("omarchy-shell", "shell", "rescanPlugins") +} + +func run(name string, args ...string) error { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + cmd := proc.CommandContext(ctx, name, args...) + cmd.Stdin = nil + if out, err := cmd.CombinedOutput(); err != nil { + return fmt.Errorf("%s %s: %v: %s", name, strings.Join(args, " "), err, strings.TrimSpace(string(out))) + } + return nil +} diff --git a/internal/omarchy/widget/Widget.qml b/internal/omarchy/widget/Widget.qml new file mode 100644 index 000000000..8d0520e37 --- /dev/null +++ b/internal/omarchy/widget/Widget.qml @@ -0,0 +1,29 @@ +import QtQuick +import Quickshell +import qs.Commons +import qs.Ui + +// magpie's icon in Omarchy's bar, put there by magpie (Settings → Bar icon). +// A click drops down its panel under the bar, where the click was; a right +// click opens its window. magpie is started if it isn't running. +BarWidget { + id: root + moduleName: "usemagpie.magpie" + + // written in by magpie when it puts the widget here + readonly property string magpie: "__MAGPIE__" + + implicitWidth: button.implicitWidth + implicitHeight: button.implicitHeight + + BarIconButton { + id: button + anchors.fill: parent + bar: root.bar + text: String.fromCodePoint(0xf15c6) // nf-md-bird + tooltipText: "magpie" + onPressed: function(b) { + Quickshell.execDetached(b === Qt.RightButton ? [root.magpie, "app"] : [root.magpie, "panel"]) + } + } +} diff --git a/internal/omarchy/widget/manifest.json b/internal/omarchy/widget/manifest.json new file mode 100644 index 000000000..64d82d042 --- /dev/null +++ b/internal/omarchy/widget/manifest.json @@ -0,0 +1,21 @@ +{ + "schemaVersion": 1, + "id": "usemagpie.magpie", + "name": "magpie", + "version": "1.0.0", + "author": "magpie", + "license": "MIT", + "description": "magpie's icon in the bar: a click drops down its panel, a right click opens its window.", + "kinds": ["bar-widget"], + "entryPoints": { + "barWidget": "Widget.qml" + }, + "barWidget": { + "displayName": "magpie", + "description": "Pick every agent's model from the bar: a click drops down magpie's panel, a right click opens its window.", + "category": "AI", + "aliases": ["magpie"], + "allowMultiple": false, + "defaultSection": "right" + } +} diff --git a/internal/omarchy/widget_test.go b/internal/omarchy/widget_test.go new file mode 100644 index 000000000..6497ac455 --- /dev/null +++ b/internal/omarchy/widget_test.go @@ -0,0 +1,68 @@ +package omarchy + +import ( + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestWidgetFiles(t *testing.T) { + exe := `/opt/my "apps"/magpie` + files, err := widget(exe) + if err != nil { + t.Fatal(err) + } + var m struct { + ID string + Kinds []string + EntryPoints struct{ BarWidget string } + } + if err := json.Unmarshal(files["manifest.json"], &m); err != nil { + t.Fatal(err) + } + if m.ID != WidgetID || len(m.Kinds) != 1 || m.Kinds[0] != "bar-widget" || m.EntryPoints.BarWidget != "Widget.qml" { + t.Errorf("manifest: %+v", m) + } + qml := string(files["Widget.qml"]) + if strings.Contains(qml, "__MAGPIE__") || !strings.Contains(qml, `magpie: "/opt/my \"apps\"/magpie"`) { + t.Errorf("the executable isn't written in, quoted:\n%s", qml) + } + for _, s := range []string{`[root.magpie, "panel"]`, `[root.magpie, "app"]`, "Qt.RightButton"} { + if !strings.Contains(qml, s) { + t.Errorf("Widget.qml lacks %s", s) + } + } +} + +// KeepWidget does nothing when the widget isn't in, and nothing (running no +// omarchy command, which isn't here) when it is and is up to date. +func TestKeepWidget(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("PATH", t.TempDir()) + if WidgetOn() { + t.Fatal("on in an empty config") + } + if err := KeepWidget("/usr/bin/magpie"); err != nil { + t.Fatal(err) + } + if WidgetOn() { + t.Fatal("KeepWidget put it in") + } + files, _ := widget("/usr/bin/magpie") + os.MkdirAll(widgetDir(), 0o755) + for name, b := range files { + os.WriteFile(filepath.Join(widgetDir(), name), b, 0o644) + } + if err := KeepWidget("/usr/bin/magpie"); err != nil { + t.Fatalf("up to date: %v", err) + } + // moved: it is written again, then the shell is asked to load it + if err := KeepWidget("/opt/magpie"); err == nil || !strings.Contains(err.Error(), "omarchy") { + t.Fatalf("moved: %v", err) + } + if b, _ := os.ReadFile(filepath.Join(widgetDir(), "Widget.qml")); !strings.Contains(string(b), `"/opt/magpie"`) { + t.Error("not rewritten") + } +} diff --git a/main.go b/main.go index 08bf24ae4..2add6b052 100644 --- a/main.go +++ b/main.go @@ -30,6 +30,7 @@ const usage = `magpie — one place to pick every agent's model magpie open the app: a window plus a menu bar icon magpie tray start in the menu bar only + magpie panel open the menu bar icon's quick panel, or close it magpie autostart [on|off] open magpie (in the menu bar) when you log in, or say whether it does magpie tui the same thing, in the terminal magpie web [--addr host:port] [--lan] [--no-open] @@ -145,6 +146,8 @@ func run(args []string) error { return runGUI(true, "") case "tray": return runGUI(false, "") + case "panel": + return runPanel() case "autostart": return autostartCmd(args[1:]) case "-h", "--help", "help":