{"messages": [{"role": "system", "content": "You are an Omarchy plugin expert. You write complete, valid Omarchy (Quattro / omarchy-shell, Quickshell QML) plugins. Manifests use schemaVersion 1, a namespaced id that never uses the reserved omarchy.* namespace, name, version, kinds (bar-widget|panel|overlay|menu|service|bar) with a matching safe relative entryPoints path for every kind, and no symlinks. Return every file in full as '### path' followed by a fenced code block."}, {"role": "user", "content": "Write the manifest and entry-point file(s) (Panel.qml) for the Omarchy plugin `acme.agents` \"Agents\" (bar-widget): Claude Code, Codex, Grok, and Fireworks usage, limits, and pace in a native Omarchy bar panel. These sibling files already exist in the folder and can be referenced:\n- Agent.qml (1 KB)\n- Main.qml (30 KB)"}, {"role": "assistant", "content": "### manifest.json\n```json\n{\n \"schemaVersion\": 1,\n \"id\": \"acme.agents\",\n \"name\": \"Agents\",\n \"version\": \"1.0.0\",\n \"author\": \"Omarchy\",\n \"license\": \"MIT\",\n \"description\": \"Claude Code, Codex, Grok, and Fireworks usage, limits, and pace in a native Omarchy bar panel.\",\n \"kinds\": [\n \"bar-widget\"\n ],\n \"activation\": \"on-demand\",\n \"entryPoints\": {\n \"barWidget\": \"Panel.qml\"\n },\n \"barWidget\": {\n \"displayName\": \"Agents\",\n \"description\": \"One bar icon and one panel: rate-limit meters with pace, today, the last week, and the all-time model breakdown for every subscription.\",\n \"category\": \"AI\",\n \"aliases\": [\n \"agents\",\n \"model-usage\"\n ],\n \"allowMultiple\": false,\n \"defaults\": {\n \"providers\": {\n \"claude\": {\n \"enabled\": true\n },\n \"codex\": {\n \"enabled\": true\n },\n \"grok\": {\n \"enabled\": true\n },\n \"fireworks\": {\n \"enabled\": true\n }\n },\n \"refreshIntervalSec\": 900,\n \"syncMode\": \"Off\",\n \"syncDir\": \"\",\n \"syncFileName\": \"\",\n \"syncDeviceId\": \"\"\n },\n \"schema\": [\n {\n \"key\": \"refreshIntervalSec\",\n \"type\": \"integer\",\n \"label\": \"Refresh interval (seconds)\",\n \"min\": 30,\n \"max\": 3600,\n \"step\": 30,\n \"defaultValue\": 900\n },\n {\n \"key\": \"syncMode\",\n \"type\": \"enum\",\n \"label\": \"Synced aggregation\",\n \"options\": [\n \"Off\",\n \"On\"\n ],\n \"defaultValue\": \"Off\",\n \"description\": \"When On, write this machine's local usage snapshot and merge snapshots from other machines.\"\n },\n {\n \"key\": \"syncDir\",\n \"type\": \"path\",\n \"label\": \"Sync folder\",\n \"defaultValue\": \"\",\n \"description\": \"A folder synced by Syncthing, Dropbox, rsync, etc.\"\n },\n {\n \"key\": \"syncFileName\",\n \"type\": \"string\",\n \"label\": \"Snapshot file name\",\n \"defaultValue\": \"\",\n \"description\": \"Optional. Defaults to .json. Use a different file name on each machine, such as laptop.json or desktop.json.\"\n },\n {\n \"key\": \"syncDeviceId\",\n \"type\": \"string\",\n \"label\": \"Device id\",\n \"defaultValue\": \"\",\n \"description\": \"Optional stable device name used inside synced aggregate snapshots.\"\n }\n ]\n }\n}\n```\n\n### Panel.qml\n```qml\nimport QtQuick\nimport QtQuick.Controls\nimport Quickshell\nimport Quickshell.Io\nimport qs.Commons\nimport qs.Commons as Commons\nimport qs.Ui\n\nPanel {\n id: root\n moduleName: \"omarchy.agents\"\n ipcTarget: \"omarchy.agents\"\n manageIpc: false\n\n readonly property color foreground: bar ? bar.foreground : Commons.Color.foreground\n readonly property color urgent: bar ? bar.urgent : Commons.Color.urgent\n readonly property color dim: Qt.darker(foreground, 1.55)\n readonly property color surface: Commons.Color.popups.background\n readonly property color track: Style.selectedFillFor(foreground, Commons.Color.accent)\n readonly property string fontFamily: bar ? bar.fontFamily : Style.font.family\n\n // Every subscription on one page, limits first: the question this panel\n // answers is how much room is left, and where.\n readonly property var providers: usage.enabledProviders\n\n property bool cursorActive: false\n\n // Countdowns and \"last updated\" ages read this instead of Date.now() so the\n // panel keeps telling the truth while it sits open.\n property double nowMs: Date.now()\n\n // Every account of every provider that has more than one, in page order.\n // The keyboard picks one by its position; picking only looks, and Enter on\n // a picked account is what moves new sessions to it.\n readonly property var accountEntries: {\n var out = []\n for (var i = 0; i < providers.length; i++) {\n var list = providerAccounts(providers[i])\n if (list.length < 2) continue\n for (var j = 0; j < list.length; j++) out.push({ provider: providers[i], account: list[j] })\n }\n return out\n }\n readonly property var pickedEntry: keyTarget && [\"account\", \"autoswitch\", \"signin\"].indexOf(keyTarget.kind) >= 0\n ? accountEntries[keyTarget.index] || null\n : null\n\n // The keyboard walks everything on the page that does something, in\n // reading order, one row at a time: the hero's buttons, then each agent's\n // header, its Sign-in required link or switchable accounts, and the starter\n // tiles, or the agents to add while picking one. Up and down change rows, left and right move along one.\n // Hovering moves the same cursor, so only one thing is lit.\n readonly property var keyRows: {\n var rows = []\n var hero = []\n if (addButtonShown) hero.push({ kind: \"add\", index: 0 })\n if (addStage === \"\") hero.push({ kind: \"launch\", index: 0 })\n if (hero.length > 0) rows.push(hero)\n if (picking) {\n var choices = []\n for (var k = 0; k < addProviders.length; k++) choices.push({ kind: \"choice\", index: k })\n rows.push(choices)\n } else if (addStage === \"\") {\n // Accounts count in the same order as accountEntries. Only what can be\n // done is a stop: one that isn't active offers Autoswitch beside Use, a\n // lapsed sign-in comes first, and the active account with nothing to\n // fix is skipped.\n var entry = 0\n for (var p = 0; p < providers.length; p++) {\n // Every agent's header is a stop, so Ctrl+Up/Down can move it.\n rows.push([{ kind: \"provider\", index: p }])\n var accounts = providerAccounts(providers[p])\n if (accounts.length < 2) {\n if (needsSignIn(providers[p])) rows.push([{ kind: \"providerSignin\", index: p }])\n continue\n }\n for (var a = 0; a < accounts.length; a++, entry++) {\n var row = []\n if (needsSignIn(accounts[a])) row.push({ kind: \"signin\", index: entry })\n if (!accounts[a].active) {\n row.push({ kind: \"autoswitch\", index: entry })\n row.push({ kind: \"account\", index: entry })\n }\n if (row.length > 0) rows.push(row)\n }\n }\n if (!blankSlate) {\n var tiles = []\n for (var j = 0; j < starterPrompts.length; j++) tiles.push({ kind: \"starter\", index: j })\n rows.push(tiles)\n }\n }\n return rows\n }\n property int keyRow: 0\n property int keyColumn: 0\n readonly property var keyTarget: {\n if (!cursorActive || keyRow < 0 || keyRow >= keyRows.length) return null\n var row = keyRows[keyRow]\n return row[Math.min(keyColumn, row.length - 1)]\n }\n\n function hasKey(kind, index) {\n return !!keyTarget && keyTarget.kind === kind && keyTarget.index === (index || 0)\n }\n\n function pointAt(kind, index) {\n for (var r = 0; r < keyRows.length; r++) {\n for (var c = 0; c < keyRows[r].length; c++) {\n if (keyRows[r][c].kind === kind && keyRows[r][c].index === (index || 0)) {\n keyRow = r\n keyColumn = c\n cursorActive = true\n return\n }\n }\n }\n }\n\n // The first arrow only shows where the cursor is, as in the other panels.\n function moveKey(dx, dy) {\n if (keyRows.length === 0) return\n if (!cursorActive) {\n keyRow = clamp(keyRow, 0, keyRows.length - 1)\n keyColumn = 0\n cursorActive = true\n return\n }\n if (dy !== 0) {\n keyRow = clamp(keyRow + dy, 0, keyRows.length - 1)\n // Arriving on an account lands on Use; left reaches Autoswitch.\n var row = keyRows[keyRow]\n var use = -1\n for (var c = 0; c < row.length; c++) if (row[c].kind === \"account\") use = c\n keyColumn = use >= 0 ? use : Math.min(keyColumn, row.length - 1)\n } else if (dx !== 0) {\n keyColumn = clamp(Math.min(keyColumn, keyRows[keyRow].length - 1) + dx, 0, keyRows[keyRow].length - 1)\n }\n }\n\n // The agent the cursor is in, by its position on the page.\n function providerIndexOfKey() {\n var target = keyTarget\n if (!target) return -1\n if (target.kind === \"provider\" || target.kind === \"providerSignin\") return target.index\n if ([\"account\", \"autoswitch\", \"signin\"].indexOf(target.kind) < 0) return -1\n var entry = accountEntries[target.index]\n return entry ? providers.indexOf(entry.provider) : -1\n }\n\n // Ctrl+Up/Down carries the agent the cursor is in up or down the page, and\n // the cursor along with it.\n function reorderProvider(dy) {\n var from = providerIndexOfKey()\n if (from < 0) return\n var to = clamp(from + dy, 0, providers.length - 1)\n if (to === from) return\n usage.moveProvider(providers[from].providerId, to)\n Qt.callLater(function() { pointAt(\"provider\", to) })\n }\n\n // Dragging an agent by its mark lights the header it would land on, and\n // moves it there on release: the sections are rebuilt when the order\n // changes, which would drop a drag still in progress.\n property string dragProviderId: \"\"\n property int dragTarget: -1\n // An account name being edited keeps Ctrl+Up/Down: moving its agent would\n // rebuild the section and drop the unfinished name.\n property bool renaming: false\n\n function dragProviderOver(y) {\n for (var i = 0; i < providerSections.count; i++) {\n var item = providerSections.itemAt(i)\n if (item && y >= item.y && y < item.y + item.height) {\n dragTarget = i\n return\n }\n }\n }\n\n function dropProvider() {\n var id = dragProviderId\n var to = dragTarget\n dragProviderId = \"\"\n dragTarget = -1\n if (id === \"\" || to < 0) return\n usage.moveProvider(id, to)\n Qt.callLater(function() { pointAt(\"provider\", to) })\n }\n\n // Keeps whatever the cursor lands on inside the scrolled view.\n function revealItem(item) {\n if (!item || !panelFlick || !panelFlick.interactive) return\n var top = item.mapToItem(column, 0, 0).y\n var margin = Style.space(12)\n if (top - margin < panelFlick.contentY)\n panelFlick.contentY = Math.max(0, top - margin)\n else if (top + item.height + margin > panelFlick.contentY + panelFlick.height)\n panelFlick.contentY = Math.min(panelFlick.contentHeight - panelFlick.height, top + item.height + margin - panelFlick.height)\n }\n\n // The bar icon lights up when any account new sessions use is nearly out,\n // or a prepaid balance is down to its last 10%.\n readonly property bool alarming: {\n for (var i = 0; i < providers.length; i++) {\n var window = bindingWindow(providers[i])\n if (window && window.percent >= 0.9) return true\n if (balanceAlarming(providers[i].balance)) return true\n }\n return false\n }\n\n function clamp(v, lo, hi) { return Math.max(lo, Math.min(hi, v)) }\n function alpha(c, a) { return Qt.rgba(c.r, c.g, c.b, a) }\n\n // A provider's accounts, when it has any. The list arrives as a sequence\n // rather than a JS array once it has passed through a model, so it's\n // judged by its length.\n function providerAccounts(p) {\n return p && p.accounts && p.accounts.length > 0 ? p.accounts : []\n }\n\n function refreshNow() {\n usage.refreshAll(true)\n }\n\n // ------------------------------------------------------------ adding\n //\n // Adding a subscription happens right here: pick a provider, name it if\n // it's a second account, then sign in through the browser while the panel\n // follows omarchy-agent-account-add --events. The browser taking focus may\n // close the panel; the login carries on, and its result arrives as a\n // notification too.\n\n readonly property var addProviders: [\n { providerId: \"claude\", providerName: \"Claude Code\" },\n { providerId: \"codex\", providerName: \"Codex\" },\n { providerId: \"grok\", providerName: \"Grok\" }\n ]\n property string addStage: \"\"\n property string addProvider: \"\"\n property var addChecks: ({})\n property string addStatus: \"\"\n property string addCode: \"\"\n property string addUrl: \"\"\n property bool addNeedsPaste: false\n property string addResult: \"\"\n // Whether the sign-in in progress opened a private window, so reopening its\n // page does too.\n property bool addPrivate: false\n\n function addProviderName(id) {\n for (var i = 0; i < addProviders.length; i++)\n if (addProviders[i].providerId === id) return addProviders[i].providerName\n return id\n }\n\n function addAccount() {\n if (addStage === \"running\") return\n addStage = \"pick\"\n addChecks = ({})\n if (!checkProcess.running) checkProcess.running = true\n }\n\n function chooseAddProvider(id) {\n var state = addChecks[id] || \"\"\n if (state === \"\") return\n addProvider = id\n if (state === \"additional\") addStage = \"name\"\n else startAdd(\"\")\n }\n\n function startAdd(label) {\n addPrivate = (addChecks[addProvider] || \"\") === \"additional\"\n addStatus = \"Starting…\"\n addCode = \"\"\n addUrl = \"\"\n // Claude's login offers pasting a code back whenever its page shows one,\n // and its prompt for it has no newline to read it by, so the field is\n // there from the start.\n addNeedsPaste = addProvider === \"claude\"\n addResult = \"\"\n addStage = \"running\"\n addProcess.command = [\"omarchy-agent-account-add\", \"--events\", addProvider].concat(label !== \"\" ? [label] : [])\n addProcess.running = true\n }\n\n function cancelAdd() {\n if (addProcess.running) addProcess.signal(15)\n addStage = \"\"\n root.focusKeys()\n }\n\n // A first sign-in keeps saying so until its limits arrive, rather than\n // flashing the choices again while the record is written.\n onBlankSlateChanged: if (!blankSlate && addStage === \"done\") addStage = \"\"\n\n function submitPaste(code) {\n if (!addProcess.running || code.trim() === \"\") return\n addProcess.write(code.trim() + \"\\n\")\n addStatus = \"Checking the code…\"\n }\n\n // The add command's own lines are tagged; everything else is the CLI\n // talking, and only two things in it matter here: a code to confirm in the\n // browser (Grok), and an invitation to paste one back (Claude).\n function handleAddLine(line) {\n var text = String(line).replace(/\\u001b\\[[0-9;]*m/g, \"\")\n var tagged = text.match(/^@@omarchy (status|done|error) (.*)$/)\n if (tagged) {\n if (tagged[1] === \"status\") {\n addStatus = tagged[2]\n } else {\n addResult = tagged[2]\n addStage = tagged[1]\n if (tagged[1] === \"done\") {\n usage.refreshLimits()\n addDoneTimer.restart()\n // Nothing to show yet means the sign-in is what counts as set up.\n if (providers.length === 0 && !checkProcess.running) {\n addChecks = ({})\n checkProcess.running = true\n }\n }\n }\n return\n }\n var code = text.match(/^\\s*([A-Z0-9]{4}-[A-Z0-9]{4})\\s*$/)\n if (code) addCode = code[1]\n if (/paste code/i.test(text)) addNeedsPaste = true\n var url = text.match(/(https:\\/\\/\\S+)/)\n if (url && addUrl === \"\") addUrl = url[1]\n }\n\n function reopenSignIn() {\n if (addUrl === \"\") return\n Util.execArgv(addPrivate ? [\"omarchy-launch-browser\", \"--private\", addUrl] : [\"omarchy-launch-browser\", addUrl])\n }\n\n // A few ways into making Omarchy your own, handed to the default agent.\n readonly property var starterPrompts: [\n { glyph: \"󰏘\", label: \"Theme\", prompt: \"Make me a new Omarchy theme. Ask me what look or inspiration I have in mind, then build it following the Omarchy skill's theming guide and switch to it.\" },\n { glyph: \"󰐱\", label: \"Plugin\", prompt: \"Make me a new Omarchy shell plugin. Ask me what I'd like it to do, then build it following the Omarchy skill's plugin guide and enable it.\" },\n { glyph: \"󰣆\", label: \"App\", prompt: \"Make me a new app for my Omarchy desktop. Ask me what it should do, then build it following the omarchy-app skill and install it so it shows up in the app launcher.\" }\n ]\n\n function startPrompt(prompt) {\n root.close()\n Util.execArgv([\"omarchy-agent-prompt\", prompt])\n }\n\n function renameAccount(p, account, label) {\n if (!p || !account) return\n Util.execArgv([\"omarchy-agent-account-rename\", p.providerId, String(account.id), label])\n }\n\n function useAccount(p, account) {\n if (!p || !account || account.active) return\n Util.execArgv([\"omarchy-agent-account-use\", p.providerId, String(account.id)])\n }\n\n function autoSwitchFor(p) {\n return !!p && !!p.accountSwitch && p.accountSwitch.mode === \"auto\"\n }\n\n function switchThreshold(p) {\n return p && p.accountSwitch ? Number(p.accountSwitch.threshold || 95) : 95\n }\n\n function setSwitchMode(p, mode) {\n if (!p || providerAccounts(p).length < 2 || mode === (autoSwitchFor(p) ? \"auto\" : \"manual\")) return\n Util.execArgv([\"bash\", \"-c\", 'omarchy-agent-account-mode \"$1\" \"$2\" >/dev/null && omarchy-agent-usage-update --limits-only \"$1\"',\n \"omarchy-agent-account-mode\", p.providerId, mode])\n }\n\n // `m` flips autoswitch for the picked account's provider, or the first\n // provider with several accounts when nothing is picked.\n function toggleSwitchMode() {\n var p = pickedEntry ? pickedEntry.provider : (accountEntries.length > 0 ? accountEntries[0].provider : null)\n if (p) setSwitchMode(p, autoSwitchFor(p) ? \"manual\" : \"auto\")\n }\n\n function activateSelection() {\n var target = keyTarget\n if (!target) refreshNow()\n else if (target.kind === \"add\") addStage !== \"\" ? cancelAdd() : addAccount()\n else if (target.kind === \"choice\") chooseAddProvider(addProviders[target.index].providerId)\n else if (target.kind === \"launch\") launchAgent()\n else if (target.kind === \"starter\") startPrompt(starterPrompts[target.index].prompt)\n else if (target.kind === \"providerSignin\") signInAgain(providers[target.index], null)\n else if (target.kind === \"signin\") signInAgain(pickedEntry.provider, pickedEntry.account)\n else if (target.kind === \"autoswitch\") setSwitchMode(pickedEntry.provider, autoSwitchFor(pickedEntry.provider) ? \"manual\" : \"auto\")\n else if (pickedEntry && !pickedEntry.account.active) useAccount(pickedEntry.provider, pickedEntry.account)\n }\n\n function isPicked(p, account) {\n return !!pickedEntry && !!p && !!account\n && pickedEntry.provider.providerId === p.providerId && pickedEntry.account.id === account.id\n }\n\n // Hands the keyboard back to the panel after an inline edit.\n function focusKeys() {\n keyCatcher.forceActiveFocus()\n }\n\n function accountDetail(account) {\n var parts = []\n if (String(account.plan || \"\") !== \"\") parts.push(account.plan)\n if (account.resetCredits && Number(account.resetCredits.available) > 0)\n parts.push(account.resetCredits.available + \" free reset\" + (Number(account.resetCredits.available) === 1 ? \"\" : \"s\"))\n return parts.join(\" · \")\n }\n\n // A lapsed or missing sign-in is something you can fix from here; any other\n // trouble is only reported.\n function needsSignIn(item) {\n var status = String(item && item.usageStatusText || \"\")\n return status === \"Sign-in expired\" || status === \"Waiting for auth\"\n }\n\n function otherTrouble(item) {\n var status = String(item && item.usageStatusText || \"\")\n return status !== \"\" && status !== \"Limits paused\" && !needsSignIn(item) ? status : \"\"\n }\n\n function pausedWithoutLimits(item) {\n return !!item && item.usageStatusText === \"Limits paused\" && limitWindows(item).length === 0\n }\n\n // Sign an account that's already here in again, following along in the\n // add view just like adding one.\n function signInAgain(p, account) {\n if (!p || addStage === \"running\") return\n addProvider = p.providerId\n addPrivate = !!account && account.primary !== true\n addStatus = \"Starting…\"\n addCode = \"\"\n addUrl = \"\"\n // Claude's login offers pasting a code back whenever its page shows one,\n // and its prompt for it has no newline to read it by, so the field is\n // there from the start.\n addNeedsPaste = addProvider === \"claude\"\n addResult = \"\"\n addStage = \"running\"\n addProcess.command = [\"omarchy-agent-account-add\", \"--events\", \"--reauth\",\n account && account.primary !== true ? String(account.id) : \":primary\", p.providerId]\n addProcess.running = true\n }\n\n function resetCreditsText(credits) {\n if (!credits || !(Number(credits.available) > 0)) return \"\"\n var count = Number(credits.available)\n var text = count + \" free reset\" + (count === 1 ? \"\" : \"s\")\n var expires = new Date(String(credits.nextExpiresAt || \"\")).getTime()\n if (isFinite(expires) && expires > nowMs) text += \" · next expires in \" + formatDuration(expires - nowMs)\n return text\n }\n\n function planLabel(p) {\n var tier = String(p && p.tierLabel || \"\")\n return tier === \"\" ? \"\" : tier.charAt(0).toUpperCase() + tier.slice(1)\n }\n\n function launchAgent() {\n if (root.bar) root.bar.run(\"omarchy-agent --pick\")\n root.close()\n }\n\n // ---------------------------------------------------------------- limits\n //\n // Both providers report the same two shapes: a short rolling session window\n // and a long weekly one. Everything below normalizes them into one record so\n // the meters speak a single language.\n\n // Claude spells its windows out (\"Session (5-hour)\"), Codex abbreviates\n // them (\"5h window\", \"30m window\"). Both have to land on the same record.\n function windowIsLong(text) {\n return text.indexOf(\"week\") >= 0 || text.indexOf(\"7-day\") >= 0 || text.indexOf(\"seven\") >= 0\n || text.indexOf(\"month\") >= 0 || text.indexOf(\"30-day\") >= 0\n }\n\n function windowSpanMs(label) {\n var text = String(label || \"\").toLowerCase()\n if (text.indexOf(\"month\") >= 0 || text.indexOf(\"30-day\") >= 0) return 30 * 24 * 3600 * 1000\n if (windowIsLong(text)) return 7 * 24 * 3600 * 1000\n var hours = text.match(/(\\d+)\\s*-?\\s*h(?:our)?\\b/)\n if (hours) return Number(hours[1]) * 3600 * 1000\n var minutes = text.match(/(\\d+)\\s*-?\\s*m(?:in(?:ute)?s?)?\\b/)\n if (minutes) return Number(minutes[1]) * 60 * 1000\n return 0\n }\n\n function windowTitle(label) {\n var text = String(label || \"\").toLowerCase()\n if (text.indexOf(\"month\") >= 0) return \"Monthly\"\n if (windowIsLong(text)) return \"Weekly\"\n if (text.indexOf(\"session\") >= 0 || windowSpanMs(label) > 0) return \"Session\"\n var plain = String(label || \"\").replace(/\\s*\\(.*\\)\\s*/, \"\").trim()\n return plain === \"\" ? \"Limit\" : plain\n }\n\n // A collector that already knows which window a limit belongs to says so,\n // and that beats reading it back out of the label: a model-scoped limit is\n // titled after its model, and a name like \"Opus 5 (1M context)\" would parse\n // as a one-minute window.\n function limitWindow(label, percent, resetAt, title) {\n var reset = new Date(String(resetAt || \"\")).getTime()\n var expired = isFinite(reset) && reset <= root.nowMs\n return {\n title: String(title || \"\") !== \"\" ? String(title) : windowTitle(label),\n percent: expired ? 0 : Number(percent),\n resetAt: expired ? \"\" : String(resetAt || \"\")\n }\n }\n\n function limitWindows(p) {\n if (!p) return []\n var out = []\n var list = p.limits || []\n for (var i = 0; i < list.length; i++) {\n var entry = list[i] || {}\n var percent = Number(entry.percent)\n if (percent >= 0) out.push(limitWindow(entry.label, percent, entry.resetsAt, entry.title))\n }\n return out\n }\n\n // A model-scoped window (\"Fable Weekly\") is its own allowance, but it runs\n // on the same clock as the window it's named for, so it's shown attached to\n // that row rather than as a row of its own. One with nothing to attach to\n // still gets its own row.\n function scopedPart(title) {\n var match = String(title || \"\").match(/^(.+) (Session|Weekly|Monthly)$/)\n return match ? { model: match[1], window: match[2] } : null\n }\n\n function displayWindows(p) {\n var windows = limitWindows(p)\n var out = []\n var byTitle = {}\n for (var i = 0; i < windows.length; i++) {\n if (scopedPart(windows[i].title)) continue\n windows[i].scoped = []\n out.push(windows[i])\n byTitle[windows[i].title] = windows[i]\n }\n for (var j = 0; j < windows.length; j++) {\n var part = scopedPart(windows[j].title)\n if (!part) continue\n var base = byTitle[part.window]\n if (base) {\n base.scoped.push({ title: part.model, percent: windows[j].percent, resetAt: windows[j].resetAt })\n } else {\n windows[j].scoped = []\n out.push(windows[j])\n }\n }\n return out\n }\n\n // The window that decides how much room is left — the fullest one, since\n // that is what stops the next prompt.\n function bindingWindow(p) {\n var windows = limitWindows(p)\n var best = null\n for (var i = 0; i < windows.length; i++) {\n if (!best || windows[i].percent > best.percent) best = windows[i]\n }\n return best\n }\n\n function resetMsFor(w) {\n if (!w || w.resetAt === \"\") return -1\n var ms = new Date(w.resetAt).getTime()\n return isFinite(ms) ? ms - root.nowMs : -1\n }\n\n function formatDuration(ms) {\n if (!(ms > 0)) return \"now\"\n var minutes = Math.floor(ms / 60000)\n var hours = Math.floor(minutes / 60)\n var days = Math.floor(hours / 24)\n if (days > 0) return days + \"d \" + (hours % 24) + \"h\"\n if (hours > 0) return hours + \"h \" + (minutes % 60) + \"m\"\n return Math.max(1, minutes) + \"m\"\n }\n\n // ---------------------------------------------------------------- balance\n //\n // Prepaid agents report a credit ledger instead of rate-limit windows: the\n // record's balance object carries remaining, funded, and spent amounts.\n\n // A prepaid account runs low the way a subscription window fills up: the\n // last 10% of the funded credits lights the same alarm.\n function balanceAlarming(b) {\n return !!b && b.funded > 0 && b.remaining / b.funded <= 0.1\n }\n\n function currencyPrefix(currency) {\n var code = String(currency || \"USD\").toUpperCase()\n if (code === \"USD\") return \"$\"\n if (code === \"EUR\") return \"€\"\n if (code === \"GBP\") return \"£\"\n return code + \" \"\n }\n\n function formatMoney(value, currency) {\n var amount = Number(value)\n if (!isFinite(amount)) amount = 0\n return currencyPrefix(currency) + amount.toFixed(2)\n }\n\n function balanceDetailText(b) {\n if (!b || !(b.funded > 0)) return \"\"\n var text = formatMoney(b.spent, b.currency) + \" spent of \" + formatMoney(b.funded, b.currency) + \" funded\"\n if (b.estimated) text += \" · estimated\"\n return text\n }\n\n // ---------------------------------------------------------------- summary\n //\n // The hero's line rotates through what the token counts add up to across\n // every agent, now that they no longer get charts of their own.\n\n readonly property var summaryPhrases: {\n var rev = usage.dataRevision\n var week = 0\n var today = 0\n var prompts = 0\n var sessions = 0\n var byDay = {}\n var byModel = {}\n for (var i = 0; i < providers.length; i++) {\n var p = providers[i]\n var days = p.recentDays || []\n for (var d = 0; d < days.length; d++) {\n var tokens = Number(days[d].messageCount || 0)\n week += tokens\n byDay[days[d].date] = (byDay[days[d].date] || 0) + tokens\n }\n today += Number(p.todayTotalTokens || 0)\n if (p.hasPromptStats !== false) {\n prompts += Number(p.todayPrompts || 0)\n sessions += Number(p.todaySessions || 0)\n }\n var models = p.modelUsage || {}\n for (var id in models) {\n var bucket = models[id] || {}\n var total = Number(bucket.inputTokens || 0) + Number(bucket.outputTokens || 0)\n + Number(bucket.cacheReadInputTokens || 0) + Number(bucket.cacheCreationInputTokens || 0)\n var name = usage.friendlyModelName(id)\n byModel[name] = (byModel[name] || 0) + total\n }\n }\n\n var phrases = []\n if (week > 0) phrases.push(usage.formatTokenCount(week) + \" tokens this week\")\n if (today > 0) phrases.push(usage.formatTokenCount(today) + \" tokens today\")\n var topModel = \"\"\n for (var model in byModel) if (topModel === \"\" || byModel[model] > byModel[topModel]) topModel = model\n if (topModel !== \"\" && byModel[topModel] > 0) phrases.push(\"Mostly \" + topModel)\n var busiest = \"\"\n for (var date in byDay) if (busiest === \"\" || byDay[date] > byDay[busiest]) busiest = date\n if (busiest !== \"\" && byDay[busiest] > 0) phrases.push(\"Busiest day: \" + dayName(busiest))\n if (prompts > 0) phrases.push(prompts + \" prompt\" + (prompts === 1 ? \"\" : \"s\") + \" today\")\n if (sessions > 0) phrases.push(sessions + \" session\" + (sessions === 1 ? \"\" : \"s\") + \" today\")\n return phrases\n }\n property int phraseIndex: 0\n // Every record that lands rebuilds the phrases, and opening the panel\n // refreshes each agent in turn. Indexing the live list would swap the line\n // on each of those, so the hero holds what it shows until the next fade.\n property string shownPhrase: \"\"\n readonly property string heroPhrase: addStage !== \"\" || blankSlate\n ? addHeading\n : (shownPhrase !== \"\" ? shownPhrase : \"Subscriptions\")\n\n function showPhrase() {\n var n = summaryPhrases.length\n shownPhrase = n > 0 ? summaryPhrases[phraseIndex % n] : \"\"\n }\n\n onSummaryPhrasesChanged: if (shownPhrase === \"\" || summaryPhrases.length <= 1) showPhrase()\n\n function dayName(date) {\n var parsed = new Date(String(date || \"\") + \"T00:00:00\")\n if (isNaN(parsed.getTime())) return String(date || \"\")\n return [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"][parsed.getDay()]\n }\n\n // Only speaks up when the numbers cover more than this machine.\n function footerText() {\n if (usage.syncStatusText !== \"\") return usage.syncStatusText\n for (var i = 0; i < providers.length; i++) {\n var count = Number(providers[i].syncDeviceCount || 0)\n if (providers[i].syncEnabled && count > 0)\n return \"Merged from \" + count + \" device\" + (count === 1 ? \"\" : \"s\")\n }\n return \"\"\n }\n\n // Agents that ship a white mark carry an `assets/-light.svg` twin for\n // light surfaces; marks that work on both (Claude's brand-orange) ship one\n // file. The luminance check decides which candidate to try first.\n function colorChannelLuminance(value) {\n var channel = Number(value)\n if (!isFinite(channel)) return 0\n return channel <= 0.03928 ? channel / 12.92 : Math.pow((channel + 0.055) / 1.055, 2.4)\n }\n\n function colorLuminance(color) {\n return 0.2126 * colorChannelLuminance(color.r)\n + 0.7152 * colorChannelLuminance(color.g)\n + 0.0722 * colorChannelLuminance(color.b)\n }\n\n // Marks resolve by convention, so a new agent's data file needs nothing\n // from this panel: assets/.svg if it ships one, the module's bar glyph\n // if it doesn't.\n function iconCandidatesForProvider(p, surfaceColor) {\n if (!p) return []\n var candidates = []\n if (colorLuminance(surfaceColor || Commons.Color.background) >= 0.5)\n candidates.push(Qt.resolvedUrl(\"assets/\" + p.providerId + \"-light.svg\"))\n candidates.push(Qt.resolvedUrl(\"assets/\" + p.providerId + \".svg\"))\n return candidates\n }\n\n // Always in the bar: on a machine with no agent yet, the panel is where you\n // set one up.\n readonly property bool anySignedIn: {\n for (var id in addChecks)\n if (addChecks[id] !== \"first\") return true\n return false\n }\n readonly property bool blankSlate: providers.length === 0 && !anySignedIn\n // Choosing a provider: asked for with the +, or simply what the panel is\n // while nothing is set up. It's derived rather than switched into, so\n // records that load a moment after the panel opens take its place.\n readonly property bool picking: addStage === \"pick\" || (blankSlate && addStage === \"\")\n // The + in the hero turns into the X that leaves adding. A first setup has\n // nothing to go back to until an agent is chosen.\n readonly property bool addButtonShown: !blankSlate || !picking\n\n // Adding takes over the hero's line, and the cursor starts over.\n readonly property string addHeading: picking || addProvider === \"\"\n ? \"Add an account\"\n : \"Add \" + (/^[AEIOU]/.test(addProviderName(addProvider)) ? \"an \" : \"a \") + addProviderName(addProvider) + \" account\"\n onAddStageChanged: {\n phraseSwap.stop()\n hero.metaOpacity = 1.0\n resetKeys()\n }\n\n // A first setup ends when the records land, which swaps the rows under the\n // cursor without any stage change.\n onPickingChanged: resetKeys()\n\n // Picking an agent to add starts on the first one, ready for Enter. The\n // rows follow the same stage change, so the cursor waits a tick for them.\n function resetKeys() {\n cursorActive = false\n keyRow = 0\n keyColumn = 0\n Qt.callLater(function() { if (picking) pointAt(\"choice\", 0) })\n }\n implicitWidth: button.implicitWidth\n implicitHeight: button.implicitHeight\n\n onOpenedChanged: if (opened) {\n if (addStage !== \"running\") addStage = \"\"\n resetKeys()\n if (providers.length === 0 && !checkProcess.running) checkProcess.running = true\n nowMs = Date.now()\n if (panelFlick) panelFlick.contentY = 0\n usage.refreshLimits()\n Qt.callLater(function() { keyCatcher.forceActiveFocus() })\n }\n\n Main {\n id: usage\n settings: root.settings\n }\n\n Process {\n id: checkProcess\n running: false\n command: [\"omarchy-agent-account-add\", \"--check\"]\n stdout: SplitParser {\n onRead: function(line) {\n var parts = String(line).trim().split(\" \")\n if (parts.length !== 2) return\n var checks = Object.assign({}, root.addChecks)\n checks[parts[0]] = parts[1]\n root.addChecks = checks\n }\n }\n }\n\n Process {\n id: addProcess\n running: false\n stdinEnabled: true\n stdout: SplitParser { onRead: function(line) { root.handleAddLine(line) } }\n onExited: {\n if (root.addStage === \"running\") {\n root.addResult = \"The sign-in didn't finish.\"\n root.addStage = \"error\"\n }\n }\n }\n\n Timer {\n id: addDoneTimer\n interval: 2500\n onTriggered: if (root.addStage === \"done\" && !root.blankSlate) root.addStage = \"\"\n }\n\n // Cheap enough to keep running: it only re-evaluates text bindings, and a\n // stale \"resets in 2h\" on a panel that is open is worse than a timer.\n Timer {\n interval: 30000\n running: root.opened\n repeat: true\n onTriggered: root.nowMs = Date.now()\n }\n\n Timer {\n interval: 2800\n running: root.opened && root.summaryPhrases.length > 1 && root.addStage === \"\" && !root.blankSlate\n repeat: true\n onTriggered: phraseSwap.restart()\n }\n\n SequentialAnimation {\n id: phraseSwap\n PropertyAnimation {\n target: hero; property: \"metaOpacity\"\n to: 0.0; duration: Style.duration(180); easing.type: Easing.OutQuad\n }\n ScriptAction {\n script: {\n root.phraseIndex = (root.phraseIndex + 1) % Math.max(1, root.summaryPhrases.length)\n root.showPhrase()\n }\n }\n PropertyAnimation {\n target: hero; property: \"metaOpacity\"\n to: 1.0; duration: Style.duration(260); easing.type: Easing.InQuad\n }\n }\n\n ShellIpc {\n target: root.ipcTarget\n function open(): void { root.open() }\n function close(): void { root.close() }\n function show(): void { root.open() }\n function hide(): void { root.close() }\n function toggle(): void { root.toggle() }\n function refresh(): string { root.refreshNow(); return \"ok\" }\n }\n\n BarIconButton {\n id: button\n anchors.fill: parent\n bar: root.bar\n text: \"󱚣\"\n active: root.alarming\n onPressed: function(buttonCode) {\n if (buttonCode === Qt.RightButton) root.launchAgent()\n else if (buttonCode === Qt.MiddleButton) root.refreshNow()\n else root.toggle()\n }\n }\n\n KeyboardPanel {\n id: panel\n anchorItem: button\n owner: root\n bar: root.bar\n open: root.opened\n focusTarget: keyCatcher\n contentWidth: panel.fittedContentWidth(Style.space(380))\n contentHeight: panel.fittedContentHeight(column.implicitHeight, Style.space(860))\n\n PanelKeyCatcher {\n id: keyCatcher\n anchors.fill: parent\n reorderable: root.addStage === \"\" && !root.renaming\n onReorderRequested: function(dy) { root.reorderProvider(dy) }\n\n onMoveRequested: function(dx, dy) {\n // Naming and signing in have their own fields; there the arrows scroll.\n if (root.addStage === \"\" || root.picking) root.moveKey(dx, dy)\n else if (dy !== 0)\n panelFlick.contentY = root.clamp(panelFlick.contentY + dy * Style.space(56), 0,\n Math.max(0, panelFlick.contentHeight - panelFlick.height))\n }\n onActivateRequested: root.activateSelection()\n onCloseRequested: {\n if (root.addStage !== \"\") root.cancelAdd()\n else root.close()\n }\n onTabRequested: function(direction) { root.switchPanel(direction) }\n onTextKey: function(t) {\n if (t === \"r\" || t === \"R\") root.refreshNow()\n else if (t === \"m\" || t === \"M\") root.toggleSwitchMode()\n else if (root.addStage === \"\" && t >= \"1\" && t <= \"9\" && Number(t) <= root.accountEntries.length) root.pointAt(\"account\", Number(t) - 1)\n }\n\n Flickable {\n id: panelFlick\n // Reaches a little into the panel's padding on the left, with the\n // content shifted back, so the box around a lit agent mark isn't\n // clipped where it overhangs the content's edge.\n readonly property real overhang: Style.space(8)\n anchors.fill: parent\n anchors.leftMargin: -overhang\n contentWidth: width\n contentHeight: column.implicitHeight\n clip: true\n boundsBehavior: Flickable.StopAtBounds\n flickableDirection: Flickable.VerticalFlick\n interactive: contentHeight > height\n ScrollBar.vertical: ScrollBar {\n id: panelScroll\n policy: ScrollBar.AsNeeded\n }\n\n Column {\n id: column\n x: panelFlick.overhang\n // When the panel scrolls, the bar gets its own strip rather than\n // sitting on top of the right-aligned numbers.\n width: panelFlick.width - panelFlick.overhang - (panelFlick.interactive ? panelScroll.width + Style.space(6) : 0)\n spacing: Style.space(16)\n\n // ---------- Hero: agents · rotating summary · add ----------\n PanelHero {\n id: hero\n width: parent.width\n title: \"Agents\"\n meta: root.heroPhrase\n foreground: root.foreground\n fontFamily: root.fontFamily\n\n iconComponent: Component {\n Text {\n textFormat: Text.PlainText\n text: button.text\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.display\n }\n }\n\n trailingControl: Component {\n Row {\n spacing: Style.space(6)\n visible: root.addStage === \"\" || root.addButtonShown\n\n HeroButton {\n visible: root.addButtonShown\n hasCursor: root.hasKey(\"add\")\n onHovered: root.pointAt(\"add\")\n readonly property bool adding: root.addStage !== \"\"\n glyph: adding ? \"󰅖\" : \"󰐕\"\n tooltip: adding ? \"Back to the limits\" : \"Add a subscription\"\n onClicked: adding ? root.cancelAdd() : root.addAccount()\n }\n\n HeroButton {\n visible: root.addStage === \"\"\n hasCursor: root.hasKey(\"launch\")\n onHovered: root.pointAt(\"launch\")\n glyph: \"󰞷\"\n tooltip: \"Start the default agent\"\n onClicked: root.launchAgent()\n }\n }\n }\n }\n\n AddView {\n visible: root.addStage !== \"\" || root.blankSlate\n width: column.width\n }\n\n Repeater {\n id: providerSections\n model: root.addStage === \"\" ? root.providers : []\n\n ProviderSection {\n required property var modelData\n required property int index\n width: column.width\n provider: modelData\n providerIndex: index\n }\n }\n\n // ---------- Make something ----------\n PanelSeparator {\n visible: root.addStage === \"\" && !root.blankSlate\n foreground: root.foreground\n }\n\n Column {\n visible: root.addStage === \"\" && !root.blankSlate\n width: parent.width\n spacing: Style.space(12)\n\n PanelSectionHeader {\n text: \"MAKE SOMETHING COOL\"\n foreground: root.foreground\n fontFamily: root.fontFamily\n }\n\n Row {\n id: tileRow\n width: parent.width\n spacing: Style.space(10)\n\n Repeater {\n model: root.starterPrompts\n\n StarterTile {\n required property var modelData\n required property int index\n hasCursor: root.hasKey(\"starter\", index)\n onHovered: root.pointAt(\"starter\", index)\n width: (tileRow.width - tileRow.spacing * 2) / 3\n glyph: modelData.glyph\n title: modelData.label\n onClicked: root.startPrompt(modelData.prompt)\n }\n }\n }\n }\n\n Text {\n textFormat: Text.PlainText\n visible: text !== \"\"\n width: parent.width\n topPadding: Style.space(2)\n text: root.footerText()\n color: root.dim\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n horizontalAlignment: Text.AlignHCenter\n elide: Text.ElideRight\n }\n }\n }\n }\n }\n\n // Adding a subscription, in place of the list: pick, name, sign in.\n component AddView: Column {\n id: add\n spacing: Style.space(14)\n\n PanelSeparator { foreground: root.foreground }\n\n Text {\n visible: root.blankSlate && root.picking\n width: parent.width\n text: \"Sign in to an AI coding subscription, and this panel keeps track of how much of it you have left.\"\n color: root.dim\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n wrapMode: Text.WordWrap\n }\n\n // Pick: each agent by a large mark over its name, three across.\n Row {\n id: choiceRow\n visible: root.picking\n width: parent.width\n spacing: Style.space(10)\n\n Repeater {\n model: root.picking ? root.addProviders : []\n\n Item {\n id: choice\n required property var modelData\n required property int index\n readonly property string state: root.addChecks[modelData.providerId] || \"\"\n readonly property bool available: state === \"first\" || state === \"additional\"\n readonly property bool hasCursor: root.hasKey(\"choice\", index)\n width: (choiceRow.width - choiceRow.spacing * (root.addProviders.length - 1)) / root.addProviders.length\n implicitHeight: choiceBody.implicitHeight + Style.space(16)\n onHasCursorChanged: if (hasCursor) root.revealItem(choice)\n\n Column {\n id: choiceBody\n anchors.centerIn: parent\n spacing: Style.space(10)\n\n ProviderIcon {\n anchors.horizontalCenter: parent.horizontalCenter\n provider: choice.modelData\n size: Style.font.display * 1.6\n scale: choice.hasCursor ? 1.08 : 1.0\n Behavior on scale { NumberAnimation { duration: Style.duration(120); easing.type: Easing.OutQuad } }\n }\n\n Text {\n anchors.horizontalCenter: parent.horizontalCenter\n textFormat: Text.PlainText\n text: choice.modelData.providerName\n color: choice.hasCursor ? Commons.Color.accent : root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.body\n font.bold: true\n }\n }\n\n MouseArea {\n anchors.fill: parent\n hoverEnabled: true\n cursorShape: choice.available ? Qt.PointingHandCursor : Qt.ArrowCursor\n onEntered: root.pointAt(\"choice\", choice.index)\n onClicked: root.chooseAddProvider(choice.modelData.providerId)\n }\n\n }\n }\n }\n\n // Name: a second account needs telling apart from the first.\n Column {\n visible: root.addStage === \"name\"\n width: parent.width\n spacing: Style.space(10)\n\n Text {\n width: parent.width\n text: \"Name this account. It signs in through a private window, so your browser's current account isn't picked up.\"\n color: root.dim\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n wrapMode: Text.WordWrap\n }\n\n TextField {\n id: addNameField\n width: parent.width\n placeholderText: \"Work\"\n foreground: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.body\n onVisibleChanged: if (visible) { text = \"\"; forceActiveFocus() }\n onAccepted: root.startAdd(text.trim())\n Keys.onEscapePressed: function(event) { root.cancelAdd(); event.accepted = true }\n }\n }\n\n // Running: what's happening, and whatever the sign-in needs from you.\n Column {\n visible: root.addStage === \"running\"\n width: parent.width\n spacing: Style.space(12)\n\n Text {\n width: parent.width\n textFormat: Text.PlainText\n text: root.addStatus\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n wrapMode: Text.WordWrap\n }\n\n Column {\n visible: root.addCode !== \"\"\n width: parent.width\n spacing: Style.space(4)\n\n Text {\n text: \"Confirm this code in your browser\"\n color: root.dim\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n }\n\n Text {\n textFormat: Text.PlainText\n text: root.addCode\n color: Commons.Color.accent\n font.family: root.fontFamily\n font.pixelSize: Style.font.display\n font.bold: true\n font.letterSpacing: 2\n }\n }\n\n Column {\n visible: root.addNeedsPaste\n width: parent.width\n spacing: Style.space(6)\n\n Text {\n width: parent.width\n text: \"If the page shows a code instead of finishing, paste it here.\"\n color: root.dim\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n wrapMode: Text.WordWrap\n }\n\n TextField {\n id: pasteField\n width: parent.width\n placeholderText: \"Code\"\n foreground: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.body\n onAccepted: { root.submitPaste(text); text = \"\" }\n Keys.onEscapePressed: function(event) { root.cancelAdd(); event.accepted = true }\n }\n }\n\n TextLink {\n visible: root.addUrl !== \"\"\n text: \"Open the sign-in page again\"\n onClicked: root.reopenSignIn()\n }\n }\n\n // Done or failed.\n Text {\n visible: root.addStage === \"done\" || root.addStage === \"error\"\n width: parent.width\n textFormat: Text.PlainText\n text: root.addResult\n color: root.addStage === \"error\" ? root.urgent : root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n wrapMode: Text.WordWrap\n }\n }\n\n // One provider: its mark, name, and plan, then its limits — or, with\n // several accounts, each account's name, state, and limits in turn. A\n // prepaid provider shows its balance instead.\n component ProviderSection: Column {\n id: section\n property var provider: null\n property int providerIndex: -1\n readonly property var accounts: root.providerAccounts(provider)\n readonly property bool multi: accounts.length > 1\n readonly property var windows: root.displayWindows(provider)\n readonly property var balance: provider ? (provider.balance || null) : null\n spacing: Style.space(16)\n opacity: root.dragProviderId !== \"\" && provider && root.dragProviderId === provider.providerId ? 0.5 : 1.0\n\n PanelSeparator { foreground: root.foreground }\n\n Item {\n id: sectionHead\n width: parent.width\n implicitHeight: Math.max(sectionMark.height, sectionName.implicitHeight)\n // Lit for the keyboard, and as the drop spot while an agent is dragged.\n readonly property bool lit: root.dragProviderId !== \"\" ? root.dragTarget === section.providerIndex : root.hasKey(\"provider\", section.providerIndex)\n onLitChanged: if (lit && root.dragProviderId === \"\") root.revealItem(sectionHead)\n\n // Only the mark is lit: it's the handle the agent moves by.\n CursorSurface {\n anchors.fill: sectionMark\n anchors.margins: -Style.space(5)\n z: -1\n hasCursor: sectionHead.lit\n foreground: root.foreground\n }\n\n ProviderIcon {\n id: sectionMark\n anchors.left: parent.left\n anchors.verticalCenter: parent.verticalCenter\n provider: section.provider\n\n // The mark is the handle for dragging the agent up or down the page.\n MouseArea {\n anchors.fill: parent\n anchors.margins: -Style.space(4)\n hoverEnabled: true\n preventStealing: true\n cursorShape: pressed ? Qt.ClosedHandCursor : Qt.OpenHandCursor\n onPressed: {\n root.dragProviderId = section.provider ? section.provider.providerId : \"\"\n root.dragTarget = section.providerIndex\n }\n onPositionChanged: function(mouse) {\n if (pressed) root.dragProviderOver(mapToItem(column, mouse.x, mouse.y).y)\n }\n onReleased: root.dropProvider()\n onCanceled: { root.dragProviderId = \"\"; root.dragTarget = -1 }\n }\n }\n\n Text {\n id: sectionName\n anchors.left: sectionMark.right\n anchors.leftMargin: Style.space(10)\n anchors.verticalCenter: parent.verticalCenter\n textFormat: Text.PlainText\n text: section.provider ? section.provider.providerName : \"\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.body\n font.bold: true\n }\n\n Text {\n anchors.right: parent.right\n anchors.verticalCenter: parent.verticalCenter\n visible: !section.multi\n textFormat: Text.PlainText\n text: root.planLabel(section.provider)\n color: root.dim\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n }\n }\n\n // Sign-in and endpoint trouble for a single-account provider; with\n // several, each account says so on its own line.\n TextLink {\n visible: !section.multi && root.needsSignIn(section.provider)\n picked: root.hasKey(\"providerSignin\", section.providerIndex)\n text: \"Sign-in required\"\n idleColor: root.urgent\n tooltip: \"Sign in to \" + (section.provider ? section.provider.providerName : \"\") + \" again\"\n onClicked: root.signInAgain(section.provider, null)\n }\n\n Text {\n visible: !section.multi && root.otherTrouble(section.provider) !== \"\"\n width: parent.width\n textFormat: Text.PlainText\n // Shown for the status, so a record with no help to offer says the status rather than nothing.\n text: section.provider ? String(section.provider.authHelpText || section.provider.usageStatusText || \"\") : \"\"\n color: root.urgent\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n wrapMode: Text.WordWrap\n }\n\n UnavailableUsage {\n visible: !section.multi && root.pausedWithoutLimits(section.provider)\n width: parent.width\n record: section.provider\n }\n\n Column {\n visible: !section.multi && section.windows.length > 0\n width: parent.width\n spacing: Style.space(12)\n\n Repeater {\n model: section.multi ? [] : section.windows\n\n CompactLimit {\n required property var modelData\n width: section.width\n window: modelData\n stale: !!section.provider && section.provider.limitsStale === true\n fetchedAt: section.provider ? Number(section.provider.limitsFetchedAt || 0) : 0\n }\n }\n\n Text {\n textFormat: Text.PlainText\n visible: text !== \"\"\n width: parent.width\n text: root.resetCreditsText(section.provider ? section.provider.resetCredits : null)\n color: root.dim\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n }\n }\n\n // The meter shows what is left, not what is used: a prepaid account\n // drains toward empty rather than filling toward a cap.\n Column {\n visible: !!section.balance\n width: parent.width\n spacing: Style.space(6)\n\n Item {\n width: parent.width\n implicitHeight: balanceTitle.implicitHeight\n\n Text {\n id: balanceTitle\n textFormat: Text.PlainText\n width: parent.width * 0.3\n anchors.verticalCenter: parent.verticalCenter\n text: \"Balance\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n }\n\n Meter {\n anchors.left: balanceTitle.right\n anchors.right: balanceValue.left\n anchors.rightMargin: Style.spacing.md\n anchors.verticalCenter: parent.verticalCenter\n value: section.balance && section.balance.funded > 0 ? section.balance.remaining / section.balance.funded : -1\n alarming: root.balanceAlarming(section.balance)\n }\n\n Text {\n id: balanceValue\n textFormat: Text.PlainText\n width: Style.space(96)\n anchors.right: parent.right\n anchors.verticalCenter: parent.verticalCenter\n horizontalAlignment: Text.AlignRight\n text: section.balance ? root.formatMoney(section.balance.remaining, section.balance.currency) : \"\"\n color: root.balanceAlarming(section.balance) ? root.urgent : root.dim\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n }\n }\n\n Text {\n textFormat: Text.PlainText\n visible: text !== \"\"\n width: parent.width\n text: root.balanceDetailText(section.balance)\n color: root.dim\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n }\n }\n\n Repeater {\n model: section.multi ? section.accounts : []\n\n Column {\n id: accountBlock\n required property var modelData\n required property int index\n width: section.width\n topPadding: index > 0 ? Style.space(6) : 0\n spacing: Style.space(14)\n\n AccountHeader {\n width: parent.width\n account: accountBlock.modelData\n owner: section.provider\n picked: root.isPicked(section.provider, accountBlock.modelData)\n }\n\n Column {\n width: parent.width\n spacing: Style.space(12)\n\n UnavailableUsage {\n width: parent.width\n record: accountBlock.modelData\n }\n\n Repeater {\n model: root.displayWindows({ limits: accountBlock.modelData.limits || [] })\n\n CompactLimit {\n required property var modelData\n width: accountBlock.width\n window: modelData\n stale: accountBlock.modelData.stale === true\n fetchedAt: Number(accountBlock.modelData.fetchedAt || 0)\n }\n }\n }\n }\n }\n }\n\n // A provider's mark, falling back to the bar glyph when it ships none.\n component ProviderIcon: Item {\n id: mark\n property var provider: null\n property var candidates: root.iconCandidatesForProvider(provider, root.surface)\n property string candidatesKey: candidates.join(\"\\n\")\n property int candidateIndex: 0\n onCandidatesKeyChanged: candidateIndex = 0\n property real size: Style.font.heading\n\n width: size\n height: size\n\n Image {\n id: markImage\n anchors.fill: parent\n source: mark.candidateIndex < mark.candidates.length ? mark.candidates[mark.candidateIndex] : \"\"\n sourceSize.width: mark.size * 2\n sourceSize.height: mark.size * 2\n fillMode: Image.PreserveAspectFit\n // Advancing source from inside its own status change trips the\n // binding-loop detector; defer the step one tick.\n onStatusChanged: if (status === Image.Error && mark.candidateIndex < mark.candidates.length)\n Qt.callLater(function() { mark.candidateIndex++ })\n }\n\n Text {\n anchors.centerIn: parent\n visible: markImage.status !== Image.Ready\n textFormat: Text.PlainText\n text: button.text\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: mark.size\n }\n }\n\n // A starter: its glyph and what it makes, on a soft tile that warms to the\n // accent on hover.\n component StarterTile: Rectangle {\n id: tile\n signal clicked()\n signal hovered()\n property string glyph: \"\"\n property string title: \"\"\n property bool hasCursor: false\n implicitHeight: tileBody.implicitHeight + Style.space(20)\n radius: Style.cornerRadius\n color: hasCursor ? root.alpha(Commons.Color.accent, 0.14) : root.alpha(root.foreground, 0.05)\n onHasCursorChanged: if (hasCursor) root.revealItem(tile)\n\n Row {\n id: tileBody\n anchors.centerIn: parent\n spacing: Style.space(8)\n\n Text {\n anchors.verticalCenter: parent.verticalCenter\n textFormat: Text.PlainText\n text: tile.glyph\n color: Commons.Color.accent\n font.family: root.fontFamily\n font.pixelSize: Style.font.heading\n }\n\n Text {\n anchors.verticalCenter: parent.verticalCenter\n textFormat: Text.PlainText\n text: tile.title\n color: tile.hasCursor ? Commons.Color.accent : root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.body\n font.bold: true\n }\n }\n\n MouseArea {\n id: tileMouse\n anchors.fill: parent\n hoverEnabled: true\n cursorShape: Qt.PointingHandCursor\n onEntered: tile.hovered()\n onClicked: tile.clicked()\n }\n\n PanelToolTip {\n visible: tileMouse.containsMouse\n text: \"Start your default agent on a new \" + tile.title.toLowerCase()\n }\n }\n\n // The tinted square in the hero's corner: start an agent, add a subscription.\n component HeroButton: Rectangle {\n id: heroButton\n signal clicked()\n signal hovered()\n property string glyph: \"\"\n property string tooltip: \"\"\n property bool hasCursor: false\n implicitWidth: Style.space(34)\n implicitHeight: implicitWidth\n radius: Style.cornerRadius\n // The cursor needs more than a shade deeper to read on a tinted square.\n color: root.alpha(Commons.Color.accent, hasCursor ? 0.3 : 0.12)\n border.width: hasCursor ? Math.max(1, Style.hoverBorderWidth) : 0\n border.color: Commons.Color.accent\n onHasCursorChanged: if (hasCursor) root.revealItem(heroButton)\n\n Text {\n anchors.centerIn: parent\n textFormat: Text.PlainText\n text: heroButton.glyph\n color: Commons.Color.accent\n font.family: root.fontFamily\n font.pixelSize: Style.font.heading\n }\n\n MouseArea {\n id: heroMouse\n anchors.fill: parent\n hoverEnabled: true\n cursorShape: Qt.PointingHandCursor\n onEntered: heroButton.hovered()\n onClicked: heroButton.clicked()\n }\n\n PanelToolTip {\n visible: heroMouse.containsMouse\n text: heroButton.tooltip\n }\n }\n\n // A plain-text control: dim until hovered or picked, accent when it's the\n // current choice. Stands in for bordered buttons, which pile up here.\n component TextLink: Text {\n id: link\n signal clicked()\n property bool current: false\n property bool picked: false\n property string tooltip: \"\"\n property color idleColor: root.dim\n readonly property bool hot: linkMouse.containsMouse || picked\n onPickedChanged: if (picked) root.revealItem(link)\n textFormat: Text.PlainText\n color: current ? Commons.Color.accent : (hot ? root.foreground : idleColor)\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n font.bold: current\n font.underline: hot && !current\n\n MouseArea {\n id: linkMouse\n anchors.fill: parent\n anchors.margins: -Style.space(4)\n hoverEnabled: true\n cursorShape: Qt.PointingHandCursor\n onClicked: link.clicked()\n }\n\n PanelToolTip {\n visible: link.tooltip !== \"\" && linkMouse.containsMouse\n text: link.tooltip\n }\n }\n\n // An account's name, email and plan, with ACTIVE or a Use link on the\n // right. Clicking the name edits it in place: Enter renames, Esc or\n // clicking away leaves it as it was.\n component AccountHeader: Item {\n id: head\n property var account: ({})\n property var owner: null\n property bool picked: false\n property bool editing: false\n // The new name shows at once; the record catches up a moment later.\n property string renamedTo: \"\"\n readonly property bool isActive: account.active === true\n readonly property bool autoOn: root.autoSwitchFor(owner)\n // Which of the row's links the keyboard is on, when it's on this row.\n readonly property string pickedKind: picked && root.keyTarget ? root.keyTarget.kind : \"\"\n readonly property string label: renamedTo !== \"\" ? renamedTo : String(account.label || account.id || \"\")\n\n onAccountChanged: renamedTo = \"\"\n onEditingChanged: root.renaming = editing\n onPickedChanged: if (picked) root.revealItem(head)\n\n // Anywhere on the line counts, so Use can show up when it's hidden.\n HoverHandler { id: useHover }\n implicitHeight: Math.max(headText.implicitHeight, headAction.implicitHeight)\n\n function startRename() {\n editing = true\n nameField.text = label\n nameField.forceActiveFocus()\n nameField.selectAll()\n }\n\n function finishRename(save) {\n if (!editing) return\n var value = nameField.text.trim()\n editing = false\n root.focusKeys()\n if (save && value !== \"\" && value !== label) {\n renamedTo = value\n root.renameAccount(owner, account, value)\n }\n }\n\n // One line: the name, then its plan and any caveats, quieter. The\n // email is the name's tooltip.\n Item {\n id: headText\n anchors.left: parent.left\n anchors.right: headAction.left\n anchors.rightMargin: Style.spacing.sm\n implicitHeight: head.editing ? nameField.implicitHeight : nameText.implicitHeight\n\n Text {\n id: nameText\n textFormat: Text.PlainText\n visible: !head.editing\n anchors.left: parent.left\n anchors.verticalCenter: parent.verticalCenter\n width: Math.min(implicitWidth, parent.width * 0.6)\n text: head.label\n color: head.picked ? Commons.Color.accent : root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.body\n font.bold: head.isActive\n font.underline: nameMouse.containsMouse\n elide: Text.ElideRight\n\n MouseArea {\n id: nameMouse\n anchors.fill: parent\n hoverEnabled: true\n cursorShape: Qt.IBeamCursor\n onClicked: head.startRename()\n }\n\n PanelToolTip {\n visible: nameMouse.containsMouse && String(head.account.email || \"\") !== \"\"\n text: String(head.account.email || \"\")\n }\n }\n\n // Bounded by the actions on the right: the plan and any trouble shorten\n // first, and the Sign-in required link keeps its whole width.\n Row {\n id: detailRow\n visible: !head.editing\n anchors.left: nameText.right\n anchors.leftMargin: Style.space(8)\n anchors.verticalCenter: nameText.verticalCenter\n width: Math.max(0, parent.width - nameText.width - Style.space(8))\n spacing: Style.space(8)\n\n Text {\n textFormat: Text.PlainText\n visible: text !== \"\"\n width: Math.max(0, Math.min(implicitWidth, detailRow.width\n - (signInDot.visible ? signInDot.implicitWidth + detailRow.spacing : 0)\n - (signInLink.visible ? signInLink.implicitWidth + detailRow.spacing : 0)))\n elide: Text.ElideRight\n text: {\n var parts = []\n var detail = root.accountDetail(head.account)\n if (detail !== \"\") parts.push(detail)\n var trouble = root.otherTrouble(head.account)\n if (trouble !== \"\") parts.push(trouble)\n return parts.length > 0 ? \"· \" + parts.join(\" · \") : \"\"\n }\n color: root.otherTrouble(head.account) !== \"\" ? root.urgent : root.dim\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n }\n\n // The dot is punctuation, not part of the link.\n Text {\n id: signInDot\n visible: root.needsSignIn(head.account)\n text: \"·\"\n color: root.dim\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n }\n\n TextLink {\n id: signInLink\n visible: root.needsSignIn(head.account)\n picked: head.pickedKind === \"signin\"\n text: \"Sign-in required\"\n idleColor: root.urgent\n tooltip: \"Sign in to this account again\"\n onClicked: root.signInAgain(head.owner, head.account)\n }\n }\n\n TextField {\n id: nameField\n visible: head.editing\n anchors.left: parent.left\n anchors.right: parent.right\n anchors.verticalCenter: parent.verticalCenter\n foreground: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.body\n horizontalPadding: Style.space(4)\n verticalPadding: Style.space(1)\n onAccepted: head.finishRename(true)\n onActiveFocusChanged: if (!activeFocus) head.finishRename(false)\n Keys.onEscapePressed: function(event) {\n head.finishRename(false)\n event.accepted = true\n }\n }\n }\n\n Item {\n id: headAction\n anchors.right: parent.right\n anchors.top: parent.top\n implicitWidth: head.isActive ? headActive.implicitWidth : useRow.implicitWidth\n implicitHeight: head.isActive ? headActive.implicitHeight : useRow.implicitHeight\n\n Text {\n id: headActive\n visible: head.isActive\n anchors.right: parent.right\n text: \"ACTIVE\"\n color: Commons.Color.accent\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n font.bold: true\n }\n\n // Switching now is Use. Hovering it also offers Autoswitch: move new\n // sessions over by themselves once the active account reaches the\n // threshold. While that's on it stays in view in place of Use, and\n // clicking it again goes back to only being notified.\n Row {\n id: useRow\n visible: !head.isActive\n anchors.right: parent.right\n spacing: Style.space(12)\n\n TextLink {\n visible: head.autoOn || useHover.hovered || head.picked\n text: head.pickedKind === \"autoswitch\" ? \"Autoswitch ⏎\" : \"Autoswitch\"\n picked: head.pickedKind === \"autoswitch\"\n current: head.autoOn\n tooltip: head.autoOn\n ? \"Stop switching automatically\"\n : \"Switch here automatically at \" + root.switchThreshold(head.owner) + \"%\"\n onClicked: root.setSwitchMode(head.owner, head.autoOn ? \"manual\" : \"auto\")\n }\n\n // With Autoswitch on, Use waits until the line is hovered or picked.\n TextLink {\n visible: !head.autoOn || useHover.hovered || head.picked\n text: head.pickedKind === \"account\" ? \"Use ⏎\" : \"Use\"\n picked: head.pickedKind === \"account\"\n onClicked: root.useAccount(head.owner, head.account)\n }\n }\n }\n }\n\n // With no measured windows, leave a place to discover how to get usage.\n component UnavailableUsage: Item {\n id: unavailable\n property var record: null\n visible: root.pausedWithoutLimits(record)\n implicitHeight: unavailableLabel.implicitHeight\n\n Text {\n id: unavailableLabel\n text: \"Usage unavailable\"\n color: root.dim\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n }\n\n HoverHandler { id: unavailableHover }\n\n PanelToolTip {\n visible: unavailableHover.hovered && unavailable.visible\n text: unavailable.record ? String(unavailable.record.authHelpText || \"Usage has not been updated yet.\") : \"\"\n }\n }\n\n // One line per limit window: title, meter, percentage, and reset. A\n // model-scoped allowance on the same clock (\"Fable\" on Weekly) is a marker\n // on this row's meter, named in the row's tooltip.\n component CompactLimit: Item {\n id: compact\n property var window: null\n // The age of numbers kept past a failed check is shown only on hover.\n property bool stale: false\n property real fetchedAt: 0\n readonly property var scoped: window && window.scoped ? window.scoped : []\n readonly property bool alarming: window && window.percent >= 0.9\n readonly property real resetMs: root.resetMsFor(window)\n implicitHeight: Math.max(compactTitle.implicitHeight, compactValue.implicitHeight)\n\n HoverHandler { id: compactHover }\n\n PanelToolTip {\n visible: compactHover.hovered && !!compact.window\n text: {\n var lines = []\n if (compact.window) {\n lines.push(compact.window.title + \": \" + Math.round(compact.window.percent * 100) + \"% used\"\n + (compact.resetMs > 0 ? \" · resets in \" + root.formatDuration(compact.resetMs) : \"\"))\n }\n if (compact.stale)\n lines.push(compact.fetchedAt > 0 && root.nowMs - compact.fetchedAt > 60000\n ? \"Last updated \" + root.formatDuration(root.nowMs - compact.fetchedAt) + \" ago\"\n : compact.fetchedAt > 0 ? \"Last updated less than a minute ago\" : \"Last updated time unavailable\")\n for (var i = 0; i < compact.scoped.length; i++)\n lines.push(compact.scoped[i].title + \": \" + Math.round(compact.scoped[i].percent * 100) + \"% of its \"\n + String(compact.window ? compact.window.title : \"\").toLowerCase() + \" allowance\")\n return lines.join(\"\\n\")\n }\n }\n\n Text {\n id: compactTitle\n textFormat: Text.PlainText\n width: parent.width * 0.3\n anchors.verticalCenter: parent.verticalCenter\n text: compact.window ? compact.window.title : \"\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n elide: Text.ElideRight\n }\n\n Meter {\n anchors.left: compactTitle.right\n anchors.right: compactValue.left\n anchors.rightMargin: Style.space(20)\n anchors.verticalCenter: parent.verticalCenter\n value: compact.window ? compact.window.percent : -1\n alarming: compact.alarming\n markers: compact.scoped\n }\n\n // Sized to the widest time left (\"19h 40m\"), so every meter ends in the\n // same place.\n TextMetrics {\n id: compactValueMetrics\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n text: \"00h 00m\"\n }\n\n // How long until the window resets. The meter says how full it is; the\n // exact percentage is in the row's tooltip.\n Text {\n id: compactValue\n width: Math.ceil(compactValueMetrics.advanceWidth)\n anchors.right: parent.right\n anchors.verticalCenter: parent.verticalCenter\n textFormat: Text.PlainText\n horizontalAlignment: Text.AlignRight\n text: compact.resetMs > 0 ? root.formatDuration(compact.resetMs) : \"\"\n color: root.dim\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n }\n }\n\n // Rounded track showing the percentage of the allowance used.\n component Meter: Item {\n id: meter\n property real value: -1\n property bool alarming: false\n property real thickness: Math.max(Style.space(4), Math.round(Style.spacing.controlHeight * 0.14))\n\n // Other allowances on the same clock, drawn as ticks across the track.\n property var markers: []\n\n implicitHeight: thickness\n\n Rectangle {\n id: meterTrack\n anchors.fill: parent\n radius: height / 2\n color: root.track\n }\n\n Rectangle {\n anchors.left: meterTrack.left\n anchors.verticalCenter: meterTrack.verticalCenter\n height: meterTrack.height\n radius: meterTrack.radius\n width: meterTrack.width * root.clamp(meter.value, 0, 1)\n color: meter.alarming ? root.urgent : root.foreground\n\n Behavior on width {\n NumberAnimation { duration: Style.duration(160); easing.type: Easing.OutCubic }\n }\n }\n\n Repeater {\n model: meter.markers\n\n Rectangle {\n required property var modelData\n width: Math.max(2, Math.round(meter.thickness * 0.5))\n height: meter.thickness * 2.5\n radius: width / 2\n anchors.verticalCenter: meterTrack.verticalCenter\n x: root.clamp(meterTrack.width * root.clamp(Number(modelData.percent), 0, 1) - width / 2, 0, meterTrack.width - width)\n color: meter.alarming ? root.urgent : root.foreground\n }\n }\n }\n}\n```"}], "task": "chunk_manifest_entry", "meta": {"origin": "first-party", "repo": "https://github.com/basecamp/omarchy", "commit": "9480d1b6a98156314dbabe6bfef08f39f8b9cd07", "license": "MIT", "plugin_path": "shell/plugins/agents", "kinds": ["bar-widget"], "complexity": "large", "group": "a4845861", "chunked": true, "validate_tree": true, "validator": "pass", "qmllint": "clean", "qml_files": 1, "chars": 74332, "tokens": 18288, "split": "train"}} {"messages": [{"role": "system", "content": "You are an Omarchy plugin expert. You write complete, valid Omarchy (Quattro / omarchy-shell, Quickshell QML) plugins. Manifests use schemaVersion 1, a namespaced id that never uses the reserved omarchy.* namespace, name, version, kinds (bar-widget|panel|overlay|menu|service|bar) with a matching safe relative entryPoints path for every kind, and no symlinks. Return every file in full as '### path' followed by a fenced code block."}, {"role": "user", "content": "Omarchy plugin `acme.agents` (bar-widget). Manifest:\n```json\n{\n \"schemaVersion\": 1,\n \"id\": \"acme.agents\",\n \"name\": \"Agents\",\n \"version\": \"1.0.0\",\n \"author\": \"Omarchy\",\n \"license\": \"MIT\",\n \"description\": \"Claude Code, Codex, Grok, and Fireworks usage, limits, and pace in a native Omarchy bar panel.\",\n \"kinds\": [\n \"bar-widget\"\n ],\n \"activation\": \"on-demand\",\n \"entryPoints\": {\n \"barWidget\": \"Panel.qml\"\n },\n \"barWidget\": {\n \"displayName\": \"Agents\",\n \"description\": \"One bar icon and one panel: rate-limit meters with pace, today, the last week, and the all-time model breakdown for every subscription.\",\n \"category\": \"AI\",\n \"aliases\": [\n \"agents\",\n \"model-usage\"\n ],\n \"allowMultiple\": false,\n \"defaults\": {\n \"providers\": {\n \"claude\": {\n \"enabled\": true\n },\n \"codex\": {\n \"enabled\": true\n },\n \"grok\": {\n \"enabled\": true\n },\n \"fireworks\": {\n \"enabled\": true\n }\n },\n \"refreshIntervalSec\": 900,\n \"syncMode\": \"Off\",\n \"syncDir\": \"\",\n \"syncFileName\": \"\",\n \"syncDeviceId\": \"\"\n },\n \"schema\": [\n {\n \"key\": \"refreshIntervalSec\",\n \"type\": \"integer\",\n \"label\": \"Refresh interval (seconds)\",\n \"min\": 30,\n \"max\": 3600,\n \"step\": 30,\n \"defaultValue\": 900\n },\n {\n \"key\": \"syncMode\",\n \"type\": \"enum\",\n \"label\": \"Synced aggregation\",\n \"options\": [\n \"Off\",\n \"On\"\n ],\n \"defaultValue\": \"Off\",\n \"description\": \"When On, write this machine's local usage snapshot and merge snapshots from other machines.\"\n },\n {\n \"key\": \"syncDir\",\n \"type\": \"path\",\n \"label\": \"Sync folder\",\n \"defaultValue\": \"\",\n \"description\": \"A folder synced by Syncthing, Dropbox, rsync, etc.\"\n },\n {\n \"key\": \"syncFileName\",\n \"type\": \"string\",\n \"label\": \"Snapshot file name\",\n \"defaultValue\": \"\",\n \"description\": \"Optional. Defaults to .json. Use a different file name on each machine, such as laptop.json or desktop.json.\"\n },\n {\n \"key\": \"syncDeviceId\",\n \"type\": \"string\",\n \"label\": \"Device id\",\n \"defaultValue\": \"\",\n \"description\": \"Optional stable device name used inside synced aggregate snapshots.\"\n }\n ]\n }\n}\n```\nSibling files:\n- Agent.qml (1 KB)\n- Panel.qml (71 KB)\n\nImplement `Main.qml` in full."}, {"role": "assistant", "content": "### Main.qml\n```qml\nimport QtQuick\nimport Quickshell\nimport Quickshell.Io\n\n// The display side of agent usage. All extraction lives behind\n// omarchy-agent-usage-update, which writes one JSON record per agent into\n// the usage directory; this file only discovers those records, watches them\n// for changes, and optionally merges snapshots synced from other machines.\nItem {\n id: root\n visible: false\n\n property var settings: ({})\n\n readonly property string home: Quickshell.env(\"HOME\") || \"\"\n readonly property string usageDir: (Quickshell.env(\"XDG_STATE_HOME\") || home + \"/.local/state\") + \"/omarchy/agents/usage\"\n\n // ------------------------------------------------------------- discovery\n\n property var agentIds: []\n property var agents: []\n property int dataRevision: 0\n\n Process {\n id: listProcess\n running: false\n command: [\"find\", root.usageDir, \"-maxdepth\", \"1\", \"-name\", \"*.json\", \"-printf\", \"%f\\n\"]\n\n stdout: StdioCollector {\n waitForEnd: true\n onStreamFinished: root.applyAgentListing(text)\n }\n }\n\n function rescanAgents() {\n if (!listProcess.running) listProcess.running = true\n }\n\n function applyAgentListing(output) {\n var ids = []\n var lines = String(output || \"\").split(\"\\n\")\n for (var i = 0; i < lines.length; i++) {\n var name = lines[i].trim()\n if (name.slice(-5) === \".json\") ids.push(name.slice(0, -5))\n }\n ids.sort()\n // Same list, same objects: reassigning the model would tear down every\n // FileView just to build identical ones.\n if (JSON.stringify(ids) !== JSON.stringify(agentIds)) agentIds = ids\n }\n\n Instantiator {\n id: agentInstantiator\n model: root.agentIds\n\n delegate: Agent {\n required property var modelData\n agentId: modelData\n path: root.usageDir + \"/\" + modelData + \".json\"\n onRecordChanged: root.recordsChanged()\n }\n\n onObjectAdded: (index, object) => root.rebuildAgents()\n onObjectRemoved: (index, object) => root.rebuildAgents()\n }\n\n // Each record's FileView follows its file on its own; this catches the ones\n // whose watch was lost when an update replaced the file underneath them.\n function reloadRecords() {\n for (var i = 0; i < agents.length; i++)\n if (agents[i]) agents[i].reload()\n }\n\n function rebuildAgents() {\n var result = []\n for (var i = 0; i < agentInstantiator.count; i++) {\n var agent = agentInstantiator.objectAt(i)\n if (agent) result.push(agent)\n }\n agents = result\n recordsChanged()\n }\n\n function recordsChanged() {\n dataRevision++\n scheduleLimitsRetry()\n scheduleSync()\n }\n\n // A collector that could not reach its limits endpoint at all — typically\n // the seconds after login before the network is up — writes retryAdvised\n // into its record. Honor it with one sooner try instead of waiting out the\n // full refresh interval; a run that reaches the endpoint clears the flag.\n // Only the advising agents rerun, so an outage at one provider does not\n // put every other collector on a 30-second treadmill.\n property var retryAgentIds: []\n\n Timer {\n id: limitsRetry\n interval: 30000\n repeat: false\n onTriggered: root.runUpdate(\"limits\", root.retryAgentIds)\n }\n\n function scheduleLimitsRetry() {\n var advising = []\n for (var i = 0; i < agents.length; i++) {\n var record = agents[i] ? agents[i].record : null\n if (record && record.retryAdvised === true && providerEnabled(String(record.id || \"\")))\n advising.push(String(record.id))\n }\n retryAgentIds = advising\n if (advising.length > 0) limitsRetry.restart()\n else limitsRetry.stop()\n }\n\n Component.onCompleted: {\n rescanAgents()\n if (syncConfigured()) scheduleSync()\n }\n\n // -------------------------------------------------------------- refresh\n\n property int refreshIntervalSec: Math.max(30, Number(setting(\"refreshIntervalSec\", 900)))\n property string pendingUpdateKind: \"\"\n\n // A fifteen-minute interval can't catch an account crossing its switch\n // threshold, so while any provider with several accounts has its active one\n // within 15 points of that threshold (80% at the default 95%), the limits\n // are checked every three minutes. Those runs\n // reuse the transcript scans; only the limits probes are new, and any more\n // often than this Anthropic starts refusing them.\n readonly property bool nearLimit: {\n var rev = dataRevision\n for (var i = 0; i < agents.length; i++) {\n var record = agents[i] ? agents[i].record : null\n if (!record || !Array.isArray(record.accounts) || record.accounts.length < 2) continue\n var limits = Array.isArray(record.limits) ? record.limits : []\n var threshold = Number(record.accountSwitch && record.accountSwitch.threshold || 95)\n var from = Math.min(0.8, (threshold - 15) / 100)\n for (var j = 0; j < limits.length; j++)\n if (Number(limits[j] && limits[j].percent) >= from) return true\n }\n return false\n }\n\n Timer {\n interval: root.nearLimit ? Math.min(180, root.refreshIntervalSec) * 1000 : root.refreshIntervalSec * 1000\n running: true\n repeat: true\n triggeredOnStart: true\n onTriggered: root.runUpdate(root.nearLimit ? \"limits\" : \"normal\")\n }\n\n Process {\n id: updateProcess\n running: false\n onExited: {\n root.rescanAgents()\n root.reloadRecords()\n if (root.pendingUpdateKind !== \"\") {\n var kind = root.pendingUpdateKind\n root.pendingUpdateKind = \"\"\n root.runUpdate(kind)\n }\n }\n\n stderr: StdioCollector {\n waitForEnd: true\n onStreamFinished: if (text.trim() !== \"\") console.warn(\"agents\", text.trim())\n }\n }\n\n function updateCommand(kind, agentIds) {\n var command = [\"omarchy-agent-usage-update\"]\n if (kind === \"force\") command.push(\"--force\")\n if (kind === \"limits\") command.push(\"--limits-only\")\n var providers = settings && settings.providers ? settings.providers : {}\n for (var id in providers) {\n if (providers[id] && providers[id].enabled === false) command.push(\"--except\", id)\n }\n if (agentIds) {\n for (var i = 0; i < agentIds.length; i++) command.push(agentIds[i])\n }\n return command\n }\n\n function runUpdate(kind, agentIds) {\n if (updateProcess.running) {\n // Collapse queued requests to one full rerun; a forced refresh outranks\n // the cheaper kinds it might have been queued behind.\n if (kind === \"force\" || root.pendingUpdateKind === \"\") root.pendingUpdateKind = kind\n return\n }\n updateProcess.command = updateCommand(kind, agentIds)\n updateProcess.running = true\n }\n\n function refresh() { refreshAll(true) }\n function refreshAll(force) { runUpdate(force === true ? \"force\" : \"normal\") }\n\n // Opening the panel wants the numbers that go stale on the wire, not\n // another walk over every transcript on disk — the collectors reuse their\n // recent scans in this mode.\n function refreshLimits() { runUpdate(\"limits\") }\n\n // ------------------------------------------------------------- providers\n\n // An agent earns a place in the bar and the panel by being switched on in\n // settings and having actually produced numbers — locally or on a synced\n // device. With nothing to show, the whole module collapses out of the bar\n // rather than sitting there dimmed.\n property var enabledProviders: {\n var rev = dataRevision\n var syncRev = syncRevision\n var result = []\n var localIds = {}\n for (var i = 0; i < agents.length; i++) {\n var record = agents[i] ? agents[i].record : null\n if (!record || !record.id) continue\n var id = String(record.id)\n localIds[id] = true\n if (!providerEnabled(id)) continue\n var display = displayProvider(record)\n if (providerHasData(display)) result.push(display)\n }\n // An agent that only ever ran on another machine has no local record, but\n // its synced numbers still deserve a tab. Rate limits stay blank — they\n // are per-account and never travel.\n var syncedProviders = syncConfigured() && aggregateData && aggregateData.providers ? aggregateData.providers : {}\n for (var syncedId in syncedProviders) {\n if (localIds[syncedId] || !providerEnabled(syncedId)) continue\n var stats = syncedProviders[syncedId] || {}\n var syncedDisplay = displayProvider({ id: syncedId, name: stats.providerName || syncedId })\n if (providerHasData(syncedDisplay)) result.push(syncedDisplay)\n }\n return orderedProviders(result)\n }\n\n // ----------------------------------------------------------------- order\n //\n // The panel's agents in the order someone dragged them into, kept beside the\n // usage records. An agent the order doesn't name yet keeps its place after\n // the ones it does.\n readonly property string orderPath: (Quickshell.env(\"XDG_STATE_HOME\") || home + \"/.local/state\") + \"/omarchy/agents/order.json\"\n property var providerOrder: []\n\n function orderedProviders(list) {\n var order = providerOrder\n var rank = function(p) {\n var i = order.indexOf(p.providerId)\n return i < 0 ? order.length : i\n }\n return list.slice().sort(function(a, b) { return rank(a) - rank(b) })\n }\n\n // Moves one agent to a position among the ones shown, and saves the result.\n function moveProvider(id, to) {\n var ids = enabledProviders.map(function(p) { return p.providerId })\n var from = ids.indexOf(id)\n if (from < 0) return\n to = Math.max(0, Math.min(ids.length - 1, to))\n if (from === to) return\n ids.splice(to, 0, ids.splice(from, 1)[0])\n for (var i = 0; i < providerOrder.length; i++)\n if (ids.indexOf(providerOrder[i]) < 0) ids.push(providerOrder[i])\n providerOrder = ids\n orderFile.setText(JSON.stringify(ids) + \"\\n\")\n }\n\n FileView {\n id: orderFile\n path: root.orderPath\n watchChanges: true\n atomicWrites: true\n printErrors: false\n onLoaded: {\n var parsed = []\n try { parsed = JSON.parse(text()) } catch (e) { parsed = [] }\n root.providerOrder = Array.isArray(parsed) ? parsed.map(String) : []\n }\n onFileChanged: reload()\n }\n\n function providerEnabled(id) {\n if (!settings || !settings.providers || !settings.providers[id]) return true\n return settings.providers[id].enabled !== false\n }\n\n // All-time keeps a quiet day from hiding an agent; today's counts admit a\n // machine whose only source is history.jsonl, which knows nothing older. A\n // signed-in agent with a plan shows before its first numbers arrive, so a\n // lapsed sign-in still has somewhere to say so.\n function providerHasData(p) {\n return numberValue(p.totalPrompts) > 0 || numberValue(p.totalSessions) > 0\n || numberValue(p.activeDays) > 0 || numberValue(p.todayPrompts) > 0\n || numberValue(p.todaySessions) > 0 || (p.limits && p.limits.length > 0)\n || (p.accounts && p.accounts.length > 0) || !!p.balance\n || (p.ready === true && p.tierLabel !== \"\")\n }\n\n // A prepaid agent's credit ledger. Like rate limits, the balance is\n // per-account and never merged across devices.\n function balanceValue(raw) {\n if (!raw || typeof raw !== \"object\") return null\n var remaining = Number(raw.remaining)\n var funded = Number(raw.funded)\n if (!isFinite(remaining) || remaining < 0) return null\n return {\n remaining: remaining,\n funded: isFinite(funded) && funded > 0 ? funded : 0,\n spent: Math.max(0, Number(raw.spent) || 0),\n currency: String(raw.currency || \"USD\"),\n estimated: raw.estimated === true\n }\n }\n\n function displayProvider(record) {\n var stats = syncedStatsFor(String(record.id))\n var synced = !!stats\n var deviceCount = synced ? Number(stats.deviceCount || aggregateData.deviceCount || 0) : 0\n\n return {\n providerId: String(record.id),\n providerName: String(record.name || record.id),\n ready: record.ready === true || synced,\n usageStatusText: String(record.usageStatusText || \"\"),\n authHelpText: String(record.authHelpText || \"\"),\n\n // Rate limits and balances stay per-account and are never merged\n // across devices.\n limits: Array.isArray(record.limits) ? record.limits : [],\n limitsStale: record.limitsStale === true,\n limitsFetchedAt: numberValue(record.limitsFetchedAt),\n tierLabel: String(record.tierLabel || \"\"),\n // Every subscription account's own limits, once there's more than one.\n accounts: Array.isArray(record.accounts) ? record.accounts : [],\n accountSwitch: record.accountSwitch || ({ mode: \"manual\", threshold: 95 }),\n // Codex's free full resets of its rate limits, when it has any.\n resetCredits: record.resetCredits || null,\n balance: balanceValue(record.balance),\n\n todayPrompts: synced ? numberValue(stats.todayPrompts) : numberValue(record.todayPrompts),\n todaySessions: synced ? numberValue(stats.todaySessions) : numberValue(record.todaySessions),\n todayTotalTokens: synced ? numberValue(stats.todayTotalTokens) : numberValue(record.todayTotalTokens),\n todayTokensByModel: synced ? (stats.todayTokensByModel || ({})) : (record.todayTokensByModel || ({})),\n recentDays: synced ? (stats.recentDays || []) : (record.recentDays || []),\n totalPrompts: synced ? numberValue(stats.totalPrompts) : numberValue(record.totalPrompts),\n totalSessions: synced ? numberValue(stats.totalSessions) : numberValue(record.totalSessions),\n activeDays: synced ? numberValue(stats.activeDays) : numberValue(record.activeDays),\n modelUsage: synced ? (stats.modelUsage || ({})) : (record.modelUsage || ({})),\n hasLocalStats: synced ? (stats.hasLocalStats !== false) : (record.hasLocalStats !== false),\n hasPromptStats: synced ? (stats.hasPromptStats !== false) : (record.hasPromptStats !== false),\n\n syncEnabled: synced,\n syncDeviceCount: deviceCount,\n syncUpdatedAt: aggregateData && aggregateData.updatedAt ? aggregateData.updatedAt : \"\"\n }\n }\n\n function setting(name, fallback) {\n var value = settings ? settings[name] : undefined\n return value === undefined || value === null ? fallback : value\n }\n\n // ------------------------------------------------------------------ sync\n\n property var syncModeSetting: setting(\"syncMode\", setting(\"syncEnabled\", false))\n property bool syncEnabled: parseSyncEnabled(syncModeSetting)\n property string syncDir: String(setting(\"syncDir\", \"\"))\n property string syncFileName: String(setting(\"syncFileName\", \"\"))\n property string syncDeviceId: String(setting(\"syncDeviceId\", \"\"))\n property string detectedHostname: \"\"\n readonly property string syncEffectiveDir: expandPath(syncDir)\n readonly property string syncEffectiveFileName: safeSnapshotFileName(syncFileName, syncDeviceId)\n readonly property string syncEffectiveDeviceId: safeDeviceId(syncDeviceId || syncEffectiveFileName.replace(/\\.json$/i, \"\"))\n readonly property string syncSnapshotPath: syncConfigured() ? syncEffectiveDir + \"/\" + syncEffectiveFileName : home + \"/.cache/omarchy/agents-disabled.json\"\n property var aggregateData: ({})\n property int syncRevision: 0\n property bool syncRunning: false\n property bool syncRequestedWhileRunning: false\n property string syncStatusText: \"\"\n property double aggregateUpdatedAtMs: aggregateData && aggregateData.updatedAtMs ? Number(aggregateData.updatedAtMs) : 0\n\n onSyncEnabledChanged: syncSettingsChanged()\n onSyncDirChanged: syncSettingsChanged()\n onSyncFileNameChanged: if (syncConfigured()) scheduleSync()\n onSyncDeviceIdChanged: if (syncConfigured()) scheduleSync()\n\n Timer {\n id: syncDebounce\n interval: 1000\n repeat: false\n onTriggered: root.runSync()\n }\n\n Process {\n id: syncMkdirProcess\n running: false\n onRunningChanged: root.updateSyncRunning()\n onExited: function(exitCode) {\n if (exitCode !== 0) {\n if (root.syncConfigured()) root.syncStatusText = \"Usage sync mkdir failed\"\n root.finishSyncRun()\n return\n }\n root.writeSyncSnapshot()\n }\n }\n\n Process {\n id: syncScanProcess\n running: false\n onRunningChanged: root.updateSyncRunning()\n onExited: function(exitCode) {\n if (exitCode !== 0 && root.syncConfigured()) root.syncStatusText = \"Usage sync scan failed\"\n root.finishSyncRun()\n }\n\n stdout: StdioCollector {\n waitForEnd: true\n onStreamFinished: root.parseSyncScanOutput(text)\n }\n\n stderr: StdioCollector {\n waitForEnd: true\n onStreamFinished: if (text.trim() !== \"\") console.warn(\"agents/sync\", text.trim())\n }\n }\n\n FileView {\n id: syncSnapshotFile\n path: root.syncSnapshotPath\n watchChanges: false\n atomicWrites: true\n printErrors: false\n }\n\n FileView {\n id: hostnameFile\n path: \"/etc/hostname\"\n watchChanges: false\n printErrors: false\n onLoaded: root.detectedHostname = String(text() || \"\").trim()\n }\n\n function parseSyncEnabled(value) {\n if (value === true) return true\n var text = String(value || \"\").trim().toLowerCase()\n return text === \"on\" || text === \"enabled\" || text === \"true\" || text === \"yes\" || text === \"1\"\n }\n\n function syncConfigured() {\n return root.syncEnabled === true && String(root.syncDir || \"\").trim() !== \"\"\n }\n\n function syncSettingsChanged() {\n if (syncConfigured()) {\n scheduleSync()\n } else {\n syncDebounce.stop()\n syncRequestedWhileRunning = false\n aggregateData = ({})\n syncStatusText = \"\"\n syncRevision++\n }\n }\n\n function updateSyncRunning() {\n root.syncRunning = syncMkdirProcess.running || syncScanProcess.running\n }\n\n function scheduleSync() {\n if (!syncConfigured()) return\n syncDebounce.restart()\n }\n\n function runSync() {\n if (!syncConfigured()) return\n if (root.syncRunning) {\n syncRequestedWhileRunning = true\n return\n }\n\n syncRequestedWhileRunning = false\n syncStatusText = \"\"\n syncMkdirProcess.command = [\"mkdir\", \"-p\", root.syncEffectiveDir]\n syncMkdirProcess.running = true\n }\n\n function writeSyncSnapshot() {\n if (!syncConfigured()) {\n finishSyncRun()\n return\n }\n syncSnapshotFile.setText(JSON.stringify(localSnapshot(), null, 2) + \"\\n\")\n Qt.callLater(root.startSyncScan)\n }\n\n function startSyncScan() {\n if (!syncConfigured()) {\n finishSyncRun()\n return\n }\n var script = \"dir=$0; [[ -d \\\"$dir\\\" ]] || exit 0; shopt -s nullglob; for f in \\\"$dir\\\"/*.json; do [[ -f \\\"$f\\\" ]] || continue; printf '===%s===\\\\n' \\\"$f\\\"; cat \\\"$f\\\"; printf '\\\\n=== EOM ===\\\\n'; done\"\n syncScanProcess.command = [\"bash\", \"-c\", script, root.syncEffectiveDir]\n syncScanProcess.running = true\n }\n\n function finishSyncRun() {\n if (syncRequestedWhileRunning && syncConfigured()) {\n syncRequestedWhileRunning = false\n scheduleSync()\n }\n }\n\n function expandPath(path) {\n var value = String(path || \"\").trim()\n if (value === \"\") return \"\"\n if (value === \"~\") return home\n if (value.indexOf(\"~/\") === 0) return home + value.substring(1)\n if (value.indexOf(\"$HOME/\") === 0) return home + value.substring(5)\n if (value.charAt(0) !== \"/\") return home + \"/\" + value\n return value\n }\n\n function safeDeviceId(raw) {\n var value = String(raw || \"\").trim()\n if (value === \"\") value = Quickshell.env(\"HOSTNAME\") || root.detectedHostname || Quickshell.env(\"HOST\") || Quickshell.env(\"USER\") || \"device\"\n value = value.replace(/[^A-Za-z0-9_.-]+/g, \"-\").replace(/^[._-]+|[._-]+$/g, \"\")\n if (value === \"\") value = \"device\"\n return value.length > 80 ? value.substring(0, 80) : value\n }\n\n function safeSnapshotFileName(rawFileName, rawDeviceId) {\n var value = String(rawFileName || \"\").trim()\n if (value === \"\") value = safeDeviceId(rawDeviceId) + \".json\"\n value = value.split(\"/\").pop().replace(/[^A-Za-z0-9_.-]+/g, \"-\").replace(/^[._-]+|[._-]+$/g, \"\")\n if (value === \"\") value = safeDeviceId(rawDeviceId) + \".json\"\n if (!/\\.json$/i.test(value)) value += \".json\"\n return value.length > 100 ? value.substring(0, 95) + \".json\" : value\n }\n\n function parseSyncScanOutput(output) {\n var lines = String(output || \"\").split(\"\\n\")\n var snapshots = []\n var currentPath = \"\"\n var currentJson = []\n\n function flush() {\n if (currentPath === \"\") return\n var raw = currentJson.join(\"\\n\").trim()\n try {\n var parsed = JSON.parse(raw)\n if (parsed && parsed.providers) snapshots.push(parsed)\n } catch (e) {\n console.warn(\"agents/sync\", \"Ignoring bad snapshot\", currentPath, e)\n }\n currentPath = \"\"\n currentJson = []\n }\n\n for (var i = 0; i < lines.length; i++) {\n var line = lines[i]\n var start = line.match(/^===(.+)===$/)\n if (start && line !== \"=== EOM ===\") {\n flush()\n currentPath = start[1]\n currentJson = []\n continue\n }\n if (line === \"=== EOM ===\") {\n flush()\n continue\n }\n if (currentPath !== \"\") currentJson.push(line)\n }\n flush()\n\n aggregateData = aggregateSnapshots(snapshots)\n syncStatusText = \"\"\n syncRevision++\n }\n\n function cloneValue(value, fallback) {\n if (value === undefined || value === null) return fallback\n try {\n return JSON.parse(JSON.stringify(value))\n } catch (e) {\n return fallback\n }\n }\n\n function numberValue(value) {\n var n = Number(value || 0)\n return isFinite(n) ? Math.round(n) : 0\n }\n\n function dateString(date) {\n var y = date.getFullYear()\n var m = String(date.getMonth() + 1).padStart(2, \"0\")\n var d = String(date.getDate()).padStart(2, \"0\")\n return y + \"-\" + m + \"-\" + d\n }\n\n function recentDateStrings() {\n var result = []\n for (var offset = 6; offset >= 0; offset--) {\n var date = new Date()\n date.setDate(date.getDate() - offset)\n result.push(dateString(date))\n }\n return result\n }\n\n function emptyTokenBucket() {\n return { inputTokens: 0, outputTokens: 0, cacheReadInputTokens: 0, cacheCreationInputTokens: 0 }\n }\n\n // Device-scoped stats add up across machines; account-scoped stats\n // (Fireworks' billing API) are replicas of the same upstream truth on\n // every synced device, so the widest value wins — summing them would\n // double every token per machine.\n function combineNumber(additive, current, value) {\n return additive ? numberValue(current) + numberValue(value) : Math.max(numberValue(current), numberValue(value))\n }\n\n function combineObjectNumbers(additive, target, source) {\n if (!source) return\n for (var key in source) target[key] = combineNumber(additive, target[key], source[key])\n }\n\n function aggregateSnapshots(snapshots) {\n var dates = recentDateStrings()\n var devices = {}\n var providers = {}\n\n function providerAcc(id) {\n if (providers[id]) return providers[id]\n var recentByDay = {}\n for (var d = 0; d < dates.length; d++) recentByDay[dates[d]] = 0\n providers[id] = {\n providerId: id,\n providerName: \"\",\n ready: false,\n hasLocalStats: false,\n hasPromptStats: false,\n todayPrompts: 0,\n todaySessions: 0,\n todayTotalTokens: 0,\n todayTokensByModel: ({}),\n recentByDay: recentByDay,\n totalPrompts: 0,\n totalSessions: 0,\n activeDays: 0,\n activeDates: ({}),\n modelUsage: ({}),\n devices: ({})\n }\n return providers[id]\n }\n\n for (var i = 0; i < snapshots.length; i++) {\n var snapshot = snapshots[i]\n var device = safeDeviceId(snapshot.deviceId || \"device\")\n devices[device] = true\n var snapshotProviders = snapshot.providers || {}\n for (var providerId in snapshotProviders) {\n var stats = snapshotProviders[providerId] || {}\n var acc = providerAcc(String(providerId))\n acc.devices[device] = true\n if (stats.providerName && acc.providerName === \"\") acc.providerName = String(stats.providerName)\n acc.ready = acc.ready || stats.ready === true\n acc.hasLocalStats = acc.hasLocalStats || stats.hasLocalStats !== false\n // Snapshots from before the field existed only came from agents that\n // count prompts, so a missing value reads as true.\n acc.hasPromptStats = acc.hasPromptStats || stats.hasPromptStats !== false\n var additive = String(stats.scope || \"device\") !== \"account\"\n acc.todayPrompts = combineNumber(additive, acc.todayPrompts, stats.todayPrompts)\n acc.todaySessions = combineNumber(additive, acc.todaySessions, stats.todaySessions)\n acc.todayTotalTokens = combineNumber(additive, acc.todayTotalTokens, stats.todayTotalTokens)\n acc.totalPrompts = combineNumber(additive, acc.totalPrompts, stats.totalPrompts)\n acc.totalSessions = combineNumber(additive, acc.totalSessions, stats.totalSessions)\n // Active days overlap between machines, so union the dates rather than\n // summing counts. Snapshots written before activeDates existed only\n // carry a count; the widest one stands in for them.\n var activeDates = Array.isArray(stats.activeDates) ? stats.activeDates : []\n for (var ad = 0; ad < activeDates.length; ad++) acc.activeDates[String(activeDates[ad])] = true\n acc.activeDays = Math.max(acc.activeDays, numberValue(stats.activeDays))\n combineObjectNumbers(additive, acc.todayTokensByModel, stats.todayTokensByModel || {})\n\n var recent = Array.isArray(stats.recentDays) ? stats.recentDays : []\n for (var r = 0; r < recent.length; r++) {\n var day = recent[r] || {}\n var date = String(day.date || \"\")\n if (acc.recentByDay[date] !== undefined)\n acc.recentByDay[date] = combineNumber(additive, acc.recentByDay[date], day.messageCount)\n }\n\n var usage = stats.modelUsage || {}\n for (var modelId in usage) {\n var bucket = acc.modelUsage[modelId]\n if (!bucket) bucket = acc.modelUsage[modelId] = emptyTokenBucket()\n combineObjectNumbers(additive, bucket, usage[modelId] || {})\n }\n }\n }\n\n var outProviders = {}\n for (var id in providers) {\n var acc = providers[id]\n var recentDays = []\n for (var di = 0; di < dates.length; di++) recentDays.push({ date: dates[di], messageCount: acc.recentByDay[dates[di]] || 0 })\n var providerDevices = Object.keys(acc.devices).sort()\n outProviders[id] = {\n providerId: acc.providerId,\n providerName: acc.providerName,\n ready: acc.ready || providerDevices.length > 0,\n hasLocalStats: acc.hasLocalStats,\n hasPromptStats: acc.hasPromptStats,\n todayPrompts: acc.todayPrompts,\n todaySessions: acc.todaySessions,\n todayTotalTokens: acc.todayTotalTokens,\n todayTokensByModel: acc.todayTokensByModel,\n recentDays: recentDays,\n totalPrompts: acc.totalPrompts,\n totalSessions: acc.totalSessions,\n activeDays: Math.max(acc.activeDays, Object.keys(acc.activeDates).length),\n modelUsage: acc.modelUsage,\n deviceCount: providerDevices.length,\n devices: providerDevices\n }\n }\n\n return {\n schemaVersion: 1,\n updatedAt: new Date().toISOString(),\n updatedAtMs: Date.now(),\n deviceCount: Object.keys(devices).length,\n devices: Object.keys(devices).sort(),\n providers: outProviders\n }\n }\n\n // Snapshots keep the field names older Omarchy versions wrote, so a fleet\n // of machines on mixed versions still merges cleanly in both directions.\n function providerSnapshot(record) {\n return {\n providerId: String(record.id),\n providerName: String(record.name || record.id),\n ready: record.ready === true,\n hasLocalStats: record.hasLocalStats !== false,\n hasPromptStats: record.hasPromptStats !== false,\n scope: String(record.scope || \"device\"),\n todayPrompts: numberValue(record.todayPrompts),\n todaySessions: numberValue(record.todaySessions),\n todayTotalTokens: numberValue(record.todayTotalTokens),\n todayTokensByModel: cloneValue(record.todayTokensByModel, ({})),\n recentDays: cloneValue(record.recentDays, []),\n totalPrompts: numberValue(record.totalPrompts),\n totalSessions: numberValue(record.totalSessions),\n activeDays: numberValue(record.activeDays),\n activeDates: cloneValue(record.activeDates, []),\n modelUsage: cloneValue(record.modelUsage, ({}))\n }\n }\n\n function localSnapshot() {\n var providerMap = {}\n for (var i = 0; i < agents.length; i++) {\n var record = agents[i] ? agents[i].record : null\n if (!record || !record.id) continue\n if (!providerEnabled(String(record.id))) continue\n providerMap[String(record.id)] = providerSnapshot(record)\n }\n return {\n schemaVersion: 1,\n deviceId: syncEffectiveDeviceId,\n updatedAt: new Date().toISOString(),\n providers: providerMap\n }\n }\n\n function syncedStatsFor(providerId) {\n var rev = syncRevision\n if (!syncConfigured() || !aggregateData || !aggregateData.providers) return null\n return aggregateData.providers[providerId] || null\n }\n\n // ---------------------------------------------------------------- format\n\n function formatTokenCount(n) {\n if (n === undefined || n === null) return \"0\"\n if (n >= 1e9) return (n / 1e9).toFixed(1) + \"B\"\n if (n >= 1e6) return (n / 1e6).toFixed(1) + \"M\"\n if (n >= 1e3) return (n / 1e3).toFixed(1) + \"K\"\n return String(n)\n }\n\n function modelWordCase(word) {\n if (word === \"gpt\") return \"GPT\"\n if (word === \"deepseek\") return \"DeepSeek\"\n return word.charAt(0).toUpperCase() + word.slice(1)\n }\n\n // Model ids arrive hyphenated with the version split across segments\n // (`claude-opus-4-8`, `gpt-5.6-sol`). Rejoin the numeric run into one\n // version and title-case the words around it.\n function friendlyModelName(id) {\n if (!id) return \"Unknown\"\n var name = String(id).replace(/^claude-/, \"\").replace(/-\\d{8}$/, \"\")\n var parts = name.split(\"-\")\n var words = []\n var version = []\n for (var i = 0; i < parts.length; i++) {\n var part = parts[i]\n if (part === \"\") continue\n if (/^\\d/.test(part)) {\n version.push(part)\n continue\n }\n if (version.length > 0) {\n words.push(version.join(\".\"))\n version = []\n }\n words.push(modelWordCase(part))\n }\n if (version.length > 0) words.push(version.join(\".\"))\n return words.length > 0 ? words.join(\" \") : \"Unknown\"\n }\n}\n```"}], "task": "chunk_component", "meta": {"origin": "first-party", "repo": "https://github.com/basecamp/omarchy", "commit": "9480d1b6a98156314dbabe6bfef08f39f8b9cd07", "license": "MIT", "plugin_path": "shell/plugins/agents", "kinds": ["bar-widget"], "complexity": "large", "group": "a4845861", "chunked": true, "validate_tree": true, "validator": "pass", "qmllint": "clean", "qml_files": 1, "chars": 33393, "tokens": 8267, "split": "train"}} {"messages": [{"role": "system", "content": "You are an Omarchy plugin expert. You write complete, valid Omarchy (Quattro / omarchy-shell, Quickshell QML) plugins. Manifests use schemaVersion 1, a namespaced id that never uses the reserved omarchy.* namespace, name, version, kinds (bar-widget|panel|overlay|menu|service|bar) with a matching safe relative entryPoints path for every kind, and no symlinks. Return every file in full as '### path' followed by a fenced code block."}, {"role": "user", "content": "Omarchy plugin `acme.agents` (bar-widget). Manifest:\n```json\n{\n \"schemaVersion\": 1,\n \"id\": \"acme.agents\",\n \"name\": \"Agents\",\n \"version\": \"1.0.0\",\n \"author\": \"Omarchy\",\n \"license\": \"MIT\",\n \"description\": \"Claude Code, Codex, Grok, and Fireworks usage, limits, and pace in a native Omarchy bar panel.\",\n \"kinds\": [\n \"bar-widget\"\n ],\n \"activation\": \"on-demand\",\n \"entryPoints\": {\n \"barWidget\": \"Panel.qml\"\n },\n \"barWidget\": {\n \"displayName\": \"Agents\",\n \"description\": \"One bar icon and one panel: rate-limit meters with pace, today, the last week, and the all-time model breakdown for every subscription.\",\n \"category\": \"AI\",\n \"aliases\": [\n \"agents\",\n \"model-usage\"\n ],\n \"allowMultiple\": false,\n \"defaults\": {\n \"providers\": {\n \"claude\": {\n \"enabled\": true\n },\n \"codex\": {\n \"enabled\": true\n },\n \"grok\": {\n \"enabled\": true\n },\n \"fireworks\": {\n \"enabled\": true\n }\n },\n \"refreshIntervalSec\": 900,\n \"syncMode\": \"Off\",\n \"syncDir\": \"\",\n \"syncFileName\": \"\",\n \"syncDeviceId\": \"\"\n },\n \"schema\": [\n {\n \"key\": \"refreshIntervalSec\",\n \"type\": \"integer\",\n \"label\": \"Refresh interval (seconds)\",\n \"min\": 30,\n \"max\": 3600,\n \"step\": 30,\n \"defaultValue\": 900\n },\n {\n \"key\": \"syncMode\",\n \"type\": \"enum\",\n \"label\": \"Synced aggregation\",\n \"options\": [\n \"Off\",\n \"On\"\n ],\n \"defaultValue\": \"Off\",\n \"description\": \"When On, write this machine's local usage snapshot and merge snapshots from other machines.\"\n },\n {\n \"key\": \"syncDir\",\n \"type\": \"path\",\n \"label\": \"Sync folder\",\n \"defaultValue\": \"\",\n \"description\": \"A folder synced by Syncthing, Dropbox, rsync, etc.\"\n },\n {\n \"key\": \"syncFileName\",\n \"type\": \"string\",\n \"label\": \"Snapshot file name\",\n \"defaultValue\": \"\",\n \"description\": \"Optional. Defaults to .json. Use a different file name on each machine, such as laptop.json or desktop.json.\"\n },\n {\n \"key\": \"syncDeviceId\",\n \"type\": \"string\",\n \"label\": \"Device id\",\n \"defaultValue\": \"\",\n \"description\": \"Optional stable device name used inside synced aggregate snapshots.\"\n }\n ]\n }\n}\n```\nSibling files:\n- Main.qml (30 KB)\n- Panel.qml (71 KB)\n\nImplement `Agent.qml` in full."}, {"role": "assistant", "content": "### Agent.qml\n```qml\nimport QtQuick\nimport Quickshell.Io\n\n// One agent's usage record, read straight off the data file that\n// omarchy-agent-usage-update maintains. The panel never learns how the\n// numbers were made — a record that appears in the usage directory is an\n// agent, whoever wrote it.\nItem {\n id: root\n visible: false\n\n property string agentId: \"\"\n property string path: \"\"\n property var record: null\n\n // The text the current record was parsed from, so a reload that finds the\n // file unchanged doesn't hand every listener an identical new record.\n property string parsedText: \"\"\n\n FileView {\n id: agentFile\n path: root.path\n watchChanges: true\n printErrors: false\n onFileChanged: reload()\n onLoaded: root.parse(text())\n onLoadFailed: root.clear()\n }\n\n // The usage update rewrites records with an atomic mv, which replaces the\n // inode. Should inotify fail to rearm on the new one (watch quota, ENOSPC),\n // the FileView goes quiet, so Main.qml also reloads every record after each\n // update run (#9974).\n function reload() { agentFile.reload() }\n\n function clear() {\n root.parsedText = \"\"\n root.record = null\n }\n\n function parse(content) {\n var text = String(content || \"\")\n if (root.record && text === root.parsedText) return\n try {\n var parsed = JSON.parse(text)\n root.record = parsed && typeof parsed === \"object\" ? parsed : null\n root.parsedText = root.record ? text : \"\"\n } catch (e) {\n console.warn(\"agents\", \"Ignoring bad usage record\", root.path, e)\n root.clear()\n }\n }\n}\n```"}], "task": "chunk_component", "meta": {"origin": "first-party", "repo": "https://github.com/basecamp/omarchy", "commit": "9480d1b6a98156314dbabe6bfef08f39f8b9cd07", "license": "MIT", "plugin_path": "shell/plugins/agents", "kinds": ["bar-widget"], "complexity": "large", "group": "a4845861", "chunked": true, "validate_tree": true, "validator": "pass", "qmllint": "clean", "qml_files": 1, "chars": 4536, "tokens": 1183, "split": "train"}} {"messages": [{"role": "system", "content": "You are an Omarchy plugin expert. You write complete, valid Omarchy (Quattro / omarchy-shell, Quickshell QML) plugins. Manifests use schemaVersion 1, a namespaced id that never uses the reserved omarchy.* namespace, name, version, kinds (bar-widget|panel|overlay|menu|service|bar) with a matching safe relative entryPoints path for every kind, and no symlinks. Return every file in full as '### path' followed by a fenced code block."}, {"role": "user", "content": "Write the manifest and entry-point file(s) (Bar.qml) for the Omarchy plugin `acme.bar` \"Bar\" (bar): Status bar with widgets. These sibling files already exist in the folder and can be referenced:\n- BarModel.js (13 KB)\n- indicators/Dnd.qml (1 KB)\n- indicators/NightLight.qml (1 KB)\n- indicators/PasswordlessSudo.qml (1 KB)\n- indicators/Reminder.qml (1 KB)\n- indicators/RemoteSession.qml (1 KB)\n- indicators/ScreenRecording.qml (1 KB)\n- indicators/StayAwake.qml (1 KB)\n- widgets/ActiveWindow.qml (1 KB)\n- widgets/Indicators.qml (15 KB)\n- widgets/KeyboardLayout.qml (10 KB)\n- widgets/KeyboardLayoutModel.js (6 KB)\n- widgets/Microphone.qml (2 KB)\n- widgets/Spacer.qml (1 KB)\n- widgets/SystemUpdate.qml (1 KB)\n- widgets/Tray.qml (30 KB)\n- widgets/TrayModel.js (1 KB)\n- widgets/Workspaces.qml (4 KB)"}, {"role": "assistant", "content": "### manifest.json\n```json\n{\n \"schemaVersion\": 1,\n \"id\": \"acme.bar\",\n \"name\": \"Bar\",\n \"version\": \"1.0.0\",\n \"author\": \"Omarchy\",\n \"description\": \"Status bar with widgets\",\n \"kinds\": [\n \"bar\"\n ],\n \"entryPoints\": {\n \"bar\": \"Bar.qml\"\n }\n}\n```\n\n### Bar.qml\n```qml\nimport Quickshell\nimport Quickshell.Hyprland\nimport Quickshell.Io\nimport Quickshell.Wayland\nimport QtQuick\nimport QtQuick.Layouts\nimport qs.Commons\nimport qs.Commons as Commons\nimport qs.Ui\nimport \"BarModel.js\" as BarModel\n\nItem {\n id: root\n\n // The omarchy-shell host injects omarchyPath from OMARCHY_PATH.\n property string omarchyPath: Quickshell.env(\"OMARCHY_PATH\")\n // Injected by the host shell so bar slots can resolve enabled widgets.\n property var barWidgetRegistry: fallbackBarWidgetRegistry\n // Read-only registry view for third-party full bars; the built-in bar does\n // not otherwise need it, but declaring it keeps clone construction atomic.\n property var pluginRegistry: null\n // Injected by the host shell every time shell.json is reloaded. Holds the\n // `bar:` subtree: position, centerAnchor, layout. The host owns file IO;\n // the bar just renders whatever it's handed. The bar font follows the\n // OS-level fontconfig monospace binding — it is not stored in shell.json.\n property var barConfig: ({})\n // Injected by the host shell. Used for shell-wide actions such as opening\n // settings and persisting inline widget state.\n property var shell: null\n // Manifest for the active bar option. Present for custom bars and useful for\n // diagnostics; the built-in bar does not otherwise need it.\n property var manifest: null\n QtObject {\n id: fallbackBarWidgetRegistry\n property var widgets: ({})\n property int revision: 0\n function metadataFor(id) { return null }\n }\n // Mirrors the on-disk `bar-off` flag so the user can hide the bar without\n // killing the entire shell. Hidden panels stay mapped but park off-screen\n // without an exclusion zone; updated by the FileView watcher further down.\n property bool barHidden: false\n property string home: Quickshell.env(\"HOME\")\n property string stateHome: home + \"/.local/state\"\n property string omarchyConfigDir: home + \"/.config/omarchy\"\n property var fallbackBarConfig: ({\n position: \"top\",\n background: \"opaque\",\n centerAnchor: \"omarchy.clock\",\n layout: { left: [], center: [], right: [] }\n })\n property var layoutConfig: fallbackBarConfig.layout\n property string centerAnchor: \"\"\n property bool requestedTransparent: false\n property bool useTransparentForeground: false\n property bool transparent: false\n // A see-through bar that Hyprland blurs behind (the bar-glassy toggle), so\n // its theme background stays faintly. A transparent bar wins over it.\n property bool glassy: false\n // The look the blur behind the bar was last synced for. A background set by\n // editing shell.json skips the CLI, so the bar syncs Hyprland's blur itself.\n property string glassSyncedLook: \"\"\n property bool centerSectionHovered: false\n // One bar surface exists per monitor and each reports into this count, so a\n // pointer crossing from one monitor's bar to another's stays counted however\n // the enter and leave interleave. A single shared bool would be left false by\n // whichever event landed last.\n property int barHoverCount: 0\n // True while the pointer is over any bar, widgets included.\n readonly property bool barHovered: barHoverCount > 0\n property bool centerSectionRevealHeld: false\n property bool centerHoverRevealSuppressed: false\n property int barConfigSerial: 0\n property string position: \"top\"\n // Resolves through fontconfig at paint time (Style.font.family defaults\n // to \"monospace\"), so changing the system font (via `omarchy-font-set`)\n // updates the bar without a reload.\n property string fontFamily: Style.font.family\n // Bound to the central Color singleton so the bar tracks shell.toml's\n // [bar] section. Property names kept for the rest of this file's bindings.\n property color themeForeground: Commons.Color.bar.text\n property color themeContrastForeground: Commons.Color.background\n property color transparentForeground: Commons.Color.bar.text\n property color foreground: themeForeground\n property color barForeground: useTransparentForeground ? transparentForeground : themeForeground\n property bool foregroundAnimationEnabled: true\n property color background: Commons.Color.bar.background\n readonly property color glassBackground: Qt.rgba(background.r, background.g, background.b, Math.min(background.a, 0.35))\n property color urgent: Commons.Color.bar.active\n\n Behavior on barForeground { enabled: root.foregroundAnimationEnabled; ColorAnimation { duration: Style.duration(420); easing.type: Easing.OutCubic } }\n Behavior on background { ColorAnimation { duration: Style.duration(420); easing.type: Easing.OutCubic } }\n Behavior on urgent { ColorAnimation { duration: Style.duration(420); easing.type: Easing.OutCubic } }\n property var tooltipTarget: null\n property var pendingTooltipTarget: null\n property string tooltipText: \"\"\n property string pendingTooltipText: \"\"\n property bool tooltipShown: false\n property int tooltipRequest: 0\n property var activePopout: null\n property var barDragSource: null\n property var barDragTarget: null\n property var barDragTargetGeometry: null\n property bool barDragAfter: false\n property var barDragWindow: null\n property var barDragScreen: null\n property url barDragImageUrl: \"\"\n property real barDragSceneX: 0\n property real barDragSceneY: 0\n property real barDragScreenX: 0\n property real barDragScreenY: 0\n property real barDragOffsetX: 0\n property real barDragOffsetY: 0\n property bool barMoveActive: false\n property string barMoveCandidate: \"\"\n property var barMoveWindow: null\n property var barMoveScreen: null\n property var clickTargets: []\n property var moduleSlots: []\n property var pluginBarApis: ({})\n // target -> { target, pluginId, clickTarget, popout }. Keyed by object so a\n // registration edits one entry in place instead of copying and rescanning an\n // array in QML; Qt's Map still finds a key by a native linear scan.\n readonly property var pluginObjectOwners: new Map()\n property bool pluginBarApiSyncQueued: false\n\n Component {\n id: pluginBarApiComponent\n PluginBarApi { }\n }\n\n function publicLayoutConfig() {\n return JSON.parse(JSON.stringify(root.layoutConfig || {}))\n }\n\n function bindPluginBarApi(api) {\n if (!api) return\n api.foreground = Qt.binding(function() { return root.foreground })\n api.barForeground = Qt.binding(function() { return root.barForeground })\n api.background = Qt.binding(function() { return root.background })\n api.urgent = Qt.binding(function() { return root.urgent })\n api.fontFamily = Qt.binding(function() { return root.fontFamily })\n api.position = Qt.binding(function() { return root.position })\n api.vertical = Qt.binding(function() { return root.vertical })\n api.barSize = Qt.binding(function() { return root.barSize })\n api.transparent = Qt.binding(function() { return root.transparent })\n api.foregroundAnimationEnabled = Qt.binding(function() { return root.foregroundAnimationEnabled })\n api.centerSectionRevealHeld = Qt.binding(function() { return root.centerSectionRevealHeld })\n api._centerHoverRevealSuppressed = Qt.binding(function() { return root.centerHoverRevealSuppressed })\n root.syncPluginBarApiObjects(api)\n }\n\n // Each api keeps its own detached copy of the layout. A flush serialises\n // the layout once and passes the string in so it is not re-serialised for\n // every plugin.\n function syncPluginBarApiObjects(api, layoutSnapshot) {\n if (!api) return\n api.activePopout = root.pluginOwnsBarObject(api.pluginId, root.activePopout)\n ? root.activePopout : (root.activePopout ? api.foreignPopoutMarker : null)\n api.clickTargets = root.pluginClickTargets(api.pluginId)\n api.layoutConfig = layoutSnapshot !== undefined\n ? JSON.parse(layoutSnapshot) : root.publicLayoutConfig()\n }\n\n function pluginObjectRecord(target) {\n return target ? (pluginObjectOwners.get(target) || null) : null\n }\n\n function markPluginObject(pluginId, target, role) {\n var key = String(pluginId || \"\")\n if (!key || !target) return false\n var record = root.pluginObjectRecord(target)\n if (record && record.pluginId !== key) return false\n if (!record) {\n record = { target: target, pluginId: key, clickTarget: false, popout: false }\n pluginObjectOwners.set(target, record)\n }\n record[role] = true\n return true\n }\n\n function unmarkPluginObject(pluginId, target, role) {\n var key = String(pluginId || \"\")\n var record = root.pluginObjectRecord(target)\n if (!record || record.pluginId !== key) return\n record[role] = false\n if (!record.clickTarget && !record.popout) pluginObjectOwners.delete(target)\n }\n\n function pluginOwnsBarObject(pluginId, target) {\n var record = target ? root.pluginObjectRecord(target) : null\n return !!record && record.pluginId === String(pluginId || \"\")\n }\n\n function pluginClickTargets(pluginId) {\n var out = []\n for (var i = 0; i < root.clickTargets.length; i++) {\n var target = root.clickTargets[i]\n if (root.pluginOwnsBarObject(pluginId, target)) out.push(target)\n }\n return out\n }\n\n // Every click target registration, popout change and layout change used to\n // resync every plugin api synchronously. Startup alone is hundreds of\n // registrations, each walking every api and every target, so coalesce them\n // into one resync per event-loop turn (as onModuleSlotsChanged already does\n // for prunePluginBarApis). bindPluginBarApi still syncs a brand-new api\n // directly so a widget never sees an empty api on its first read.\n function schedulePluginBarApiSync() {\n if (pluginBarApiSyncQueued) return\n pluginBarApiSyncQueued = true\n Qt.callLater(root.syncAllPluginBarApiObjects)\n }\n\n function syncAllPluginBarApiObjects() {\n pluginBarApiSyncQueued = false\n var layoutSnapshot = JSON.stringify(root.layoutConfig || {})\n for (var id in pluginBarApis) {\n var api = pluginBarApis[id]\n if (api) root.syncPluginBarApiObjects(api, layoutSnapshot)\n }\n }\n\n function registerPluginClickTarget(pluginId, target) {\n if (!root.markPluginObject(pluginId, target, \"clickTarget\")) return\n root.registerClickTarget(target)\n }\n\n function unregisterPluginClickTarget(pluginId, target) {\n if (!root.pluginOwnsBarObject(pluginId, target)) return\n root.unregisterClickTarget(target)\n root.unmarkPluginObject(pluginId, target, \"clickTarget\")\n }\n\n // A plugin may read api.activePopout right after asking for its popout, so\n // its own api is brought up to date inline; everyone else waits for the\n // coalesced resync.\n function requestPluginPopout(pluginId, owner) {\n if (!root.markPluginObject(pluginId, owner, \"popout\")) return\n root.requestPopout(owner)\n root.syncPluginBarApiObjects(pluginBarApis[String(pluginId || \"\")])\n }\n\n function releasePluginPopout(pluginId, owner) {\n if (!root.pluginOwnsBarObject(pluginId, owner)) return\n root.releasePopout(owner)\n root.unmarkPluginObject(pluginId, owner, \"popout\")\n root.syncPluginBarApiObjects(pluginBarApis[String(pluginId || \"\")])\n }\n\n function pluginBarApiFor(pluginId, moduleName, registered) {\n var key = String(pluginId || \"\")\n if (!key) return null\n\n var pluginShell = null\n if (registered && root.shell && typeof root.shell.pluginShellForId === \"function\") {\n // Only the trusted built-in bar receives ShellRoot and can request a\n // service-capable facade for the widget it is instantiating.\n pluginShell = root.shell.pluginShellForId(moduleName)\n } else if (root.shell && typeof root.shell.pluginShellForBarEntry === \"function\") {\n // Replacement bars receive a service-less entry facade. Giving an\n // untrusted bar a generic facade factory would let it retrieve another\n // third-party plugin's live service object.\n pluginShell = root.shell.pluginShellForBarEntry(key, moduleName)\n }\n\n if (pluginBarApis[key]) {\n pluginBarApis[key].shell = pluginShell\n return pluginBarApis[key]\n }\n\n var api = pluginBarApiComponent.createObject(null, {\n pluginId: key,\n moduleName: String(moduleName || \"\"),\n shell: pluginShell,\n _showTooltip: function(target, text) { root.showTooltip(target, text) },\n _hideTooltip: function(target) { root.hideTooltip(target) },\n _registerClickTarget: function(target) { root.registerPluginClickTarget(key, target) },\n _unregisterClickTarget: function(target) { root.unregisterPluginClickTarget(key, target) },\n _requestPopout: function(owner) { root.requestPluginPopout(key, owner) },\n _releasePopout: function(owner) { root.releasePluginPopout(key, owner) },\n _switchPanelFrom: function(owner, direction) { return root.switchPanelFrom(owner, direction) },\n _targetBelongsToWindow: function(target, window) { return root.targetBelongsToWindow(target, window) },\n _moduleWidgets: function(requestedId) {\n return String(requestedId || \"\") === String(moduleName || \"\")\n ? root.moduleWidgets(moduleName) : []\n },\n _run: function(command) { root.run(command) },\n _setCenterHoverRevealSuppressed: function(value) {\n root.centerHoverRevealSuppressed = !!value\n }\n })\n if (!api) return null\n root.bindPluginBarApi(api)\n\n var next = ({})\n for (var id in pluginBarApis) next[id] = pluginBarApis[id]\n next[key] = api\n pluginBarApis = next\n return api\n }\n\n function pluginBarApiUsed(pluginId) {\n for (var i = 0; i < moduleSlots.length; i++) {\n var slot = moduleSlots[i]\n if (slot && slot.pluginApiId === pluginId) return true\n }\n return false\n }\n\n function releasePluginObjects(pluginId) {\n var owned = Array.from(pluginObjectOwners.values())\n for (var i = 0; i < owned.length; i++) {\n var record = owned[i]\n if (!record || record.pluginId !== pluginId) continue\n if (record.clickTarget) root.unregisterClickTarget(record.target)\n if (record.popout && root.activePopout === record.target) root.releasePopout(record.target)\n pluginObjectOwners.delete(record.target)\n }\n }\n\n function prunePluginBarApis() {\n var next = ({})\n for (var id in pluginBarApis) {\n var api = pluginBarApis[id]\n if (root.pluginBarApiUsed(id)) {\n next[id] = api\n continue\n }\n root.releasePluginObjects(id)\n if (api && typeof api.destroy === \"function\") api.destroy()\n }\n pluginBarApis = next\n }\n\n onActivePopoutChanged: schedulePluginBarApiSync()\n onClickTargetsChanged: schedulePluginBarApiSync()\n onLayoutConfigChanged: schedulePluginBarApiSync()\n onModuleSlotsChanged: Qt.callLater(prunePluginBarApis)\n\n Component.onDestruction: {\n for (var id in pluginBarApis) {\n root.releasePluginObjects(id)\n if (pluginBarApis[id] && typeof pluginBarApis[id].destroy === \"function\")\n pluginBarApis[id].destroy()\n }\n pluginBarApis = ({})\n }\n\n function registerClickTarget(target) {\n if (!target || clickTargets.indexOf(target) !== -1) return\n var next = clickTargets.slice()\n next.push(target)\n clickTargets = next\n }\n\n function unregisterClickTarget(target) {\n var next = clickTargets.filter(function(item) { return item !== target })\n clickTargets = next\n }\n\n function registerModuleSlot(slot) {\n if (!slot || moduleSlots.indexOf(slot) !== -1) return\n var next = moduleSlots.slice()\n next.push(slot)\n moduleSlots = next\n }\n\n function unregisterModuleSlot(slot) {\n var next = moduleSlots.filter(function(item) { return item !== slot })\n moduleSlots = next\n }\n\n function debugBarGeometry() {\n var out = []\n for (var i = 0; i < moduleSlots.length; i++) {\n var slot = moduleSlots[i]\n if (!slot || !slot.activeItem) continue\n var point = { x: slot.x, y: slot.y }\n try {\n point = slot.mapToItem(null, 0, 0)\n } catch (e) {\n }\n out.push({\n id: slot.moduleName,\n section: slot.region,\n x: Math.round(point.x),\n y: Math.round(point.y),\n width: Math.round(slot.width),\n height: Math.round(slot.height),\n visible: slot.visible === true && slot.width > 0 && slot.height > 0,\n itemVisible: slot.activeItem.visible === true,\n itemWidth: Math.round(slot.activeItem.implicitWidth || 0),\n itemHeight: Math.round(slot.activeItem.implicitHeight || 0)\n })\n }\n return out\n }\n\n function targetWindow(target) {\n return target && target.QsWindow ? target.QsWindow.window : null\n }\n\n function targetBelongsToWindow(target, window) {\n return !!target && !!window && targetWindow(target) === window\n }\n\n function slotWindow(slot) {\n if (!slot) return null\n return targetWindow(slot.activeItem) || targetWindow(slot)\n }\n\n function sameWindow(left, right) {\n if (!left || !right) return false\n if (left === right) return true\n return !!left.screen && !!right.screen && !!left.screen.name && !!right.screen.name && left.screen.name === right.screen.name\n }\n\n function targetTooltipHovered(target) {\n return !!target && target.visible !== false && target.opacity !== 0 && target.tooltipHovered === true\n }\n\n function clearTooltip() {\n tooltipTimer.stop()\n pendingTooltipTarget = null\n pendingTooltipText = \"\"\n tooltipTarget = null\n tooltipText = \"\"\n tooltipShown = false\n }\n\n function clearBarDrag() {\n barDragSource = null\n barDragWindow = null\n barDragScreen = null\n barDragImageUrl = \"\"\n barDragTarget = null\n barDragTargetGeometry = null\n barDragAfter = false\n barDragSceneX = 0\n barDragSceneY = 0\n barDragScreenX = 0\n barDragScreenY = 0\n barDragOffsetX = 0\n barDragOffsetY = 0\n }\n\n function windowScreenPoint(scenePoint, window) {\n var x = scenePoint ? scenePoint.x : 0\n var y = scenePoint ? scenePoint.y : 0\n if (!window || !window.screen) return { x: x, y: y }\n\n if (root.position === \"bottom\")\n y += Math.max(0, window.screen.height - window.height)\n else if (root.position === \"right\")\n x += Math.max(0, window.screen.width - window.width)\n\n return { x: x, y: y }\n }\n\n function barDragScreenPoint(scenePoint) {\n return windowScreenPoint(scenePoint, barDragWindow)\n }\n\n function dropMarkerRect(slot, after) {\n if (!slot) return null\n\n try {\n var slotPoint = slot.mapToItem(null, 0, 0)\n var screenPoint = barDragScreenPoint(slotPoint)\n var thickness = Style.spacing.xs\n if (vertical) {\n return {\n x: screenPoint.x,\n y: screenPoint.y + (after ? slot.height : 0) - thickness / 2,\n width: slot.width,\n height: thickness\n }\n }\n\n return {\n x: screenPoint.x + (after ? slot.width : 0) - thickness / 2,\n y: screenPoint.y,\n width: thickness,\n height: slot.height\n }\n } catch (e) {\n return null\n }\n }\n\n // Split the screen along its diagonals (in normalized space, so widescreens\n // don't bias toward left/right): whichever triangle holds the cursor names\n // the candidate edge.\n function nearestScreenEdge(point, screen) {\n var nx = screen.width > 0 ? Util.clamp(point.x / screen.width, 0, 1) : 0.5\n var ny = screen.height > 0 ? Util.clamp(point.y / screen.height, 0, 1) : 0.5\n\n var edge = \"top\"\n var best = ny\n if (1 - ny < best) { edge = \"bottom\"; best = 1 - ny }\n if (nx < best) { edge = \"left\"; best = nx }\n if (1 - nx < best) { edge = \"right\"; best = 1 - nx }\n return edge\n }\n\n function beginBarMove(window) {\n barMoveWindow = window\n barMoveScreen = window ? window.screen : null\n barMoveCandidate = position\n barMoveActive = true\n }\n\n function updateBarMove(screenPoint) {\n if (!barMoveActive || !barMoveScreen) return\n barMoveCandidate = nearestScreenEdge(screenPoint, barMoveScreen)\n }\n\n function clearBarMove() {\n barMoveActive = false\n barMoveCandidate = \"\"\n barMoveWindow = null\n barMoveScreen = null\n }\n\n function finishBarMove() {\n var edge = barMoveCandidate\n if (!barMoveActive || !edge || edge === position) {\n clearBarMove()\n return\n }\n\n clearBarMove()\n setBarPosition(edge)\n }\n\n function setBarPosition(value) {\n var next = normalizePosition(value)\n if (root.shell && typeof root.shell.mutateShellConfig === \"function\") {\n root.shell.mutateShellConfig(function(config) {\n if (!Util.isPlainObject(config.bar)) config.bar = {}\n config.bar.position = next\n })\n } else {\n root.position = next\n }\n }\n\n function captureBarDragGhost(slot) {\n var item = slot && slot.activeItem ? slot.activeItem : null\n barDragImageUrl = \"\"\n if (!item || typeof item.grabToImage !== \"function\") return\n\n var grabWidth = Math.max(1, Math.ceil(item.width || item.implicitWidth || slot.width || 1))\n var grabHeight = Math.max(1, Math.ceil(item.height || item.implicitHeight || slot.height || 1))\n item.grabToImage(function(result) {\n if (root.barDragSource !== slot || !result || !result.url) return\n root.barDragImageUrl = result.url\n }, Qt.size(grabWidth, grabHeight))\n }\n\n function requestPopout(owner) {\n if (activePopout === owner) return\n if (activePopout) {\n if (\"closeForPopoutSwitch\" in activePopout) activePopout.closeForPopoutSwitch()\n else if (\"close\" in activePopout) activePopout.close()\n }\n activePopout = owner\n }\n\n function releasePopout(owner) {\n if (activePopout === owner) activePopout = null\n }\n\n readonly property bool vertical: position === \"left\" || position === \"right\"\n readonly property int barSize: vertical ? Style.bar.sizeVertical : Style.bar.sizeHorizontal\n\n // Display cutouts (a camera notch) the platform's own package describes in\n // the fixed platform root, which no environment variable moves. Most machines\n // have none. It is read as the shell starts (blockLoading), so a bar surface\n // knows before it maps whether its screen may have one. See\n // BarModel.parseCutouts.\n readonly property var displayCutouts: displayCutoutsFile.missing ? [] : BarModel.parseCutouts(displayCutoutsFile.text())\n FileView {\n id: displayCutoutsFile\n\n // A file that went away describes nothing, whatever text() still holds.\n property bool missing: false\n\n path: \"/usr/share/omarchy-platform/display-cutouts.json\"\n blockLoading: true\n watchChanges: true\n printErrors: false\n onLoaded: missing = false\n onLoadFailed: missing = true\n onFileChanged: reload()\n }\n\n // The physical mode Hyprland reports for a screen, as hyprctl monitors does.\n // Qt's whole-number devicePixelRatio can't rebuild it at a fractional scale.\n function panelModeFor(screen) {\n var monitor = screen ? Hyprland.monitorFor(screen) : null\n return monitor ? ({\n width: monitor.width,\n height: monitor.height,\n transform: monitor.lastIpcObject ? monitor.lastIpcObject.transform : 0\n }) : null\n }\n\n // How thick the bar is on a screen. A top bar shorter than a panel's camera\n // cutout leaves a sliver of every window peeking out beside the camera, so\n // the cutout is this panel's minimum sensible top-bar height. An\n // intentionally taller bar still wins.\n function thicknessFor(screen) {\n if (root.vertical || !screen) return root.barSize\n return Math.max(root.barSize, BarModel.notchFloor(root.displayCutouts, root.position, screen.name, screen.width, screen.height, screen.devicePixelRatio, root.panelModeFor(screen), Style.bar.notchHeight))\n }\n\n // Each screen's bar thickness, by screen name: barSize, or more where a notch\n // floor raises a top bar. Toasts and plugins clear the bar by it; barSize\n // stays the configured size the widgets are drawn at.\n readonly property var screenBarSizes: {\n var sizes = ({})\n var screens = Quickshell.screens\n for (var i = 0; i < screens.length; i++) sizes[screens[i].name] = root.thicknessFor(screens[i])\n return sizes\n }\n\n function barSizeFor(screenName) {\n return BarModel.barSizeFor(root.screenBarSizes, screenName, root.barSize)\n }\n\n function normalizePosition(value) {\n return BarModel.normalizePosition(value)\n }\n\n // Apply tray-pinning on top of the shared layout normalization so the\n // bar host and scriptable config helpers can't drift on entry shape.\n function normalizeLayout(layout) {\n var normalized = Util.normalizeLayout(Util.isPlainObject(layout) ? layout : fallbackBarConfig.layout)\n return {\n left: pinTrayToInner(normalized.left, \"left\"),\n center: pinTrayToInner(normalized.center, \"center\"),\n right: pinTrayToInner(normalized.right, \"right\")\n }\n }\n\n // The tray drawer reveals inward (away from the bar edge). Place it at the\n // section's inner edge: start of the right section, end of the left/center\n // sections. The drawer's reserved space then sits next to the bar center,\n // not stranded mid-section.\n function pinTrayToInner(entries, section) {\n return BarModel.pinTrayToInner(entries, section)\n }\n\n function applyBarConfig() {\n var config = Util.isPlainObject(barConfig) ? barConfig : fallbackBarConfig\n\n position = normalizePosition(config.position)\n // opaque, glassy or none; a config from before background says\n // transparent instead.\n var look = config.background || (config.transparent === true ? \"none\" : \"opaque\")\n setRequestedTransparency(look === \"none\")\n // A bar going clear waits for its text color before dropping its\n // background, so a glassy one stays glassy until then rather than\n // flashing opaque. Once clear, transparent wins over a stale glassy.\n if (look !== \"none\") glassy = look === \"glassy\"\n if (look !== glassSyncedLook) {\n glassSyncedLook = look\n Util.execDetached(\"omarchy-bar sync-glass\")\n }\n centerAnchor = Util.canonicalWidgetId(config.centerAnchor || \"\")\n\n // layoutEntries feeds plain JS arrays to the module Repeaters, and QML\n // cannot diff those: reassigning layoutConfig rebuilds every widget on\n // every monitor. When a shell.json write only changed inline widget\n // settings, patch the live layout and running widgets in place instead.\n var next = normalizeLayout(config.layout)\n var delta = BarModel.inlineSettingsDelta(layoutConfig, next)\n if (delta) {\n applySettingsDelta(delta)\n return\n }\n layoutConfig = next\n barConfigSerial++\n }\n\n function applySettingsDelta(delta) {\n for (var i = 0; i < delta.length; i++) {\n var change = delta[i]\n layoutConfig[change.region][change.index] = change.entry\n var settings = entrySettings(change.entry)\n for (var s = 0; s < moduleSlots.length; s++) {\n var slot = moduleSlots[s]\n if (!slot || slot.region !== change.region || slot.moduleName !== entryId(change.entry)) continue\n var item = slot.activeItem\n if (item && \"settings\" in item) item.settings = settings\n }\n }\n }\n\n onBarConfigChanged: applyBarConfig()\n\n function layoutEntries(region) {\n var serial = barConfigSerial\n var entries = layoutConfig ? layoutConfig[region] : null\n return Array.isArray(entries) ? entries : []\n }\n\n // Tab order for the panels in one bar region. Scoped to a single bar surface\n // so tabbing walks the bar the open panel belongs to instead of hopping the\n // panel to another monitor's copy of the same widget.\n function panelNavigationSlots(region, window) {\n var entries = layoutEntries(region)\n var slots = []\n for (var i = 0; i < entries.length; i++) {\n var id = entryId(entries[i])\n for (var j = 0; j < moduleSlots.length; j++) {\n var slot = moduleSlots[j]\n if (!slot || slot.region !== region || slot.moduleName !== id) continue\n if (window && !sameWindow(slotWindow(slot), window)) continue\n var item = slot.activeItem\n if (!item || item.visible !== true || slot.visible !== true || slot.width <= 0 || slot.height <= 0) continue\n if (typeof item.open !== \"function\" || typeof item.close !== \"function\" || item.opened === undefined) continue\n slots.push(slot)\n break\n }\n }\n return slots\n }\n\n // The Nth panel in a bar region, counted the way the bar reads: layout order,\n // and only the panels actually on screen. A widget with no panel (the tray)\n // and one that is hiding itself are passed over, so the number lands on the\n // Nth panel icon the user can see rather than the Nth layout entry.\n // One-based, because it exists for hotkeys; anything else lands on no slot.\n //\n // Counting any bar surface is enough: every monitor lays its bar out from the\n // one layout, and summoning the id routes through pickPanelSlot, which opens\n // the focused monitor's copy whichever surface was counted.\n function panelWidgetIdAt(region, index) {\n var slots = panelNavigationSlots(String(region || \"\"), null)\n var slot = slots[Math.round(Number(index)) - 1]\n return slot ? String(slot.moduleName || \"\") : \"\"\n }\n\n function switchPanelFrom(owner, direction) {\n if (!owner) return false\n\n var currentSlot = null\n for (var i = 0; i < moduleSlots.length; i++) {\n var slot = moduleSlots[i]\n if (slot && slot.activeItem === owner) {\n currentSlot = slot\n break\n }\n }\n if (!currentSlot) return false\n\n var slots = panelNavigationSlots(currentSlot.region, slotWindow(currentSlot))\n if (slots.length < 2) return false\n\n var currentIndex = -1\n for (var j = 0; j < slots.length; j++) {\n if (slots[j] === currentSlot) {\n currentIndex = j\n break\n }\n }\n if (currentIndex < 0) return false\n\n var step = direction < 0 ? -1 : 1\n var nextSlot = slots[(currentIndex + step + slots.length) % slots.length]\n if (!nextSlot || !nextSlot.activeItem || nextSlot.activeItem === owner) return false\n\n nextSlot.activeItem.open()\n return true\n }\n\n // Every live instance of a widget id. A bar surface is built per monitor, so\n // a widget that appears once in the layout is still live once per screen.\n function moduleWidgets(pluginId) {\n var id = String(pluginId || \"\")\n var items = []\n if (!id) return items\n for (var i = 0; i < moduleSlots.length; i++) {\n var slot = moduleSlots[i]\n if (!slot || !slot.activeItem || slot.moduleName !== id) continue\n items.push(slot.activeItem)\n }\n return items\n }\n\n function slotScreenName(slot) {\n var window = slotWindow(slot)\n return window && window.screen ? String(window.screen.name || \"\") : \"\"\n }\n\n // The output Hyprland has focused, which is where a keyboard-summoned panel\n // belongs. Empty until Hyprland reports one, which leaves panel routing on\n // its per-monitor fallback rather than guessing at an output.\n function focusedScreenName() {\n var monitor = Hyprland.focusedMonitor\n return monitor ? String(monitor.name || \"\") : \"\"\n }\n\n // Resolve the live bar-widget instance for a plugin id (e.g. \"omarchy.bluetooth\").\n // Only widgets that expose popup open/close methods count; plain indicators\n // (clock, workspaces, tray) return null. Used by shell.summon/toggle so\n // panel hotkeys route through the bar instead of a per-target IPC handler\n // that only reaches whichever per-monitor instance claimed the target.\n function findPanelWidget(pluginId) {\n var id = String(pluginId || \"\")\n if (!id) return null\n var candidates = []\n for (var i = 0; i < moduleSlots.length; i++) {\n var slot = moduleSlots[i]\n if (!slot || !slot.activeItem) continue\n if (slot.moduleName !== id) continue\n var item = slot.activeItem\n if (typeof item.open !== \"function\" || typeof item.close !== \"function\" || item.opened === undefined) continue\n candidates.push({ slot: slot, screenName: slotScreenName(slot), opened: item.opened === true })\n }\n // One copy per monitor, plus a zero-size placeholder for anchored center\n // modules. See BarModel.pickPanelSlot for which one a hotkey acts on.\n var chosen = BarModel.pickPanelSlot(candidates, focusedScreenName())\n return chosen ? chosen.activeItem : null\n }\n\n function summonBarWidget(pluginId) {\n var item = findPanelWidget(pluginId)\n if (!item || typeof item.open !== \"function\") return false\n item.open()\n return true\n }\n\n function hideBarWidget(pluginId) {\n var item = findPanelWidget(pluginId)\n if (!item || typeof item.close !== \"function\") return false\n item.close()\n return true\n }\n\n function isBarWidgetOpen(pluginId) {\n var item = findPanelWidget(pluginId)\n return !!item && item.opened === true\n }\n\n function entrySettings(entry) {\n return BarModel.entrySettings(entry)\n }\n\n function entryId(entry) {\n return BarModel.entryId(entry)\n }\n\n function moduleString(entry, key, fallback) {\n return BarModel.moduleString(entry, key, fallback)\n }\n\n function entryIndex(entries, name) {\n return BarModel.entryIndex(entries, name)\n }\n\n function entriesBefore(entries, name) {\n return BarModel.entriesBefore(entries, name)\n }\n\n function entriesAfter(entries, name) {\n return BarModel.entriesAfter(entries, name)\n }\n\n function canonicalWidgetId(name) {\n return Util.canonicalWidgetId(name)\n }\n\n function expandPath(path) {\n return BarModel.expandPath(path, home)\n }\n\n function customModuleSafeName(name) {\n return BarModel.customModuleSafeName(name)\n }\n\n function customModuleType(entry) {\n return BarModel.customModuleType(entry)\n }\n\n function customModuleSource(entry) {\n var source = BarModel.customModulePath(entry, home, omarchyConfigDir)\n return source ? Util.fileUrl(source) : \"\"\n }\n\n Component.onCompleted: applyBarConfig()\n\n // Revealing the indicators widens their section, which can slide a neighbour\n // under a stationary pointer. Collapsing on that un-hover would move it back\n // out and re-open the peek, so hold until the pointer leaves the bar.\n function setCenterSectionHovered(hovered) {\n centerSectionHovered = hovered\n if (hovered) {\n centerSectionRevealTimer.stop()\n centerSectionRevealHeld = true\n } else {\n centerSectionRevealTimer.restart()\n }\n }\n\n function setBarHovered(hovered) {\n barHoverCount = Math.max(0, barHoverCount + (hovered ? 1 : -1))\n if (barHoverCount === 0) centerSectionRevealTimer.restart()\n }\n\n function setCenterHoverRevealSuppressed(value) {\n centerHoverRevealSuppressed = !!value\n }\n\n Timer {\n id: centerSectionRevealTimer\n interval: 120\n // Collapse only. Opening the peek is the center section's own gesture, done\n // in setCenterSectionHovered, so a timer left pending by a pointer that dipped\n // off the bar and came back cannot reveal indicators it never pointed at.\n onTriggered: if (!root.centerSectionHovered && !root.barHovered) root.centerSectionRevealHeld = false\n }\n\n function run(command) {\n if (!command) return\n\n Util.execDetached(command)\n }\n\n // Steps the bar background from clear to glassy to opaque and around. Through\n // omarchy-bar, which keeps Hyprland's blur behind a glassy bar in step.\n function cycleBackground() {\n Util.execDetached(\"omarchy-bar background cycle\")\n }\n\n function rawLayoutSection(config, region) {\n if (!Util.isPlainObject(config.bar)) config.bar = {}\n if (!Util.isPlainObject(config.bar.layout)) config.bar.layout = {}\n if (!Array.isArray(config.bar.layout[region])) config.bar.layout[region] = []\n\n return config.bar.layout[region]\n }\n\n function rawEntryIndex(entries, name) {\n for (var i = 0; i < entries.length; i++) {\n if (root.entryId(entries[i]) === name) return i\n }\n\n return -1\n }\n\n function moveModuleInConfig(config, fromRegion, fromName, toRegion, beforeName) {\n var fromEntries = rawLayoutSection(config, fromRegion)\n var toEntries = rawLayoutSection(config, toRegion)\n var fromIndex = rawEntryIndex(fromEntries, fromName)\n if (fromIndex < 0) return false\n\n var toIndex = beforeName ? rawEntryIndex(toEntries, beforeName) : toEntries.length\n if (toIndex < 0) toIndex = toEntries.length\n\n if (fromRegion === toRegion && fromIndex === toIndex) return false\n\n var movedEntry = fromEntries[fromIndex]\n fromEntries.splice(fromIndex, 1)\n\n if (fromRegion === toRegion && fromIndex < toIndex) toIndex -= 1\n if (toIndex < 0) toIndex = 0\n if (toIndex > toEntries.length) toIndex = toEntries.length\n if (fromRegion === toRegion && fromIndex === toIndex) {\n fromEntries.splice(fromIndex, 0, movedEntry)\n return false\n }\n\n toEntries.splice(toIndex, 0, movedEntry)\n return true\n }\n\n function dropBarModule(source, toRegion, beforeName) {\n if (!source || !source.region || !source.moduleName || !toRegion) return false\n if (source.region === toRegion && source.moduleName === beforeName) return false\n if (!root.shell || typeof root.shell.mutateShellConfig !== \"function\") return false\n\n var changed = false\n root.shell.mutateShellConfig(function(config) {\n changed = moveModuleInConfig(config, source.region, source.moduleName, toRegion, beforeName)\n })\n return changed\n }\n\n function moduleDropAtScene(scenePoint, sourceSlot) {\n var sourceWindow = root.slotWindow(sourceSlot) || root.barDragWindow\n if (sourceWindow && sourceWindow.contentItem) {\n var barPoint = sourceWindow.contentItem.mapFromItem(null, scenePoint.x, scenePoint.y)\n if (barPoint.x < 0 || barPoint.x > sourceWindow.contentItem.width ||\n barPoint.y < 0 || barPoint.y > sourceWindow.contentItem.height)\n return null\n }\n\n var candidates = []\n for (var i = 0; i < moduleSlots.length; i++) {\n var slot = moduleSlots[i]\n if (!slot || slot === sourceSlot || !slot.visible || slot.width <= 0 || slot.height <= 0) continue\n if (sourceWindow && !root.sameWindow(root.slotWindow(slot), sourceWindow)) continue\n\n var slotPoint = { x: slot.x, y: slot.y }\n try {\n slotPoint = slot.mapToItem(null, 0, 0)\n } catch (e) {\n }\n\n candidates.push({\n slot: slot,\n x: slotPoint.x,\n y: slotPoint.y,\n width: slot.width,\n height: slot.height\n })\n }\n\n return BarModel.nearestDropTarget(candidates, scenePoint, root.vertical)\n }\n\n function visibleModuleSlot(region, name, sourceSlot) {\n var sourceWindow = root.slotWindow(sourceSlot) || root.barDragWindow\n for (var i = 0; i < moduleSlots.length; i++) {\n var slot = moduleSlots[i]\n if (!slot || slot === sourceSlot || slot.region !== region || slot.moduleName !== name ||\n !slot.visible || slot.width <= 0 || slot.height <= 0) continue\n if (sourceWindow && !root.sameWindow(root.slotWindow(slot), sourceWindow)) continue\n return slot\n }\n\n return null\n }\n\n function nextVisibleModuleName(region, afterName, sourceSlot) {\n var entries = layoutEntries(region)\n var found = false\n for (var i = 0; i < entries.length; i++) {\n var name = entryId(entries[i])\n if (!found) {\n found = name === afterName\n continue\n }\n\n if (visibleModuleSlot(region, name, sourceSlot)) return name\n }\n\n return \"\"\n }\n\n function dropBarModuleAtTarget(sourceSlot, targetSlot, afterTarget) {\n if (!sourceSlot || !targetSlot) return false\n\n var beforeName = afterTarget ? nextVisibleModuleName(targetSlot.region, targetSlot.moduleName, sourceSlot) : targetSlot.moduleName\n return dropBarModule(sourceSlot, targetSlot.region, beforeName)\n }\n\n function moduleTargetClickable(target) {\n return target\n && target.visible !== false\n && target.opacity !== 0\n && target.interactive !== false\n && target.pressable !== false\n && target.concealed !== true\n && typeof target.triggerPress === \"function\"\n }\n\n function moduleClickTargetAt(slot, localX, localY) {\n for (var i = clickTargets.length - 1; i >= 0; i--) {\n var target = clickTargets[i]\n if (!moduleTargetClickable(target)) continue\n\n var targetPoint = { x: localX, y: localY }\n try {\n targetPoint = slot.mapToItem(target, localX, localY)\n } catch (e) {\n continue\n }\n\n if (targetPoint.x >= 0 && targetPoint.x <= target.width &&\n targetPoint.y >= 0 && targetPoint.y <= target.height) {\n return target\n }\n }\n\n if (moduleTargetClickable(slot.activeItem)) return slot.activeItem\n return null\n }\n\n function pressModuleClickTarget(slot, button, localX, localY) {\n var target = moduleClickTargetAt(slot, localX, localY)\n if (!target) return false\n\n target.triggerPress(button)\n return true\n }\n\n function colorHex(colorValue) {\n var c = colorValue\n if (typeof c === \"string\") c = Qt.color(c)\n function hexChannel(value) {\n var s = Math.round(Util.clamp(value, 0, 1) * 255).toString(16)\n return s.length < 2 ? \"0\" + s : s\n }\n return \"#\" + hexChannel(c.r) + hexChannel(c.g) + hexChannel(c.b)\n }\n\n function setRequestedTransparency(value) {\n var nextTransparent = value === true\n requestedTransparent = nextTransparent\n if (!nextTransparent) {\n foregroundAnimationEnabled = false\n useTransparentForeground = false\n transparent = false\n transparentForeground = themeForeground\n restoreForegroundAnimation()\n return\n }\n scheduleTransparentForegroundRefresh()\n }\n\n function restoreForegroundAnimation() {\n Qt.callLater(function() {\n Qt.callLater(function() { root.foregroundAnimationEnabled = true })\n })\n }\n\n function scheduleTransparentForegroundRefresh() {\n if (!requestedTransparent) {\n transparentForeground = themeForeground\n return\n }\n transparentForegroundTimer.restart()\n }\n\n function refreshTransparentForeground() {\n if (!requestedTransparent || transparentForegroundProc.running) return\n\n transparentForegroundProc.command = [\n \"omarchy-bar-text-color\",\n root.position,\n String(root.barSize),\n colorHex(root.themeForeground),\n colorHex(root.themeContrastForeground)\n ]\n transparentForegroundProc.running = true\n }\n\n onRequestedTransparentChanged: scheduleTransparentForegroundRefresh()\n onPositionChanged: scheduleTransparentForegroundRefresh()\n onThemeForegroundChanged: scheduleTransparentForegroundRefresh()\n onThemeContrastForegroundChanged: scheduleTransparentForegroundRefresh()\n\n Timer {\n id: transparentForegroundTimer\n interval: 120\n repeat: false\n onTriggered: root.refreshTransparentForeground()\n }\n\n Process {\n id: transparentForegroundProc\n stdout: SplitParser {\n onRead: function(line) {\n var value = String(line || \"\").trim()\n if (!/^#[0-9A-Fa-f]{6}$/.test(value)) return\n\n root.foregroundAnimationEnabled = false\n root.transparentForeground = value\n if (root.requestedTransparent) {\n root.useTransparentForeground = true\n root.transparent = true\n }\n root.restoreForegroundAnimation()\n }\n }\n }\n\n FileView {\n path: root.stateHome + \"/omarchy/current\"\n watchChanges: true\n printErrors: false\n onFileChanged: root.scheduleTransparentForegroundRefresh()\n }\n\n function runProcess(process) {\n if (!process.running)\n process.running = true\n }\n\n function showTooltip(target, text) {\n clearTooltip()\n\n if (!targetTooltipHovered(target) || !text) {\n tooltipRequest += 1\n return\n }\n\n var request = tooltipRequest + 1\n tooltipRequest = request\n pendingTooltipTarget = target\n pendingTooltipText = text\n\n Qt.callLater(function() {\n if (request !== tooltipRequest) return\n if (!targetTooltipHovered(pendingTooltipTarget)) {\n clearTooltip()\n return\n }\n tooltipTarget = pendingTooltipTarget\n tooltipText = pendingTooltipText\n pendingTooltipTarget = null\n pendingTooltipText = \"\"\n tooltipTimer.restart()\n })\n }\n\n function hideTooltip(target) {\n if (tooltipTarget !== target && pendingTooltipTarget !== target) return\n\n tooltipRequest += 1\n clearTooltip()\n }\n\n Timer {\n id: tooltipTimer\n interval: 400\n onTriggered: {\n if (root.targetTooltipHovered(root.tooltipTarget)) root.tooltipShown = true\n else root.clearTooltip()\n }\n }\n\n Timer {\n interval: 100\n running: root.tooltipShown\n repeat: true\n onTriggered: if (!root.targetTooltipHovered(root.tooltipTarget)) root.hideTooltip(root.tooltipTarget)\n }\n\n // Presence of the `bar-off` flag = bar hidden. Watching the parent toggles\n // directory because FileView can't observe a file that doesn't exist yet,\n // and the flag is created/removed by `omarchy-toggle-bar`.\n Process {\n id: barHiddenProbe\n running: true\n command: [\"bash\", \"-c\", \"[[ -f $HOME/.local/state/omarchy/toggles/bar-off ]] && echo yes || echo no\"]\n stdout: SplitParser { onRead: function(line) { root.barHidden = String(line).trim() === \"yes\" } }\n }\n FileView {\n path: root.home + \"/.local/state/omarchy/toggles\"\n watchChanges: true\n printErrors: false\n onFileChanged: barHiddenProbe.running = true\n }\n\n // The directory watch can permanently stop delivering events after flag\n // changes land in quick succession, stranding the bar off screen until the\n // shell restarts. `omarchy-toggle-bar` nudges this after flipping the flag\n // so the probe re-reads it even when the watch has gone quiet.\n ShellIpc {\n target: \"omarchy.bar\"\n\n // Start rather than restart: a probe already in flight was launched by the\n // directory watch after the flag flipped, so its answer is current, and\n // killing it here can swallow the result entirely.\n function syncHidden(): void {\n barHiddenProbe.running = true\n }\n }\n\n Variants {\n model: Quickshell.screens\n\n delegate: Component {\n BarPanel {\n required property var modelData\n\n screen: modelData\n }\n }\n }\n\n Variants {\n model: Quickshell.screens\n\n delegate: Component {\n DragGhostPanel {\n required property var modelData\n\n screen: modelData\n ghostScreen: modelData\n }\n }\n }\n\n Variants {\n model: Quickshell.screens\n\n delegate: Component {\n BarMoveGhostPanel {\n required property var modelData\n\n screen: modelData\n ghostScreen: modelData\n }\n }\n }\n\n component BarPanel: PanelWindow {\n id: barWindow\n\n // Hiding parks the bar just past its screen edge instead of unmapping it.\n // Unmapping frees the layer surface and the whole scene graph, so every\n // reveal has to rebuild them — new surface, re-shaped glyphs, re-uploaded\n // textures — which measures ~150ms against ~20ms to tear down. Parking\n // keeps the surface alive, so showing is only a margin change.\n //\n // A top bar that can't tell its notch floor yet waits for Hyprland's mode\n // before it maps (see BarModel.cutoutPending), so it maps at its floor\n // instead of growing once the windows are laid out. The wait ends once, for\n // good: when the mode settles it, or after two seconds without one.\n visible: !remapGuard.remapping && (cutoutWaitOver || !cutoutPending)\n exclusionMode: root.barHidden ? ExclusionMode.Ignore : ExclusionMode.Auto\n\n ScreenMoveRemap {\n id: remapGuard\n window: barWindow\n }\n\n // Parked by its full thickness, which a notch floor may make more than\n // barSize, so no strip of it stays on screen.\n margins {\n top: root.barHidden && root.position === \"top\" ? -barWindow.thickness : 0\n bottom: root.barHidden && root.position === \"bottom\" ? -barWindow.thickness : 0\n left: root.barHidden && root.position === \"left\" ? -barWindow.thickness : 0\n right: root.barHidden && root.position === \"right\" ? -barWindow.thickness : 0\n }\n\n anchors {\n top: root.position === \"top\" || root.vertical\n bottom: root.position === \"bottom\" || root.vertical\n left: root.position === \"left\" || !root.vertical\n right: root.position === \"right\" || !root.vertical\n }\n\n readonly property var panelMode: root.panelModeFor(screen)\n\n readonly property bool centerBesideRight: BarModel.centerBesideRight(root.displayCutouts, root.position, screen.name, screen.width, screen.height, screen.devicePixelRatio, panelMode)\n\n readonly property bool cutoutPending: BarModel.cutoutPending(root.displayCutouts, root.position, screen.name, screen.width, screen.height, screen.devicePixelRatio, panelMode)\n property bool cutoutWaitOver: false\n onCutoutPendingChanged: if (!cutoutPending) cutoutWaitOver = true\n Component.onCompleted: if (!cutoutPending) cutoutWaitOver = true\n\n Timer {\n interval: 2000\n running: barWindow.cutoutPending && !barWindow.cutoutWaitOver\n onTriggered: barWindow.cutoutWaitOver = true\n }\n\n // The same thickness the bar publishes for its screen (screenBarSizes).\n readonly property int thickness: root.thicknessFor(screen)\n\n implicitWidth: root.vertical ? thickness : 0\n implicitHeight: root.vertical ? 0 : thickness\n color: root.transparent ? \"transparent\" : (root.glassy ? root.glassBackground : root.background)\n surfaceFormat.opaque: false\n WlrLayershell.namespace: \"omarchy-bar\"\n WlrLayershell.layer: WlrLayer.Top\n\n Loader {\n anchors.fill: parent\n sourceComponent: root.vertical ? verticalBar : horizontalBar\n\n // A child of the loader, not a sibling of the sections: an ancestor stays\n // hovered while the pointer is over a widget, where a sibling would lose\n // hover to the section the pointer entered.\n HoverHandler {\n onHoveredChanged: root.setBarHovered(hovered)\n // Unplugging a monitor destroys its bar without a leave event, which\n // would strand this surface's tally and hold the peek open for good.\n Component.onDestruction: if (hovered) root.setBarHovered(false)\n }\n }\n\n PopupWindow {\n id: tooltipWindow\n\n visible: root.tooltipShown && root.tooltipTarget !== null && root.tooltipText !== \"\" && root.targetBelongsToWindow(root.tooltipTarget, barWindow)\n color: \"transparent\"\n implicitWidth: Math.ceil(tooltipBubble.implicitWidth)\n implicitHeight: Math.ceil(tooltipBubble.implicitHeight)\n\n anchor {\n id: tooltipAnchor\n window: barWindow\n adjustment: PopupAdjustment.Slide\n edges: Edges.Top | Edges.Left\n gravity: Edges.Bottom | Edges.Right\n rect.width: 1\n rect.height: 1\n\n onAnchoring: {\n var target = root.tooltipTarget\n if (!root.targetBelongsToWindow(target, barWindow)) return\n\n var popupWidth = tooltipWindow.implicitWidth\n var popupHeight = tooltipWindow.implicitHeight\n var localX = target.width / 2 - popupWidth / 2\n var localY = target.height + 6\n\n if (root.position === \"bottom\") {\n localY = -popupHeight - 6\n } else if (root.position === \"left\") {\n localX = target.width + 6\n localY = target.height / 2 - popupHeight / 2\n } else if (root.position === \"right\") {\n localX = -popupWidth - 6\n localY = target.height / 2 - popupHeight / 2\n }\n\n var point = barWindow.contentItem.mapFromItem(target, localX, localY)\n tooltipAnchor.rect.x = Math.round(point.x)\n tooltipAnchor.rect.y = Math.round(point.y)\n }\n }\n\n BorderSurface {\n id: tooltipBubble\n implicitWidth: tooltipLabel.implicitWidth + 20\n implicitHeight: tooltipLabel.implicitHeight + 14\n color: Commons.Color.tooltip.background\n borderSpec: Border.surfaceSpec(\"tooltip\", \"border\", Commons.Color.tooltip.border, 1)\n radius: Style.cornerRadius\n\n Text {\n id: tooltipLabel\n textFormat: Text.PlainText\n anchors.centerIn: parent\n text: root.tooltipText\n color: Commons.Color.tooltip.text\n font.family: root.fontFamily\n font.pixelSize: Style.font.body\n horizontalAlignment: Text.AlignHCenter\n verticalAlignment: Text.AlignVCenter\n }\n }\n }\n\n Component {\n id: horizontalBar\n\n Item {\n anchors.fill: parent\n\n CenterModules {\n anchors.fill: parent\n entries: barWindow.centerBesideRight ? [] : root.layoutEntries(\"center\")\n }\n\n LeftModules {\n anchors.left: parent.left\n anchors.leftMargin: Style.space(8)\n anchors.verticalCenter: parent.verticalCenter\n }\n\n RightModules {\n id: rightModules\n anchors.right: parent.right\n anchors.rightMargin: Style.space(8)\n anchors.verticalCenter: parent.verticalCenter\n }\n\n // Keeps the center region, so settings pushes, drag and drop, and panel\n // routing still address it. The gap lets a drop at the seam land in\n // the section the pointer is nearer to.\n ModuleList {\n entries: barWindow.centerBesideRight ? root.layoutEntries(\"center\") : []\n region: \"center\"\n anchors.right: rightModules.left\n anchors.rightMargin: Style.space(4)\n anchors.verticalCenter: parent.verticalCenter\n }\n }\n }\n\n Component {\n id: verticalBar\n\n Item {\n anchors.fill: parent\n\n CenterModules { anchors.fill: parent }\n\n LeftModules {\n anchors.top: parent.top\n anchors.topMargin: Style.space(8)\n anchors.horizontalCenter: parent.horizontalCenter\n }\n\n RightModules {\n anchors.bottom: parent.bottom\n anchors.bottomMargin: Style.space(8)\n anchors.horizontalCenter: parent.horizontalCenter\n }\n }\n }\n }\n\n Component { id: emptyModuleComponent; Item { implicitWidth: 0; implicitHeight: 0; visible: false } }\n\n component DragGhostPanel: PanelWindow {\n id: ghostWindow\n\n required property var ghostScreen\n readonly property bool screenMatches: root.barDragScreen === ghostScreen ||\n (root.barDragScreen && ghostScreen && root.barDragScreen.name && ghostScreen.name && root.barDragScreen.name === ghostScreen.name)\n readonly property bool active: root.barDragSource && root.barDragScreen && screenMatches\n readonly property var sourceItem: root.barDragSource ? root.barDragSource.activeItem : null\n readonly property int ghostPadding: Style.space(1)\n readonly property int ghostWidth: sourceItem ? Math.max(1, Math.ceil(sourceItem.width)) : 1\n readonly property int ghostHeight: sourceItem ? Math.max(1, Math.ceil(sourceItem.height)) : 1\n\n visible: active && sourceItem !== null\n color: \"transparent\"\n exclusionMode: ExclusionMode.Ignore\n WlrLayershell.namespace: \"omarchy-bar-drag-ghost\"\n WlrLayershell.layer: WlrLayer.Overlay\n WlrLayershell.keyboardFocus: WlrKeyboardFocus.None\n\n anchors {\n top: true\n bottom: true\n left: true\n right: true\n }\n\n // Visual-only drag feedback. Keep the input region empty so the ghost can\n // sit under the cursor without stealing the MouseArea's active pointer grab.\n mask: Region {}\n\n Item {\n visible: ghostWindow.visible\n x: Math.round(root.barDragScreenX - root.barDragOffsetX - ghostWindow.ghostPadding)\n y: Math.round(root.barDragScreenY - root.barDragOffsetY - ghostWindow.ghostPadding)\n width: ghostWindow.ghostWidth + ghostWindow.ghostPadding * 2\n height: ghostWindow.ghostHeight + ghostWindow.ghostPadding * 2\n\n BorderSurface {\n anchors.fill: parent\n color: root.transparent ? \"transparent\" : root.background\n borderSpec: Border.flat(root.barForeground, 1)\n radius: Math.min(Style.cornerRadius, height / 2)\n opacity: root.transparent ? 0.45 : 0.94\n }\n\n Image {\n anchors.fill: parent\n anchors.margins: ghostWindow.ghostPadding\n source: root.barDragImageUrl\n fillMode: Image.Stretch\n smooth: true\n opacity: 0.84\n }\n }\n\n Rectangle {\n readonly property var targetRect: root.barDragTargetGeometry\n\n visible: ghostWindow.active && targetRect !== null\n x: targetRect ? Math.round(targetRect.x) : 0\n y: targetRect ? Math.round(targetRect.y) : 0\n width: targetRect ? targetRect.width : 0\n height: targetRect ? targetRect.height : 0\n color: Commons.Color.accent\n radius: Math.min(width, height) / 2\n }\n }\n\n component BarMoveGhostPanel: PanelWindow {\n id: moveGhostWindow\n\n required property var ghostScreen\n readonly property bool screenMatches: root.barMoveScreen === ghostScreen ||\n (root.barMoveScreen && ghostScreen && root.barMoveScreen.name && ghostScreen.name && root.barMoveScreen.name === ghostScreen.name)\n visible: root.barMoveActive && screenMatches\n color: \"transparent\"\n exclusionMode: ExclusionMode.Ignore\n WlrLayershell.namespace: \"omarchy-bar-move-ghost\"\n WlrLayershell.layer: WlrLayer.Overlay\n WlrLayershell.keyboardFocus: WlrKeyboardFocus.None\n\n anchors {\n top: true\n bottom: true\n left: true\n right: true\n }\n\n // Visual-only preview of the candidate edge. Keep the input region empty\n // so the overlay never steals the gesture area's active pointer grab.\n mask: Region {}\n\n // One fixed-geometry slab per edge, crossfaded on candidate changes.\n // Resizing a single slab between edges repaints mid-transition and\n // flickers; fading between static ones does not.\n Repeater {\n model: [\"top\", \"bottom\", \"left\", \"right\"]\n\n BorderSurface {\n id: edgeSlab\n\n required property string modelData\n readonly property bool edgeVertical: modelData === \"left\" || modelData === \"right\"\n readonly property int edgeSize: edgeVertical ? Style.bar.sizeVertical : Style.bar.sizeHorizontal\n\n x: modelData === \"right\" ? parent.width - edgeSize : 0\n y: modelData === \"bottom\" ? parent.height - edgeSize : 0\n width: edgeVertical ? edgeSize : parent.width\n height: edgeVertical ? parent.height : edgeSize\n color: root.transparent ? \"transparent\" : root.background\n borderSpec: Border.flat(root.barForeground, 1)\n visible: opacity > 0\n opacity: root.barMoveCandidate === modelData ? (root.transparent ? 0.45 : 0.7) : 0\n\n Behavior on opacity {\n NumberAnimation { duration: Style.duration(140); easing.type: Easing.OutCubic }\n }\n }\n }\n }\n\n function findCenterAnchorEntry(entries) {\n var idx = root.entryIndex(entries, root.centerAnchor)\n return idx === -1 ? null : entries[idx]\n }\n\n component LeftModules: ModuleList {\n entries: root.layoutEntries(\"left\")\n region: \"left\"\n }\n\n component RightModules: ModuleList {\n entries: root.layoutEntries(\"right\")\n region: \"right\"\n }\n\n component CenterModules: Item {\n id: centerRoot\n\n property var entries: root.layoutEntries(\"center\")\n readonly property bool hasAnchor: root.entryIndex(entries, root.centerAnchor) !== -1\n readonly property var anchorEntry: root.findCenterAnchorEntry(entries)\n\n Loader {\n anchors.fill: parent\n sourceComponent: root.vertical ? verticalCenterModules : horizontalCenterModules\n }\n\n Component {\n id: horizontalCenterModules\n\n Item {\n anchors.fill: parent\n\n CenterGestureArea { anchors.fill: parent }\n\n Item {\n anchors.left: parent.left\n anchors.right: centerRoot.hasAnchor ? centerAnchorModule.left : parent.right\n anchors.top: parent.top\n anchors.bottom: parent.bottom\n\n HoverHandler {\n onHoveredChanged: root.setCenterSectionHovered(hovered)\n }\n }\n\n ModuleList {\n visible: !centerRoot.hasAnchor\n entries: centerRoot.entries\n region: \"center\"\n anchors.centerIn: parent\n }\n\n ModuleList {\n visible: centerRoot.hasAnchor\n entries: root.entriesBefore(centerRoot.entries, root.centerAnchor)\n region: \"center\"\n anchors.right: centerAnchorModule.left\n anchors.verticalCenter: centerAnchorModule.verticalCenter\n }\n\n ModuleSlot {\n id: centerAnchorModule\n visible: centerRoot.hasAnchor\n entry: centerRoot.anchorEntry\n region: \"center\"\n anchors.centerIn: parent\n }\n\n ModuleList {\n visible: centerRoot.hasAnchor\n entries: root.entriesAfter(centerRoot.entries, root.centerAnchor)\n region: \"center\"\n anchors.left: centerAnchorModule.right\n anchors.verticalCenter: centerAnchorModule.verticalCenter\n }\n }\n }\n\n Component {\n id: verticalCenterModules\n\n Item {\n anchors.fill: parent\n\n CenterGestureArea { anchors.fill: parent }\n\n Item {\n anchors.left: parent.left\n anchors.right: parent.right\n anchors.top: parent.top\n anchors.bottom: centerRoot.hasAnchor ? centerAnchorModule.top : parent.bottom\n\n HoverHandler {\n onHoveredChanged: root.setCenterSectionHovered(hovered)\n }\n }\n\n ModuleList {\n visible: !centerRoot.hasAnchor\n entries: centerRoot.entries\n region: \"center\"\n anchors.centerIn: parent\n }\n\n ModuleList {\n visible: centerRoot.hasAnchor\n entries: root.entriesBefore(centerRoot.entries, root.centerAnchor)\n region: \"center\"\n anchors.bottom: centerAnchorModule.top\n anchors.horizontalCenter: centerAnchorModule.horizontalCenter\n }\n\n ModuleSlot {\n id: centerAnchorModule\n visible: centerRoot.hasAnchor\n entry: centerRoot.anchorEntry\n region: \"center\"\n anchors.centerIn: parent\n }\n\n ModuleList {\n visible: centerRoot.hasAnchor\n entries: root.entriesAfter(centerRoot.entries, root.centerAnchor)\n region: \"center\"\n anchors.top: centerAnchorModule.bottom\n anchors.horizontalCenter: centerAnchorModule.horizontalCenter\n }\n }\n }\n }\n\n component CenterGestureArea: MouseArea {\n id: gestureArea\n\n property bool dragging: false\n property bool suppressClick: false\n property real pressedX: 0\n property real pressedY: 0\n readonly property real dragThreshold: Style.space(4)\n\n acceptedButtons: Qt.LeftButton\n cursorShape: dragging ? Qt.ClosedHandCursor : Qt.ArrowCursor\n pressAndHoldInterval: 200\n\n function startDrag(x, y) {\n if (dragging) return\n dragging = true\n root.beginBarMove(root.targetWindow(gestureArea))\n var scenePoint = gestureArea.mapToItem(null, x, y)\n root.updateBarMove(root.windowScreenPoint(scenePoint, root.barMoveWindow))\n }\n\n onPressed: function(mouse) {\n dragging = false\n suppressClick = false\n pressedX = mouse.x\n pressedY = mouse.y\n }\n\n onPressAndHold: function(mouse) {\n // A widget above us propagates its composed press-and-hold down here without\n // ever handing over the grab, so we'd get no release or cancel to end the move.\n if (!gestureArea.pressed) return\n startDrag(mouse.x, mouse.y)\n }\n\n onPositionChanged: function(mouse) {\n if (!(mouse.buttons & Qt.LeftButton)) return\n\n if (!dragging) {\n var distance = Math.abs(mouse.x - pressedX) + Math.abs(mouse.y - pressedY)\n if (distance < dragThreshold) return\n startDrag(mouse.x, mouse.y)\n return\n }\n\n var scenePoint = gestureArea.mapToItem(null, mouse.x, mouse.y)\n root.updateBarMove(root.windowScreenPoint(scenePoint, root.barMoveWindow))\n }\n\n onReleased: function(mouse) {\n if (!dragging) return\n dragging = false\n suppressClick = true\n root.finishBarMove()\n mouse.accepted = true\n }\n\n onCanceled: {\n dragging = false\n suppressClick = false\n root.clearBarMove()\n }\n\n onClicked: function(mouse) {\n if (suppressClick) {\n suppressClick = false\n mouse.accepted = true\n }\n }\n\n onDoubleClicked: function(mouse) {\n if (suppressClick) {\n suppressClick = false\n return\n }\n if (mouse.button === Qt.LeftButton) {\n root.cycleBackground()\n mouse.accepted = true\n }\n }\n }\n\n component ModuleList: Loader {\n id: moduleListRoot\n\n property var entries: []\n property string region: \"\"\n\n visible: entries.length > 0\n // A hidden list must not build its modules. The center section declares\n // both an anchored and an unanchored arrangement and shows whichever\n // fits, so leaving the other one loaded mounts every center module\n // twice — two IPC handlers registered for the same target, two clocks\n // ticking, two of every timer and fetch behind them.\n active: visible && entries.length > 0\n sourceComponent: root.vertical ? verticalModuleList : horizontalModuleList\n width: item ? item.implicitWidth : 0\n height: item ? item.implicitHeight : 0\n\n Component {\n id: horizontalModuleList\n\n Row {\n spacing: 0\n\n Repeater {\n model: moduleListRoot.entries\n\n ModuleSlot {\n required property var modelData\n entry: modelData\n region: moduleListRoot.region\n }\n }\n }\n }\n\n Component {\n id: verticalModuleList\n\n Column {\n spacing: 0\n\n Repeater {\n model: moduleListRoot.entries\n\n ModuleSlot {\n required property var modelData\n entry: modelData\n region: moduleListRoot.region\n }\n }\n }\n }\n }\n\n component ModuleSlot: Item {\n id: slot\n\n required property var entry\n property string region: \"\"\n readonly property string moduleName: root.entryId(entry)\n readonly property var moduleSettings: root.entrySettings(entry)\n readonly property string customType: root.customModuleType(entry)\n readonly property var registryMetadata: root.barWidgetRegistry.metadataFor(root.canonicalWidgetId(moduleName))\n readonly property bool firstParty: registryMetadata && registryMetadata.firstParty === true\n readonly property string pluginApiId: registered ? root.canonicalWidgetId(moduleName) : \"bar-entry:\" + moduleName\n // Re-evaluate when the registry mutates (Component reference changes,\n // plugin enabled/disabled, etc.). Reading the `widgets` property creates\n // the binding dependency — the wrapped function call alone wouldn't.\n readonly property var registryComponent: {\n var w = root.barWidgetRegistry.widgets\n if (customType) return null\n var registryName = root.canonicalWidgetId(moduleName)\n return w[registryName] ? w[registryName].component : null\n }\n readonly property bool qmlCustom: customType === \"qml\"\n readonly property bool commandCustom: customType === \"command\"\n readonly property bool registered: registryComponent !== null\n readonly property var activeItem: {\n if (registered) return registryLoader.item\n if (qmlCustom) return qmlLoader.item\n return componentLoader.item\n }\n readonly property bool hovered: moduleHover.hovered\n readonly property bool dragSource: root.barDragSource === slot\n readonly property bool panelOpen: root.activePopout === slot.activeItem\n // Modules bigger than the mark they want (a text label in a padded slot,\n // a multi-line stack on a vertical bar) can say how long the open-panel\n // dot should be along the bar, so it tracks what the module paints\n // instead of a fraction of whatever slot it happens to fill.\n readonly property real panelIndicatorExtent: {\n var key = root.vertical ? \"openPanelIndicatorHeight\" : \"openPanelIndicatorWidth\"\n var hint = activeItem && key in activeItem ? activeItem[key] : undefined\n if (hint !== undefined && hint !== null && hint > 0) return Math.round(hint)\n return Math.max(Style.space(10), Math.round((root.vertical ? slot.height : slot.width) * 0.55))\n }\n implicitWidth: activeItem && activeItem.visible ? (root.vertical ? root.barSize : activeItem.implicitWidth) : 0\n implicitHeight: activeItem && activeItem.visible ? activeItem.implicitHeight : 0\n width: implicitWidth\n height: implicitHeight\n z: modulePointer.dragging ? 100 : 0\n\n Component.onCompleted: root.registerModuleSlot(slot)\n Component.onDestruction: {\n if (root.barDragSource === slot) root.clearBarDrag()\n root.unregisterModuleSlot(slot)\n }\n\n HoverHandler { id: moduleHover }\n\n BorderSurface {\n visible: slot.dragSource\n anchors.fill: parent\n anchors.margins: Style.space(1)\n color: root.transparent ? \"transparent\" : root.background\n borderSpec: Border.flat(root.barForeground, 1)\n radius: Math.min(Style.cornerRadius, height / 2)\n opacity: root.transparent ? 0.22 : 0.32\n }\n\n Loader {\n id: componentLoader\n active: !slot.qmlCustom && !slot.registered\n sourceComponent: slot.commandCustom ? customCommandModuleComponent : emptyModuleComponent\n anchors.fill: parent\n opacity: slot.dragSource ? 0.22 : 1.0\n onLoaded: {\n slot.injectProps()\n Qt.callLater(slot.injectProps)\n }\n }\n\n Loader {\n id: registryLoader\n active: slot.registered\n sourceComponent: slot.registered ? slot.registryComponent : null\n anchors.fill: parent\n opacity: slot.dragSource ? 0.22 : 1.0\n onLoaded: {\n slot.injectProps()\n Qt.callLater(slot.injectProps)\n }\n }\n\n Loader {\n id: qmlLoader\n active: slot.qmlCustom\n source: slot.qmlCustom ? root.customModuleSource(slot.entry) : \"\"\n anchors.fill: parent\n opacity: slot.dragSource ? 0.22 : 1.0\n onLoaded: {\n slot.injectProps()\n Qt.callLater(slot.injectProps)\n }\n }\n\n Rectangle {\n id: openPanelIndicator\n\n readonly property int inset: Style.space(2)\n\n visible: opacity > 0\n opacity: slot.panelOpen && !slot.dragSource ? 0.9 : 0\n color: Commons.Color.accent\n radius: Math.min(width, height) / 2\n width: root.vertical ? Style.space(2) : slot.panelIndicatorExtent\n height: root.vertical ? slot.panelIndicatorExtent : Style.space(2)\n // The mark sits on the module's inner edge — the one facing the\n // desktop — so it underlines a top bar, overlines a bottom one, and\n // points inward from a left or right one. It reads as pointing at the\n // panel that opens on that side.\n // Snap toward the start of the slot, matching native glyph rendering.\n x: root.vertical\n ? (root.position === \"left\" ? parent.width - width - inset : inset)\n : Math.floor((parent.width - width) / 2)\n y: root.vertical\n ? Math.floor((parent.height - height) / 2)\n : (root.position === \"top\" ? parent.height - height - inset : inset)\n z: 50\n\n Behavior on opacity {\n NumberAnimation { duration: Style.duration(120); easing.type: Easing.OutCubic }\n }\n }\n\n MouseArea {\n id: modulePointer\n\n property bool dragging: false\n property bool suppressClick: false\n property real pressedX: 0\n property real pressedY: 0\n readonly property bool canReorder: root.shell && typeof root.shell.mutateShellConfig === \"function\"\n readonly property real dragThreshold: Style.space(4)\n\n anchors.fill: parent\n acceptedButtons: Qt.LeftButton\n enabled: slot.visible && slot.width > 0 && slot.height > 0\n propagateComposedEvents: true\n // Only the hovered slot needs the hit test; without the guard every\n // slot on every monitor re-ran it on each click target change.\n cursorShape: moduleHover.hovered && root.moduleClickTargetAt(slot, mouseX, mouseY) ? Qt.PointingHandCursor : Qt.ArrowCursor\n // Do not assign drag.target here: ModuleSlot is owned by Row/Column\n // positioners, and mutating slot.x/slot.y can leave stale offsets that\n // make neighboring modules overlap after a small aborted drag.\n\n onPressed: function(mouse) {\n dragging = false\n suppressClick = false\n pressedX = mouse.x\n pressedY = mouse.y\n root.clearBarDrag()\n }\n\n onPositionChanged: function(mouse) {\n if (!canReorder || !(mouse.buttons & Qt.LeftButton)) return\n\n var distance = Math.abs(mouse.x - pressedX) + Math.abs(mouse.y - pressedY)\n if (distance >= dragThreshold) {\n if (!dragging) {\n root.barDragWindow = root.targetWindow(slot.activeItem) || root.targetWindow(slot)\n root.barDragScreen = root.barDragWindow ? root.barDragWindow.screen : null\n root.barDragOffsetX = pressedX\n root.barDragOffsetY = pressedY\n root.captureBarDragGhost(slot)\n root.barDragSource = slot\n }\n dragging = true\n root.hideTooltip(slot.activeItem)\n }\n\n if (dragging) {\n var scenePoint = slot.mapToItem(null, mouse.x, mouse.y)\n var screenPoint = root.barDragScreenPoint(scenePoint)\n root.barDragSceneX = scenePoint.x\n root.barDragSceneY = scenePoint.y\n root.barDragScreenX = screenPoint.x\n root.barDragScreenY = screenPoint.y\n\n var drop = root.moduleDropAtScene(scenePoint, slot)\n root.barDragTarget = drop ? drop.slot : null\n root.barDragAfter = drop ? drop.after : false\n root.barDragTargetGeometry = drop ? root.dropMarkerRect(drop.slot, drop.after) : null\n }\n }\n\n onReleased: function(mouse) {\n var wasDragging = dragging\n var targetSlot = root.barDragTarget\n var afterTarget = root.barDragAfter\n\n if (wasDragging) suppressClick = true\n\n dragging = false\n root.clearBarDrag()\n\n if (wasDragging && targetSlot) {\n root.dropBarModuleAtTarget(slot, targetSlot, afterTarget)\n mouse.accepted = true\n } else if (!wasDragging) {\n mouse.accepted = false\n }\n }\n\n onCanceled: {\n dragging = false\n suppressClick = false\n root.clearBarDrag()\n }\n\n onClicked: function(mouse) {\n if (suppressClick) {\n suppressClick = false\n mouse.accepted = true\n return\n }\n\n if (!root.pressModuleClickTarget(slot, mouse.button, mouse.x, mouse.y)) mouse.accepted = false\n }\n }\n\n onActiveItemChanged: Qt.callLater(injectProps)\n onModuleSettingsChanged: injectProps()\n\n function injectProps() {\n var target = activeItem\n if (!target) return\n if (\"bar\" in target) target.bar = firstParty\n ? root : root.pluginBarApiFor(pluginApiId, moduleName, registered)\n if (\"moduleName\" in target) target.moduleName = moduleName\n if (\"settings\" in target) target.settings = moduleSettings\n }\n\n Component {\n id: customCommandModuleComponent\n CustomCommandModule { entry: slot.entry }\n }\n }\n\n component CustomCommandModule: WidgetButton {\n id: customRoot\n\n required property var entry\n readonly property string moduleName: root.entryId(entry)\n readonly property var settings: root.entrySettings(entry)\n property string outputText: \"\"\n property string outputTooltip: \"\"\n property bool outputActive: false\n\n function setting(name, fallback) {\n var value = settings ? settings[name] : undefined\n return value === undefined || value === null ? fallback : value\n }\n\n function update(raw) {\n var data = Util.parseModuleJson(raw)\n var klass = data.class || data.alt || \"\"\n\n outputText = data.text || String(raw || \"\").trim()\n outputTooltip = data.tooltip || String(setting(\"tooltip\", \"\"))\n outputActive = klass === \"active\" || (Array.isArray(klass) && klass.indexOf(\"active\") !== -1)\n }\n\n bar: root\n text: outputText || String(setting(\"text\", \"\"))\n tooltipText: outputTooltip || String(setting(\"tooltip\", \"\"))\n active: outputActive\n keepSpace: setting(\"keepSpace\", false) === true\n horizontalMargin: Number(setting(\"horizontalMargin\", 7.5))\n verticalPadding: Number(setting(\"verticalPadding\", 6))\n fontSize: Number(setting(\"fontSize\", 12))\n\n onPressed: function(button) {\n var command = \"\"\n if (button === Qt.RightButton)\n command = String(setting(\"onRightClick\", \"\"))\n else if (button === Qt.MiddleButton)\n command = String(setting(\"onMiddleClick\", \"\"))\n else\n command = String(setting(\"onClick\", \"\"))\n\n if (command) root.run(command)\n }\n\n Process {\n id: customProc\n command: [\"bash\", \"-lc\", String(customRoot.setting(\"exec\", \"\"))]\n stdout: StdioCollector {\n waitForEnd: true\n onStreamFinished: customRoot.update(text)\n }\n }\n\n Timer {\n interval: Math.max(1, Number(customRoot.setting(\"interval\", 5))) * 1000\n running: String(customRoot.setting(\"exec\", \"\")) !== \"\"\n repeat: true\n triggeredOnStart: true\n onTriggered: root.runProcess(customProc)\n }\n }\n}\n```"}], "task": "chunk_manifest_entry", "meta": {"origin": "first-party", "repo": "https://github.com/basecamp/omarchy", "commit": "9480d1b6a98156314dbabe6bfef08f39f8b9cd07", "license": "MIT", "plugin_path": "shell/plugins/bar", "kinds": ["bar"], "complexity": "large", "group": "3e63fc3c", "chunked": true, "validate_tree": true, "validator": "pass", "qmllint": "clean", "qml_files": 1, "chars": 78555, "tokens": 18736, "split": "train"}} {"messages": [{"role": "system", "content": "You are an Omarchy plugin expert. You write complete, valid Omarchy (Quattro / omarchy-shell, Quickshell QML) plugins. Manifests use schemaVersion 1, a namespaced id that never uses the reserved omarchy.* namespace, name, version, kinds (bar-widget|panel|overlay|menu|service|bar) with a matching safe relative entryPoints path for every kind, and no symlinks. Return every file in full as '### path' followed by a fenced code block."}, {"role": "user", "content": "Omarchy plugin `acme.bar` (bar). Manifest:\n```json\n{\n \"schemaVersion\": 1,\n \"id\": \"acme.bar\",\n \"name\": \"Bar\",\n \"version\": \"1.0.0\",\n \"author\": \"Omarchy\",\n \"description\": \"Status bar with widgets\",\n \"kinds\": [\n \"bar\"\n ],\n \"entryPoints\": {\n \"bar\": \"Bar.qml\"\n }\n}\n```\nSibling files:\n- Bar.qml (77 KB)\n- BarModel.js (13 KB)\n- indicators/Dnd.qml (1 KB)\n- indicators/NightLight.qml (1 KB)\n- indicators/PasswordlessSudo.qml (1 KB)\n- indicators/Reminder.qml (1 KB)\n- indicators/RemoteSession.qml (1 KB)\n- indicators/ScreenRecording.qml (1 KB)\n- indicators/StayAwake.qml (1 KB)\n- widgets/ActiveWindow.qml (1 KB)\n- widgets/Indicators.qml (15 KB)\n- widgets/KeyboardLayout.qml (10 KB)\n- widgets/KeyboardLayoutModel.js (6 KB)\n- widgets/Microphone.qml (2 KB)\n- widgets/Spacer.qml (1 KB)\n- widgets/SystemUpdate.qml (1 KB)\n- widgets/TrayModel.js (1 KB)\n- widgets/Workspaces.qml (4 KB)\n\nImplement `widgets/Tray.qml` in full."}, {"role": "assistant", "content": "### widgets/Tray.qml\n```qml\nimport Quickshell\nimport QtQuick\nimport QtQuick.Controls\nimport QtQuick.Effects\nimport Quickshell.Services.SystemTray\nimport qs.Commons\nimport qs.Commons as Commons\nimport qs.Ui\nimport \"TrayModel.js\" as TrayModel\n\nBarWidget {\n id: root\n moduleName: \"omarchy.tray\"\n\n property bool expanded: false\n property bool managePopupOpen: false\n property bool trayMenuOpen: false\n property var activeTrayItem: null\n property var activeTrayAnchor: null\n readonly property color foreground: bar ? bar.foreground : Commons.Color.foreground\n readonly property string fontFamily: bar ? bar.fontFamily : Style.font.family\n readonly property var pinnedIds: settings.pinned instanceof Array ? settings.pinned : []\n readonly property var hiddenIds: settings.hidden instanceof Array ? settings.hidden : []\n readonly property var pinnedItems: bucket(\"pinned\")\n readonly property var drawerItems: bucket(\"drawer\")\n readonly property var allItems: bucket(\"all\")\n readonly property int drawerCount: drawerItems.length\n readonly property int trayItemExtent: Style.bar.iconSlot\n readonly property int trayItemGap: 0\n readonly property int trayJoinGap: 0\n readonly property int drawerExtent: drawerCount > 0 ? drawerCount * trayItemExtent + (drawerCount - 1) * trayItemGap : 0\n // Match Waybar's group/tray-expander drawer transition-duration.\n readonly property int animationDuration: 600\n property real revealProgress: expanded ? 1 : 0\n readonly property real revealExtent: drawerExtent * revealProgress\n\n // Submenu drill-down state. QsMenuEntry.display() renders a *platform* menu,\n // which Quickshell refuses unless the shell root sets `//@ pragma\n // UseQApplication` - omarchy's shell.qml does not, so every submenu click was\n // a silent no-op (\"Cannot display PlatformMenuEntry as quickshell was not\n // started in QApplication mode\" in the shell log) and apps whose whole UI is\n // submenus, e.g. radiotray-ng's station list, were unusable. QsMenuEntry\n // inherits QsMenuHandle, so a child entry can feed a nested QsMenuOpener and\n // render inside this popup instead of going through the platform. Each level\n // keeps its own live opener: a child entry is owned by its parent opener's\n // model, so collapsing the stack to a single opener would destroy the very\n // entry being displayed (submenu turns up empty).\n property var submenuStack: []\n readonly property int submenuDepth: submenuStack.length\n readonly property string currentTitle: submenuDepth > 0 ? submenuStack[submenuDepth - 1].title : \"\"\n readonly property var currentChildren: submenuDepth > 0\n ? submenuStack[submenuDepth - 1].opener.children\n : trayMenuOpener.children\n\n // Changing level rebuilds the row delegates synchronously, so the next\n // row lands under a cursor that hasn't moved. Submenu clicks used to be\n // silent no-ops, which trained users to click them twice, and that second\n // click would now fire whatever entry took the spot. Ignore row clicks for\n // a beat after each level change; a deliberate follow-up click is slower.\n property bool menuLevelSettling: false\n\n Component {\n id: submenuOpenerComponent\n QsMenuOpener {}\n }\n\n Timer {\n id: menuLevelSettleTimer\n interval: 250\n onTriggered: root.menuLevelSettling = false\n }\n\n function settleMenuLevel() {\n menuLevelSettling = true\n menuLevelSettleTimer.restart()\n }\n\n function resetTrayMenu() {\n menuLevelSettling = false\n menuLevelSettleTimer.stop()\n // Flickable keeps its offset across a model swap whenever the new content\n // is still tall enough to hold it, so a menu dismissed while scrolled\n // would otherwise reopen part-way down with its first entries off screen.\n trayMenuFlick.contentY = 0\n // Clear the reactive stack before tearing anything down, so no binding can\n // read a partially-destroyed opener while this runs. Then destroy deepest\n // first: an inner opener's menu entry is owned by its parent's children\n // model, so destroying a parent first would invalidate an entry a still-\n // live child opener references.\n var openers = submenuStack\n submenuStack = []\n for (var i = openers.length - 1; i >= 0; i--) openers[i].opener.destroy()\n }\n\n function enterSubmenu(entry, title) {\n var opener = submenuOpenerComponent.createObject(root, { menu: entry })\n if (!opener) return\n var stack = submenuStack.slice()\n stack.push({ opener: opener, title: title })\n submenuStack = stack\n settleMenuLevel()\n }\n\n function leaveSubmenu() {\n if (submenuStack.length === 0) return\n var stack = submenuStack.slice()\n var top = stack.pop()\n submenuStack = stack\n top.opener.destroy()\n settleMenuLevel()\n }\n\n function close() {\n managePopupOpen = false\n trayMenuOpen = false\n }\n\n function openTrayMenu(item, anchorItem, mouse) {\n if (!item || !item.menu) {\n var point = anchorItem.QsWindow.contentItem.mapFromItem(anchorItem, mouse.x, mouse.y)\n item.display(anchorItem.QsWindow.window, point.x, point.y)\n return\n }\n\n // Reset before switching items: trayMenuOpener.menu binds to\n // activeTrayItem.menu, so assigning a new item invalidates the old root's\n // children immediately, before any nested opener referencing them would\n // otherwise get torn down.\n resetTrayMenu()\n activeTrayItem = item\n activeTrayAnchor = anchorItem\n trayMenuOpen = true\n }\n\n function trayIconSource(icon) {\n // Quickshell already resolves the tray icon into a ready-to-use image://\n // URL, including a \"?path=\" fallback search dir for apps that ship their\n // tray icon outside a standard theme (e.g. Steam's flat public/ dir). Hand\n // it straight to IconImage; guessing a theme sub-directory here only broke\n // apps whose layout didn't match the guess.\n return String(icon || \"\")\n }\n\n // Symbolic icons ship a fixed fill (often near-white) that the host is meant\n // to recolor to its foreground; detect them by the freedesktop \"-symbolic\"\n // name suffix so they can be tinted instead of rendered as-is.\n function iconIsSymbolic(icon) {\n var name = String(icon || \"\").split(\"?\")[0]\n return name.slice(-9) === \"-symbolic\"\n }\n\n function trayTooltip(item) {\n return item.tooltipTitle || item.title || item.id || \"\"\n }\n\n function classifyItem(item) {\n var iid = String(item.id || \"\")\n if (hiddenIds.indexOf(iid) !== -1) return \"hidden\"\n if (pinnedIds.indexOf(iid) !== -1) return \"pinned\"\n return \"drawer\"\n }\n\n function ownedByOmarchy(item) {\n var layout = root.bar && root.bar.layoutConfig ? root.bar.layoutConfig : null\n return TrayModel.ownedByOmarchy(item, layout)\n }\n\n function bucket(category) {\n var values = SystemTray.items.values\n var result = []\n for (var i = 0; i < values.length; i++) {\n var item = values[i]\n if (item.status === Status.Passive) continue\n if (ownedByOmarchy(item)) continue\n if (category === \"all\") {\n result.push(item)\n continue\n }\n if (classifyItem(item) === category) result.push(item)\n }\n return result\n }\n\n function persistTrayState(pinned, hidden) {\n if (!root.bar || !root.bar.shell || typeof root.bar.shell.updateEntryInline !== \"function\") return\n var id = root.moduleName || \"omarchy.tray\"\n root.bar.shell.updateEntryInline(id, { id: id, pinned: pinned, hidden: hidden })\n }\n\n function togglePin(iid) {\n var p = pinnedIds.slice(), h = hiddenIds.slice()\n var idx = p.indexOf(iid)\n if (idx !== -1) p.splice(idx, 1)\n else {\n p.push(iid)\n var hi = h.indexOf(iid)\n if (hi !== -1) h.splice(hi, 1)\n }\n persistTrayState(p, h)\n }\n\n function toggleHide(iid) {\n var p = pinnedIds.slice(), h = hiddenIds.slice()\n var idx = h.indexOf(iid)\n if (idx !== -1) h.splice(idx, 1)\n else {\n h.push(iid)\n var pi = p.indexOf(iid)\n if (pi !== -1) p.splice(pi, 1)\n }\n persistTrayState(p, h)\n }\n\n visible: pinnedItems.length > 0 || drawerCount > 0\n clip: false\n implicitWidth: root.vertical ? root.barSize : trayContent.implicitWidth\n implicitHeight: root.vertical ? trayContent.implicitHeight : root.barSize\n\n Behavior on revealProgress {\n NumberAnimation { duration: Style.duration(root.animationDuration); easing.type: Easing.OutCubic }\n }\n\n Loader {\n id: trayContent\n anchors.fill: parent\n sourceComponent: root.vertical ? verticalTray : horizontalTray\n }\n\n Component {\n id: horizontalTray\n\n Item {\n id: horizontalTrayRoot\n\n readonly property int pinnedWidth: pinnedRow.implicitWidth\n readonly property int drawerBlockWidth: root.allItems.length > 0 ? expandIcon.implicitWidth + root.drawerExtent : 0\n\n implicitWidth: pinnedWidth + drawerBlockWidth\n implicitHeight: root.barSize\n\n // Mask out the empty area the collapsed drawer reserves for its slide-in,\n // so hovering it doesn't trigger expand and clicks pass through.\n containmentMask: QtObject {\n function contains(point: point): bool {\n if (point.y < 0 || point.y > horizontalTrayRoot.height) return false\n // Drawer reveals leftward; chevron sits at the right end when collapsed\n // and slides left as it opens. The visible region starts at the chevron.\n var chevronX = root.drawerExtent - root.revealExtent\n if (point.x >= chevronX && point.x <= horizontalTrayRoot.drawerBlockWidth) return true\n // Pinned items, placed to the right of the drawer block.\n var pinnedStart = horizontalTrayRoot.drawerBlockWidth\n return point.x >= pinnedStart && point.x <= horizontalTrayRoot.implicitWidth\n }\n }\n\n Item {\n id: drawerArea\n x: 0\n width: horizontalTrayRoot.drawerBlockWidth\n height: root.barSize\n visible: root.allItems.length > 0\n\n HoverHandler {\n onHoveredChanged: root.expanded = hovered\n }\n\n BarIconButton {\n id: expandIcon\n bar: root.bar\n width: implicitWidth\n height: implicitHeight\n x: root.drawerExtent - root.revealExtent\n text: \"\\uf053\"\n onPressed: function(button) {\n if (button === Qt.RightButton) root.managePopupOpen = !root.managePopupOpen\n }\n }\n\n Item {\n id: trayClip\n x: expandIcon.width\n anchors.verticalCenter: parent.verticalCenter\n width: root.drawerExtent\n height: root.barSize\n clip: true\n\n Row {\n id: trayIcons\n x: root.drawerExtent - root.revealExtent\n anchors.verticalCenter: parent.verticalCenter\n spacing: root.trayItemGap\n layer.enabled: true\n\n Repeater {\n model: root.drawerItems\n TrayItem {}\n }\n }\n }\n }\n\n Row {\n id: pinnedRow\n x: drawerArea.x + horizontalTrayRoot.drawerBlockWidth\n anchors.verticalCenter: parent.verticalCenter\n spacing: root.trayItemGap\n leftPadding: root.pinnedItems.length > 0 && root.allItems.length > 0 ? root.trayJoinGap : 0\n Repeater {\n model: root.pinnedItems\n TrayItem {}\n }\n }\n }\n }\n\n Component {\n id: verticalTray\n\n Item {\n id: verticalTrayRoot\n\n readonly property int pinnedHeight: pinnedCol.implicitHeight\n readonly property int drawerBlockHeight: root.allItems.length > 0 ? expandIcon.implicitHeight + root.drawerExtent : 0\n\n implicitWidth: root.barSize\n implicitHeight: pinnedHeight + drawerBlockHeight\n\n containmentMask: QtObject {\n function contains(point: point): bool {\n if (point.x < 0 || point.x > verticalTrayRoot.width) return false\n var chevronY = root.drawerExtent - root.revealExtent\n if (point.y >= chevronY && point.y <= verticalTrayRoot.drawerBlockHeight) return true\n var pinnedStart = verticalTrayRoot.drawerBlockHeight\n return point.y >= pinnedStart && point.y <= verticalTrayRoot.implicitHeight\n }\n }\n\n Item {\n id: drawerArea\n y: 0\n width: root.barSize\n height: verticalTrayRoot.drawerBlockHeight\n visible: root.allItems.length > 0\n\n HoverHandler {\n onHoveredChanged: root.expanded = hovered\n }\n\n BarIconButton {\n id: expandIcon\n bar: root.bar\n width: implicitWidth\n height: implicitHeight\n y: root.drawerExtent - root.revealExtent\n text: \"\\uf053\"\n textRotation: 90\n onPressed: function(button) {\n if (button === Qt.RightButton) root.managePopupOpen = !root.managePopupOpen\n }\n }\n\n Item {\n id: trayClip\n y: expandIcon.height\n anchors.horizontalCenter: parent.horizontalCenter\n width: root.barSize\n height: root.drawerExtent\n clip: true\n\n Column {\n id: trayIcons\n y: root.drawerExtent - root.revealExtent\n anchors.horizontalCenter: parent.horizontalCenter\n spacing: root.trayItemGap\n layer.enabled: true\n\n Repeater {\n model: root.drawerItems\n TrayItem {}\n }\n }\n }\n }\n\n Column {\n id: pinnedCol\n y: drawerArea.y + verticalTrayRoot.drawerBlockHeight\n anchors.horizontalCenter: parent.horizontalCenter\n spacing: root.trayItemGap\n topPadding: root.pinnedItems.length > 0 && root.allItems.length > 0 ? root.trayJoinGap : 0\n Repeater {\n model: root.pinnedItems\n TrayItem {}\n }\n }\n }\n }\n\n PopupCard {\n id: managePopup\n anchorItem: root\n owner: root\n bar: root.bar\n open: root.managePopupOpen\n contentWidth: managePopup.fittedContentWidth(Style.space(300))\n contentHeight: managePopup.fittedContentHeight(manageColumn.implicitHeight)\n\n Column {\n id: manageColumn\n anchors.fill: parent\n spacing: Style.space(8)\n\n Text {\n text: \"Tray icons\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.body\n font.bold: true\n }\n\n Text {\n text: \"Pinned icons stay visible. Hidden icons never show.\"\n color: Qt.darker(root.foreground, 1.4)\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n wrapMode: Text.WordWrap\n width: parent.width\n }\n\n Text {\n visible: root.allItems.length === 0\n text: \"No tray items reporting.\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n font.italic: true\n }\n\n Repeater {\n model: root.allItems\n delegate: Item {\n id: rowRoot\n required property var modelData\n required property int index\n width: manageColumn.width\n implicitHeight: 28\n\n readonly property string itemId: String(modelData.id || \"\")\n readonly property string displayName: {\n var t = String(modelData.title || \"\").trim()\n if (t) return t\n var tt = String(modelData.tooltipTitle || \"\").trim()\n if (tt) return tt\n var id = String(modelData.id || \"\")\n var slash = id.lastIndexOf(\"/\")\n return slash !== -1 ? id.substring(slash + 1) : (id || \"Unknown\")\n }\n readonly property bool isPinned: root.pinnedIds.indexOf(itemId) !== -1\n readonly property bool isHidden: root.hiddenIds.indexOf(itemId) !== -1\n\n TrayIcon {\n id: rowIcon\n anchors.verticalCenter: parent.verticalCenter\n anchors.left: parent.left\n width: 16\n height: 16\n icon: rowRoot.modelData.icon\n }\n\n Text {\n textFormat: Text.PlainText\n anchors.verticalCenter: parent.verticalCenter\n anchors.left: rowIcon.right\n anchors.leftMargin: Style.space(10)\n anchors.right: rowHideBtn.left\n anchors.rightMargin: Style.space(8)\n text: rowRoot.displayName\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n elide: Text.ElideRight\n }\n\n Button {\n id: rowPinBtn\n anchors.verticalCenter: parent.verticalCenter\n anchors.right: parent.right\n iconText: \"\\uf08d\"\n text: rowRoot.isPinned ? \"Unpin\" : \"Pin\"\n foreground: root.foreground\n horizontalPadding: 8\n verticalPadding: 3\n iconSize: Style.font.bodySmall\n fontSize: Style.font.bodySmall\n onClicked: root.togglePin(rowRoot.itemId)\n }\n\n Button {\n id: rowHideBtn\n anchors.verticalCenter: parent.verticalCenter\n anchors.right: rowPinBtn.left\n anchors.rightMargin: Style.space(6)\n iconText: \"\\uf06e\"\n text: rowRoot.isHidden ? \"Show\" : \"Hide\"\n foreground: root.foreground\n horizontalPadding: 8\n verticalPadding: 3\n iconSize: Style.font.bodySmall\n fontSize: Style.font.bodySmall\n onClicked: root.toggleHide(rowRoot.itemId)\n }\n }\n }\n }\n }\n\n QsMenuOpener {\n id: trayMenuOpener\n menu: root.activeTrayItem ? root.activeTrayItem.menu : null\n }\n\n PopupCard {\n id: trayMenuPopup\n anchorItem: root.activeTrayAnchor || root\n owner: root\n bar: root.bar\n open: root.trayMenuOpen\n // The card fades out over 140ms (visible stays true for that whole time --\n // see PopupCard's own visible: open || card.opacity > 0), so resetting on\n // \"open\" would swap a live submenu for the root menu mid-fade: a visible\n // flash, and a resize/reposition if the two have different geometry. Wait\n // for the fade to actually finish. Switching to a different tray item\n // still resets immediately, from openTrayMenu() itself.\n onVisibleChanged: if (!visible) root.resetTrayMenu()\n padding: Style.space(8)\n borderColor: Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.45)\n contentWidth: trayMenuPopup.fittedContentWidth(Style.space(232))\n contentHeight: trayMenuPopup.fittedContentHeight(menuHeaderHeight + trayMenuColumn.implicitHeight, Style.space(420))\n\n // Column skips invisible children but keeps reporting their height, so\n // read the header's extent through its own visibility.\n readonly property int menuHeaderHeight: menuHeader.visible ? menuHeader.implicitHeight : 0\n\n Column {\n id: trayMenuLayout\n anchors.fill: parent\n spacing: 0\n\n // Header for a drilled-into submenu: names where we are and walks back\n // out. Pinned above the Flickable rather than scrolling with the rows,\n // so the way back stays reachable in a submenu taller than the card.\n // Only present below the root level, so the root menu is unchanged.\n Column {\n id: menuHeader\n visible: root.submenuDepth > 0\n width: trayMenuLayout.width\n spacing: 0\n\n Item {\n id: menuBackRow\n width: menuHeader.width\n implicitHeight: Style.space(30)\n\n Rectangle {\n anchors.fill: parent\n radius: Math.max(2, Style.cornerRadius)\n color: backMouse.containsMouse ? Style.hoverFillFor(root.foreground, root.foreground) : \"transparent\"\n }\n\n Text {\n anchors.verticalCenter: parent.verticalCenter\n anchors.left: parent.left\n width: Style.space(22)\n horizontalAlignment: Text.AlignHCenter\n text: \"\\u2039\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n }\n\n Text {\n textFormat: Text.PlainText\n anchors.verticalCenter: parent.verticalCenter\n anchors.left: parent.left\n anchors.leftMargin: Style.space(28)\n anchors.right: parent.right\n anchors.rightMargin: Style.space(10)\n text: root.currentTitle\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n elide: Text.ElideRight\n }\n\n MouseArea {\n id: backMouse\n anchors.fill: parent\n hoverEnabled: true\n cursorShape: Qt.PointingHandCursor\n onClicked: {\n if (root.menuLevelSettling) return\n // Reset before the model swap so the parent level shows from\n // the top (same ordering as the row delegate below).\n trayMenuFlick.contentY = 0\n root.leaveSubmenu()\n }\n }\n }\n\n Item {\n width: menuHeader.width\n implicitHeight: Style.space(11)\n\n Rectangle {\n anchors.left: parent.left\n anchors.leftMargin: Style.space(10)\n anchors.right: parent.right\n anchors.rightMargin: Style.space(10)\n anchors.verticalCenter: parent.verticalCenter\n height: 1\n color: Commons.Color.popups.border\n opacity: 0.45\n }\n }\n }\n\n Flickable {\n id: trayMenuFlick\n width: trayMenuLayout.width\n height: trayMenuLayout.height - trayMenuPopup.menuHeaderHeight\n contentWidth: width\n contentHeight: trayMenuColumn.implicitHeight\n clip: true\n boundsBehavior: Flickable.StopAtBounds\n flickableDirection: Flickable.VerticalFlick\n interactive: contentHeight > height\n\n ScrollBar.vertical: ScrollBar { policy: ScrollBar.AsNeeded }\n\n Column {\n id: trayMenuColumn\n width: trayMenuFlick.width\n spacing: 0\n\n Repeater {\n model: root.currentChildren\n\n delegate: Item {\n id: menuRow\n required property var modelData\n required property int index\n\n readonly property string rowText: String(modelData.text || \"\")\n readonly property string activeTitle: root.activeTrayItem ? String(root.activeTrayItem.title || root.activeTrayItem.id || \"\") : \"\"\n // Both only ever describe the root menu; inside a submenu the first\n // rows are real entries and must not be swallowed.\n readonly property bool atRoot: root.submenuDepth === 0\n readonly property bool rootTitleEntry: atRoot && index === 0 && modelData.hasChildren && rowText.toLowerCase() === activeTitle.toLowerCase()\n readonly property bool leadingSeparator: atRoot && modelData.isSeparator && index <= 1\n readonly property bool hiddenRow: rootTitleEntry || leadingSeparator\n\n visible: !hiddenRow\n width: trayMenuColumn.width\n implicitHeight: hiddenRow ? 0 : (modelData.isSeparator ? Style.space(11) : Style.space(30))\n opacity: modelData.enabled ? 1.0 : 0.45\n\n Rectangle {\n visible: menuRow.modelData.isSeparator\n anchors.left: parent.left\n anchors.leftMargin: Style.space(10)\n anchors.right: parent.right\n anchors.rightMargin: Style.space(10)\n anchors.verticalCenter: parent.verticalCenter\n height: 1\n color: Commons.Color.popups.border\n opacity: 0.45\n }\n\n Rectangle {\n visible: !menuRow.modelData.isSeparator\n anchors.fill: parent\n radius: Math.max(2, Style.cornerRadius)\n color: rowMouse.containsMouse && menuRow.modelData.enabled ? Style.hoverFillFor(root.foreground, root.foreground) : \"transparent\"\n }\n\n Text {\n textFormat: Text.PlainText\n visible: !menuRow.modelData.isSeparator && menuRow.modelData.buttonType !== QsMenuButtonType.None\n anchors.verticalCenter: parent.verticalCenter\n anchors.left: parent.left\n width: Style.space(22)\n horizontalAlignment: Text.AlignHCenter\n text: menuRow.modelData.checkState === Qt.Checked ? \"\\uf00c\" : \"\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n }\n\n Image {\n id: menuIcon\n visible: !menuRow.modelData.isSeparator && String(menuRow.modelData.icon || \"\") !== \"\"\n anchors.verticalCenter: parent.verticalCenter\n anchors.left: parent.left\n anchors.leftMargin: Style.space(24)\n width: Style.space(16)\n height: Style.space(16)\n fillMode: Image.PreserveAspectFit\n // Decode at physical pixels: IconImage uses the logical size,\n // which leaves PNG icons upscaled and blurry on HiDPI displays.\n sourceSize.width: width * Screen.devicePixelRatio\n sourceSize.height: height * Screen.devicePixelRatio\n source: menuRow.modelData.icon\n }\n\n Text {\n textFormat: Text.PlainText\n visible: !menuRow.modelData.isSeparator\n anchors.verticalCenter: parent.verticalCenter\n anchors.left: parent.left\n anchors.leftMargin: menuIcon.visible ? Style.space(46) : Style.space(28)\n anchors.right: submenuGlyph.left\n anchors.rightMargin: Style.space(8)\n text: menuRow.rowText\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n elide: Text.ElideRight\n }\n\n Text {\n id: submenuGlyph\n visible: !menuRow.modelData.isSeparator && menuRow.modelData.hasChildren\n anchors.verticalCenter: parent.verticalCenter\n anchors.right: parent.right\n anchors.rightMargin: Style.space(10)\n text: \"\\u203a\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n }\n\n MouseArea {\n id: rowMouse\n anchors.fill: parent\n hoverEnabled: true\n enabled: !menuRow.modelData.isSeparator && menuRow.modelData.enabled\n cursorShape: enabled ? Qt.PointingHandCursor : Qt.ArrowCursor\n onClicked: {\n if (root.menuLevelSettling) return\n if (menuRow.modelData.hasChildren) {\n // Reset scroll BEFORE swapping the model: the swap destroys\n // this delegate synchronously and ids stop resolving after.\n trayMenuFlick.contentY = 0\n root.enterSubmenu(menuRow.modelData, menuRow.rowText)\n } else {\n menuRow.modelData.triggered()\n root.close()\n }\n }\n }\n }\n }\n }\n }\n }\n }\n\n // Renders a tray icon, recoloring symbolic icons to the bar foreground so\n // they stay visible on any theme (a raw symbolic icon keeps its baked-in\n // fill and disappears against a matching background).\n component TrayIcon: Item {\n id: trayIconRoot\n required property var icon\n readonly property bool symbolic: root.iconIsSymbolic(icon)\n\n Image {\n id: trayIconImage\n anchors.fill: parent\n fillMode: Image.PreserveAspectFit\n // Decode at physical pixels: IconImage uses the logical size,\n // which leaves PNG icons upscaled and blurry on HiDPI displays.\n sourceSize.width: Math.round(Math.min(width, height) * Screen.devicePixelRatio)\n sourceSize.height: Math.round(Math.min(width, height) * Screen.devicePixelRatio)\n source: root.trayIconSource(trayIconRoot.icon)\n // Kept as a hidden layer so the effect can sample it as a texture.\n visible: !trayIconRoot.symbolic\n layer.enabled: trayIconRoot.symbolic\n }\n\n MultiEffect {\n anchors.fill: trayIconImage\n source: trayIconImage\n visible: trayIconRoot.symbolic\n colorization: 1.0\n colorizationColor: root.foreground\n }\n }\n\n component TrayItem: Item {\n id: trayItemRoot\n\n required property var modelData\n\n visible: modelData.status !== Status.Passive\n implicitWidth: visible ? root.trayItemExtent : 0\n implicitHeight: visible ? root.trayItemExtent : 0\n\n function displayMenu(mouse) {\n root.openTrayMenu(trayItemRoot.modelData, trayItemRoot, mouse)\n }\n\n TrayIcon {\n x: (parent.width - width) / 2\n y: (parent.height - height) / 2\n width: Style.bar.iconSize\n height: Style.bar.iconSize\n icon: trayItemRoot.modelData.icon\n }\n\n MouseArea {\n id: mouseArea\n anchors.fill: parent\n acceptedButtons: Qt.LeftButton | Qt.RightButton | Qt.MiddleButton\n hoverEnabled: true\n cursorShape: Qt.PointingHandCursor\n onEntered: if (root.bar) root.bar.showTooltip(trayItemRoot, root.trayTooltip(modelData))\n onExited: if (root.bar) root.bar.hideTooltip(trayItemRoot)\n onPressed: function(mouse) {\n if (mouse.button === Qt.RightButton) {\n trayItemRoot.displayMenu(mouse)\n mouse.accepted = true\n }\n }\n onClicked: function(mouse) {\n if (mouse.button === Qt.RightButton) {\n mouse.accepted = true\n } else if (mouse.button === Qt.MiddleButton) {\n trayItemRoot.modelData.secondaryActivate()\n } else if (trayItemRoot.modelData.onlyMenu) {\n trayItemRoot.displayMenu(mouse)\n } else {\n trayItemRoot.modelData.activate()\n }\n }\n onWheel: function(wheel) {\n trayItemRoot.modelData.scroll(wheel.angleDelta.y, false)\n }\n }\n\n readonly property bool tooltipHovered: visible && opacity > 0 && mouseArea.containsMouse\n }\n}\n```"}], "task": "chunk_component", "meta": {"origin": "first-party", "repo": "https://github.com/basecamp/omarchy", "commit": "9480d1b6a98156314dbabe6bfef08f39f8b9cd07", "license": "MIT", "plugin_path": "shell/plugins/bar", "kinds": ["bar"], "complexity": "large", "group": "3e63fc3c", "chunked": true, "validate_tree": true, "validator": "pass", "qmllint": "clean", "qml_files": 1, "chars": 31778, "tokens": 7319, "split": "train"}} {"messages": [{"role": "system", "content": "You are an Omarchy plugin expert. You write complete, valid Omarchy (Quattro / omarchy-shell, Quickshell QML) plugins. Manifests use schemaVersion 1, a namespaced id that never uses the reserved omarchy.* namespace, name, version, kinds (bar-widget|panel|overlay|menu|service|bar) with a matching safe relative entryPoints path for every kind, and no symlinks. Return every file in full as '### path' followed by a fenced code block."}, {"role": "user", "content": "Omarchy plugin `acme.bar` (bar). Manifest:\n```json\n{\n \"schemaVersion\": 1,\n \"id\": \"acme.bar\",\n \"name\": \"Bar\",\n \"version\": \"1.0.0\",\n \"author\": \"Omarchy\",\n \"description\": \"Status bar with widgets\",\n \"kinds\": [\n \"bar\"\n ],\n \"entryPoints\": {\n \"bar\": \"Bar.qml\"\n }\n}\n```\nSibling files:\n- Bar.qml (77 KB)\n- BarModel.js (13 KB)\n- indicators/Dnd.qml (1 KB)\n- indicators/NightLight.qml (1 KB)\n- indicators/PasswordlessSudo.qml (1 KB)\n- indicators/Reminder.qml (1 KB)\n- indicators/RemoteSession.qml (1 KB)\n- indicators/ScreenRecording.qml (1 KB)\n- indicators/StayAwake.qml (1 KB)\n- widgets/ActiveWindow.qml (1 KB)\n- widgets/KeyboardLayout.qml (10 KB)\n- widgets/KeyboardLayoutModel.js (6 KB)\n- widgets/Microphone.qml (2 KB)\n- widgets/Spacer.qml (1 KB)\n- widgets/SystemUpdate.qml (1 KB)\n- widgets/Tray.qml (30 KB)\n- widgets/TrayModel.js (1 KB)\n- widgets/Workspaces.qml (4 KB)\n\nImplement `widgets/Indicators.qml` in full."}, {"role": "assistant", "content": "### widgets/Indicators.qml\n```qml\nimport QtQuick\nimport Quickshell\nimport Quickshell.Io\nimport qs.Commons\nimport qs.Ui\n\nBarWidget {\n id: root\n moduleName: \"omarchy.indicators\"\n\n readonly property var defaultIndicatorEntries: [ \"PasswordlessSudo\", \"ScreenRecording\", \"RemoteSession\", \"Reminder\", \"NightLight\", \"Dnd\", \"StayAwake\" ]\n readonly property var indicatorEntries: indicatorEntriesFromSettings(settings)\n property var activeIndicatorIds: []\n property var indicatorActiveStates: ({})\n property bool indicatorAreaHovered: false\n property bool indicatorItemHovered: false\n readonly property bool alwaysShowIndicators: setting(\"alwaysShow\", false) === true\n readonly property bool revealInactiveIndicators: alwaysShowIndicators || indicatorAreaHovered || indicatorItemHovered || (bar && bar.centerSectionRevealHeld === true && bar.centerHoverRevealSuppressed !== true)\n\n signal refreshRequested()\n\n ListModel { id: activeIndicatorModel }\n\n function entryId(entry) {\n if (typeof entry === \"string\") return entry\n if (Util.isPlainObject(entry)) {\n var id = entry[\"id\"]\n if (id !== undefined && id !== null && String(id) !== \"\") return String(id)\n }\n return \"\"\n }\n\n function entrySettings(entry) {\n if (!Util.isPlainObject(entry)) return {}\n var copy = {}\n for (var key in entry) {\n if (key === \"id\") continue\n copy[key] = entry[key]\n }\n return copy\n }\n\n function indicatorEntriesFromSettings(settings) {\n var source = defaultIndicatorEntries\n if (settings.items && typeof settings.items.length === \"number\" && settings.items.length > 0) source = settings.items\n else if (settings.indicators && typeof settings.indicators.length === \"number\" && settings.indicators.length > 0) source = settings.indicators\n\n var result = []\n for (var i = 0; i < source.length; i++) {\n var item = source[i]\n if (typeof item !== \"string\" && item !== null && typeof item === \"object\") {\n try {\n item = JSON.parse(JSON.stringify(item))\n } catch (error) {\n }\n }\n var id = entryId(item)\n if (id !== \"\") result.push(item)\n }\n return result\n }\n\n function setIndicatorAreaHovered(hovered) {\n indicatorAreaHovered = hovered\n if (hovered) indicatorHideTimer.stop()\n else indicatorHideTimer.restart()\n }\n\n function setIndicatorItemHovered(hovered) {\n if (hovered) {\n indicatorItemHovered = true\n indicatorHideTimer.stop()\n } else {\n indicatorHideTimer.restart()\n }\n }\n\n function hasIndicatorId(id) {\n for (var i = 0; i < indicatorEntries.length; i++) {\n if (entryId(indicatorEntries[i]) === id) return true\n }\n return false\n }\n\n function entryForId(id) {\n for (var i = 0; i < indicatorEntries.length; i++) {\n var entry = indicatorEntries[i]\n if (entryId(entry) === id) return entry\n }\n\n return { id: id }\n }\n\n function activeModelIndex(id) {\n for (var i = 0; i < activeIndicatorModel.count; i++) {\n if (activeIndicatorModel.get(i).activeId === id) return i\n }\n return -1\n }\n\n function copyActiveStates() {\n var states = {}\n for (var id in indicatorActiveStates) {\n if (indicatorActiveStates[id] === true) states[id] = true\n }\n return states\n }\n\n function orderedActiveIds(states, preferredOrder) {\n var ids = []\n\n for (var i = 0; i < preferredOrder.length; i++) {\n var id = preferredOrder[i]\n if (ids.indexOf(id) === -1 && hasIndicatorId(id) && states[id] === true) ids.push(id)\n }\n\n return ids\n }\n\n function syncActiveIndicatorModel() {\n for (var i = activeIndicatorModel.count - 1; i >= 0; i--) {\n if (activeIndicatorIds.indexOf(activeIndicatorModel.get(i).activeId) === -1)\n activeIndicatorModel.remove(i)\n }\n\n for (var j = 0; j < activeIndicatorIds.length; j++) {\n var id = activeIndicatorIds[j]\n var index = activeModelIndex(id)\n if (index === -1) activeIndicatorModel.insert(j, { activeId: id })\n else if (index !== j) activeIndicatorModel.move(index, j, 1)\n }\n }\n\n function setIndicatorActive(entry, active) {\n var id = entryId(entry)\n if (id === \"\") return\n\n var states = copyActiveStates()\n if (active) states[id] = true\n else delete states[id]\n\n indicatorActiveStates = states\n\n var ids = orderedActiveIds(states, activeIndicatorIds)\n // The active block sits closest to the clock, so newcomers go on the far\n // side of it. Appending would shove everything already showing sideways.\n if (active && ids.indexOf(id) === -1 && hasIndicatorId(id)) ids.unshift(id)\n activeIndicatorIds = ids\n syncActiveIndicatorModel()\n }\n\n function syncActiveIndicatorOrder() {\n activeIndicatorIds = orderedActiveIds(indicatorActiveStates, activeIndicatorIds)\n syncActiveIndicatorModel()\n }\n\n function refresh() { root.refreshRequested() }\n\n onIndicatorEntriesChanged: syncActiveIndicatorOrder()\n\n // Only the tree for the current orientation exists (see orientationLoader\n // below); its wrapper keeps the stock sizing expressions, so the root's\n // implicit size still follows the blocks synchronously rather than waiting\n // on a positioner's polish.\n implicitWidth: orientationLoader.item ? orientationLoader.item.implicitWidth : 0\n implicitHeight: orientationLoader.item ? orientationLoader.item.implicitHeight : 0\n\n ShellIpc {\n target: \"omarchy.indicators\"\n\n function refresh(): void {\n root.broadcast(\"refresh\")\n }\n }\n\n Timer {\n id: indicatorHideTimer\n interval: 120\n onTriggered: {\n if (!root.indicatorAreaHovered)\n root.indicatorItemHovered = false\n }\n }\n\n Component.onCompleted: root.refreshRequested()\n\n // Instantiating both orientation trees and toggling `visible` doubled every\n // indicator per bar (and every process an indicator spawns, once per\n // monitor). Load only the tree that matches the bar orientation instead.\n Loader {\n id: orientationLoader\n sourceComponent: root.vertical ? verticalIndicatorsTree : horizontalIndicatorsTree\n }\n\n Component {\n id: horizontalIndicatorsTree\n\n Item {\n implicitWidth: activeHorizontalBlock.implicitWidth + inactiveHorizontalArea.implicitWidth\n implicitHeight: Math.max(activeHorizontalBlock.implicitHeight, inactiveHorizontalArea.implicitHeight)\n width: implicitWidth\n height: implicitHeight\n\n Row {\n id: horizontalIndicators\n\n spacing: 0\n\n HoverHandler {\n onHoveredChanged: root.setIndicatorAreaHovered(hovered)\n }\n\n Item {\n id: inactiveHorizontalArea\n\n implicitWidth: root.revealInactiveIndicators ? inactiveHorizontalBlock.implicitWidth : 0\n implicitHeight: Math.max(inactiveHorizontalBlock.implicitHeight, root.barSize)\n width: implicitWidth\n height: implicitHeight\n clip: true\n\n IndicatorBlock {\n id: inactiveHorizontalBlock\n anchors.verticalCenter: parent.verticalCenter\n indicatorsModule: root\n indicatorEntries: root.indicatorEntries\n indicatorBlock: \"inactive\"\n horizontal: true\n reportActiveState: !root.vertical\n }\n\n HoverHandler {\n onHoveredChanged: root.setIndicatorAreaHovered(hovered)\n }\n }\n\n ActiveIndicatorBlock {\n id: activeHorizontalBlock\n indicatorsModule: root\n indicatorModel: activeIndicatorModel\n horizontal: true\n reportActiveState: !root.vertical\n }\n }\n }\n }\n\n Component {\n id: verticalIndicatorsTree\n\n Item {\n implicitWidth: Math.max(activeVerticalBlock.implicitWidth, inactiveVerticalArea.implicitWidth)\n implicitHeight: activeVerticalBlock.implicitHeight + inactiveVerticalArea.implicitHeight\n width: implicitWidth\n height: implicitHeight\n\n Column {\n id: verticalIndicators\n\n spacing: 0\n\n HoverHandler {\n onHoveredChanged: root.setIndicatorAreaHovered(hovered)\n }\n\n Item {\n id: inactiveVerticalArea\n\n implicitWidth: Math.max(inactiveVerticalBlock.implicitWidth, root.barSize)\n implicitHeight: root.revealInactiveIndicators ? inactiveVerticalBlock.implicitHeight : 0\n width: implicitWidth\n height: implicitHeight\n clip: true\n\n IndicatorBlock {\n id: inactiveVerticalBlock\n anchors.horizontalCenter: parent.horizontalCenter\n indicatorsModule: root\n indicatorEntries: root.indicatorEntries\n indicatorBlock: \"inactive\"\n horizontal: false\n reportActiveState: root.vertical\n }\n\n HoverHandler {\n onHoveredChanged: root.setIndicatorAreaHovered(hovered)\n }\n }\n\n ActiveIndicatorBlock {\n id: activeVerticalBlock\n indicatorsModule: root\n indicatorModel: activeIndicatorModel\n horizontal: false\n reportActiveState: root.vertical\n }\n }\n }\n }\n\n HoverHandler {\n onHoveredChanged: root.setIndicatorAreaHovered(hovered)\n }\n\n component ActiveIndicatorBlock: Item {\n id: activeIndicatorBlockRoot\n\n property var indicatorModel: null\n property var indicatorsModule: null\n property bool horizontal: true\n property bool reportActiveState: false\n\n implicitWidth: blockLoader.item ? blockLoader.item.implicitWidth : 0\n implicitHeight: blockLoader.item ? blockLoader.item.implicitHeight : 0\n width: implicitWidth\n height: implicitHeight\n\n Loader {\n id: blockLoader\n\n anchors.centerIn: parent\n sourceComponent: activeIndicatorBlockRoot.horizontal ? horizontalActiveIndicatorBlock : verticalActiveIndicatorBlock\n }\n\n Component {\n id: horizontalActiveIndicatorBlock\n\n Row {\n spacing: 0\n\n Repeater {\n model: activeIndicatorBlockRoot.indicatorModel\n\n IndicatorLoader {\n required property string activeId\n indicatorsModule: activeIndicatorBlockRoot.indicatorsModule\n entry: activeIndicatorBlockRoot.indicatorsModule.entryForId(activeId)\n indicatorBlock: \"active\"\n reportActiveState: activeIndicatorBlockRoot.reportActiveState\n }\n }\n }\n }\n\n Component {\n id: verticalActiveIndicatorBlock\n\n Column {\n spacing: 0\n\n Repeater {\n model: activeIndicatorBlockRoot.indicatorModel\n\n IndicatorLoader {\n required property string activeId\n indicatorsModule: activeIndicatorBlockRoot.indicatorsModule\n entry: activeIndicatorBlockRoot.indicatorsModule.entryForId(activeId)\n indicatorBlock: \"active\"\n reportActiveState: activeIndicatorBlockRoot.reportActiveState\n }\n }\n }\n }\n }\n\n component IndicatorBlock: Item {\n id: indicatorBlockRoot\n\n property var indicatorEntries: []\n property var indicatorsModule: null\n property string indicatorBlock: \"active\"\n property bool horizontal: true\n property bool reportActiveState: false\n\n implicitWidth: blockLoader.item ? blockLoader.item.implicitWidth : 0\n implicitHeight: blockLoader.item ? blockLoader.item.implicitHeight : 0\n width: implicitWidth\n height: implicitHeight\n\n Loader {\n id: blockLoader\n\n anchors.centerIn: parent\n sourceComponent: indicatorBlockRoot.horizontal ? horizontalIndicatorBlock : verticalIndicatorBlock\n }\n\n Component {\n id: horizontalIndicatorBlock\n\n Row {\n spacing: 0\n\n Repeater {\n model: indicatorBlockRoot.indicatorEntries\n\n IndicatorLoader {\n required property var modelData\n indicatorsModule: indicatorBlockRoot.indicatorsModule\n entry: modelData\n indicatorBlock: indicatorBlockRoot.indicatorBlock\n reportActiveState: indicatorBlockRoot.reportActiveState\n }\n }\n }\n }\n\n Component {\n id: verticalIndicatorBlock\n\n Column {\n spacing: 0\n\n Repeater {\n model: indicatorBlockRoot.indicatorEntries\n\n IndicatorLoader {\n required property var modelData\n indicatorsModule: indicatorBlockRoot.indicatorsModule\n entry: modelData\n indicatorBlock: indicatorBlockRoot.indicatorBlock\n reportActiveState: indicatorBlockRoot.reportActiveState\n }\n }\n }\n }\n }\n\n component IndicatorLoader: Item {\n id: indicatorSlot\n\n required property var entry\n property var indicatorsModule: null\n required property string indicatorBlock\n property bool reportActiveState: false\n property bool activeStateObserved: false\n readonly property string indicatorId: root.entryId(entry)\n readonly property var indicatorSettings: root.entrySettings(entry)\n readonly property var barRef: root.bar\n\n implicitWidth: indicatorSource.item && indicatorSource.item.visible ? indicatorSource.item.implicitWidth : 0\n implicitHeight: indicatorSource.item && indicatorSource.item.visible ? indicatorSource.item.implicitHeight : 0\n width: implicitWidth\n height: implicitHeight\n onEntryChanged: {\n activeStateObserved = false\n injectProps()\n syncActiveState()\n }\n onIndicatorBlockChanged: injectProps()\n onIndicatorSettingsChanged: injectProps()\n onIndicatorsModuleChanged: {\n injectProps()\n syncActiveState()\n }\n onReportActiveStateChanged: syncActiveState()\n onBarRefChanged: injectProps()\n\n Loader {\n id: indicatorSource\n\n anchors.fill: parent\n source: indicatorSlot.indicatorId ? Qt.resolvedUrl(\"../indicators/\" + indicatorSlot.indicatorId + \".qml\") : \"\"\n onLoaded: {\n indicatorSlot.injectProps()\n indicatorSlot.syncActiveState()\n }\n onStatusChanged: if (status === Loader.Error) console.warn(\"Indicator loader error\", indicatorSlot.indicatorId, source)\n }\n\n Connections {\n target: indicatorSource.item\n ignoreUnknownSignals: true\n function onActiveChanged() { indicatorSlot.syncActiveState() }\n }\n\n function injectProps() {\n var target = indicatorSource.item\n if (!target) return\n if (\"bar\" in target) target.bar = root.bar\n if (\"moduleName\" in target) target.moduleName = indicatorId\n if (\"settings\" in target) target.settings = indicatorSettings\n if (\"indicatorBlock\" in target) target.indicatorBlock = indicatorBlock\n if (\"indicatorHost\" in target) target.indicatorHost = root\n if (\"activeOverride\" in target) target.activeOverride = indicatorBlock === \"active\" ? true : null\n }\n\n function syncActiveState() {\n if (!reportActiveState || !indicatorsModule || !indicatorsModule.setIndicatorActive) return\n\n var active = !!indicatorSource.item && indicatorSource.item.active === true\n if (indicatorBlock === \"active\") {\n if (active) activeStateObserved = true\n else if (!activeStateObserved) return\n }\n\n indicatorsModule.setIndicatorActive(entry, active)\n }\n }\n}\n```"}], "task": "chunk_component", "meta": {"origin": "first-party", "repo": "https://github.com/basecamp/omarchy", "commit": "9480d1b6a98156314dbabe6bfef08f39f8b9cd07", "license": "MIT", "plugin_path": "shell/plugins/bar", "kinds": ["bar"], "complexity": "large", "group": "3e63fc3c", "chunked": true, "validate_tree": true, "validator": "pass", "qmllint": "clean", "qml_files": 1, "chars": 16476, "tokens": 3742, "split": "train"}} {"messages": [{"role": "system", "content": "You are an Omarchy plugin expert. You write complete, valid Omarchy (Quattro / omarchy-shell, Quickshell QML) plugins. Manifests use schemaVersion 1, a namespaced id that never uses the reserved omarchy.* namespace, name, version, kinds (bar-widget|panel|overlay|menu|service|bar) with a matching safe relative entryPoints path for every kind, and no symlinks. Return every file in full as '### path' followed by a fenced code block."}, {"role": "user", "content": "Omarchy plugin `acme.bar` (bar). Manifest:\n```json\n{\n \"schemaVersion\": 1,\n \"id\": \"acme.bar\",\n \"name\": \"Bar\",\n \"version\": \"1.0.0\",\n \"author\": \"Omarchy\",\n \"description\": \"Status bar with widgets\",\n \"kinds\": [\n \"bar\"\n ],\n \"entryPoints\": {\n \"bar\": \"Bar.qml\"\n }\n}\n```\nSibling files:\n- Bar.qml (77 KB)\n- indicators/Dnd.qml (1 KB)\n- indicators/NightLight.qml (1 KB)\n- indicators/PasswordlessSudo.qml (1 KB)\n- indicators/Reminder.qml (1 KB)\n- indicators/RemoteSession.qml (1 KB)\n- indicators/ScreenRecording.qml (1 KB)\n- indicators/StayAwake.qml (1 KB)\n- widgets/ActiveWindow.qml (1 KB)\n- widgets/Indicators.qml (15 KB)\n- widgets/KeyboardLayout.qml (10 KB)\n- widgets/KeyboardLayoutModel.js (6 KB)\n- widgets/Microphone.qml (2 KB)\n- widgets/Spacer.qml (1 KB)\n- widgets/SystemUpdate.qml (1 KB)\n- widgets/Tray.qml (30 KB)\n- widgets/TrayModel.js (1 KB)\n- widgets/Workspaces.qml (4 KB)\n\nImplement `BarModel.js` in full."}, {"role": "assistant", "content": "### BarModel.js\n```javascript\nfunction isPlainObject(value) {\n return !!value && typeof value === \"object\" && !Array.isArray(value)\n}\n\nfunction normalizePosition(value) {\n var next = String(value || \"\").trim()\n return /^(top|bottom|left|right)$/.test(next) ? next : \"top\"\n}\n\nfunction entrySettings(entry) {\n if (!isPlainObject(entry)) return {}\n var copy = {}\n for (var key in entry) {\n if (key === \"id\") continue\n copy[key] = entry[key]\n }\n return copy\n}\n\nfunction entryId(entry) {\n if (typeof entry === \"string\") return entry\n if (isPlainObject(entry)) {\n var id = entry[\"id\"]\n if (id !== undefined && id !== null && String(id) !== \"\") return String(id)\n }\n return \"\"\n}\n\nfunction pinTrayToInner(entries, section) {\n var trayEntry = null\n var result = []\n var values = Array.isArray(entries) ? entries : []\n for (var i = 0; i < values.length; i++) {\n if (entryId(values[i]) === \"omarchy.tray\") trayEntry = values[i]\n else result.push(values[i])\n }\n if (trayEntry) {\n if (section === \"right\") result.unshift(trayEntry)\n else result.push(trayEntry)\n }\n return result\n}\n\nfunction moduleString(entry, key, fallback) {\n var settings = entrySettings(entry)\n var value = settings[key]\n return value === undefined || value === null ? fallback : String(value)\n}\n\nfunction entryIndex(entries, name) {\n if (!Array.isArray(entries)) return -1\n for (var i = 0; i < entries.length; i++) {\n if (entryId(entries[i]) === name) return i\n }\n return -1\n}\n\nfunction entriesBefore(entries, name) {\n var index = entryIndex(entries, name)\n return index <= 0 ? [] : entries.slice(0, index)\n}\n\nfunction entriesAfter(entries, name) {\n var index = entryIndex(entries, name)\n return index === -1 ? [] : entries.slice(index + 1)\n}\n\n// A shell.json write that only changes inline widget settings (the battery\n// percentage toggle, a clock format change) must not rebuild the bar.\n// Compare two normalized layouts: when the structure is unchanged — same\n// entry ids in the same order per region — return the settings-only changes\n// as {region, index, entry}. Return null when the change is structural, or\n// touches an entry a live settings push cannot safely reach: custom modules\n// read their entry directly rather than an injected settings property, and\n// a duplicated id makes the push ambiguous.\nfunction inlineSettingsDelta(current, next) {\n if (!isPlainObject(current) || !isPlainObject(next)) return null\n var regions = [\"left\", \"center\", \"right\"]\n var counts = {}\n for (var r = 0; r < regions.length; r++) {\n var entries = Array.isArray(next[regions[r]]) ? next[regions[r]] : []\n for (var i = 0; i < entries.length; i++) {\n var id = entryId(entries[i])\n counts[id] = (counts[id] || 0) + 1\n }\n }\n var changes = []\n for (var s = 0; s < regions.length; s++) {\n var region = regions[s]\n var a = Array.isArray(current[region]) ? current[region] : []\n var b = Array.isArray(next[region]) ? next[region] : []\n if (a.length !== b.length) return null\n for (var j = 0; j < a.length; j++) {\n if (entryId(a[j]) !== entryId(b[j])) return null\n if (JSON.stringify(a[j]) === JSON.stringify(b[j])) continue\n if (customModuleType(a[j]) || customModuleType(b[j])) return null\n if (counts[entryId(b[j])] > 1) return null\n changes.push({ region: region, index: j, entry: b[j] })\n }\n }\n return changes\n}\n\nfunction expandPath(value, home) {\n var path = String(value || \"\")\n if (path === \"\") return \"\"\n if (path.indexOf(\"~/\") === 0) return home + path.substring(1)\n if (path.indexOf(\"$HOME/\") === 0) return home + path.substring(5)\n return path\n}\n\nfunction customModuleSafeName(name) {\n var value = String(name || \"\")\n return value !== \"\" && value.indexOf(\"..\") === -1 && value[0] !== \"/\"\n}\n\nfunction customModuleType(entry) {\n var settings = entrySettings(entry)\n var type = String(settings.type || \"\")\n if (type) return type\n if (settings.exec) return \"command\"\n if (settings.source) return \"qml\"\n return \"\"\n}\n\nfunction customModulePath(entry, home, configDir) {\n var settings = entrySettings(entry)\n var name = entryId(entry)\n var source = settings.source ? expandPath(settings.source, home) : \"\"\n if (!source && customModuleSafeName(name))\n source = String(configDir || \"\") + \"/bar/modules/\" + String(name) + \".qml\"\n return source\n}\n\n// A center module is mounted twice once an anchor is set: the copy that is\n// actually drawn, and a zero-size placeholder holding its place in the flow\n// beside the anchor. Panel routing has to pick the drawn one — it is the only\n// one that can anchor a popup, carry the open-panel mark, or be found again\n// by switchPanelFrom — and fall back to the placeholder only when nothing is\n// on screen. The order the two are registered in is not stable across a live\n// bar reconfiguration, so picking the first match is not good enough.\nfunction isDrawnSlot(slot) {\n return !!slot && slot.visible === true && slot.width > 0 && slot.height > 0\n}\n\nfunction pickDrawnSlot(slots) {\n var placeholder = null\n var list = slots || []\n for (var i = 0; i < list.length; i++) {\n if (!list[i]) continue\n if (isDrawnSlot(list[i])) return list[i]\n if (!placeholder) placeholder = list[i]\n }\n return placeholder\n}\n\n// A bar surface is built per monitor, so a panel hotkey has several live\n// copies of the same widget to route to, and the panel opens on whichever\n// monitor's copy answers. Candidates are `{ slot, screenName, opened }`.\n//\n// An open copy wins first: hide and toggle have to reach the panel the user\n// can actually see, wherever it was opened from. Otherwise the focused\n// monitor's copy wins, so a summon lands where the user is working instead of\n// on whichever output registered its slot first. Neither narrowing applies on\n// a single monitor, or when the focused output has no bar of its own.\nfunction pickPanelSlot(candidates, focusedScreen) {\n var rows = Array.isArray(candidates) ? candidates : []\n var pool = rows.filter(function(row) { return row && row.opened === true })\n if (pool.length === 0) pool = rows.filter(function(row) { return !!row })\n\n var focused = String(focusedScreen || \"\")\n if (focused) {\n var onFocused = pool.filter(function(row) { return row.screenName === focused })\n if (onFocused.length > 0) pool = onFocused\n }\n\n return pickDrawnSlot(pool.map(function(row) { return row.slot }))\n}\n\n// Resolve a pointer anywhere along the bar to the closest insertion edge.\n// Requiring the pointer to sit inside another widget makes the empty space\n// around a centered group a dead zone, even though it visually reads as the\n// most natural place to drop.\nfunction nearestDropTarget(candidates, point, vertical) {\n var rows = Array.isArray(candidates) ? candidates : []\n var axis = vertical ? Number(point && point.y) : Number(point && point.x)\n if (!isFinite(axis)) return null\n\n var best = null\n var bestDistance = Infinity\n for (var i = 0; i < rows.length; i++) {\n var row = rows[i]\n if (!row || !row.slot) continue\n\n var start = Number(vertical ? row.y : row.x)\n var size = Number(vertical ? row.height : row.width)\n if (!isFinite(start) || !isFinite(size) || size <= 0) continue\n\n var beforeDistance = Math.abs(axis - start)\n var afterDistance = Math.abs(axis - (start + size))\n var after = afterDistance < beforeDistance\n var distance = after ? afterDistance : beforeDistance\n if (distance < bestDistance) {\n best = { slot: row.slot, after: after }\n bestDistance = distance\n }\n }\n return best\n}\n\n// Display cutouts (a camera notch at the top of a laptop panel) are described\n// by the platform's own package, in /usr/share/omarchy-platform/display-cutouts.json:\n//\n// { \"panels\": [ { \"connector\": \"eDP\", \"width\": 3024, \"height\": 1964, \"top\": 64 } ] }\n//\n// A panel matches a screen whose connector name starts with `connector` and\n// whose mode is width x height physical pixels; `top` is how many physical rows\n// at its top the cutout covers. Anything malformed is dropped.\nfunction parseCutouts(text) {\n var parsed\n try {\n parsed = JSON.parse(String(text || \"\"))\n } catch (error) {\n return []\n }\n var panels = parsed && Array.isArray(parsed.panels) ? parsed.panels : []\n var cutouts = []\n for (var i = 0; i < panels.length; i++) {\n var panel = panels[i] || {}\n var width = Number(panel.width)\n var height = Number(panel.height)\n var top = Number(panel.top)\n if (typeof panel.connector !== \"string\" || panel.connector === \"\") continue\n if (!(width > 0) || !(height > 0) || !(top > 0) || top >= height) continue\n cutouts.push({ connector: panel.connector, width: width, height: height, top: top })\n }\n return cutouts\n}\n\n// The cutout at the top of this screen, in logical pixels, or 0. `mode` is the\n// output's physical mode as Hyprland reports it ({ width, height, transform }).\n// Qt's devicePixelRatio is a whole number even at a fractional scale, so the\n// logical size times it rebuilds the mode only at whole scales; that stands in\n// just until Hyprland's answer arrives. A mode Hyprland reports that matches no\n// panel has no cutout.\nfunction cutoutTop(cutouts, screenName, logicalWidth, logicalHeight, devicePixelRatio, mode) {\n var name = String(screenName || \"\")\n var logical = Number(logicalWidth)\n var logicalTall = Number(logicalHeight)\n if (!(logical > 0) || !(logicalTall > 0)) return 0\n var width = Number(mode && mode.width)\n var height = Number(mode && mode.height)\n if (width > 0 && height > 0) {\n // Turned a quarter or upside down, the cutout is on another edge.\n var transform = Number(mode.transform) || 0\n if (transform !== 0 && transform !== 4) return 0\n if ((width > height) !== (logical > logicalTall)) return 0\n } else {\n var scale = Number(devicePixelRatio) > 0 ? Number(devicePixelRatio) : 1\n width = Math.round(logical * scale)\n height = Math.round(logicalTall * scale)\n }\n var list = Array.isArray(cutouts) ? cutouts : []\n for (var i = 0; i < list.length; i++) {\n var panel = list[i]\n if (name.indexOf(panel.connector) !== 0) continue\n // Logical sizes are rounded, so a rebuilt mode can be a couple of pixels off.\n if (Math.abs(width - panel.width) <= 4 && Math.abs(height - panel.height) <= 4)\n return Math.ceil(panel.top * logical / width)\n }\n return 0\n}\n\n// The height a top bar on this screen must reach to cover its cutout, or a\n// calibrated [bar] notch-height in its place. A screen without a cutout, or a\n// bar on another edge, has no floor, so a calibration never reaches an\n// external monitor.\nfunction notchFloor(cutouts, position, screenName, logicalWidth, logicalHeight, devicePixelRatio, mode, calibrated) {\n if (position !== \"top\") return 0\n var top = cutoutTop(cutouts, screenName, logicalWidth, logicalHeight, devicePixelRatio, mode)\n if (!(top > 0)) return 0\n return Number(calibrated) > 0 ? Math.round(Number(calibrated)) : top\n}\n\n// A cutout covers the middle of a top bar, so that bar draws its center\n// section beside the right one.\nfunction centerBesideRight(cutouts, position, screenName, logicalWidth, logicalHeight, devicePixelRatio, mode) {\n return position === \"top\" && cutoutTop(cutouts, screenName, logicalWidth, logicalHeight, devicePixelRatio, mode) > 0\n}\n\n// Whether a top bar can't tell its floor yet: Hyprland hasn't reported the\n// screen's mode, the logical size times Qt's ratio matched no panel (as at a\n// fractional scale), and a described panel's connector matches the screen, so\n// the mode may still bring a cutout. Such a bar waits for the mode before it\n// maps rather than guess a floor. A screen no entry's connector matches never\n// waits.\nfunction cutoutPending(cutouts, position, screenName, logicalWidth, logicalHeight, devicePixelRatio, mode) {\n if (position !== \"top\") return false\n if (Number(mode && mode.width) > 0 && Number(mode && mode.height) > 0) return false\n var name = String(screenName || \"\")\n var list = Array.isArray(cutouts) ? cutouts : []\n var described = false\n for (var i = 0; i < list.length; i++) {\n if (name.indexOf(list[i].connector) === 0) described = true\n }\n return described && !(cutoutTop(cutouts, screenName, logicalWidth, logicalHeight, devicePixelRatio, mode) > 0)\n}\n\n// The bar's thickness on the screen with this name, from the sizes a bar\n// publishes by screen name, or `fallback` (its configured size) for a screen\n// it has none for.\nfunction barSizeFor(sizes, screenName, fallback) {\n var name = String(screenName || \"\")\n var size = sizes && Object.prototype.hasOwnProperty.call(sizes, name) ? Number(sizes[name]) : 0\n return size > 0 ? size : fallback\n}\n\nif (typeof module !== \"undefined\") {\n module.exports = {\n barSizeFor: barSizeFor,\n centerBesideRight: centerBesideRight,\n cutoutPending: cutoutPending,\n cutoutTop: cutoutTop,\n isDrawnSlot: isDrawnSlot,\n notchFloor: notchFloor,\n parseCutouts: parseCutouts,\n pickDrawnSlot: pickDrawnSlot,\n pickPanelSlot: pickPanelSlot,\n nearestDropTarget: nearestDropTarget,\n normalizePosition: normalizePosition,\n entrySettings: entrySettings,\n entryId: entryId,\n pinTrayToInner: pinTrayToInner,\n moduleString: moduleString,\n entryIndex: entryIndex,\n entriesBefore: entriesBefore,\n entriesAfter: entriesAfter,\n inlineSettingsDelta: inlineSettingsDelta,\n expandPath: expandPath,\n customModuleSafeName: customModuleSafeName,\n customModuleType: customModuleType,\n customModulePath: customModulePath\n }\n}\n```"}], "task": "chunk_component", "meta": {"origin": "first-party", "repo": "https://github.com/basecamp/omarchy", "commit": "9480d1b6a98156314dbabe6bfef08f39f8b9cd07", "license": "MIT", "plugin_path": "shell/plugins/bar", "kinds": ["bar"], "complexity": "large", "group": "3e63fc3c", "chunked": true, "validate_tree": true, "validator": "pass", "qmllint": "clean", "qml_files": 0, "chars": 14865, "tokens": 3942, "split": "train"}} {"messages": [{"role": "system", "content": "You are an Omarchy plugin expert. You write complete, valid Omarchy (Quattro / omarchy-shell, Quickshell QML) plugins. Manifests use schemaVersion 1, a namespaced id that never uses the reserved omarchy.* namespace, name, version, kinds (bar-widget|panel|overlay|menu|service|bar) with a matching safe relative entryPoints path for every kind, and no symlinks. Return every file in full as '### path' followed by a fenced code block."}, {"role": "user", "content": "Omarchy plugin `acme.bar` (bar). Manifest:\n```json\n{\n \"schemaVersion\": 1,\n \"id\": \"acme.bar\",\n \"name\": \"Bar\",\n \"version\": \"1.0.0\",\n \"author\": \"Omarchy\",\n \"description\": \"Status bar with widgets\",\n \"kinds\": [\n \"bar\"\n ],\n \"entryPoints\": {\n \"bar\": \"Bar.qml\"\n }\n}\n```\nSibling files:\n- Bar.qml (77 KB)\n- BarModel.js (13 KB)\n- indicators/Dnd.qml (1 KB)\n- indicators/NightLight.qml (1 KB)\n- indicators/PasswordlessSudo.qml (1 KB)\n- indicators/Reminder.qml (1 KB)\n- indicators/RemoteSession.qml (1 KB)\n- indicators/ScreenRecording.qml (1 KB)\n- indicators/StayAwake.qml (1 KB)\n- widgets/ActiveWindow.qml (1 KB)\n- widgets/Indicators.qml (15 KB)\n- widgets/KeyboardLayoutModel.js (6 KB)\n- widgets/Microphone.qml (2 KB)\n- widgets/Spacer.qml (1 KB)\n- widgets/SystemUpdate.qml (1 KB)\n- widgets/Tray.qml (30 KB)\n- widgets/TrayModel.js (1 KB)\n- widgets/Workspaces.qml (4 KB)\n\nImplement `widgets/KeyboardLayout.qml` in full."}, {"role": "assistant", "content": "### widgets/KeyboardLayout.qml\n```qml\nimport QtQuick\nimport Quickshell\nimport Quickshell.Hyprland\nimport Quickshell.Io\nimport qs.Ui\nimport qs.Commons\nimport \"KeyboardLayoutModel.js\" as KeyboardLayoutModel\n\nBarWidget {\n id: root\n moduleName: \"omarchy.keyboard-layout\"\n\n\n property string layoutFull: \"\"\n // The keyboard the last reading spoke for, which is the one a click switches,\n // and separately the one activelayout named as being typed on. A reading\n // confirms the first is really there, so the click has a keyboard to reach\n // from the first reading onwards rather than only after a switch, and stops\n // naming one that has been unplugged.\n property string keyboardName: \"\"\n property string typedKeyboardName: \"\"\n // Keyboards on the seat, buttons and virtual ones excluded, and whether the\n // last reading left that shape in doubt.\n property int keyboardCount: 0\n property bool keyboardUnresolved: false\n // Nothing to read or switch on the single-layout install most people run, so\n // the widget ships on the bar and stays out of the way until there are two.\n // An older Hyprland that doesn't report the list keeps showing the label.\n property bool multipleLayouts: true\n // Where the reading sits in the layout list, how long that list is, and every\n // keyboard sharing it. A switch moves that set together, so it needs all three.\n property int layoutIndex: 0\n property int layoutCount: 0\n property var syncNames: []\n // Short language code per layout description (\"English (US)\": \"en\"), read from\n // xkb's own table rather than maintained by hand.\n property var layoutBriefs: ({})\n readonly property string layoutLabel: KeyboardLayoutModel.shortLabel(layoutFull, layoutBriefs)\n readonly property var inputState: InputMethodState.state\n readonly property bool multipleInputs: (inputState.methods || []).length > 1\n readonly property string inputLabel: KeyboardLayoutModel.inputLabel(inputState, layoutLabel)\n\n // A query already in flight was started before this event, so it may read the\n // layout the switch replaced. Remember the request and re-run once it lands\n // rather than dropping it; nothing else would correct the label afterwards.\n property bool refreshPending: false\n\n function refresh() {\n if (queryProc.running) {\n refreshPending = true\n return\n }\n\n refreshPending = false\n queryProc.running = true\n }\n\n // Keyboards someone can actually type on, which is not everything Hyprland\n // calls a keyboard.\n function typedKeyboards(keyboards) {\n return keyboards.filter(k => KeyboardLayoutModel.isTypedKeyboard(k.name))\n }\n\n // The main flag names no keyboard for long: fcitx5 takes it with the virtual\n // keyboard it binds to inject, which leaves no typed keyboard holding it and\n // nothing to read at all, and once that unbinds it lands on whichever device\n // Hyprland saw last, a power button included. Go by layout progress instead,\n // and by the keyboard activelayout named.\n function selectKeyboard(typed) {\n return KeyboardLayoutModel.selectKeyboard(typed, root.typedKeyboardName)\n }\n\n // switchxkblayout is a hyprctl command rather than a dispatcher, so it has to\n // be run rather than sent over the dispatch socket.\n //\n // Move every keyboard holding the same layout list, rather than the single one\n // the last reading spoke for. Naming one device puts the whole switch behind\n // UNTYPED_KEYBOARDS recognising every non-keyboard by name, and that list\n // cannot keep up with what a seat carries: vendor hotkey blocks\n // (intel-hid-events, dell-wmi-hotkeys), HID consumer controls, and Bluetooth\n // AVRCP endpoints from a pair of headphones all arrive holding the seat's\n // layout list, and they sort ahead of the keyboard being typed on. The click\n // then advances a device nobody types on; that device is now the furthest\n // along, so it wins the next reading too, and the label describes it while the\n // real keyboard never moved.\n //\n // An absolute index rather than \"next\", because \"next\" advances each device\n // from wherever it already sits: a seat that has drifted apart stays drifted\n // and merely inverts. One index converges them in a single click, and a seat\n // in lockstep is what leaves the reading nothing to disagree about afterwards.\n //\n // Keyboards given their own kb_layout hold a different list and are left out:\n // an index into this list would not mean the same layout to them.\n function cycleLayout() {\n if (!root.bar || root.layoutCount < 2 || root.syncNames.length === 0) return\n const next = (root.layoutIndex + 1) % root.layoutCount\n root.bar.run(root.syncNames.map(name =>\n \"hyprctl switchxkblayout \" + Util.shellQuote(name) + \" \" + next).join(\"; \"))\n refreshTimer.restart()\n }\n\n Component.onCompleted: {\n briefsProc.running = true\n refresh()\n }\n\n Connections {\n target: Hyprland\n function onRawEvent(event) {\n if (!event || !event.name) return\n var name = String(event.name)\n // The event names the keyboard that switched ahead of the layout it moved\n // to, and that is the keyboard being typed on whatever holds the main flag.\n if (name === \"activelayout\") {\n const named = KeyboardLayoutModel.eventKeyboardName(event)\n if (named) root.typedKeyboardName = named\n }\n\n // A reload that adds a layout to kb_layout decides whether the widget\n // shows at all, and leaves every keyboard on the layout it was already\n // reading, so it raises no activelayout to notice it by.\n if (name.indexOf(\"activelayout\") !== -1 || name === \"configreloaded\") root.refresh()\n }\n }\n\n Process {\n id: queryProc\n command: [\"hyprctl\", \"-j\", \"devices\"]\n onRunningChanged: {\n if (running) {\n stallTimer.restart()\n return\n }\n\n stallTimer.stop()\n if (root.refreshPending) root.refresh()\n }\n stdout: StdioCollector {\n waitForEnd: true\n onStreamFinished: {\n let listed\n try {\n listed = JSON.parse(text || \"{}\").keyboards\n } catch (e) {\n return\n }\n\n // A query the watchdog killed reports nothing at all, and an empty\n // string parses into the same shape a seat with no keyboards would.\n // Tell them apart by the list itself, so only a reading that reached\n // hyprctl gets to speak for the seat.\n if (!Array.isArray(listed)) return\n\n const typed = root.typedKeyboards(listed)\n const kb = root.selectKeyboard(typed)\n if (!kb || !kb.active_keymap) {\n // Either the last keyboard has been unplugged, which the label has to\n // stop describing and the click has to stop naming, or keyboards are\n // there and none of them reports a keymap. Both leave the shape in\n // doubt, so keep asking rather than letting a count from before it\n // changed settle the poll.\n root.keyboardUnresolved = true\n if (typed.length === 0) {\n root.layoutFull = \"\"\n root.keyboardName = \"\"\n }\n return\n }\n\n root.keyboardUnresolved = false\n root.keyboardCount = typed.length\n root.keyboardName = String(kb.name || \"\")\n root.multipleLayouts = kb.layout === undefined || String(kb.layout).indexOf(\",\") !== -1\n root.layoutIndex = kb.active_layout_index || 0\n root.layoutCount = kb.layout === undefined ? 0 : String(kb.layout).split(\",\").length\n // Buttons and virtual keyboards are included on purpose: they hold the\n // same list, and leaving them behind is what lets a reading drift onto\n // one of them later.\n root.syncNames = listed.filter(k => String(k.layout) === String(kb.layout))\n .map(k => String(k.name || \"\"))\n .filter(name => name !== \"\")\n root.layoutFull = kb.active_keymap\n }\n }\n }\n\n // The table only changes when xkb data is upgraded, so read it at startup and\n // leave it alone. The bar is built per monitor, so this runs once per widget.\n // The exotic rulesets cover layouts like trans (IPA) that ship in the same xkb\n // package and set just as well, so load them or those labels lose their code.\n Process {\n id: briefsProc\n command: [\"xkbcli\", \"list\", \"--load-exotic\"]\n stdout: StdioCollector {\n waitForEnd: true\n onStreamFinished: root.layoutBriefs = KeyboardLayoutModel.layoutBriefs(text)\n }\n }\n\n Timer {\n id: refreshTimer\n interval: 600\n onTriggered: root.refresh()\n }\n\n // A query that never returns would freeze the label until the shell restarts,\n // since a Process that is already running can't be re-run. Give up on one that\n // overstays so the next refresh gets through, and ask again: the reading it\n // never delivered may have been the only one due on a settled seat, and\n // nothing else would come back for it.\n Timer {\n id: stallTimer\n interval: 5000\n onTriggered: {\n queryProc.running = false\n refreshTimer.restart()\n }\n }\n\n // Which keyboard on a crowded seat the label is describing can change without\n // Hyprland announcing it, since a device arriving or leaving raises no event\n // of its own, and that can only be learned by asking. Poll while there is that\n // ambiguity, until a first reading lands so a query that failed at login still\n // recovers, and while a reading has left the seat's shape in doubt. The\n // one-keyboard install has none of those, and is left alone rather than\n // spawning hyprctl forever for an answer that cannot change.\n Timer {\n interval: 10000\n running: !root.keyboardName || root.keyboardUnresolved || root.keyboardCount > 1\n repeat: true\n onTriggered: root.refresh()\n }\n\n visible: inputLabel !== \"\" && KeyboardLayoutModel.showIndicator(layoutLabel, multipleLayouts, multipleInputs)\n implicitWidth: button.implicitWidth\n implicitHeight: button.implicitHeight\n\n WidgetButton {\n id: button\n anchors.fill: parent\n bar: root.bar\n text: root.inputLabel\n fontSize: Style.font.caption\n horizontalMargin: 6\n tooltipText: KeyboardLayoutModel.inputTooltip(root.inputState, root.layoutFull, root.multipleLayouts)\n onPressed: function(button) {\n if (root.multipleInputs && button === Qt.LeftButton) {\n InputMethodState.cycle()\n } else if (root.multipleLayouts) {\n root.cycleLayout()\n }\n }\n }\n}\n```"}], "task": "chunk_component", "meta": {"origin": "first-party", "repo": "https://github.com/basecamp/omarchy", "commit": "9480d1b6a98156314dbabe6bfef08f39f8b9cd07", "license": "MIT", "plugin_path": "shell/plugins/bar", "kinds": ["bar"], "complexity": "large", "group": "3e63fc3c", "chunked": true, "validate_tree": true, "validator": "pass", "qmllint": "clean", "qml_files": 1, "chars": 11819, "tokens": 2879, "split": "train"}} {"messages": [{"role": "system", "content": "You are an Omarchy plugin expert. You write complete, valid Omarchy (Quattro / omarchy-shell, Quickshell QML) plugins. Manifests use schemaVersion 1, a namespaced id that never uses the reserved omarchy.* namespace, name, version, kinds (bar-widget|panel|overlay|menu|service|bar) with a matching safe relative entryPoints path for every kind, and no symlinks. Return every file in full as '### path' followed by a fenced code block."}, {"role": "user", "content": "Write a complete Omarchy plugin `acme.dev-gallery` called \"Dev gallery\" (panel). Visual reference for omarchy-shell common UI components. Summon with: omarchy-shell shell summon omarchy.dev-gallery '{}' (or run: omarchy dev ui-preview). (It's a third-party plugin, so don't use the reserved omarchy.* namespace.)"}, {"role": "assistant", "content": "### manifest.json\n```json\n{\n \"schemaVersion\": 1,\n \"id\": \"acme.dev-gallery\",\n \"name\": \"Dev gallery\",\n \"version\": \"1.0.0\",\n \"author\": \"Omarchy\",\n \"description\": \"Visual reference for omarchy-shell common UI components. Summon with: omarchy-shell shell summon omarchy.dev-gallery '{}' (or run: omarchy dev ui-preview).\",\n \"kinds\": [\n \"panel\"\n ],\n \"entryPoints\": {\n \"panel\": \"GalleryPanel.qml\"\n }\n}\n```\n\n### GalleryPanel.qml\n```qml\nimport QtQuick\nimport QtQuick.Controls\nimport Quickshell\nimport qs.Ui\nimport qs.Commons\nimport qs.Commons as Commons\n\n// Visual reference + live playground for omarchy-shell's common UI\n// components. Summon with `omarchy dev ui-preview`, or directly via:\n// omarchy-shell shell summon omarchy.dev-gallery \"{}\"\n//\n// Every section here renders the REAL component (not a copy) so the\n// gallery doubles as a smoke test. When you add a new common component,\n// add a section here. Maintenance discipline: this file should ONLY use\n// imported common components, never inline reimplementations of them.\nItem {\n id: root\n\n // ---- plugin lifecycle ---------------------------------------------------\n property bool closingFromHost: false\n\n function open(payloadJson) {\n closingFromHost = false\n window.visible = true\n\n // Optional { section: \"button\" } in the payload lets `omarchy dev\n // ui-preview
` open the gallery with the cursor already on\n // a specific component, so iterating on one widget doesn't require\n // scrolling from the top each time. Unknown section names are\n // ignored — the gallery opens at its default position.\n var requested = \"\"\n if (payloadJson) {\n try {\n var parsed = JSON.parse(String(payloadJson))\n if (parsed && typeof parsed.section === \"string\") requested = parsed.section\n } catch (e) { /* ignore */ }\n }\n\n // Defer the section assignment + focus so the FloatingWindow's\n // content tree is mounted. The hasCursor bindings on each demo\n // target then scroll themselves into view via onHasCursorChanged.\n Qt.callLater(function() {\n if (requested && visibleSections.indexOf(requested) !== -1) {\n focusSection = requested\n selectedIndex = sectionFirstIndex(requested)\n }\n if (keyCatcher) keyCatcher.forceActiveFocus()\n })\n }\n\n // Host-initiated close (`shell hide`). Visibility flips without\n // notifying the host back — it already knows.\n function close() {\n closingFromHost = true\n window.visible = false\n closingFromHost = false\n }\n\n // User-initiated close (Esc, window close button). Tell the shell so its\n // openPanelIds map stays consistent and `toggle` works on the next call.\n function requestClose() {\n if (shell && typeof shell.hide === \"function\") shell.hide(\"omarchy.dev-gallery\")\n else window.visible = false\n }\n\n // ---- host injections ----------------------------------------------------\n property var shell: null\n\n // ---- theme --------------------------------------------------------------\n readonly property color foreground: Commons.Color.foreground\n readonly property color background: Commons.Color.background\n readonly property color accent: Commons.Color.accent\n readonly property color urgent: Commons.Color.urgent\n readonly property string fontFamily: \"monospace\"\n\n // Fake `bar` for components that take a whole bar object (e.g. Slider).\n readonly property var fakeBar: QtObject {\n readonly property color foreground: root.foreground\n readonly property color background: root.background\n readonly property color urgent: root.urgent\n readonly property string fontFamily: root.fontFamily\n readonly property string position: \"top\"\n readonly property bool vertical: false\n readonly property int barSize: 26\n }\n\n // ---- cursor model -------------------------------------------------------\n //\n // The gallery itself uses the same recipe wifi / audio / bluetooth /\n // monitor panels use: focusSection + selectedIndex drive a single\n // highlight that crosses kit primitives uniformly, with j/k walking\n // targets (jumping section boundaries automatically), h/l acting\n // locally (horizontal rows / slider adjustment), Enter activating, and\n // Esc closing. Mouse hover updates the same (focusSection,\n // selectedIndex) so keyboard and pointer never diverge.\n //\n // Plugin authors: copy this section verbatim as a template. Replace\n // the section IDs with whatever your panel needs. The shape\n // (visibleSections, sectionCount, sectionIsHorizontal,\n // sectionAdjustsValue, moveCursor, moveCursorH, activateCursor,\n // ensureCursorVisible, clampCursor) is the canonical pattern.\n property string focusSection: \"cursor-surface\"\n property int selectedIndex: 0\n\n // Demo state mutated by interaction.\n property string choiceDemoValue: \"top\"\n property bool toggleDemoOn: true\n property bool toggleSquareOn: false\n property bool switchDemoOn: true\n property bool switchBusyOn: false\n property string dropdownDemoValue: \"Clock\"\n property string searchableDemoValue: \"\"\n property int numberDemoValue: 15\n\n readonly property var visibleSections: [\n \"cursor-surface\", \"button\", \"button-group\", \"panel-action-button\",\n \"panel-tool-tip\", \"slider\", \"text-field\", \"number-field\",\n \"toggle\", \"toggle-switch\", \"dropdown\", \"searchable-dropdown\", \"composed\"\n ]\n\n function sectionCount(section) {\n switch (section) {\n case \"cursor-surface\": return 3\n case \"button\": return 5\n case \"button-group\": return 4\n case \"panel-action-button\": return 4\n case \"panel-tool-tip\": return 1\n case \"slider\": return 1\n case \"text-field\": return 2\n case \"number-field\": return 1\n case \"toggle\": return 2\n case \"toggle-switch\": return 2\n case \"dropdown\": return 1\n case \"searchable-dropdown\": return 1\n case \"composed\": return 2\n }\n return 0\n }\n\n // True for sections whose primitives lay out horizontally (a row of\n // buttons) — j/k jumps to the next/prev section, h/l walks within the row.\n function sectionIsHorizontal(section) {\n return section === \"button\"\n || section === \"button-group\"\n || section === \"panel-action-button\"\n || section === \"toggle-switch\"\n }\n\n // True for sections where h/l should adjust a value rather than walk.\n function sectionAdjustsValue(section) {\n return section === \"slider\"\n }\n\n // Where to land when entering a section from above / below.\n function sectionFirstIndex(section) { return 0 }\n function sectionLastIndex(section) { return Math.max(0, sectionCount(section) - 1) }\n\n function moveCursor(delta) {\n var sections = visibleSections\n var sIdx = sections.indexOf(focusSection)\n if (sIdx < 0) {\n focusSection = sections[0]\n selectedIndex = sectionFirstIndex(focusSection)\n return\n }\n if (sectionIsHorizontal(focusSection) || sectionAdjustsValue(focusSection)\n || sectionCount(focusSection) <= 1) {\n // Single-row / horizontal / value-adjust sections: j/k crosses to\n // the next section.\n if (delta > 0 && sIdx < sections.length - 1) {\n focusSection = sections[sIdx + 1]\n selectedIndex = sectionFirstIndex(focusSection)\n } else if (delta < 0 && sIdx > 0) {\n focusSection = sections[sIdx - 1]\n selectedIndex = sectionLastIndex(focusSection)\n }\n return\n }\n // Vertical multi-row section: walk within, then cross at boundaries.\n var next = selectedIndex + delta\n if (next < 0) {\n if (sIdx > 0) {\n focusSection = sections[sIdx - 1]\n selectedIndex = sectionLastIndex(focusSection)\n }\n } else if (next >= sectionCount(focusSection)) {\n if (sIdx < sections.length - 1) {\n focusSection = sections[sIdx + 1]\n selectedIndex = sectionFirstIndex(focusSection)\n }\n } else {\n selectedIndex = next\n }\n }\n\n function moveCursorH(delta) {\n if (sectionAdjustsValue(focusSection)) {\n // h/l on the slider section nudges the demo volume by 5%.\n sliderRow.demoVolume = Math.max(0, Math.min(1, sliderRow.demoVolume + delta * 0.05))\n return\n }\n if (!sectionIsHorizontal(focusSection)) return\n var next = selectedIndex + delta\n var max = sectionCount(focusSection) - 1\n if (next < 0) next = 0\n if (next > max) next = max\n selectedIndex = next\n }\n\n function activateCursor() {\n if (focusSection === \"button-group\") {\n var opts = [\"top\", \"right\", \"bottom\", \"left\"]\n if (selectedIndex >= 0 && selectedIndex < opts.length)\n root.choiceDemoValue = opts[selectedIndex]\n return\n }\n if (focusSection === \"toggle\") {\n if (selectedIndex === 0) root.toggleDemoOn = !root.toggleDemoOn\n else root.toggleSquareOn = !root.toggleSquareOn\n return\n }\n if (focusSection === \"toggle-switch\") {\n // The busy switch swallows activation the same way it swallows clicks.\n if (selectedIndex === 0) root.switchDemoOn = !root.switchDemoOn\n return\n }\n if (focusSection === \"dropdown\") {\n demoDropdown.toggle()\n return\n }\n if (focusSection === \"searchable-dropdown\") {\n demoSearchableDropdown.toggle()\n return\n }\n if (focusSection === \"text-field\") {\n if (selectedIndex === 0) demoTextField.forceActiveFocus()\n else demoPasswordField.forceActiveFocus()\n return\n }\n if (focusSection === \"number-field\") {\n numberDemo.field.forceActiveFocus()\n return\n }\n // pill / panel-action-button / cursor-surface / composed: nothing to\n // mutate in a demo, but real consumers would call their clicked().\n }\n\n function clampCursor() {\n var sections = visibleSections\n if (sections.indexOf(focusSection) < 0) {\n focusSection = sections[0]\n selectedIndex = sectionFirstIndex(focusSection)\n return\n }\n if (selectedIndex < 0) selectedIndex = 0\n var max = sectionLastIndex(focusSection)\n if (selectedIndex > max) selectedIndex = max\n }\n\n // Scroll the gallery so the given Item is fully visible inside\n // scrollArea's viewport, with a 20px breathing margin. Wired into the\n // hasCursor change handler of every cursor target below.\n function ensureCursorVisible(item) {\n if (!item || !scrollArea) return\n var flick = scrollArea.contentItem\n if (!flick || flick.contentY === undefined) return\n var pt = item.mapToItem(flick.contentItem || flick, 0, 0)\n var top = pt.y\n var bottom = top + (item.height || 0)\n var viewTop = flick.contentY\n var viewBottom = viewTop + flick.height\n var margin = 12\n if (top < viewTop + margin) flick.contentY = Math.max(0, top - margin)\n else if (bottom > viewBottom - margin)\n flick.contentY = bottom + margin - flick.height\n }\n\n FloatingWindow {\n id: window\n title: \"Omarchy shell – dev gallery\"\n color: root.background\n implicitWidth: 720\n implicitHeight: 760\n minimumSize: Qt.size(560, 520)\n\n onVisibleChanged: {\n if (!visible && !root.closingFromHost && root.shell && typeof root.shell.hide === \"function\")\n root.shell.hide(\"omarchy.dev-gallery\")\n }\n\n FocusScope {\n id: focusScope\n anchors.fill: parent\n focus: true\n\n function scrollBy(dy) {\n var sb = scrollArea.ScrollBar.vertical\n if (!sb || scrollArea.contentHeight <= scrollArea.height) return\n var newPos = sb.position + dy / scrollArea.contentHeight\n sb.position = Math.max(0, Math.min(1 - sb.size, newPos))\n }\n\n // Page/Home/End handled here so they bubble up past keyCatcher\n // (which only consumes Esc / Enter / j-k-h-l / x / text keys).\n Keys.priority: Keys.AfterItem\n Keys.onPressed: function(event) {\n if (event.key === Qt.Key_PageDown) {\n focusScope.scrollBy(300); event.accepted = true\n } else if (event.key === Qt.Key_PageUp) {\n focusScope.scrollBy(-300); event.accepted = true\n } else if (event.key === Qt.Key_Home) {\n scrollArea.ScrollBar.vertical.position = 0\n event.accepted = true\n } else if (event.key === Qt.Key_End) {\n var sb = scrollArea.ScrollBar.vertical\n if (sb) sb.position = Math.max(0, 1 - sb.size)\n event.accepted = true\n }\n }\n\n // Panel-style key dispatch — the gallery demonstrates the standard,\n // so it USES the standard. j/k walks cursor targets across sections,\n // h/l acts locally (rows + slider adjust), Enter activates the\n // current target, Esc closes. The catcher suspends itself while a\n // dropdown popup or text field owns keyboard input, so typing into\n // the embedded controls doesn't double-drive the panel cursor.\n PanelKeyCatcher {\n id: keyCatcher\n anchors.fill: parent\n blocked: demoDropdown.popupOpen\n || demoSearchableDropdown.popupOpen\n || demoTextField.activeFocus\n || demoPasswordField.activeFocus\n onMoveRequested: function(dx, dy) {\n if (dy !== 0) root.moveCursor(dy)\n else if (dx !== 0) root.moveCursorH(dx)\n }\n onActivateRequested: root.activateCursor()\n onCloseRequested: root.requestClose()\n\n ScrollView {\n id: scrollArea\n anchors.fill: parent\n anchors.margins: Style.space(18)\n clip: true\n ScrollBar.horizontal.policy: ScrollBar.AlwaysOff\n\n Column {\n width: scrollArea.availableWidth\n spacing: Style.space(22)\n\n // ---- Header ------------------------------------------------------\n Column {\n width: parent.width\n spacing: Style.space(4)\n\n Text {\n text: \"Omarchy shell · dev gallery\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.iconLarge\n font.bold: true\n }\n Text {\n text: \"Live previews of every type exported from qs.Ui. Use this as the visual reference when porting panels or building plugins. j/k or arrows to walk; h/l within rows; Enter to activate; Esc to close.\"\n color: Qt.darker(root.foreground, 1.4)\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n width: parent.width\n wrapMode: Text.WordWrap\n }\n }\n\n PanelSeparator { foreground: root.foreground }\n\n // ---- Kit conventions ---------------------------------------------\n Column {\n width: parent.width\n spacing: Style.space(8)\n\n Text {\n text: \"Conventions\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.subtitle\n font.bold: true\n }\n\n BorderSurface {\n width: parent.width\n implicitHeight: conventionsCol.implicitHeight + Style.spacing.rowPaddingX * 2\n color: Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.04)\n radius: Style.cornerRadius\n borderSpec: Border.flat(Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.10), 1)\n\n Column {\n id: conventionsCol\n anchors.left: parent.left\n anchors.right: parent.right\n anchors.verticalCenter: parent.verticalCenter\n anchors.leftMargin: Style.space(14)\n anchors.rightMargin: Style.space(14)\n spacing: Style.space(8)\n\n Text {\n width: parent.width\n wrapMode: Text.WordWrap\n color: Qt.darker(root.foreground, 1.4)\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n text: \"Theme. qs.Commons.Style exposes cornerRadius plus shared normal / hover-cursor / selected / focus state tokens (state colors, fill alphas, border widths, and border alphas), spacing tokens, typography, and bar dimensions. Focus defaults to hover-cursor; selected borders are off by default. Border widths are the theme-level on/off switch for state borders. qs.Commons.Color exposes foreground / background / accent / urgent plus per-surface roles. Components default-bind to these so a caller with no overrides matches the active theme.\"\n }\n Text {\n width: parent.width\n wrapMode: Text.WordWrap\n color: Qt.darker(root.foreground, 1.4)\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n text: \"Single cursor. Most reusable panel primitives expose hasCursor: bool and emit hovered(bool); composed rows (including sliders) wrap their content in CursorSurface. The panel root owns cursorActive + focusSection + selectedIndex; each element binds hasCursor: root.cursorActive && root.focusSection === 'X' && root.selectedIndex === N, and onHovered flips cursorActive on while updating the same state. No initial highlight, then one highlight on screen once the keyboard or mouse enters. See plugins/panels/audio/Panel.qml for the canonical recipe.\"\n }\n Text {\n width: parent.width\n wrapMode: Text.WordWrap\n color: Qt.darker(root.foreground, 1.4)\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n text: \"Popups + editors. Dropdown / SearchableDropdown expose popupOpen plus open() / close() / toggle(); inline TextField uses activeFocus. While any of those own the keys, set PanelKeyCatcher.blocked so the panel's cursor model freezes and the active widget handles input.\"\n }\n Text {\n width: parent.width\n wrapMode: Text.WordWrap\n color: Qt.darker(root.foreground, 1.4)\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n text: \"Adding a component. Drop the QML in Ui/, add a line to Ui/qmldir, then add a section here using the real type (not a copy). The gallery doubles as a smoke test — if a component starts misbehaving this is the fastest place to see it.\"\n }\n }\n }\n }\n\n PanelSeparator { foreground: root.foreground }\n\n // ---- Typography --------------------------------------------------\n Column {\n width: parent.width\n spacing: Style.space(8)\n\n Text {\n text: \"Typography\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.subtitle\n font.bold: true\n }\n Text {\n text: \"Style.font.* is the shell-wide type scale. Themes ship a single \"\n + \"[font] base-size in shell.toml; every token derives from it via a \"\n + \"fixed multiplier, so changing base-size rescales the whole shell \"\n + \"proportionally. There is no upper clamp. Themes can also pin \"\n + \"individual tokens (caption, heading, display, etc.) for stylistic \"\n + \"emphasis. The family follows the fontconfig monospace alias \\u2014 \"\n + \"set it with `omarchy font set `.\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n width: parent.width\n wrapMode: Text.WordWrap\n }\n\n BorderSurface {\n width: parent.width\n implicitHeight: typeCol.implicitHeight + Style.spacing.rowPaddingX * 2\n color: Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.04)\n radius: Style.cornerRadius\n borderSpec: Border.flat(Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.10), 1)\n\n Column {\n id: typeCol\n anchors.left: parent.left\n anchors.right: parent.right\n anchors.verticalCenter: parent.verticalCenter\n anchors.leftMargin: Style.space(14)\n anchors.rightMargin: Style.space(14)\n spacing: Style.space(10)\n\n Text {\n text: \"Scale\"\n color: Qt.darker(root.foreground, 1.4)\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n font.bold: true\n }\n\n // Every Style.font.* token rendered at its actual size. The\n // model is data, not a Component graph, so this list stays\n // in lockstep with the singleton without manual upkeep.\n Repeater {\n model: [\n { key: \"caption\", size: Style.font.caption, sample: \"Section header text\" },\n { key: \"bodySmall\", size: Style.font.bodySmall, sample: \"Secondary / tooltip text\" },\n { key: \"body\", size: Style.font.body, sample: \"Default label and control text\" },\n { key: \"subtitle\", size: Style.font.subtitle, sample: \"Row title text\" },\n { key: \"title\", size: Style.font.title, sample: \"Card title text\" },\n { key: \"heading\", size: Style.font.heading, sample: \"Panel heading\" },\n { key: \"display\", size: Style.font.display, sample: \"Display text\" },\n { key: \"displayLarge\", size: Style.font.displayLarge, sample: \"Display large\" },\n { key: \"iconSmall\", size: Style.font.iconSmall, sample: \"\\uf004 \\uf005 \\uf02d\" },\n { key: \"icon\", size: Style.font.icon, sample: \"\\uf004 \\uf005 \\uf02d\" },\n { key: \"iconLarge\", size: Style.font.iconLarge, sample: \"\\uf004 \\uf005 \\uf02d\" }\n ]\n delegate: Item {\n required property var modelData\n width: typeCol.width\n implicitHeight: Math.max(metaCol.implicitHeight, sampleText.implicitHeight)\n\n Column {\n id: metaCol\n anchors.left: parent.left\n anchors.verticalCenter: parent.verticalCenter\n width: Style.space(140)\n spacing: Style.space(1)\n Text {\n textFormat: Text.PlainText\n text: \"Style.font.\" + modelData.key\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n }\n Text {\n textFormat: Text.PlainText\n text: modelData.size + \" px\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n }\n }\n\n Text {\n id: sampleText\n textFormat: Text.PlainText\n anchors.left: metaCol.right\n anchors.right: parent.right\n anchors.verticalCenter: parent.verticalCenter\n anchors.leftMargin: Style.space(16)\n text: modelData.sample\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: modelData.size\n elide: Text.ElideRight\n }\n }\n }\n\n Rectangle {\n width: parent.width\n height: 1\n color: Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.10)\n }\n\n Text {\n text: \"Theme tokens\"\n color: Qt.darker(root.foreground, 1.4)\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n font.bold: true\n }\n\n Grid {\n columns: 2\n columnSpacing: Style.space(16)\n rowSpacing: Style.space(4)\n width: parent.width\n\n Text {\n text: \"Style.font.family\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n }\n Text {\n textFormat: Text.PlainText\n text: Style.font.family\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n }\n\n Text {\n text: \"Style.font.resolvedFamily\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n }\n Text {\n textFormat: Text.PlainText\n text: Style.font.resolvedFamily\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n }\n\n Text {\n text: \"Style.font.baseSize\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n }\n Text {\n textFormat: Text.PlainText\n text: Style.font.baseSize + \" px\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n }\n\n Text {\n text: \"Style.bar.sizeHorizontal\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n }\n Text {\n textFormat: Text.PlainText\n text: Style.bar.sizeHorizontal + \" px\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n }\n\n Text {\n text: \"Style.bar.sizeVertical\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n }\n Text {\n textFormat: Text.PlainText\n text: Style.bar.sizeVertical + \" px\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n }\n\n Text {\n text: \"Style.spacing.scale\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n }\n Text {\n textFormat: Text.PlainText\n text: Style.spacing.scale.toFixed(2)\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n }\n\n Text {\n text: \"Style.spacing.panelPadding\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n }\n Text {\n textFormat: Text.PlainText\n text: Style.spacing.panelPadding + \" px\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n }\n }\n }\n }\n }\n\n PanelSeparator { foreground: root.foreground }\n\n // ---- PanelSectionHeader ------------------------------------------\n Column {\n width: parent.width\n spacing: Style.space(8)\n\n Text {\n text: \"PanelSectionHeader\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.subtitle\n font.bold: true\n }\n Text {\n text: \"Small-caps-style intro label for a section.\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n }\n\n BorderSurface {\n width: parent.width\n implicitHeight: shCol.implicitHeight + Style.spacing.rowPaddingX * 2\n color: Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.04)\n radius: Style.cornerRadius\n borderSpec: Border.flat(Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.10), 1)\n\n Column {\n id: shCol\n anchors.left: parent.left\n anchors.right: parent.right\n anchors.verticalCenter: parent.verticalCenter\n anchors.leftMargin: Style.space(14)\n anchors.rightMargin: Style.space(14)\n spacing: Style.space(6)\n\n PanelSectionHeader {\n text: \"DNS provider\"\n foreground: root.foreground\n fontFamily: root.fontFamily\n }\n PanelSectionHeader {\n text: \"Wi-Fi networks\"\n foreground: root.foreground\n fontFamily: root.fontFamily\n }\n PanelSectionHeader {\n text: \"Playing\"\n foreground: root.foreground\n fontFamily: root.fontFamily\n fontSize: Style.font.bodySmall\n }\n }\n }\n }\n\n // ---- PanelSeparator ----------------------------------------------\n Column {\n width: parent.width\n spacing: Style.space(8)\n\n Text {\n text: \"PanelSeparator\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.subtitle\n font.bold: true\n }\n Text {\n text: \"1px horizontal rule. Default 0.12 alpha on foreground; tweak via strength.\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n }\n\n BorderSurface {\n width: parent.width\n implicitHeight: sepCol.implicitHeight + Style.spacing.rowPaddingX * 2\n color: Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.04)\n radius: Style.cornerRadius\n borderSpec: Border.flat(Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.10), 1)\n\n Column {\n id: sepCol\n anchors.left: parent.left\n anchors.right: parent.right\n anchors.verticalCenter: parent.verticalCenter\n anchors.leftMargin: Style.space(14)\n anchors.rightMargin: Style.space(14)\n spacing: Style.space(12)\n\n PanelSeparator { foreground: root.foreground }\n PanelSeparator { foreground: root.foreground; strength: 0.25 }\n PanelSeparator { foreground: root.foreground; strength: 0.45 }\n }\n }\n }\n\n // ---- CursorSurface -----------------------------------------------\n Column {\n width: parent.width\n spacing: Style.space(8)\n\n Text {\n text: \"CursorSurface\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.subtitle\n font.bold: true\n }\n Text {\n text: \"Single highlight chrome for keyboard+mouse navigable items. Press h/l (anywhere in this window) to move the demo cursor. The middle item is also marked `current` to show how the two states layer.\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n width: parent.width\n wrapMode: Text.WordWrap\n }\n\n BorderSurface {\n width: parent.width\n implicitHeight: csCol.implicitHeight + Style.spacing.rowPaddingX * 2\n color: Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.04)\n radius: Style.cornerRadius\n borderSpec: Border.flat(Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.10), 1)\n\n Column {\n id: csCol\n anchors.left: parent.left\n anchors.right: parent.right\n anchors.verticalCenter: parent.verticalCenter\n anchors.leftMargin: Style.space(14)\n anchors.rightMargin: Style.space(14)\n spacing: Style.space(6)\n\n Repeater {\n model: [\n { \"label\": \"Idle row\" },\n { \"label\": \"Currently-active row (e.g. connected wifi, default sink)\" },\n { \"label\": \"Forget / scan / disabled-ish row\" }\n ]\n\n CursorSurface {\n required property var modelData\n required property int index\n width: parent.width\n implicitHeight: csLabel.implicitHeight + Style.spacing.controlGap * 2\n hasCursor: root.focusSection === \"cursor-surface\" && root.selectedIndex === index\n current: index === 1\n foreground: root.foreground\n fill: Style.hoverFillFor(root.foreground, root.accent)\n onHasCursorChanged: if (hasCursor) root.ensureCursorVisible(this)\n\n Text {\n id: csLabel\n textFormat: Text.PlainText\n anchors.left: parent.left\n anchors.right: parent.right\n anchors.verticalCenter: parent.verticalCenter\n anchors.leftMargin: Style.space(10)\n anchors.rightMargin: Style.space(10)\n text: modelData.label\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.body\n elide: Text.ElideRight\n }\n\n MouseArea {\n anchors.fill: parent\n hoverEnabled: true\n cursorShape: Qt.PointingHandCursor\n onContainsMouseChanged: if (containsMouse) {\n root.focusSection = \"cursor-surface\"\n root.selectedIndex = parent.index\n }\n }\n }\n }\n }\n }\n }\n\n // ---- Button ------------------------------------------------------\n Column {\n width: parent.width\n spacing: Style.space(8)\n\n Text {\n text: \"Button\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.subtitle\n font.bold: true\n }\n Text {\n text: \"The kit's only button. State flags compose from shared tokens: hasCursor / hover paints the hover-cursor fill; active/selected add the selected fill; selected borders are off by default; bordered opts into normal/hover-cursor borders; focusable uses the same defaults as hover-cursor. Click below or press h/l to walk the demo cursor.\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n width: parent.width\n wrapMode: Text.WordWrap\n }\n\n BorderSurface {\n width: parent.width\n implicitHeight: buttonRow.implicitHeight + Style.spacing.rowPaddingX * 2\n color: Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.04)\n radius: Style.cornerRadius\n borderSpec: Border.flat(Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.10), 1)\n\n Row {\n id: buttonRow\n anchors.left: parent.left\n anchors.verticalCenter: parent.verticalCenter\n anchors.leftMargin: Style.space(14)\n spacing: Style.space(16)\n\n // Each demo Button is paired with a caption labeling the\n // state(s) it exercises so the section reads as one Button\n // showing its flag combinations side by side.\n\n Column {\n spacing: Style.space(6)\n Button {\n anchors.horizontalCenter: parent.horizontalCenter\n text: \"DHCP\"\n tooltipText: \"Use DNS from DHCP\"\n hasCursor: root.focusSection === \"button\" && root.selectedIndex === 0\n onHovered: function(h) {\n if (h) { root.focusSection = \"button\"; root.selectedIndex = 0 }\n }\n onHasCursorChanged: if (hasCursor) root.ensureCursorVisible(this)\n }\n Text {\n anchors.horizontalCenter: parent.horizontalCenter\n text: \"idle\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n }\n }\n\n Column {\n spacing: Style.space(6)\n Button {\n anchors.horizontalCenter: parent.horizontalCenter\n text: \"Cloudflare\"\n tooltipText: \"Set DNS to Cloudflare\"\n active: true\n hasCursor: root.focusSection === \"button\" && root.selectedIndex === 1\n onHovered: function(h) {\n if (h) { root.focusSection = \"button\"; root.selectedIndex = 1 }\n }\n onHasCursorChanged: if (hasCursor) root.ensureCursorVisible(this)\n }\n Text {\n anchors.horizontalCenter: parent.horizontalCenter\n text: \"active\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n }\n }\n\n Column {\n spacing: Style.space(6)\n Button {\n anchors.horizontalCenter: parent.horizontalCenter\n iconText: \"󰑐\"\n tooltipText: \"Refresh\"\n horizontalPadding: Style.spacing.controlGap\n verticalPadding: Style.spacing.labelGap\n hasCursor: root.focusSection === \"button\" && root.selectedIndex === 2\n onHovered: function(h) {\n if (h) { root.focusSection = \"button\"; root.selectedIndex = 2 }\n }\n onHasCursorChanged: if (hasCursor) root.ensureCursorVisible(this)\n }\n Text {\n anchors.horizontalCenter: parent.horizontalCenter\n text: \"icon only\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n }\n }\n\n Column {\n spacing: Style.space(6)\n Button {\n anchors.horizontalCenter: parent.horizontalCenter\n iconText: \"󰂯\"\n text: \"On\"\n tooltipText: \"Turn Bluetooth off\"\n active: true\n hasCursor: root.focusSection === \"button\" && root.selectedIndex === 3\n onHovered: function(h) {\n if (h) { root.focusSection = \"button\"; root.selectedIndex = 3 }\n }\n onHasCursorChanged: if (hasCursor) root.ensureCursorVisible(this)\n }\n Text {\n anchors.horizontalCenter: parent.horizontalCenter\n text: \"icon + active\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n }\n }\n\n Column {\n spacing: Style.space(6)\n Button {\n anchors.horizontalCenter: parent.horizontalCenter\n text: \"Apply\"\n focusable: true\n bordered: true\n hasCursor: root.focusSection === \"button\" && root.selectedIndex === 4\n onHovered: function(h) {\n if (h) { root.focusSection = \"button\"; root.selectedIndex = 4 }\n }\n onHasCursorChanged: if (hasCursor) root.ensureCursorVisible(this)\n }\n Text {\n anchors.horizontalCenter: parent.horizontalCenter\n text: \"bordered + focusable\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n }\n }\n }\n }\n }\n\n // ---- ButtonGroup -------------------------------------------------\n Column {\n id: buttonGroupSection\n width: parent.width\n spacing: Style.space(8)\n readonly property bool focused: root.focusSection === \"button-group\"\n onFocusedChanged: if (focused) root.ensureCursorVisible(this)\n\n Text {\n text: \"ButtonGroup\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.subtitle\n font.bold: true\n }\n Text {\n text: \"Mutually-exclusive row of Buttons. Each chip uses Button's bordered chrome; selected and cursor states come from the same shared Style tokens as every other control. Click to pick or press h/l + Enter.\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n width: parent.width\n wrapMode: Text.WordWrap\n }\n\n BorderSurface {\n width: parent.width\n implicitHeight: choiceRow.implicitHeight + Style.spacing.rowPaddingX * 2\n color: Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.04)\n radius: Style.cornerRadius\n borderSpec: Border.flat(Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.10), 1)\n\n ButtonGroup {\n id: choiceRow\n anchors.left: parent.left\n anchors.verticalCenter: parent.verticalCenter\n anchors.leftMargin: Style.space(14)\n options: [\"top\", \"right\", \"bottom\", \"left\"]\n value: root.choiceDemoValue\n cursorIndex: root.focusSection === \"button-group\" ? root.selectedIndex : -1\n onChanged: function(v) {\n root.focusSection = \"button-group\"\n root.choiceDemoValue = v\n }\n onHovered: function(index, isHovered) {\n if (isHovered) {\n root.focusSection = \"button-group\"\n root.selectedIndex = index\n }\n }\n }\n }\n }\n\n // ---- PanelActionButton -------------------------------------------\n Column {\n width: parent.width\n spacing: Style.space(8)\n\n Text {\n text: \"PanelActionButton\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.subtitle\n font.bold: true\n }\n Text {\n text: \"22×22 right-edge action button. Two flavors via hoverColor: default (foreground tint, e.g. confirm) and urgent (red tint, e.g. forget/unpair). Hover and click states are intrinsic; the row that owns it stays responsible for the cursor highlight.\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n width: parent.width\n wrapMode: Text.WordWrap\n }\n\n BorderSurface {\n width: parent.width\n implicitHeight: pabCol.implicitHeight + Style.spacing.rowPaddingX * 2\n color: Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.04)\n radius: Style.cornerRadius\n borderSpec: Border.flat(Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.10), 1)\n\n Row {\n id: pabCol\n anchors.left: parent.left\n anchors.verticalCenter: parent.verticalCenter\n anchors.leftMargin: Style.space(14)\n spacing: Style.space(18)\n\n PanelActionButton {\n iconText: \"󰄬\"\n tooltipText: \"Confirm (default flavor)\"\n foreground: root.foreground\n fontFamily: root.fontFamily\n hasCursor: root.focusSection === \"panel-action-button\" && root.selectedIndex === 0\n onHovered: function(h) {\n if (h) { root.focusSection = \"panel-action-button\"; root.selectedIndex = 0 }\n }\n onHasCursorChanged: if (hasCursor) root.ensureCursorVisible(this)\n }\n\n PanelActionButton {\n iconText: \"󰅙\"\n tooltipText: \"Forget network (urgent flavor)\"\n foreground: root.foreground\n hoverColor: root.urgent\n fontFamily: root.fontFamily\n hasCursor: root.focusSection === \"panel-action-button\" && root.selectedIndex === 1\n onHovered: function(h) {\n if (h) { root.focusSection = \"panel-action-button\"; root.selectedIndex = 1 }\n }\n onHasCursorChanged: if (hasCursor) root.ensureCursorVisible(this)\n }\n\n PanelActionButton {\n iconText: \"󰄬\"\n tooltipText: \"Disabled — type a passphrase first\"\n foreground: root.foreground\n fontFamily: root.fontFamily\n enabled: false\n hasCursor: root.focusSection === \"panel-action-button\" && root.selectedIndex === 2\n onHovered: function(h) {\n if (h) { root.focusSection = \"panel-action-button\"; root.selectedIndex = 2 }\n }\n onHasCursorChanged: if (hasCursor) root.ensureCursorVisible(this)\n }\n\n PanelActionButton {\n iconText: \"󰒓\"\n tooltipText: \"Focusable (settings form button)\"\n foreground: root.foreground\n fontFamily: root.fontFamily\n fontSize: Style.font.subtitle\n size: Style.space(26)\n focusable: true\n hasCursor: root.focusSection === \"panel-action-button\" && root.selectedIndex === 3\n onHovered: function(h) {\n if (h) { root.focusSection = \"panel-action-button\"; root.selectedIndex = 3 }\n }\n onHasCursorChanged: if (hasCursor) root.ensureCursorVisible(this)\n }\n }\n }\n }\n\n // ---- PanelToolTip ------------------------------------------------\n Column {\n width: parent.width\n spacing: Style.space(8)\n\n Text {\n text: \"PanelToolTip\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.subtitle\n font.bold: true\n }\n Text {\n text: \"Hover the swatch below to see the styled tooltip. Use this whenever a custom button or row needs a hover hint.\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n width: parent.width\n wrapMode: Text.WordWrap\n }\n\n BorderSurface {\n id: tipSwatch\n width: Style.space(140)\n height: Style.space(36)\n readonly property bool focused: root.focusSection === \"panel-tool-tip\"\n color: tipMouse.containsMouse || focused\n ? Style.hoverFillFor(root.foreground, root.accent)\n : Style.normalFillFor(root.foreground, root.accent)\n borderSpec: focused\n ? Border.controlSpec(\"hover-cursor\", root.foreground, root.accent)\n : Border.controlSpec(\"normal\", root.foreground, root.accent)\n radius: Style.cornerRadius\n onFocusedChanged: if (focused) root.ensureCursorVisible(this)\n\n Text {\n anchors.centerIn: parent\n text: \"hover me\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.body\n }\n\n MouseArea {\n id: tipMouse\n anchors.fill: parent\n hoverEnabled: true\n cursorShape: Qt.PointingHandCursor\n onContainsMouseChanged: if (containsMouse) {\n root.focusSection = \"panel-tool-tip\"\n root.selectedIndex = 0\n }\n }\n\n PanelToolTip {\n visible: tipMouse.containsMouse || tipSwatch.focused\n text: \"Styled tooltip — drop into any panel\"\n panelForeground: root.foreground\n fontFamily: root.fontFamily\n }\n }\n }\n\n\n // ---- Slider ------------------------------------------------------\n Column {\n width: parent.width\n spacing: Style.space(8)\n\n Text {\n text: \"Slider\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.subtitle\n font.bold: true\n }\n Text {\n text: \"Volume / progress slider. Drag, click anywhere on the track, or scroll the wheel.\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n width: parent.width\n wrapMode: Text.WordWrap\n }\n\n CursorSurface {\n id: sliderWrapper\n width: parent.width\n implicitHeight: sliderRow.implicitHeight + Style.spacing.rowPaddingX * 2\n outline: true\n foreground: root.foreground\n hasCursor: root.focusSection === \"slider\"\n onHasCursorChanged: if (hasCursor) root.ensureCursorVisible(this)\n\n HoverHandler {\n onHoveredChanged: if (hovered) {\n root.focusSection = \"slider\"\n root.selectedIndex = 0\n }\n }\n\n Row {\n id: sliderRow\n anchors.left: parent.left\n anchors.right: parent.right\n anchors.verticalCenter: parent.verticalCenter\n anchors.leftMargin: Style.space(14)\n anchors.rightMargin: Style.space(14)\n spacing: Style.space(10)\n property real demoVolume: 0.45\n\n Text {\n text: \"󰕾\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.heading\n width: 22\n horizontalAlignment: Text.AlignHCenter\n anchors.verticalCenter: parent.verticalCenter\n }\n\n PanelSlider {\n id: demoSlider\n bar: root.fakeBar\n width: parent.width - 70\n anchors.verticalCenter: parent.verticalCenter\n value: sliderRow.demoVolume\n onMoved: function(v) { sliderRow.demoVolume = v }\n }\n\n Text {\n textFormat: Text.PlainText\n text: Math.round((demoSlider.dragging ? demoSlider.liveValue : sliderRow.demoVolume) * 100) + \"%\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.body\n width: 38\n horizontalAlignment: Text.AlignRight\n anchors.verticalCenter: parent.verticalCenter\n }\n }\n }\n }\n\n // ---- TextField -----------------------------------------------------\n Column {\n width: parent.width\n spacing: Style.space(8)\n\n Text {\n text: \"TextField\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.subtitle\n font.bold: true\n }\n Text {\n text: \"Single-line input. Inherits Qt Quick Controls TextField, swaps in the kit's focus chrome and selection styling. Toggle `password: true` for masked entry.\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n width: parent.width\n wrapMode: Text.WordWrap\n }\n\n BorderSurface {\n width: parent.width\n implicitHeight: tfCol.implicitHeight + Style.spacing.rowPaddingX * 2\n color: Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.04)\n radius: Style.cornerRadius\n borderSpec: Border.flat(Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.10), 1)\n\n Column {\n id: tfCol\n anchors.left: parent.left\n anchors.right: parent.right\n anchors.verticalCenter: parent.verticalCenter\n anchors.leftMargin: Style.space(14)\n anchors.rightMargin: Style.space(14)\n spacing: Style.space(10)\n\n TextField {\n id: demoTextField\n width: parent.width\n placeholderText: \"Type something (Enter to start editing, Esc to leave)\"\n foreground: root.foreground\n accent: root.accent\n font.family: root.fontFamily\n font.pixelSize: Style.font.body\n hasCursor: !activeFocus && root.focusSection === \"text-field\" && root.selectedIndex === 0\n onHoveredChanged: if (hovered) {\n root.focusSection = \"text-field\"; root.selectedIndex = 0\n }\n onHasCursorChanged: if (hasCursor) root.ensureCursorVisible(this)\n Keys.onPressed: function(event) {\n if (event.key === Qt.Key_Escape) {\n focus = false\n event.accepted = true\n }\n }\n }\n\n TextField {\n id: demoPasswordField\n width: parent.width\n password: true\n placeholderText: \"Password\"\n foreground: root.foreground\n accent: root.accent\n font.family: root.fontFamily\n font.pixelSize: Style.font.body\n hasCursor: !activeFocus && root.focusSection === \"text-field\" && root.selectedIndex === 1\n onHoveredChanged: if (hovered) {\n root.focusSection = \"text-field\"; root.selectedIndex = 1\n }\n onHasCursorChanged: if (hasCursor) root.ensureCursorVisible(this)\n Keys.onPressed: function(event) {\n if (event.key === Qt.Key_Escape) {\n focus = false\n event.accepted = true\n }\n }\n }\n }\n }\n }\n\n // ---- NumberField ---------------------------------------------------\n Column {\n width: parent.width\n spacing: Style.space(8)\n\n Text {\n text: \"NumberField\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.subtitle\n font.bold: true\n }\n Text {\n text: \"Labeled spin box for integer settings. Up/down arrows step the value; the field accepts typed input. Pair with `from`/`to`/`stepSize` to constrain range.\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n width: parent.width\n wrapMode: Text.WordWrap\n }\n\n BorderSurface {\n width: parent.width\n implicitHeight: numberDemo.implicitHeight + Style.spacing.rowPaddingX * 2\n color: Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.04)\n borderSpec: Border.flat(Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.12), 1)\n radius: Style.cornerRadius\n\n NumberField {\n id: numberDemo\n anchors.left: parent.left\n anchors.verticalCenter: parent.verticalCenter\n anchors.leftMargin: Style.space(12)\n label: \"Auto-refresh interval (minutes)\"\n from: 1\n to: 1440\n value: root.numberDemoValue\n foreground: root.foreground\n accent: root.accent\n fontFamily: root.fontFamily\n hasCursor: root.focusSection === \"number-field\" && root.selectedIndex === 0\n onModified: function(v) { root.numberDemoValue = v }\n onHovered: function(on) {\n if (on) { root.focusSection = \"number-field\"; root.selectedIndex = 0 }\n }\n onHasCursorChanged: if (hasCursor) root.ensureCursorVisible(this)\n }\n }\n }\n\n // ---- Toggle --------------------------------------------------------\n Column {\n width: parent.width\n spacing: Style.space(8)\n\n Text {\n text: \"Toggle\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.subtitle\n font.bold: true\n }\n Text {\n text: \"Title + description + switch. Click anywhere on the row to flip; caller updates `checked` in response. Uses the same normal / hover-cursor / focus tokens as Button and the checked switch track uses selected tokens.\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n width: parent.width\n wrapMode: Text.WordWrap\n }\n\n Toggle {\n width: parent.width\n label: \"Transparent bar\"\n description: \"Hide the bar background so the wallpaper shows through.\"\n foreground: root.foreground\n accent: root.accent\n fontFamily: root.fontFamily\n checked: root.toggleDemoOn\n hasCursor: root.focusSection === \"toggle\" && root.selectedIndex === 0\n onHovered: function(h) {\n if (h) { root.focusSection = \"toggle\"; root.selectedIndex = 0 }\n }\n onHasCursorChanged: if (hasCursor) root.ensureCursorVisible(this)\n onClicked: {\n root.focusSection = \"toggle\"; root.selectedIndex = 0\n root.toggleDemoOn = !root.toggleDemoOn\n }\n }\n\n Toggle {\n width: parent.width\n label: \"Square switch (forced)\"\n description: \"`rounded: false` overrides the theme auto-detect so the switch reads square even when corners are round. Set `rounded: Style.cornerRadius > 0` (the default) to follow the theme.\"\n foreground: root.foreground\n accent: root.accent\n fontFamily: root.fontFamily\n rounded: false\n checked: root.toggleSquareOn\n hasCursor: root.focusSection === \"toggle\" && root.selectedIndex === 1\n onHovered: function(h) {\n if (h) { root.focusSection = \"toggle\"; root.selectedIndex = 1 }\n }\n onHasCursorChanged: if (hasCursor) root.ensureCursorVisible(this)\n onClicked: {\n root.focusSection = \"toggle\"; root.selectedIndex = 1\n root.toggleSquareOn = !root.toggleSquareOn\n }\n }\n }\n\n // ---- ToggleSwitch --------------------------------------------------\n Column {\n width: parent.width\n spacing: Style.space(8)\n\n Text {\n text: \"ToggleSwitch\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.subtitle\n font.bold: true\n }\n Text {\n text: \"The bare switch Toggle puts at the end of its row, for places with no room for a labeled row — a panel hero's trailingControl, for instance. Caller owns `checked` and flips it on `toggled()`. Set `busy` while an operation is in flight to swallow further clicks without disturbing hover or tooltips; services that track a desired state optimistically get an instant knob throw because `checked` is already the optimistic value.\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n width: parent.width\n wrapMode: Text.WordWrap\n }\n\n Row {\n spacing: Style.space(24)\n\n ToggleSwitch {\n checked: root.switchDemoOn\n foreground: root.foreground\n accent: root.accent\n hasCursor: root.focusSection === \"toggle-switch\" && root.selectedIndex === 0\n onHovered: function(h) {\n if (h) { root.focusSection = \"toggle-switch\"; root.selectedIndex = 0 }\n }\n onHasCursorChanged: if (hasCursor) root.ensureCursorVisible(this)\n onToggled: {\n root.focusSection = \"toggle-switch\"; root.selectedIndex = 0\n root.switchDemoOn = !root.switchDemoOn\n }\n }\n\n ToggleSwitch {\n checked: root.switchBusyOn\n busy: true\n foreground: root.foreground\n accent: root.accent\n hasCursor: root.focusSection === \"toggle-switch\" && root.selectedIndex === 1\n onHovered: function(h) {\n if (h) { root.focusSection = \"toggle-switch\"; root.selectedIndex = 1 }\n }\n onHasCursorChanged: if (hasCursor) root.ensureCursorVisible(this)\n onToggled: root.switchBusyOn = !root.switchBusyOn\n }\n }\n\n Text {\n text: \"The second switch is `busy: true` — hover still responds, clicks do not.\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n width: parent.width\n wrapMode: Text.WordWrap\n }\n }\n\n // ---- Dropdown -----------------------------------------------------\n Column {\n width: parent.width\n spacing: Style.space(8)\n\n Text {\n text: \"Dropdown\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.subtitle\n font.bold: true\n }\n Text {\n text: \"Themed single-select with a panel-styled popup. Tab to focus the trigger, Enter/Space opens, j/k or arrows walk options, Enter selects. Options can be plain strings or { value, label } objects.\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n width: parent.width\n wrapMode: Text.WordWrap\n }\n\n BorderSurface {\n width: parent.width\n implicitHeight: ddCol.implicitHeight + Style.spacing.rowPaddingX * 2\n color: Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.04)\n radius: Style.cornerRadius\n borderSpec: Border.flat(Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.10), 1)\n\n Column {\n id: ddCol\n anchors.left: parent.left\n anchors.right: parent.right\n anchors.verticalCenter: parent.verticalCenter\n anchors.leftMargin: Style.space(14)\n anchors.rightMargin: Style.space(14)\n spacing: Style.space(6)\n\n Dropdown {\n id: demoDropdown\n width: Style.spacing.dropdownWidth\n label: \"Center anchor\"\n fontFamily: root.fontFamily\n options: [\"omarchy.clock\", \"omarchy.weather\", \"omarchy.power\"]\n value: root.dropdownDemoValue\n hasCursor: root.focusSection === \"dropdown\" && root.selectedIndex === 0\n onHovered: function(h) {\n if (h) { root.focusSection = \"dropdown\"; root.selectedIndex = 0 }\n }\n onHasCursorChanged: if (hasCursor) root.ensureCursorVisible(this)\n onChanged: function(v) { root.dropdownDemoValue = v }\n }\n }\n }\n }\n\n // ---- SearchableDropdown -------------------------------------------\n Column {\n width: parent.width\n spacing: Style.space(8)\n\n Text {\n text: \"SearchableDropdown\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.subtitle\n font.bold: true\n }\n Text {\n text: \"Dropdown with an embedded filter input. Type to narrow the list, Down to jump from the search to the first match, Enter to select. Use this for long option lists where plain scrolling is friction.\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n width: parent.width\n wrapMode: Text.WordWrap\n }\n\n BorderSurface {\n width: parent.width\n implicitHeight: sddCol.implicitHeight + Style.spacing.rowPaddingX * 2\n color: Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.04)\n radius: Style.cornerRadius\n borderSpec: Border.flat(Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.10), 1)\n\n Column {\n id: sddCol\n anchors.left: parent.left\n anchors.right: parent.right\n anchors.verticalCenter: parent.verticalCenter\n anchors.leftMargin: Style.space(14)\n anchors.rightMargin: Style.space(14)\n spacing: Style.space(6)\n\n SearchableDropdown {\n id: demoSearchableDropdown\n width: Style.spacing.searchableDropdownWidth\n label: \"Add widget\"\n fontFamily: root.fontFamily\n placeholderText: \"Search widgets...\"\n hasCursor: root.focusSection === \"searchable-dropdown\" && root.selectedIndex === 0\n onHovered: function(h) {\n if (h) { root.focusSection = \"searchable-dropdown\"; root.selectedIndex = 0 }\n }\n onHasCursorChanged: if (hasCursor) root.ensureCursorVisible(this)\n options: [\n { value: \"Clock\", label: \"Clock\", description: \"Time + date display\" },\n { value: \"Weather\", label: \"Weather\", description: \"Local conditions and forecast\" },\n { value: \"omarchy.power\", label: \"Power\", description: \"Charge level + power profile\" },\n { value: \"audio\", label: \"Audio\", description: \"Output sink + volume\" },\n { value: \"network\", label: \"Network\", description: \"Wi-Fi + ethernet status\" },\n { value: \"bluetooth\", label: \"Bluetooth\", description: \"Paired and nearby devices\" },\n { value: \"monitor\", label: \"Monitor\", description: \"Brightness + scale\" },\n { value: \"Media\", label: \"Media\", description: \"Now-playing + transport\" },\n { value: \"Workspaces\", label: \"Workspaces\", description: \"Hyprland workspace pills\" },\n { value: \"system-tray\", label: \"System tray\", description: \"StatusNotifierItem icons\" },\n { value: \"omarchy-menu\", label: \"Omarchy menu\", description: \"Launcher / system menu\" },\n { value: \"power-profiles\", label: \"Power profiles\", description: \"Performance / balanced / saver\" },\n { value: \"hardware\", label: \"Hardware\", description: \"CPU, GPU, mem utilization\" },\n { value: \"notifications\", label: \"Notifications\", description: \"Recent notification history\" }\n ]\n value: root.searchableDemoValue\n onChanged: function(v) { root.searchableDemoValue = v }\n }\n }\n }\n }\n\n // ---- Composed example -------------------------------------------\n Column {\n width: parent.width\n spacing: Style.space(8)\n\n Text {\n text: \"Composed example\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.subtitle\n font.bold: true\n }\n Text {\n text: \"A miniature wifi-style row built from CursorSurface + PanelActionButton + PanelToolTip. This is what new panel rows should look like — no inline Rectangle/Text/MouseArea reimplementation.\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n width: parent.width\n wrapMode: Text.WordWrap\n }\n\n BorderSurface {\n width: parent.width\n implicitHeight: composedCol.implicitHeight + Style.spacing.rowPaddingX * 2\n color: Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.04)\n radius: Style.cornerRadius\n borderSpec: Border.flat(Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.10), 1)\n\n Column {\n id: composedCol\n anchors.left: parent.left\n anchors.right: parent.right\n anchors.verticalCenter: parent.verticalCenter\n anchors.leftMargin: Style.space(14)\n anchors.rightMargin: Style.space(14)\n spacing: Style.space(6)\n\n PanelSectionHeader {\n text: \"Wi-Fi networks\"\n foreground: root.foreground\n fontFamily: root.fontFamily\n }\n\n CursorSurface {\n width: parent.width\n implicitHeight: composedRow.implicitHeight + Style.spacing.md * 2\n current: true\n foreground: root.foreground\n fill: Style.hoverFillFor(root.foreground, root.accent)\n hasCursor: root.focusSection === \"composed\" && root.selectedIndex === 0\n onHasCursorChanged: if (hasCursor) root.ensureCursorVisible(this)\n\n HoverHandler {\n onHoveredChanged: if (hovered) {\n root.focusSection = \"composed\"; root.selectedIndex = 0\n }\n }\n\n Item {\n id: composedRow\n anchors.left: parent.left\n anchors.right: parent.right\n anchors.verticalCenter: parent.verticalCenter\n anchors.leftMargin: Style.space(10)\n anchors.rightMargin: Style.space(10)\n implicitHeight: 36\n\n Text {\n id: composedIcon\n anchors.left: parent.left\n anchors.verticalCenter: parent.verticalCenter\n text: \"󰖩\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.title\n }\n\n PanelActionButton {\n id: composedForget\n anchors.right: parent.right\n anchors.verticalCenter: parent.verticalCenter\n iconText: \"󰅙\"\n tooltipText: \"Forget network\"\n foreground: root.foreground\n hoverColor: root.urgent\n fontFamily: root.fontFamily\n }\n\n Column {\n spacing: Style.space(1)\n anchors.left: composedIcon.right\n anchors.leftMargin: Style.space(10)\n anchors.right: composedForget.left\n anchors.rightMargin: Style.space(8)\n anchors.verticalCenter: parent.verticalCenter\n\n Text {\n text: \"HughesWiFi\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.body\n elide: Text.ElideRight\n width: parent.width\n }\n Text {\n text: \"Connected\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n elide: Text.ElideRight\n width: parent.width\n }\n }\n }\n }\n\n PanelSeparator { foreground: root.foreground }\n\n CursorSurface {\n width: parent.width\n implicitHeight: idleRow.implicitHeight + Style.spacing.md * 2\n foreground: root.foreground\n fill: Style.hoverFillFor(root.foreground, root.accent)\n hasCursor: root.focusSection === \"composed\" && root.selectedIndex === 1\n onHasCursorChanged: if (hasCursor) root.ensureCursorVisible(this)\n\n HoverHandler {\n onHoveredChanged: if (hovered) {\n root.focusSection = \"composed\"; root.selectedIndex = 1\n }\n }\n\n Item {\n id: idleRow\n anchors.left: parent.left\n anchors.right: parent.right\n anchors.verticalCenter: parent.verticalCenter\n anchors.leftMargin: Style.space(10)\n anchors.rightMargin: Style.space(10)\n implicitHeight: 36\n\n Text {\n anchors.left: parent.left\n anchors.verticalCenter: parent.verticalCenter\n text: \"󰖩\"\n color: Qt.darker(root.foreground, 1.4)\n font.family: root.fontFamily\n font.pixelSize: Style.font.title\n }\n\n Text {\n anchors.left: parent.left\n anchors.leftMargin: Style.space(24)\n anchors.verticalCenter: parent.verticalCenter\n text: \"HughesATT\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.body\n }\n }\n }\n }\n }\n }\n\n Item { width: 1; height: Style.spacing.rowPaddingX }\n }\n }\n }\n }\n }\n}\n```"}], "task": "build_from_spec", "meta": {"origin": "first-party", "repo": "https://github.com/basecamp/omarchy", "commit": "9480d1b6a98156314dbabe6bfef08f39f8b9cd07", "license": "MIT", "plugin_path": "shell/plugins/dev-gallery", "kinds": ["panel"], "complexity": "large", "group": "1ceedb12", "validator": "pass", "qmllint": "clean", "qml_files": 1, "chars": 79766, "tokens": 15676, "split": "train"}} {"messages": [{"role": "system", "content": "You are an Omarchy plugin expert. You write complete, valid Omarchy (Quattro / omarchy-shell, Quickshell QML) plugins. Manifests use schemaVersion 1, a namespaced id that never uses the reserved omarchy.* namespace, name, version, kinds (bar-widget|panel|overlay|menu|service|bar) with a matching safe relative entryPoints path for every kind, and no symlinks. Return every file in full as '### path' followed by a fenced code block."}, {"role": "user", "content": "I want an Omarchy panel plugin named Dev gallery (id `acme.dev-gallery`): Visual reference for omarchy-shell common UI components. Summon with: omarchy-shell shell summon omarchy.dev-gallery '{}' (or run: omarchy dev ui-preview). Give me every file."}, {"role": "assistant", "content": "### manifest.json\n```json\n{\n \"schemaVersion\": 1,\n \"id\": \"acme.dev-gallery\",\n \"name\": \"Dev gallery\",\n \"version\": \"1.0.0\",\n \"author\": \"Omarchy\",\n \"description\": \"Visual reference for omarchy-shell common UI components. Summon with: omarchy-shell shell summon omarchy.dev-gallery '{}' (or run: omarchy dev ui-preview).\",\n \"kinds\": [\n \"panel\"\n ],\n \"entryPoints\": {\n \"panel\": \"GalleryPanel.qml\"\n }\n}\n```\n\n### GalleryPanel.qml\n```qml\nimport QtQuick\nimport QtQuick.Controls\nimport Quickshell\nimport qs.Ui\nimport qs.Commons\nimport qs.Commons as Commons\n\n// Visual reference + live playground for omarchy-shell's common UI\n// components. Summon with `omarchy dev ui-preview`, or directly via:\n// omarchy-shell shell summon omarchy.dev-gallery \"{}\"\n//\n// Every section here renders the REAL component (not a copy) so the\n// gallery doubles as a smoke test. When you add a new common component,\n// add a section here. Maintenance discipline: this file should ONLY use\n// imported common components, never inline reimplementations of them.\nItem {\n id: root\n\n // ---- plugin lifecycle ---------------------------------------------------\n property bool closingFromHost: false\n\n function open(payloadJson) {\n closingFromHost = false\n window.visible = true\n\n // Optional { section: \"button\" } in the payload lets `omarchy dev\n // ui-preview
` open the gallery with the cursor already on\n // a specific component, so iterating on one widget doesn't require\n // scrolling from the top each time. Unknown section names are\n // ignored — the gallery opens at its default position.\n var requested = \"\"\n if (payloadJson) {\n try {\n var parsed = JSON.parse(String(payloadJson))\n if (parsed && typeof parsed.section === \"string\") requested = parsed.section\n } catch (e) { /* ignore */ }\n }\n\n // Defer the section assignment + focus so the FloatingWindow's\n // content tree is mounted. The hasCursor bindings on each demo\n // target then scroll themselves into view via onHasCursorChanged.\n Qt.callLater(function() {\n if (requested && visibleSections.indexOf(requested) !== -1) {\n focusSection = requested\n selectedIndex = sectionFirstIndex(requested)\n }\n if (keyCatcher) keyCatcher.forceActiveFocus()\n })\n }\n\n // Host-initiated close (`shell hide`). Visibility flips without\n // notifying the host back — it already knows.\n function close() {\n closingFromHost = true\n window.visible = false\n closingFromHost = false\n }\n\n // User-initiated close (Esc, window close button). Tell the shell so its\n // openPanelIds map stays consistent and `toggle` works on the next call.\n function requestClose() {\n if (shell && typeof shell.hide === \"function\") shell.hide(\"omarchy.dev-gallery\")\n else window.visible = false\n }\n\n // ---- host injections ----------------------------------------------------\n property var shell: null\n\n // ---- theme --------------------------------------------------------------\n readonly property color foreground: Commons.Color.foreground\n readonly property color background: Commons.Color.background\n readonly property color accent: Commons.Color.accent\n readonly property color urgent: Commons.Color.urgent\n readonly property string fontFamily: \"monospace\"\n\n // Fake `bar` for components that take a whole bar object (e.g. Slider).\n readonly property var fakeBar: QtObject {\n readonly property color foreground: root.foreground\n readonly property color background: root.background\n readonly property color urgent: root.urgent\n readonly property string fontFamily: root.fontFamily\n readonly property string position: \"top\"\n readonly property bool vertical: false\n readonly property int barSize: 26\n }\n\n // ---- cursor model -------------------------------------------------------\n //\n // The gallery itself uses the same recipe wifi / audio / bluetooth /\n // monitor panels use: focusSection + selectedIndex drive a single\n // highlight that crosses kit primitives uniformly, with j/k walking\n // targets (jumping section boundaries automatically), h/l acting\n // locally (horizontal rows / slider adjustment), Enter activating, and\n // Esc closing. Mouse hover updates the same (focusSection,\n // selectedIndex) so keyboard and pointer never diverge.\n //\n // Plugin authors: copy this section verbatim as a template. Replace\n // the section IDs with whatever your panel needs. The shape\n // (visibleSections, sectionCount, sectionIsHorizontal,\n // sectionAdjustsValue, moveCursor, moveCursorH, activateCursor,\n // ensureCursorVisible, clampCursor) is the canonical pattern.\n property string focusSection: \"cursor-surface\"\n property int selectedIndex: 0\n\n // Demo state mutated by interaction.\n property string choiceDemoValue: \"top\"\n property bool toggleDemoOn: true\n property bool toggleSquareOn: false\n property bool switchDemoOn: true\n property bool switchBusyOn: false\n property string dropdownDemoValue: \"Clock\"\n property string searchableDemoValue: \"\"\n property int numberDemoValue: 15\n\n readonly property var visibleSections: [\n \"cursor-surface\", \"button\", \"button-group\", \"panel-action-button\",\n \"panel-tool-tip\", \"slider\", \"text-field\", \"number-field\",\n \"toggle\", \"toggle-switch\", \"dropdown\", \"searchable-dropdown\", \"composed\"\n ]\n\n function sectionCount(section) {\n switch (section) {\n case \"cursor-surface\": return 3\n case \"button\": return 5\n case \"button-group\": return 4\n case \"panel-action-button\": return 4\n case \"panel-tool-tip\": return 1\n case \"slider\": return 1\n case \"text-field\": return 2\n case \"number-field\": return 1\n case \"toggle\": return 2\n case \"toggle-switch\": return 2\n case \"dropdown\": return 1\n case \"searchable-dropdown\": return 1\n case \"composed\": return 2\n }\n return 0\n }\n\n // True for sections whose primitives lay out horizontally (a row of\n // buttons) — j/k jumps to the next/prev section, h/l walks within the row.\n function sectionIsHorizontal(section) {\n return section === \"button\"\n || section === \"button-group\"\n || section === \"panel-action-button\"\n || section === \"toggle-switch\"\n }\n\n // True for sections where h/l should adjust a value rather than walk.\n function sectionAdjustsValue(section) {\n return section === \"slider\"\n }\n\n // Where to land when entering a section from above / below.\n function sectionFirstIndex(section) { return 0 }\n function sectionLastIndex(section) { return Math.max(0, sectionCount(section) - 1) }\n\n function moveCursor(delta) {\n var sections = visibleSections\n var sIdx = sections.indexOf(focusSection)\n if (sIdx < 0) {\n focusSection = sections[0]\n selectedIndex = sectionFirstIndex(focusSection)\n return\n }\n if (sectionIsHorizontal(focusSection) || sectionAdjustsValue(focusSection)\n || sectionCount(focusSection) <= 1) {\n // Single-row / horizontal / value-adjust sections: j/k crosses to\n // the next section.\n if (delta > 0 && sIdx < sections.length - 1) {\n focusSection = sections[sIdx + 1]\n selectedIndex = sectionFirstIndex(focusSection)\n } else if (delta < 0 && sIdx > 0) {\n focusSection = sections[sIdx - 1]\n selectedIndex = sectionLastIndex(focusSection)\n }\n return\n }\n // Vertical multi-row section: walk within, then cross at boundaries.\n var next = selectedIndex + delta\n if (next < 0) {\n if (sIdx > 0) {\n focusSection = sections[sIdx - 1]\n selectedIndex = sectionLastIndex(focusSection)\n }\n } else if (next >= sectionCount(focusSection)) {\n if (sIdx < sections.length - 1) {\n focusSection = sections[sIdx + 1]\n selectedIndex = sectionFirstIndex(focusSection)\n }\n } else {\n selectedIndex = next\n }\n }\n\n function moveCursorH(delta) {\n if (sectionAdjustsValue(focusSection)) {\n // h/l on the slider section nudges the demo volume by 5%.\n sliderRow.demoVolume = Math.max(0, Math.min(1, sliderRow.demoVolume + delta * 0.05))\n return\n }\n if (!sectionIsHorizontal(focusSection)) return\n var next = selectedIndex + delta\n var max = sectionCount(focusSection) - 1\n if (next < 0) next = 0\n if (next > max) next = max\n selectedIndex = next\n }\n\n function activateCursor() {\n if (focusSection === \"button-group\") {\n var opts = [\"top\", \"right\", \"bottom\", \"left\"]\n if (selectedIndex >= 0 && selectedIndex < opts.length)\n root.choiceDemoValue = opts[selectedIndex]\n return\n }\n if (focusSection === \"toggle\") {\n if (selectedIndex === 0) root.toggleDemoOn = !root.toggleDemoOn\n else root.toggleSquareOn = !root.toggleSquareOn\n return\n }\n if (focusSection === \"toggle-switch\") {\n // The busy switch swallows activation the same way it swallows clicks.\n if (selectedIndex === 0) root.switchDemoOn = !root.switchDemoOn\n return\n }\n if (focusSection === \"dropdown\") {\n demoDropdown.toggle()\n return\n }\n if (focusSection === \"searchable-dropdown\") {\n demoSearchableDropdown.toggle()\n return\n }\n if (focusSection === \"text-field\") {\n if (selectedIndex === 0) demoTextField.forceActiveFocus()\n else demoPasswordField.forceActiveFocus()\n return\n }\n if (focusSection === \"number-field\") {\n numberDemo.field.forceActiveFocus()\n return\n }\n // pill / panel-action-button / cursor-surface / composed: nothing to\n // mutate in a demo, but real consumers would call their clicked().\n }\n\n function clampCursor() {\n var sections = visibleSections\n if (sections.indexOf(focusSection) < 0) {\n focusSection = sections[0]\n selectedIndex = sectionFirstIndex(focusSection)\n return\n }\n if (selectedIndex < 0) selectedIndex = 0\n var max = sectionLastIndex(focusSection)\n if (selectedIndex > max) selectedIndex = max\n }\n\n // Scroll the gallery so the given Item is fully visible inside\n // scrollArea's viewport, with a 20px breathing margin. Wired into the\n // hasCursor change handler of every cursor target below.\n function ensureCursorVisible(item) {\n if (!item || !scrollArea) return\n var flick = scrollArea.contentItem\n if (!flick || flick.contentY === undefined) return\n var pt = item.mapToItem(flick.contentItem || flick, 0, 0)\n var top = pt.y\n var bottom = top + (item.height || 0)\n var viewTop = flick.contentY\n var viewBottom = viewTop + flick.height\n var margin = 12\n if (top < viewTop + margin) flick.contentY = Math.max(0, top - margin)\n else if (bottom > viewBottom - margin)\n flick.contentY = bottom + margin - flick.height\n }\n\n FloatingWindow {\n id: window\n title: \"Omarchy shell – dev gallery\"\n color: root.background\n implicitWidth: 720\n implicitHeight: 760\n minimumSize: Qt.size(560, 520)\n\n onVisibleChanged: {\n if (!visible && !root.closingFromHost && root.shell && typeof root.shell.hide === \"function\")\n root.shell.hide(\"omarchy.dev-gallery\")\n }\n\n FocusScope {\n id: focusScope\n anchors.fill: parent\n focus: true\n\n function scrollBy(dy) {\n var sb = scrollArea.ScrollBar.vertical\n if (!sb || scrollArea.contentHeight <= scrollArea.height) return\n var newPos = sb.position + dy / scrollArea.contentHeight\n sb.position = Math.max(0, Math.min(1 - sb.size, newPos))\n }\n\n // Page/Home/End handled here so they bubble up past keyCatcher\n // (which only consumes Esc / Enter / j-k-h-l / x / text keys).\n Keys.priority: Keys.AfterItem\n Keys.onPressed: function(event) {\n if (event.key === Qt.Key_PageDown) {\n focusScope.scrollBy(300); event.accepted = true\n } else if (event.key === Qt.Key_PageUp) {\n focusScope.scrollBy(-300); event.accepted = true\n } else if (event.key === Qt.Key_Home) {\n scrollArea.ScrollBar.vertical.position = 0\n event.accepted = true\n } else if (event.key === Qt.Key_End) {\n var sb = scrollArea.ScrollBar.vertical\n if (sb) sb.position = Math.max(0, 1 - sb.size)\n event.accepted = true\n }\n }\n\n // Panel-style key dispatch — the gallery demonstrates the standard,\n // so it USES the standard. j/k walks cursor targets across sections,\n // h/l acts locally (rows + slider adjust), Enter activates the\n // current target, Esc closes. The catcher suspends itself while a\n // dropdown popup or text field owns keyboard input, so typing into\n // the embedded controls doesn't double-drive the panel cursor.\n PanelKeyCatcher {\n id: keyCatcher\n anchors.fill: parent\n blocked: demoDropdown.popupOpen\n || demoSearchableDropdown.popupOpen\n || demoTextField.activeFocus\n || demoPasswordField.activeFocus\n onMoveRequested: function(dx, dy) {\n if (dy !== 0) root.moveCursor(dy)\n else if (dx !== 0) root.moveCursorH(dx)\n }\n onActivateRequested: root.activateCursor()\n onCloseRequested: root.requestClose()\n\n ScrollView {\n id: scrollArea\n anchors.fill: parent\n anchors.margins: Style.space(18)\n clip: true\n ScrollBar.horizontal.policy: ScrollBar.AlwaysOff\n\n Column {\n width: scrollArea.availableWidth\n spacing: Style.space(22)\n\n // ---- Header ------------------------------------------------------\n Column {\n width: parent.width\n spacing: Style.space(4)\n\n Text {\n text: \"Omarchy shell · dev gallery\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.iconLarge\n font.bold: true\n }\n Text {\n text: \"Live previews of every type exported from qs.Ui. Use this as the visual reference when porting panels or building plugins. j/k or arrows to walk; h/l within rows; Enter to activate; Esc to close.\"\n color: Qt.darker(root.foreground, 1.4)\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n width: parent.width\n wrapMode: Text.WordWrap\n }\n }\n\n PanelSeparator { foreground: root.foreground }\n\n // ---- Kit conventions ---------------------------------------------\n Column {\n width: parent.width\n spacing: Style.space(8)\n\n Text {\n text: \"Conventions\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.subtitle\n font.bold: true\n }\n\n BorderSurface {\n width: parent.width\n implicitHeight: conventionsCol.implicitHeight + Style.spacing.rowPaddingX * 2\n color: Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.04)\n radius: Style.cornerRadius\n borderSpec: Border.flat(Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.10), 1)\n\n Column {\n id: conventionsCol\n anchors.left: parent.left\n anchors.right: parent.right\n anchors.verticalCenter: parent.verticalCenter\n anchors.leftMargin: Style.space(14)\n anchors.rightMargin: Style.space(14)\n spacing: Style.space(8)\n\n Text {\n width: parent.width\n wrapMode: Text.WordWrap\n color: Qt.darker(root.foreground, 1.4)\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n text: \"Theme. qs.Commons.Style exposes cornerRadius plus shared normal / hover-cursor / selected / focus state tokens (state colors, fill alphas, border widths, and border alphas), spacing tokens, typography, and bar dimensions. Focus defaults to hover-cursor; selected borders are off by default. Border widths are the theme-level on/off switch for state borders. qs.Commons.Color exposes foreground / background / accent / urgent plus per-surface roles. Components default-bind to these so a caller with no overrides matches the active theme.\"\n }\n Text {\n width: parent.width\n wrapMode: Text.WordWrap\n color: Qt.darker(root.foreground, 1.4)\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n text: \"Single cursor. Most reusable panel primitives expose hasCursor: bool and emit hovered(bool); composed rows (including sliders) wrap their content in CursorSurface. The panel root owns cursorActive + focusSection + selectedIndex; each element binds hasCursor: root.cursorActive && root.focusSection === 'X' && root.selectedIndex === N, and onHovered flips cursorActive on while updating the same state. No initial highlight, then one highlight on screen once the keyboard or mouse enters. See plugins/panels/audio/Panel.qml for the canonical recipe.\"\n }\n Text {\n width: parent.width\n wrapMode: Text.WordWrap\n color: Qt.darker(root.foreground, 1.4)\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n text: \"Popups + editors. Dropdown / SearchableDropdown expose popupOpen plus open() / close() / toggle(); inline TextField uses activeFocus. While any of those own the keys, set PanelKeyCatcher.blocked so the panel's cursor model freezes and the active widget handles input.\"\n }\n Text {\n width: parent.width\n wrapMode: Text.WordWrap\n color: Qt.darker(root.foreground, 1.4)\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n text: \"Adding a component. Drop the QML in Ui/, add a line to Ui/qmldir, then add a section here using the real type (not a copy). The gallery doubles as a smoke test — if a component starts misbehaving this is the fastest place to see it.\"\n }\n }\n }\n }\n\n PanelSeparator { foreground: root.foreground }\n\n // ---- Typography --------------------------------------------------\n Column {\n width: parent.width\n spacing: Style.space(8)\n\n Text {\n text: \"Typography\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.subtitle\n font.bold: true\n }\n Text {\n text: \"Style.font.* is the shell-wide type scale. Themes ship a single \"\n + \"[font] base-size in shell.toml; every token derives from it via a \"\n + \"fixed multiplier, so changing base-size rescales the whole shell \"\n + \"proportionally. There is no upper clamp. Themes can also pin \"\n + \"individual tokens (caption, heading, display, etc.) for stylistic \"\n + \"emphasis. The family follows the fontconfig monospace alias \\u2014 \"\n + \"set it with `omarchy font set `.\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n width: parent.width\n wrapMode: Text.WordWrap\n }\n\n BorderSurface {\n width: parent.width\n implicitHeight: typeCol.implicitHeight + Style.spacing.rowPaddingX * 2\n color: Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.04)\n radius: Style.cornerRadius\n borderSpec: Border.flat(Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.10), 1)\n\n Column {\n id: typeCol\n anchors.left: parent.left\n anchors.right: parent.right\n anchors.verticalCenter: parent.verticalCenter\n anchors.leftMargin: Style.space(14)\n anchors.rightMargin: Style.space(14)\n spacing: Style.space(10)\n\n Text {\n text: \"Scale\"\n color: Qt.darker(root.foreground, 1.4)\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n font.bold: true\n }\n\n // Every Style.font.* token rendered at its actual size. The\n // model is data, not a Component graph, so this list stays\n // in lockstep with the singleton without manual upkeep.\n Repeater {\n model: [\n { key: \"caption\", size: Style.font.caption, sample: \"Section header text\" },\n { key: \"bodySmall\", size: Style.font.bodySmall, sample: \"Secondary / tooltip text\" },\n { key: \"body\", size: Style.font.body, sample: \"Default label and control text\" },\n { key: \"subtitle\", size: Style.font.subtitle, sample: \"Row title text\" },\n { key: \"title\", size: Style.font.title, sample: \"Card title text\" },\n { key: \"heading\", size: Style.font.heading, sample: \"Panel heading\" },\n { key: \"display\", size: Style.font.display, sample: \"Display text\" },\n { key: \"displayLarge\", size: Style.font.displayLarge, sample: \"Display large\" },\n { key: \"iconSmall\", size: Style.font.iconSmall, sample: \"\\uf004 \\uf005 \\uf02d\" },\n { key: \"icon\", size: Style.font.icon, sample: \"\\uf004 \\uf005 \\uf02d\" },\n { key: \"iconLarge\", size: Style.font.iconLarge, sample: \"\\uf004 \\uf005 \\uf02d\" }\n ]\n delegate: Item {\n required property var modelData\n width: typeCol.width\n implicitHeight: Math.max(metaCol.implicitHeight, sampleText.implicitHeight)\n\n Column {\n id: metaCol\n anchors.left: parent.left\n anchors.verticalCenter: parent.verticalCenter\n width: Style.space(140)\n spacing: Style.space(1)\n Text {\n textFormat: Text.PlainText\n text: \"Style.font.\" + modelData.key\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n }\n Text {\n textFormat: Text.PlainText\n text: modelData.size + \" px\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n }\n }\n\n Text {\n id: sampleText\n textFormat: Text.PlainText\n anchors.left: metaCol.right\n anchors.right: parent.right\n anchors.verticalCenter: parent.verticalCenter\n anchors.leftMargin: Style.space(16)\n text: modelData.sample\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: modelData.size\n elide: Text.ElideRight\n }\n }\n }\n\n Rectangle {\n width: parent.width\n height: 1\n color: Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.10)\n }\n\n Text {\n text: \"Theme tokens\"\n color: Qt.darker(root.foreground, 1.4)\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n font.bold: true\n }\n\n Grid {\n columns: 2\n columnSpacing: Style.space(16)\n rowSpacing: Style.space(4)\n width: parent.width\n\n Text {\n text: \"Style.font.family\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n }\n Text {\n textFormat: Text.PlainText\n text: Style.font.family\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n }\n\n Text {\n text: \"Style.font.resolvedFamily\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n }\n Text {\n textFormat: Text.PlainText\n text: Style.font.resolvedFamily\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n }\n\n Text {\n text: \"Style.font.baseSize\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n }\n Text {\n textFormat: Text.PlainText\n text: Style.font.baseSize + \" px\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n }\n\n Text {\n text: \"Style.bar.sizeHorizontal\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n }\n Text {\n textFormat: Text.PlainText\n text: Style.bar.sizeHorizontal + \" px\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n }\n\n Text {\n text: \"Style.bar.sizeVertical\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n }\n Text {\n textFormat: Text.PlainText\n text: Style.bar.sizeVertical + \" px\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n }\n\n Text {\n text: \"Style.spacing.scale\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n }\n Text {\n textFormat: Text.PlainText\n text: Style.spacing.scale.toFixed(2)\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n }\n\n Text {\n text: \"Style.spacing.panelPadding\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n }\n Text {\n textFormat: Text.PlainText\n text: Style.spacing.panelPadding + \" px\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.bodySmall\n }\n }\n }\n }\n }\n\n PanelSeparator { foreground: root.foreground }\n\n // ---- PanelSectionHeader ------------------------------------------\n Column {\n width: parent.width\n spacing: Style.space(8)\n\n Text {\n text: \"PanelSectionHeader\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.subtitle\n font.bold: true\n }\n Text {\n text: \"Small-caps-style intro label for a section.\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n }\n\n BorderSurface {\n width: parent.width\n implicitHeight: shCol.implicitHeight + Style.spacing.rowPaddingX * 2\n color: Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.04)\n radius: Style.cornerRadius\n borderSpec: Border.flat(Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.10), 1)\n\n Column {\n id: shCol\n anchors.left: parent.left\n anchors.right: parent.right\n anchors.verticalCenter: parent.verticalCenter\n anchors.leftMargin: Style.space(14)\n anchors.rightMargin: Style.space(14)\n spacing: Style.space(6)\n\n PanelSectionHeader {\n text: \"DNS provider\"\n foreground: root.foreground\n fontFamily: root.fontFamily\n }\n PanelSectionHeader {\n text: \"Wi-Fi networks\"\n foreground: root.foreground\n fontFamily: root.fontFamily\n }\n PanelSectionHeader {\n text: \"Playing\"\n foreground: root.foreground\n fontFamily: root.fontFamily\n fontSize: Style.font.bodySmall\n }\n }\n }\n }\n\n // ---- PanelSeparator ----------------------------------------------\n Column {\n width: parent.width\n spacing: Style.space(8)\n\n Text {\n text: \"PanelSeparator\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.subtitle\n font.bold: true\n }\n Text {\n text: \"1px horizontal rule. Default 0.12 alpha on foreground; tweak via strength.\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n }\n\n BorderSurface {\n width: parent.width\n implicitHeight: sepCol.implicitHeight + Style.spacing.rowPaddingX * 2\n color: Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.04)\n radius: Style.cornerRadius\n borderSpec: Border.flat(Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.10), 1)\n\n Column {\n id: sepCol\n anchors.left: parent.left\n anchors.right: parent.right\n anchors.verticalCenter: parent.verticalCenter\n anchors.leftMargin: Style.space(14)\n anchors.rightMargin: Style.space(14)\n spacing: Style.space(12)\n\n PanelSeparator { foreground: root.foreground }\n PanelSeparator { foreground: root.foreground; strength: 0.25 }\n PanelSeparator { foreground: root.foreground; strength: 0.45 }\n }\n }\n }\n\n // ---- CursorSurface -----------------------------------------------\n Column {\n width: parent.width\n spacing: Style.space(8)\n\n Text {\n text: \"CursorSurface\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.subtitle\n font.bold: true\n }\n Text {\n text: \"Single highlight chrome for keyboard+mouse navigable items. Press h/l (anywhere in this window) to move the demo cursor. The middle item is also marked `current` to show how the two states layer.\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n width: parent.width\n wrapMode: Text.WordWrap\n }\n\n BorderSurface {\n width: parent.width\n implicitHeight: csCol.implicitHeight + Style.spacing.rowPaddingX * 2\n color: Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.04)\n radius: Style.cornerRadius\n borderSpec: Border.flat(Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.10), 1)\n\n Column {\n id: csCol\n anchors.left: parent.left\n anchors.right: parent.right\n anchors.verticalCenter: parent.verticalCenter\n anchors.leftMargin: Style.space(14)\n anchors.rightMargin: Style.space(14)\n spacing: Style.space(6)\n\n Repeater {\n model: [\n { \"label\": \"Idle row\" },\n { \"label\": \"Currently-active row (e.g. connected wifi, default sink)\" },\n { \"label\": \"Forget / scan / disabled-ish row\" }\n ]\n\n CursorSurface {\n required property var modelData\n required property int index\n width: parent.width\n implicitHeight: csLabel.implicitHeight + Style.spacing.controlGap * 2\n hasCursor: root.focusSection === \"cursor-surface\" && root.selectedIndex === index\n current: index === 1\n foreground: root.foreground\n fill: Style.hoverFillFor(root.foreground, root.accent)\n onHasCursorChanged: if (hasCursor) root.ensureCursorVisible(this)\n\n Text {\n id: csLabel\n textFormat: Text.PlainText\n anchors.left: parent.left\n anchors.right: parent.right\n anchors.verticalCenter: parent.verticalCenter\n anchors.leftMargin: Style.space(10)\n anchors.rightMargin: Style.space(10)\n text: modelData.label\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.body\n elide: Text.ElideRight\n }\n\n MouseArea {\n anchors.fill: parent\n hoverEnabled: true\n cursorShape: Qt.PointingHandCursor\n onContainsMouseChanged: if (containsMouse) {\n root.focusSection = \"cursor-surface\"\n root.selectedIndex = parent.index\n }\n }\n }\n }\n }\n }\n }\n\n // ---- Button ------------------------------------------------------\n Column {\n width: parent.width\n spacing: Style.space(8)\n\n Text {\n text: \"Button\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.subtitle\n font.bold: true\n }\n Text {\n text: \"The kit's only button. State flags compose from shared tokens: hasCursor / hover paints the hover-cursor fill; active/selected add the selected fill; selected borders are off by default; bordered opts into normal/hover-cursor borders; focusable uses the same defaults as hover-cursor. Click below or press h/l to walk the demo cursor.\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n width: parent.width\n wrapMode: Text.WordWrap\n }\n\n BorderSurface {\n width: parent.width\n implicitHeight: buttonRow.implicitHeight + Style.spacing.rowPaddingX * 2\n color: Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.04)\n radius: Style.cornerRadius\n borderSpec: Border.flat(Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.10), 1)\n\n Row {\n id: buttonRow\n anchors.left: parent.left\n anchors.verticalCenter: parent.verticalCenter\n anchors.leftMargin: Style.space(14)\n spacing: Style.space(16)\n\n // Each demo Button is paired with a caption labeling the\n // state(s) it exercises so the section reads as one Button\n // showing its flag combinations side by side.\n\n Column {\n spacing: Style.space(6)\n Button {\n anchors.horizontalCenter: parent.horizontalCenter\n text: \"DHCP\"\n tooltipText: \"Use DNS from DHCP\"\n hasCursor: root.focusSection === \"button\" && root.selectedIndex === 0\n onHovered: function(h) {\n if (h) { root.focusSection = \"button\"; root.selectedIndex = 0 }\n }\n onHasCursorChanged: if (hasCursor) root.ensureCursorVisible(this)\n }\n Text {\n anchors.horizontalCenter: parent.horizontalCenter\n text: \"idle\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n }\n }\n\n Column {\n spacing: Style.space(6)\n Button {\n anchors.horizontalCenter: parent.horizontalCenter\n text: \"Cloudflare\"\n tooltipText: \"Set DNS to Cloudflare\"\n active: true\n hasCursor: root.focusSection === \"button\" && root.selectedIndex === 1\n onHovered: function(h) {\n if (h) { root.focusSection = \"button\"; root.selectedIndex = 1 }\n }\n onHasCursorChanged: if (hasCursor) root.ensureCursorVisible(this)\n }\n Text {\n anchors.horizontalCenter: parent.horizontalCenter\n text: \"active\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n }\n }\n\n Column {\n spacing: Style.space(6)\n Button {\n anchors.horizontalCenter: parent.horizontalCenter\n iconText: \"󰑐\"\n tooltipText: \"Refresh\"\n horizontalPadding: Style.spacing.controlGap\n verticalPadding: Style.spacing.labelGap\n hasCursor: root.focusSection === \"button\" && root.selectedIndex === 2\n onHovered: function(h) {\n if (h) { root.focusSection = \"button\"; root.selectedIndex = 2 }\n }\n onHasCursorChanged: if (hasCursor) root.ensureCursorVisible(this)\n }\n Text {\n anchors.horizontalCenter: parent.horizontalCenter\n text: \"icon only\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n }\n }\n\n Column {\n spacing: Style.space(6)\n Button {\n anchors.horizontalCenter: parent.horizontalCenter\n iconText: \"󰂯\"\n text: \"On\"\n tooltipText: \"Turn Bluetooth off\"\n active: true\n hasCursor: root.focusSection === \"button\" && root.selectedIndex === 3\n onHovered: function(h) {\n if (h) { root.focusSection = \"button\"; root.selectedIndex = 3 }\n }\n onHasCursorChanged: if (hasCursor) root.ensureCursorVisible(this)\n }\n Text {\n anchors.horizontalCenter: parent.horizontalCenter\n text: \"icon + active\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n }\n }\n\n Column {\n spacing: Style.space(6)\n Button {\n anchors.horizontalCenter: parent.horizontalCenter\n text: \"Apply\"\n focusable: true\n bordered: true\n hasCursor: root.focusSection === \"button\" && root.selectedIndex === 4\n onHovered: function(h) {\n if (h) { root.focusSection = \"button\"; root.selectedIndex = 4 }\n }\n onHasCursorChanged: if (hasCursor) root.ensureCursorVisible(this)\n }\n Text {\n anchors.horizontalCenter: parent.horizontalCenter\n text: \"bordered + focusable\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n }\n }\n }\n }\n }\n\n // ---- ButtonGroup -------------------------------------------------\n Column {\n id: buttonGroupSection\n width: parent.width\n spacing: Style.space(8)\n readonly property bool focused: root.focusSection === \"button-group\"\n onFocusedChanged: if (focused) root.ensureCursorVisible(this)\n\n Text {\n text: \"ButtonGroup\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.subtitle\n font.bold: true\n }\n Text {\n text: \"Mutually-exclusive row of Buttons. Each chip uses Button's bordered chrome; selected and cursor states come from the same shared Style tokens as every other control. Click to pick or press h/l + Enter.\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n width: parent.width\n wrapMode: Text.WordWrap\n }\n\n BorderSurface {\n width: parent.width\n implicitHeight: choiceRow.implicitHeight + Style.spacing.rowPaddingX * 2\n color: Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.04)\n radius: Style.cornerRadius\n borderSpec: Border.flat(Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.10), 1)\n\n ButtonGroup {\n id: choiceRow\n anchors.left: parent.left\n anchors.verticalCenter: parent.verticalCenter\n anchors.leftMargin: Style.space(14)\n options: [\"top\", \"right\", \"bottom\", \"left\"]\n value: root.choiceDemoValue\n cursorIndex: root.focusSection === \"button-group\" ? root.selectedIndex : -1\n onChanged: function(v) {\n root.focusSection = \"button-group\"\n root.choiceDemoValue = v\n }\n onHovered: function(index, isHovered) {\n if (isHovered) {\n root.focusSection = \"button-group\"\n root.selectedIndex = index\n }\n }\n }\n }\n }\n\n // ---- PanelActionButton -------------------------------------------\n Column {\n width: parent.width\n spacing: Style.space(8)\n\n Text {\n text: \"PanelActionButton\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.subtitle\n font.bold: true\n }\n Text {\n text: \"22×22 right-edge action button. Two flavors via hoverColor: default (foreground tint, e.g. confirm) and urgent (red tint, e.g. forget/unpair). Hover and click states are intrinsic; the row that owns it stays responsible for the cursor highlight.\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n width: parent.width\n wrapMode: Text.WordWrap\n }\n\n BorderSurface {\n width: parent.width\n implicitHeight: pabCol.implicitHeight + Style.spacing.rowPaddingX * 2\n color: Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.04)\n radius: Style.cornerRadius\n borderSpec: Border.flat(Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.10), 1)\n\n Row {\n id: pabCol\n anchors.left: parent.left\n anchors.verticalCenter: parent.verticalCenter\n anchors.leftMargin: Style.space(14)\n spacing: Style.space(18)\n\n PanelActionButton {\n iconText: \"󰄬\"\n tooltipText: \"Confirm (default flavor)\"\n foreground: root.foreground\n fontFamily: root.fontFamily\n hasCursor: root.focusSection === \"panel-action-button\" && root.selectedIndex === 0\n onHovered: function(h) {\n if (h) { root.focusSection = \"panel-action-button\"; root.selectedIndex = 0 }\n }\n onHasCursorChanged: if (hasCursor) root.ensureCursorVisible(this)\n }\n\n PanelActionButton {\n iconText: \"󰅙\"\n tooltipText: \"Forget network (urgent flavor)\"\n foreground: root.foreground\n hoverColor: root.urgent\n fontFamily: root.fontFamily\n hasCursor: root.focusSection === \"panel-action-button\" && root.selectedIndex === 1\n onHovered: function(h) {\n if (h) { root.focusSection = \"panel-action-button\"; root.selectedIndex = 1 }\n }\n onHasCursorChanged: if (hasCursor) root.ensureCursorVisible(this)\n }\n\n PanelActionButton {\n iconText: \"󰄬\"\n tooltipText: \"Disabled — type a passphrase first\"\n foreground: root.foreground\n fontFamily: root.fontFamily\n enabled: false\n hasCursor: root.focusSection === \"panel-action-button\" && root.selectedIndex === 2\n onHovered: function(h) {\n if (h) { root.focusSection = \"panel-action-button\"; root.selectedIndex = 2 }\n }\n onHasCursorChanged: if (hasCursor) root.ensureCursorVisible(this)\n }\n\n PanelActionButton {\n iconText: \"󰒓\"\n tooltipText: \"Focusable (settings form button)\"\n foreground: root.foreground\n fontFamily: root.fontFamily\n fontSize: Style.font.subtitle\n size: Style.space(26)\n focusable: true\n hasCursor: root.focusSection === \"panel-action-button\" && root.selectedIndex === 3\n onHovered: function(h) {\n if (h) { root.focusSection = \"panel-action-button\"; root.selectedIndex = 3 }\n }\n onHasCursorChanged: if (hasCursor) root.ensureCursorVisible(this)\n }\n }\n }\n }\n\n // ---- PanelToolTip ------------------------------------------------\n Column {\n width: parent.width\n spacing: Style.space(8)\n\n Text {\n text: \"PanelToolTip\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.subtitle\n font.bold: true\n }\n Text {\n text: \"Hover the swatch below to see the styled tooltip. Use this whenever a custom button or row needs a hover hint.\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n width: parent.width\n wrapMode: Text.WordWrap\n }\n\n BorderSurface {\n id: tipSwatch\n width: Style.space(140)\n height: Style.space(36)\n readonly property bool focused: root.focusSection === \"panel-tool-tip\"\n color: tipMouse.containsMouse || focused\n ? Style.hoverFillFor(root.foreground, root.accent)\n : Style.normalFillFor(root.foreground, root.accent)\n borderSpec: focused\n ? Border.controlSpec(\"hover-cursor\", root.foreground, root.accent)\n : Border.controlSpec(\"normal\", root.foreground, root.accent)\n radius: Style.cornerRadius\n onFocusedChanged: if (focused) root.ensureCursorVisible(this)\n\n Text {\n anchors.centerIn: parent\n text: \"hover me\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.body\n }\n\n MouseArea {\n id: tipMouse\n anchors.fill: parent\n hoverEnabled: true\n cursorShape: Qt.PointingHandCursor\n onContainsMouseChanged: if (containsMouse) {\n root.focusSection = \"panel-tool-tip\"\n root.selectedIndex = 0\n }\n }\n\n PanelToolTip {\n visible: tipMouse.containsMouse || tipSwatch.focused\n text: \"Styled tooltip — drop into any panel\"\n panelForeground: root.foreground\n fontFamily: root.fontFamily\n }\n }\n }\n\n\n // ---- Slider ------------------------------------------------------\n Column {\n width: parent.width\n spacing: Style.space(8)\n\n Text {\n text: \"Slider\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.subtitle\n font.bold: true\n }\n Text {\n text: \"Volume / progress slider. Drag, click anywhere on the track, or scroll the wheel.\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n width: parent.width\n wrapMode: Text.WordWrap\n }\n\n CursorSurface {\n id: sliderWrapper\n width: parent.width\n implicitHeight: sliderRow.implicitHeight + Style.spacing.rowPaddingX * 2\n outline: true\n foreground: root.foreground\n hasCursor: root.focusSection === \"slider\"\n onHasCursorChanged: if (hasCursor) root.ensureCursorVisible(this)\n\n HoverHandler {\n onHoveredChanged: if (hovered) {\n root.focusSection = \"slider\"\n root.selectedIndex = 0\n }\n }\n\n Row {\n id: sliderRow\n anchors.left: parent.left\n anchors.right: parent.right\n anchors.verticalCenter: parent.verticalCenter\n anchors.leftMargin: Style.space(14)\n anchors.rightMargin: Style.space(14)\n spacing: Style.space(10)\n property real demoVolume: 0.45\n\n Text {\n text: \"󰕾\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.heading\n width: 22\n horizontalAlignment: Text.AlignHCenter\n anchors.verticalCenter: parent.verticalCenter\n }\n\n PanelSlider {\n id: demoSlider\n bar: root.fakeBar\n width: parent.width - 70\n anchors.verticalCenter: parent.verticalCenter\n value: sliderRow.demoVolume\n onMoved: function(v) { sliderRow.demoVolume = v }\n }\n\n Text {\n textFormat: Text.PlainText\n text: Math.round((demoSlider.dragging ? demoSlider.liveValue : sliderRow.demoVolume) * 100) + \"%\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.body\n width: 38\n horizontalAlignment: Text.AlignRight\n anchors.verticalCenter: parent.verticalCenter\n }\n }\n }\n }\n\n // ---- TextField -----------------------------------------------------\n Column {\n width: parent.width\n spacing: Style.space(8)\n\n Text {\n text: \"TextField\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.subtitle\n font.bold: true\n }\n Text {\n text: \"Single-line input. Inherits Qt Quick Controls TextField, swaps in the kit's focus chrome and selection styling. Toggle `password: true` for masked entry.\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n width: parent.width\n wrapMode: Text.WordWrap\n }\n\n BorderSurface {\n width: parent.width\n implicitHeight: tfCol.implicitHeight + Style.spacing.rowPaddingX * 2\n color: Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.04)\n radius: Style.cornerRadius\n borderSpec: Border.flat(Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.10), 1)\n\n Column {\n id: tfCol\n anchors.left: parent.left\n anchors.right: parent.right\n anchors.verticalCenter: parent.verticalCenter\n anchors.leftMargin: Style.space(14)\n anchors.rightMargin: Style.space(14)\n spacing: Style.space(10)\n\n TextField {\n id: demoTextField\n width: parent.width\n placeholderText: \"Type something (Enter to start editing, Esc to leave)\"\n foreground: root.foreground\n accent: root.accent\n font.family: root.fontFamily\n font.pixelSize: Style.font.body\n hasCursor: !activeFocus && root.focusSection === \"text-field\" && root.selectedIndex === 0\n onHoveredChanged: if (hovered) {\n root.focusSection = \"text-field\"; root.selectedIndex = 0\n }\n onHasCursorChanged: if (hasCursor) root.ensureCursorVisible(this)\n Keys.onPressed: function(event) {\n if (event.key === Qt.Key_Escape) {\n focus = false\n event.accepted = true\n }\n }\n }\n\n TextField {\n id: demoPasswordField\n width: parent.width\n password: true\n placeholderText: \"Password\"\n foreground: root.foreground\n accent: root.accent\n font.family: root.fontFamily\n font.pixelSize: Style.font.body\n hasCursor: !activeFocus && root.focusSection === \"text-field\" && root.selectedIndex === 1\n onHoveredChanged: if (hovered) {\n root.focusSection = \"text-field\"; root.selectedIndex = 1\n }\n onHasCursorChanged: if (hasCursor) root.ensureCursorVisible(this)\n Keys.onPressed: function(event) {\n if (event.key === Qt.Key_Escape) {\n focus = false\n event.accepted = true\n }\n }\n }\n }\n }\n }\n\n // ---- NumberField ---------------------------------------------------\n Column {\n width: parent.width\n spacing: Style.space(8)\n\n Text {\n text: \"NumberField\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.subtitle\n font.bold: true\n }\n Text {\n text: \"Labeled spin box for integer settings. Up/down arrows step the value; the field accepts typed input. Pair with `from`/`to`/`stepSize` to constrain range.\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n width: parent.width\n wrapMode: Text.WordWrap\n }\n\n BorderSurface {\n width: parent.width\n implicitHeight: numberDemo.implicitHeight + Style.spacing.rowPaddingX * 2\n color: Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.04)\n borderSpec: Border.flat(Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.12), 1)\n radius: Style.cornerRadius\n\n NumberField {\n id: numberDemo\n anchors.left: parent.left\n anchors.verticalCenter: parent.verticalCenter\n anchors.leftMargin: Style.space(12)\n label: \"Auto-refresh interval (minutes)\"\n from: 1\n to: 1440\n value: root.numberDemoValue\n foreground: root.foreground\n accent: root.accent\n fontFamily: root.fontFamily\n hasCursor: root.focusSection === \"number-field\" && root.selectedIndex === 0\n onModified: function(v) { root.numberDemoValue = v }\n onHovered: function(on) {\n if (on) { root.focusSection = \"number-field\"; root.selectedIndex = 0 }\n }\n onHasCursorChanged: if (hasCursor) root.ensureCursorVisible(this)\n }\n }\n }\n\n // ---- Toggle --------------------------------------------------------\n Column {\n width: parent.width\n spacing: Style.space(8)\n\n Text {\n text: \"Toggle\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.subtitle\n font.bold: true\n }\n Text {\n text: \"Title + description + switch. Click anywhere on the row to flip; caller updates `checked` in response. Uses the same normal / hover-cursor / focus tokens as Button and the checked switch track uses selected tokens.\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n width: parent.width\n wrapMode: Text.WordWrap\n }\n\n Toggle {\n width: parent.width\n label: \"Transparent bar\"\n description: \"Hide the bar background so the wallpaper shows through.\"\n foreground: root.foreground\n accent: root.accent\n fontFamily: root.fontFamily\n checked: root.toggleDemoOn\n hasCursor: root.focusSection === \"toggle\" && root.selectedIndex === 0\n onHovered: function(h) {\n if (h) { root.focusSection = \"toggle\"; root.selectedIndex = 0 }\n }\n onHasCursorChanged: if (hasCursor) root.ensureCursorVisible(this)\n onClicked: {\n root.focusSection = \"toggle\"; root.selectedIndex = 0\n root.toggleDemoOn = !root.toggleDemoOn\n }\n }\n\n Toggle {\n width: parent.width\n label: \"Square switch (forced)\"\n description: \"`rounded: false` overrides the theme auto-detect so the switch reads square even when corners are round. Set `rounded: Style.cornerRadius > 0` (the default) to follow the theme.\"\n foreground: root.foreground\n accent: root.accent\n fontFamily: root.fontFamily\n rounded: false\n checked: root.toggleSquareOn\n hasCursor: root.focusSection === \"toggle\" && root.selectedIndex === 1\n onHovered: function(h) {\n if (h) { root.focusSection = \"toggle\"; root.selectedIndex = 1 }\n }\n onHasCursorChanged: if (hasCursor) root.ensureCursorVisible(this)\n onClicked: {\n root.focusSection = \"toggle\"; root.selectedIndex = 1\n root.toggleSquareOn = !root.toggleSquareOn\n }\n }\n }\n\n // ---- ToggleSwitch --------------------------------------------------\n Column {\n width: parent.width\n spacing: Style.space(8)\n\n Text {\n text: \"ToggleSwitch\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.subtitle\n font.bold: true\n }\n Text {\n text: \"The bare switch Toggle puts at the end of its row, for places with no room for a labeled row — a panel hero's trailingControl, for instance. Caller owns `checked` and flips it on `toggled()`. Set `busy` while an operation is in flight to swallow further clicks without disturbing hover or tooltips; services that track a desired state optimistically get an instant knob throw because `checked` is already the optimistic value.\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n width: parent.width\n wrapMode: Text.WordWrap\n }\n\n Row {\n spacing: Style.space(24)\n\n ToggleSwitch {\n checked: root.switchDemoOn\n foreground: root.foreground\n accent: root.accent\n hasCursor: root.focusSection === \"toggle-switch\" && root.selectedIndex === 0\n onHovered: function(h) {\n if (h) { root.focusSection = \"toggle-switch\"; root.selectedIndex = 0 }\n }\n onHasCursorChanged: if (hasCursor) root.ensureCursorVisible(this)\n onToggled: {\n root.focusSection = \"toggle-switch\"; root.selectedIndex = 0\n root.switchDemoOn = !root.switchDemoOn\n }\n }\n\n ToggleSwitch {\n checked: root.switchBusyOn\n busy: true\n foreground: root.foreground\n accent: root.accent\n hasCursor: root.focusSection === \"toggle-switch\" && root.selectedIndex === 1\n onHovered: function(h) {\n if (h) { root.focusSection = \"toggle-switch\"; root.selectedIndex = 1 }\n }\n onHasCursorChanged: if (hasCursor) root.ensureCursorVisible(this)\n onToggled: root.switchBusyOn = !root.switchBusyOn\n }\n }\n\n Text {\n text: \"The second switch is `busy: true` — hover still responds, clicks do not.\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n width: parent.width\n wrapMode: Text.WordWrap\n }\n }\n\n // ---- Dropdown -----------------------------------------------------\n Column {\n width: parent.width\n spacing: Style.space(8)\n\n Text {\n text: \"Dropdown\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.subtitle\n font.bold: true\n }\n Text {\n text: \"Themed single-select with a panel-styled popup. Tab to focus the trigger, Enter/Space opens, j/k or arrows walk options, Enter selects. Options can be plain strings or { value, label } objects.\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n width: parent.width\n wrapMode: Text.WordWrap\n }\n\n BorderSurface {\n width: parent.width\n implicitHeight: ddCol.implicitHeight + Style.spacing.rowPaddingX * 2\n color: Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.04)\n radius: Style.cornerRadius\n borderSpec: Border.flat(Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.10), 1)\n\n Column {\n id: ddCol\n anchors.left: parent.left\n anchors.right: parent.right\n anchors.verticalCenter: parent.verticalCenter\n anchors.leftMargin: Style.space(14)\n anchors.rightMargin: Style.space(14)\n spacing: Style.space(6)\n\n Dropdown {\n id: demoDropdown\n width: Style.spacing.dropdownWidth\n label: \"Center anchor\"\n fontFamily: root.fontFamily\n options: [\"omarchy.clock\", \"omarchy.weather\", \"omarchy.power\"]\n value: root.dropdownDemoValue\n hasCursor: root.focusSection === \"dropdown\" && root.selectedIndex === 0\n onHovered: function(h) {\n if (h) { root.focusSection = \"dropdown\"; root.selectedIndex = 0 }\n }\n onHasCursorChanged: if (hasCursor) root.ensureCursorVisible(this)\n onChanged: function(v) { root.dropdownDemoValue = v }\n }\n }\n }\n }\n\n // ---- SearchableDropdown -------------------------------------------\n Column {\n width: parent.width\n spacing: Style.space(8)\n\n Text {\n text: \"SearchableDropdown\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.subtitle\n font.bold: true\n }\n Text {\n text: \"Dropdown with an embedded filter input. Type to narrow the list, Down to jump from the search to the first match, Enter to select. Use this for long option lists where plain scrolling is friction.\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n width: parent.width\n wrapMode: Text.WordWrap\n }\n\n BorderSurface {\n width: parent.width\n implicitHeight: sddCol.implicitHeight + Style.spacing.rowPaddingX * 2\n color: Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.04)\n radius: Style.cornerRadius\n borderSpec: Border.flat(Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.10), 1)\n\n Column {\n id: sddCol\n anchors.left: parent.left\n anchors.right: parent.right\n anchors.verticalCenter: parent.verticalCenter\n anchors.leftMargin: Style.space(14)\n anchors.rightMargin: Style.space(14)\n spacing: Style.space(6)\n\n SearchableDropdown {\n id: demoSearchableDropdown\n width: Style.spacing.searchableDropdownWidth\n label: \"Add widget\"\n fontFamily: root.fontFamily\n placeholderText: \"Search widgets...\"\n hasCursor: root.focusSection === \"searchable-dropdown\" && root.selectedIndex === 0\n onHovered: function(h) {\n if (h) { root.focusSection = \"searchable-dropdown\"; root.selectedIndex = 0 }\n }\n onHasCursorChanged: if (hasCursor) root.ensureCursorVisible(this)\n options: [\n { value: \"Clock\", label: \"Clock\", description: \"Time + date display\" },\n { value: \"Weather\", label: \"Weather\", description: \"Local conditions and forecast\" },\n { value: \"omarchy.power\", label: \"Power\", description: \"Charge level + power profile\" },\n { value: \"audio\", label: \"Audio\", description: \"Output sink + volume\" },\n { value: \"network\", label: \"Network\", description: \"Wi-Fi + ethernet status\" },\n { value: \"bluetooth\", label: \"Bluetooth\", description: \"Paired and nearby devices\" },\n { value: \"monitor\", label: \"Monitor\", description: \"Brightness + scale\" },\n { value: \"Media\", label: \"Media\", description: \"Now-playing + transport\" },\n { value: \"Workspaces\", label: \"Workspaces\", description: \"Hyprland workspace pills\" },\n { value: \"system-tray\", label: \"System tray\", description: \"StatusNotifierItem icons\" },\n { value: \"omarchy-menu\", label: \"Omarchy menu\", description: \"Launcher / system menu\" },\n { value: \"power-profiles\", label: \"Power profiles\", description: \"Performance / balanced / saver\" },\n { value: \"hardware\", label: \"Hardware\", description: \"CPU, GPU, mem utilization\" },\n { value: \"notifications\", label: \"Notifications\", description: \"Recent notification history\" }\n ]\n value: root.searchableDemoValue\n onChanged: function(v) { root.searchableDemoValue = v }\n }\n }\n }\n }\n\n // ---- Composed example -------------------------------------------\n Column {\n width: parent.width\n spacing: Style.space(8)\n\n Text {\n text: \"Composed example\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.subtitle\n font.bold: true\n }\n Text {\n text: \"A miniature wifi-style row built from CursorSurface + PanelActionButton + PanelToolTip. This is what new panel rows should look like — no inline Rectangle/Text/MouseArea reimplementation.\"\n color: Qt.darker(root.foreground, 1.5)\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n width: parent.width\n wrapMode: Text.WordWrap\n }\n\n BorderSurface {\n width: parent.width\n implicitHeight: composedCol.implicitHeight + Style.spacing.rowPaddingX * 2\n color: Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.04)\n radius: Style.cornerRadius\n borderSpec: Border.flat(Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.10), 1)\n\n Column {\n id: composedCol\n anchors.left: parent.left\n anchors.right: parent.right\n anchors.verticalCenter: parent.verticalCenter\n anchors.leftMargin: Style.space(14)\n anchors.rightMargin: Style.space(14)\n spacing: Style.space(6)\n\n PanelSectionHeader {\n text: \"Wi-Fi networks\"\n foreground: root.foreground\n fontFamily: root.fontFamily\n }\n\n CursorSurface {\n width: parent.width\n implicitHeight: composedRow.implicitHeight + Style.spacing.md * 2\n current: true\n foreground: root.foreground\n fill: Style.hoverFillFor(root.foreground, root.accent)\n hasCursor: root.focusSection === \"composed\" && root.selectedIndex === 0\n onHasCursorChanged: if (hasCursor) root.ensureCursorVisible(this)\n\n HoverHandler {\n onHoveredChanged: if (hovered) {\n root.focusSection = \"composed\"; root.selectedIndex = 0\n }\n }\n\n Item {\n id: composedRow\n anchors.left: parent.left\n anchors.right: parent.right\n anchors.verticalCenter: parent.verticalCenter\n anchors.leftMargin: Style.space(10)\n anchors.rightMargin: Style.space(10)\n implicitHeight: 36\n\n Text {\n id: composedIcon\n anchors.left: parent.left\n anchors.verticalCenter: parent.verticalCenter\n text: \"󰖩\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.title\n }\n\n PanelActionButton {\n id: composedForget\n anchors.right: parent.right\n anchors.verticalCenter: parent.verticalCenter\n iconText: \"󰅙\"\n tooltipText: \"Forget network\"\n foreground: root.foreground\n hoverColor: root.urgent\n fontFamily: root.fontFamily\n }\n\n Column {\n spacing: Style.space(1)\n anchors.left: composedIcon.right\n anchors.leftMargin: Style.space(10)\n anchors.right: composedForget.left\n anchors.rightMargin: Style.space(8)\n anchors.verticalCenter: parent.verticalCenter\n\n Text {\n text: \"HughesWiFi\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.body\n elide: Text.ElideRight\n width: parent.width\n }\n Text {\n text: \"Connected\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.caption\n elide: Text.ElideRight\n width: parent.width\n }\n }\n }\n }\n\n PanelSeparator { foreground: root.foreground }\n\n CursorSurface {\n width: parent.width\n implicitHeight: idleRow.implicitHeight + Style.spacing.md * 2\n foreground: root.foreground\n fill: Style.hoverFillFor(root.foreground, root.accent)\n hasCursor: root.focusSection === \"composed\" && root.selectedIndex === 1\n onHasCursorChanged: if (hasCursor) root.ensureCursorVisible(this)\n\n HoverHandler {\n onHoveredChanged: if (hovered) {\n root.focusSection = \"composed\"; root.selectedIndex = 1\n }\n }\n\n Item {\n id: idleRow\n anchors.left: parent.left\n anchors.right: parent.right\n anchors.verticalCenter: parent.verticalCenter\n anchors.leftMargin: Style.space(10)\n anchors.rightMargin: Style.space(10)\n implicitHeight: 36\n\n Text {\n anchors.left: parent.left\n anchors.verticalCenter: parent.verticalCenter\n text: \"󰖩\"\n color: Qt.darker(root.foreground, 1.4)\n font.family: root.fontFamily\n font.pixelSize: Style.font.title\n }\n\n Text {\n anchors.left: parent.left\n anchors.leftMargin: Style.space(24)\n anchors.verticalCenter: parent.verticalCenter\n text: \"HughesATT\"\n color: root.foreground\n font.family: root.fontFamily\n font.pixelSize: Style.font.body\n }\n }\n }\n }\n }\n }\n\n Item { width: 1; height: Style.spacing.rowPaddingX }\n }\n }\n }\n }\n }\n}\n```"}], "task": "build_from_spec", "meta": {"origin": "first-party", "repo": "https://github.com/basecamp/omarchy", "commit": "9480d1b6a98156314dbabe6bfef08f39f8b9cd07", "license": "MIT", "plugin_path": "shell/plugins/dev-gallery", "kinds": ["panel"], "complexity": "large", "group": "1ceedb12", "validator": "pass", "qmllint": "clean", "qml_files": 1, "chars": 79766, "tokens": 15676, "split": "train"}} {"messages": [{"role": "system", "content": "You are an Omarchy plugin expert. You write complete, valid Omarchy (Quattro / omarchy-shell, Quickshell QML) plugins. Manifests use schemaVersion 1, a namespaced id that never uses the reserved omarchy.* namespace, name, version, kinds (bar-widget|panel|overlay|menu|service|bar) with a matching safe relative entryPoints path for every kind, and no symlinks. Return every file in full as '### path' followed by a fenced code block."}, {"role": "user", "content": "Write the manifest and entry-point file(s) (Emojis.qml) for the Omarchy plugin `acme.emojis` \"Emojis\" (overlay): Search, copy, and type emojis. These sibling files already exist in the folder and can be referenced:\n- EmojiSearch.js (1 KB)\n- emojis.json (107 KB)"}, {"role": "assistant", "content": "### manifest.json\n```json\n{\n \"schemaVersion\": 1,\n \"id\": \"acme.emojis\",\n \"name\": \"Emojis\",\n \"version\": \"1.0.0\",\n \"author\": \"Omarchy\",\n \"description\": \"Search, copy, and type emojis\",\n \"kinds\": [\n \"overlay\"\n ],\n \"keepLoaded\": true,\n \"entryPoints\": {\n \"overlay\": \"Emojis.qml\"\n }\n}\n```\n\n### Emojis.qml\n```qml\nimport Quickshell\nimport Quickshell.Io\nimport Quickshell.Wayland\nimport QtQuick\nimport qs.Commons\nimport qs.Commons as Commons\nimport qs.Ui\nimport \"EmojiSearch.js\" as EmojiSearch\n\nItem {\n id: root\n\n property string omarchyPath: Quickshell.env(\"OMARCHY_PATH\")\n property var shell: null\n property var manifest: null\n\n property bool opened: false\n property string filterText: \"\"\n property int selectedIndex: 0\n property bool cursorActive: false\n property var emojis: []\n property var filteredEmojis: []\n\n // Shares the [menu] surface tokens — themes that style the menu also\n // style emojis. Selected-cell colors composed in the\n // singleton so consumers drop them straight into Rectangle bindings.\n property color background: Commons.Color.menu.background\n property color foreground: Commons.Color.menu.text\n property color border: Commons.Color.menu.border\n property var borderSpec: Border.surfaceSpec(\"menu\", \"border\", border, Math.max(1, Style.space(2)))\n property color scrim: Commons.Color.menu.scrim\n property color selectedBackground: Commons.Color.menu.selectedBackground\n property color selectedText: Commons.Color.menu.selectedText\n readonly property int cornerRadius: Style.cornerRadius\n property string fontFamily: Style.font.menuFamily\n property int contentMargin: Style.spacing.panelPadding\n property int headerHeight: Math.max(Style.space(34), Style.font.title + Style.spacing.controlPaddingY * 2)\n property int contentSpacing: Style.spacing.md\n property int cardWidth: Math.min(Style.space(400), panel.width - Style.gapsOut * 2)\n property int cardHeight: Math.min(Style.space(500), panel.height - Style.gapsOut * 2)\n\n property int cellWidth: Math.max(Style.space(44), Style.font.display + Style.spacing.md)\n property int cellHeight: Math.max(Style.space(44), Style.font.display + Style.spacing.md)\n property int columns: Math.floor((cardWidth - contentMargin * 2) / cellWidth)\n\n function open(payloadJson) {\n root.opened = true\n root.filterText = \"\"\n root.selectedIndex = 0\n root.cursorActive = true\n root.rebuildDisplay()\n Qt.callLater(function() { keyCatcher.forceActiveFocus() })\n }\n\n function close() {\n root.opened = false\n }\n\n function dismiss() {\n root.opened = false\n if (root.shell && typeof root.shell.hide === \"function\")\n root.shell.hide((root.manifest && root.manifest.id) || \"omarchy.emojis\")\n }\n\n function toggle() {\n if (root.opened) root.dismiss()\n else root.open(\"{}\")\n }\n\n function loadEmojis(raw) {\n root.emojis = EmojiSearch.parseEmojis(raw)\n if (root.opened) root.rebuildDisplay()\n }\n\n function rebuildDisplay() {\n var out = EmojiSearch.filterEmojis(root.emojis, root.filterText, 1000)\n root.filteredEmojis = out\n\n displayModel.clear()\n for (var j = 0; j < out.length; j++) {\n displayModel.append({ emoji: out[j].e, index: j })\n }\n\n if (displayModel.count === 0) selectedIndex = 0\n else if (selectedIndex >= displayModel.count) selectedIndex = displayModel.count - 1\n else if (selectedIndex < 0) selectedIndex = 0\n cursorActive = displayModel.count > 0\n\n Qt.callLater(function() {\n if (displayModel.count > 0) resultGrid.positionViewAtIndex(root.selectedIndex, GridView.Contain)\n })\n }\n\n function select(delta) {\n if (displayModel.count === 0) return\n if (!cursorActive) {\n cursorActive = true\n selectedIndex = delta < 0 ? displayModel.count - 1 : 0\n } else {\n selectedIndex = (selectedIndex + delta + displayModel.count) % displayModel.count\n }\n resultGrid.positionViewAtIndex(selectedIndex, GridView.Contain)\n }\n\n function selectRow(delta) {\n if (displayModel.count === 0) return\n if (!cursorActive) {\n cursorActive = true\n selectedIndex = delta < 0 ? displayModel.count - 1 : 0\n resultGrid.positionViewAtIndex(selectedIndex, GridView.Contain)\n return\n }\n var newIndex = selectedIndex + delta * columns\n if (newIndex < 0) newIndex = 0\n if (newIndex >= displayModel.count) newIndex = displayModel.count - 1\n selectedIndex = newIndex\n resultGrid.positionViewAtIndex(selectedIndex, GridView.Contain)\n }\n\n function selectPage(delta) {\n if (displayModel.count === 0) return\n if (!cursorActive) {\n cursorActive = true\n selectedIndex = delta < 0 ? displayModel.count - 1 : 0\n resultGrid.positionViewAtIndex(selectedIndex, GridView.Contain)\n return\n }\n var visibleRows = Math.max(1, Math.floor(resultGrid.height / cellHeight))\n var newIndex = selectedIndex + delta * columns * visibleRows\n if (newIndex < 0) newIndex = 0\n if (newIndex >= displayModel.count) newIndex = displayModel.count - 1\n selectedIndex = newIndex\n resultGrid.positionViewAtIndex(selectedIndex, GridView.Contain)\n }\n\n function setFilter(nextFilter) {\n root.filterText = nextFilter\n root.selectedIndex = 0\n root.cursorActive = true\n root.rebuildDisplay()\n }\n\n function activateIndex(index) {\n if (index < 0 || index >= displayModel.count) return\n var row = displayModel.get(index)\n root.applySelected(row.emoji)\n }\n\n function applySelected(emoji) {\n if (!emoji) return\n root.dismiss()\n Quickshell.execDetached([root.omarchyPath + \"/bin/omarchy-menu-emoji-insert\", emoji])\n }\n\n ListModel { id: displayModel }\n\n FileView {\n path: root.omarchyPath + \"/shell/plugins/emojis/emojis.json\"\n onLoaded: root.loadEmojis(text())\n }\n OverlayWindow {\n id: panel\n shown: root.opened\n WlrLayershell.namespace: \"omarchy-emojis\"\n\n Rectangle {\n anchors.fill: parent\n color: root.scrim\n }\n\n MouseArea {\n anchors.fill: parent\n onClicked: root.dismiss()\n }\n\n BorderSurface {\n id: card\n width: root.cardWidth\n height: root.cardHeight\n radius: root.cornerRadius\n anchors.centerIn: parent\n color: root.background\n borderSpec: root.borderSpec\n padding: root.contentMargin\n\n MouseArea { anchors.fill: parent; onClicked: {} }\n\n Item {\n id: keyCatcher\n anchors.fill: parent\n focus: true\n\n Keys.priority: Keys.BeforeItem\n Keys.onPressed: function(event) {\n if (event.key === Qt.Key_Escape) {\n if (root.filterText) root.setFilter(\"\")\n else root.dismiss()\n event.accepted = true\n } else if (Util.editsFilter(event, root.filterText)) {\n root.setFilter(Util.editedFilter(event, root.filterText))\n event.accepted = true\n } else if (event.key === Qt.Key_Left) {\n root.select(-1)\n event.accepted = true\n } else if (event.key === Qt.Key_Right) {\n root.select(1)\n event.accepted = true\n } else if (event.key === Qt.Key_Up) {\n root.selectRow(-1)\n event.accepted = true\n } else if (event.key === Qt.Key_Down) {\n root.selectRow(1)\n event.accepted = true\n } else if (event.key === Qt.Key_PageUp) {\n root.selectPage(-1)\n event.accepted = true\n } else if (event.key === Qt.Key_PageDown) {\n root.selectPage(1)\n event.accepted = true\n } else if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter) {\n if (root.cursorActive) root.activateIndex(root.selectedIndex)\n else if (displayModel.count > 0) root.cursorActive = true\n event.accepted = true\n } else if (event.text && event.text.length === 1 && event.text.charCodeAt(0) >= 32 && event.text.charCodeAt(0) !== 127) {\n root.setFilter(root.filterText + event.text)\n event.accepted = true\n }\n }\n }\n\n Column {\n anchors.fill: parent\n anchors.topMargin: card.contentTopInset\n anchors.rightMargin: card.contentRightInset\n anchors.bottomMargin: card.contentBottomInset\n anchors.leftMargin: card.contentLeftInset\n spacing: root.contentSpacing\n\n Rectangle {\n width: parent.width\n height: root.headerHeight\n radius: root.cornerRadius\n color: \"transparent\"\n\n Text {\n textFormat: Text.PlainText\n anchors.left: parent.left\n anchors.right: parent.right\n anchors.verticalCenter: parent.verticalCenter\n text: root.filterText || \"Search emojis…\"\n color: root.foreground\n opacity: root.filterText ? 1 : 0.58\n font.family: root.fontFamily\n font.pixelSize: Style.font.heading\n elide: Text.ElideRight\n }\n }\n\n Item {\n width: parent.width\n height: parent.height - root.headerHeight - root.contentSpacing\n\n GridView {\n id: resultGrid\n anchors.fill: parent\n model: displayModel\n clip: true\n cellWidth: root.cellWidth\n cellHeight: root.cellHeight\n boundsBehavior: Flickable.StopAtBounds\n\n delegate: Rectangle {\n required property int index\n required property string emoji\n\n readonly property bool hasCursor: root.cursorActive && index === root.selectedIndex\n\n width: root.cellWidth\n height: root.cellHeight\n radius: root.cornerRadius\n color: hasCursor ? root.selectedBackground : \"transparent\"\n\n Text {\n textFormat: Text.PlainText\n text: parent.emoji\n font.family: root.fontFamily\n font.pixelSize: Style.font.display\n anchors.centerIn: parent\n horizontalAlignment: Text.AlignHCenter\n verticalAlignment: Text.AlignVCenter\n }\n\n MouseArea {\n id: mouseArea\n anchors.fill: parent\n hoverEnabled: true\n cursorShape: Qt.PointingHandCursor\n onContainsMouseChanged: if (containsMouse) {\n root.cursorActive = true\n root.selectedIndex = index\n }\n onClicked: {\n root.cursorActive = true\n root.selectedIndex = index\n root.activateIndex(index)\n }\n }\n }\n }\n\n Column {\n anchors.centerIn: parent\n spacing: Style.space(8)\n visible: displayModel.count === 0\n\n Text {\n text: \"󰈉\"\n color: root.selectedText\n opacity: 0.8\n font.family: root.fontFamily\n font.pixelSize: Style.font.displayLarge\n horizontalAlignment: Text.AlignHCenter\n width: parent.width\n }\n\n Text {\n textFormat: Text.PlainText\n text: \"No matches for “\" + root.filterText + \"”\"\n color: root.foreground\n opacity: 0.7\n font.family: root.fontFamily\n font.pixelSize: Style.font.title\n horizontalAlignment: Text.AlignHCenter\n width: parent.width\n }\n }\n }\n }\n }\n }\n}\n```"}], "task": "chunk_manifest_entry", "meta": {"origin": "first-party", "repo": "https://github.com/basecamp/omarchy", "commit": "9480d1b6a98156314dbabe6bfef08f39f8b9cd07", "license": "MIT", "plugin_path": "shell/plugins/emojis", "kinds": ["overlay"], "complexity": "large", "group": "1af716ad", "chunked": true, "validate_tree": true, "validator": "pass", "qmllint": "clean", "qml_files": 1, "chars": 12218, "tokens": 2839, "split": "train"}} {"messages": [{"role": "system", "content": "You are an Omarchy plugin expert. You write complete, valid Omarchy (Quattro / omarchy-shell, Quickshell QML) plugins. Manifests use schemaVersion 1, a namespaced id that never uses the reserved omarchy.* namespace, name, version, kinds (bar-widget|panel|overlay|menu|service|bar) with a matching safe relative entryPoints path for every kind, and no symlinks. Return every file in full as '### path' followed by a fenced code block."}, {"role": "user", "content": "Omarchy plugin `acme.emojis` (overlay). Manifest:\n```json\n{\n \"schemaVersion\": 1,\n \"id\": \"acme.emojis\",\n \"name\": \"Emojis\",\n \"version\": \"1.0.0\",\n \"author\": \"Omarchy\",\n \"description\": \"Search, copy, and type emojis\",\n \"kinds\": [\n \"overlay\"\n ],\n \"keepLoaded\": true,\n \"entryPoints\": {\n \"overlay\": \"Emojis.qml\"\n }\n}\n```\nSibling files:\n- Emojis.qml (11 KB)\n- emojis.json (107 KB)\n\nImplement `EmojiSearch.js` in full."}, {"role": "assistant", "content": "### EmojiSearch.js\n```javascript\nfunction parseEmojis(raw) {\n try {\n var data = JSON.parse(String(raw || \"\"))\n return Array.isArray(data) ? data : []\n } catch (e) {\n return []\n }\n}\n\nfunction normalizedQuery(query) {\n return String(query || \"\").trim().toLowerCase()\n}\n\nfunction keywordText(item) {\n return String((item && item.k) || \"\").toLowerCase()\n}\n\nfunction filterEmojis(emojis, query, limit) {\n var values = Array.isArray(emojis) ? emojis : []\n var needle = normalizedQuery(query)\n var max = limit === undefined || limit === null ? 1000 : Number(limit)\n if (isNaN(max)) max = 1000\n max = Math.max(0, max)\n if (max === 0) return []\n\n var out = []\n\n for (var i = 0; i < values.length; i++) {\n var item = values[i]\n if (!item || !item.e) continue\n if (!needle || keywordText(item).indexOf(needle) >= 0) {\n out.push(item)\n if (out.length >= max) break\n }\n }\n\n return out\n}\n\nif (typeof module !== \"undefined\") {\n module.exports = {\n parseEmojis: parseEmojis,\n normalizedQuery: normalizedQuery,\n filterEmojis: filterEmojis\n }\n}\n```"}], "task": "chunk_component", "meta": {"origin": "first-party", "repo": "https://github.com/basecamp/omarchy", "commit": "9480d1b6a98156314dbabe6bfef08f39f8b9cd07", "license": "MIT", "plugin_path": "shell/plugins/emojis", "kinds": ["overlay"], "complexity": "large", "group": "1af716ad", "chunked": true, "validate_tree": true, "validator": "pass", "qmllint": "clean", "qml_files": 0, "chars": 1946, "tokens": 571, "split": "train"}} {"messages": [{"role": "system", "content": "You are an Omarchy plugin expert. You write complete, valid Omarchy (Quattro / omarchy-shell, Quickshell QML) plugins. Manifests use schemaVersion 1, a namespaced id that never uses the reserved omarchy.* namespace, name, version, kinds (bar-widget|panel|overlay|menu|service|bar) with a matching safe relative entryPoints path for every kind, and no symlinks. Return every file in full as '### path' followed by a fenced code block."}, {"role": "user", "content": "Write a complete Omarchy plugin `acme.image-picker` called \"Image picker\" (overlay). Image-grid selector overlay used for wallpapers, themes, and any other directory of images. (It's a third-party plugin, so don't use the reserved omarchy.* namespace.)"}, {"role": "assistant", "content": "### manifest.json\n```json\n{\n \"schemaVersion\": 1,\n \"id\": \"acme.image-picker\",\n \"name\": \"Image picker\",\n \"version\": \"1.0.0\",\n \"author\": \"Omarchy\",\n \"description\": \"Image-grid selector overlay used for wallpapers, themes, and any other directory of images\",\n \"kinds\": [\n \"overlay\"\n ],\n \"keepLoaded\": true,\n \"entryPoints\": {\n \"overlay\": \"ImagePicker.qml\"\n }\n}\n```\n\n### ImagePicker.qml\n```qml\nimport Quickshell\nimport Quickshell.Io\nimport Quickshell.Wayland\nimport QtQuick\nimport QtQuick.Effects\nimport QtQuick.Shapes\nimport qs.Commons\nimport qs.Commons as Commons\nimport qs.Ui\nimport \"ImagePickerModel.js\" as ImagePickerModel\n\nItem {\n id: root\n\n // Injected by omarchy-shell; defaults to the session OMARCHY_PATH.\n property string omarchyPath: Quickshell.env(\"OMARCHY_PATH\")\n property string stateHome: Quickshell.env(\"HOME\") + \"/.local/state\"\n property string userThemesPath: Quickshell.env(\"HOME\") + \"/.config/omarchy/themes\"\n property string imageDirs: Quickshell.env(\"OMARCHY_IMAGE_SELECTOR_DIRS\") || Quickshell.env(\"OMARCHY_IMAGE_SELECTOR_DIR\") || Quickshell.env(\"OMARCHY_STOCK_BACKGROUNDS_DIR\") || (stateHome + \"/omarchy/current/theme/backgrounds\")\n property string imageRows: \"\"\n property string loadedImageRows: \"\"\n property string selectionFile: Quickshell.env(\"OMARCHY_IMAGE_SELECTOR_SELECTION_FILE\") || Quickshell.env(\"OMARCHY_BACKGROUND_SELECTION_FILE\")\n property string selectedImage: Quickshell.env(\"OMARCHY_IMAGE_SELECTOR_SELECTED\")\n property int selectedIndex: 0\n property bool imagesLoaded: false\n property bool opened: false\n property bool showLabels: false\n property bool filterable: false\n property bool layoutSettled: false\n property bool neighborImagesEnabled: false\n property int renderedFrames: 0\n property bool requestActive: false\n property int requestSerial: 0\n property int applySerial: 0\n property string doneFile: \"\"\n property string filterText: \"\"\n property var doneFilesToRelease: []\n // Themes open from rows the shell already holds, so the picker shows without\n // waiting on omarchy-theme-switcher; each open refreshes them behind it.\n property string themeRows: \"\"\n property bool themeMode: false\n property bool themeOpenPending: false\n property var extraThemeNames: []\n property var stockThemeNames: []\n property bool stockThemesKnown: false\n property bool awaitingDeleteRefresh: false\n property string pendingDeleteTheme: \"\"\n property string deleteSelectionPath: \"\"\n property bool deleteConfirmOpen: false\n // Bound to the central [image-picker] section in shell.toml via Commons.Color.qml.\n // `dimColor` tints unselected slices and text outlines against the desktop\n // behind the picker; it intentionally tracks the foundational background,\n // not a surface role.\n property color dimColor: Commons.Color.background\n property color foreground: Commons.Color.imagePicker.text\n property color selectedBorder: Commons.Color.imagePicker.selectedBorder\n property color unselectedBorder: Commons.Color.imagePicker.unselectedBorder\n property int expandedWidth: 768\n property int expandedHeight: 475\n property int sliceWidth: 108\n property int sliceHeight: 432\n property int sliceSpacing: -30\n property int skewOffset: 28\n property int bottomChromeHeight: showLabels ? (filterable ? 104 : 74) : (filterable ? 60 : 30)\n // Render only what fits on this display, plus one prefetch slice per side.\n readonly property int previewRadius: Math.max(1, Math.min(16, Math.ceil((panel.width - expandedWidth) / (2 * (sliceWidth + sliceSpacing))) + 1))\n onPreviewRadiusChanged: updateVisibleItems()\n\n onOpenedChanged: if (!opened) { layoutSettled = false; renderedFrames = 0; deleteConfirmOpen = false; pendingDeleteTheme = \"\"; deleteSelectionPath = \"\"; awaitingDeleteRefresh = false }\n\n function scriptPath(name) {\n return omarchyPath + \"/shell/plugins/image-picker/\" + name\n }\n\n function focusPicker() {\n if (root.opened && root.imagesLoaded && root.layoutSettled)\n carousel.forceActiveFocus()\n }\n\n function revealWhenSettled(serial) {\n Qt.callLater(function() {\n if (serial === root.requestSerial) root.maybeReveal()\n })\n }\n\n // The card renders at opacity 0 until every visible preview has decoded\n // and its masked layers have presented, so the picker lands in one\n // complete frame instead of flashing its images in as each asynchronous\n // decode and layer upload finishes.\n function allPreviewsSettled() {\n if (!opened || !imagesLoaded || layoutSettled || imageArray.length === 0 || imageCards.count === 0) return false\n for (var i = 0; i < imageCards.count; i++) {\n var item = imageCards.itemAt(i)\n if (!item || !item.previewSettled) return false\n }\n return true\n }\n\n function settleReveal() {\n if (!opened || !imagesLoaded || layoutSettled || imageArray.length === 0) return\n layoutSettled = true\n focusPicker()\n }\n\n function maybeReveal() {\n if (!allPreviewsSettled() || renderedFrames < 2) return\n // Confirm on the next tick: delegates inserted later in the same window\n // sync must not pop in after an early all-ready reading.\n Qt.callLater(function() {\n if (root.allPreviewsSettled() && root.renderedFrames >= 2) root.settleReveal()\n })\n }\n\n function currentPath() {\n if (imageArray.length === 0 || !itemMatches(selectedIndex)) return \"\"\n return imageArray[selectedIndex].filePath\n }\n\n function nameForPath(path) {\n return ImagePickerModel.nameForPath(path)\n }\n\n function labelForPath(path) {\n return ImagePickerModel.labelForPath(path)\n }\n\n function currentLabel() {\n var path = currentPath()\n if (!path) return filterText ? \"No matches\" : \"\"\n\n return labelForPath(path)\n }\n\n function itemMatches(index) {\n return ImagePickerModel.itemMatches(imageArray, index, filterText)\n }\n\n function firstMatchingIndex() {\n return ImagePickerModel.firstMatchingIndex(imageArray, filterText)\n }\n\n function select(index, immediate) {\n if (imageArray.length === 0) return\n if (index < 0) index = 0\n else if (index >= imageArray.length) index = imageArray.length - 1\n if (!itemMatches(index)) return\n if (index === selectedIndex && immediate !== true) return\n\n selectedIndex = index\n }\n\n function selectAdjacent(direction) {\n var count = imageArray.length\n if (count === 0) return\n\n var index = selectedIndex\n for (var i = 0; i < count; i++) {\n index = (index + direction + count) % count\n if (itemMatches(index)) {\n select(index)\n return\n }\n }\n }\n\n function updateFilter(nextFilterText) {\n filterText = nextFilterText\n\n if (!itemMatches(selectedIndex)) {\n var first = ImagePickerModel.nextSelectedIndexForFilter(imageArray, selectedIndex, filterText)\n if (first >= 0) selectedIndex = first\n }\n }\n\n function releaseNextDoneFile() {\n if (releaseProc.running || doneFilesToRelease.length === 0) return\n\n var path = doneFilesToRelease.shift()\n releaseProc.command = [\"bash\", \"-c\", \": > \" + Util.shellQuote(path)]\n releaseProc.running = true\n }\n\n function finishDoneFile(path) {\n if (!path) return\n doneFilesToRelease.push(path)\n releaseNextDoneFile()\n }\n\n function applySelected() {\n if (themeMode && (deleteThemeProc.running || awaitingDeleteRefresh)) return\n var path = currentPath()\n\n if (themeMode) {\n themeMode = false\n root.opened = false\n if (path) Util.execArgv([\"omarchy-theme-set\", nameForPath(path)])\n return\n }\n\n if (!path || !selectionFile) {\n cancel()\n return\n }\n\n var activeSelectionFile = selectionFile\n var activeDoneFile = doneFile\n applySerial = requestSerial\n requestActive = false\n selectionFile = \"\"\n doneFile = \"\"\n\n applyProc.command = [\"bash\", \"-c\", \"printf '%s\\\\n' \" + Util.shellQuote(path) + \" > \" + Util.shellQuote(activeSelectionFile) + \"; : > \" + Util.shellQuote(activeDoneFile)]\n applyProc.running = true\n }\n\n function cancel() {\n themeOpenPending = false\n\n if (requestActive)\n finishDoneFile(doneFile)\n\n requestActive = false\n selectionFile = \"\"\n doneFile = \"\"\n root.opened = false\n }\n\n function closeSelector(nextDoneFile) {\n requestSerial += 1\n themeOpenPending = false\n\n if (requestActive)\n finishDoneFile(doneFile)\n\n if (nextDoneFile && nextDoneFile !== doneFile)\n finishDoneFile(nextDoneFile)\n\n requestActive = false\n selectionFile = \"\"\n doneFile = \"\"\n filterText = \"\"\n root.opened = false\n }\n\n function loadRows(rows, reveal) {\n var newImages = ImagePickerModel.loadRows(rows)\n\n root.loadedImageRows = rows\n var nextIndex = root.indexForSelectedImage(newImages)\n root.selectedIndex = ImagePickerModel.nextSelectedIndexForFilter(newImages, nextIndex, root.filterText)\n root.neighborImagesEnabled = false\n root.imageArray = newImages\n root.imagesLoaded = true\n Qt.callLater(root.enableNeighborsWhenReady)\n\n if (reveal !== false) {\n root.opened = true\n root.revealWhenSettled(root.requestSerial)\n }\n }\n\n function openSelector(nextImageDirs, nextImageRows, nextSelectedImage, nextSelectionFile, nextDoneFile, nextShowLabels, nextFilterable) {\n deleteConfirmOpen = false\n pendingDeleteTheme = \"\"\n deleteSelectionPath = \"\"\n awaitingDeleteRefresh = false\n if (requestActive && doneFile && doneFile !== nextDoneFile)\n finishDoneFile(doneFile)\n\n requestSerial += 1\n themeMode = false\n themeOpenPending = false\n\n imageDirs = nextImageDirs\n imageRows = nextImageRows\n selectedImage = nextSelectedImage\n selectionFile = nextSelectionFile\n doneFile = nextDoneFile\n requestActive = !!doneFile\n showLabels = nextShowLabels === true || nextShowLabels === \"true\"\n filterable = nextFilterable === true || nextFilterable === \"true\"\n filterText = \"\"\n layoutSettled = false\n\n if (imageRows && imageRows === loadedImageRows && imageArray.length > 0) {\n root.select(root.selectedImageIndex(), true)\n imagesLoaded = true\n opened = true\n root.revealWhenSettled(requestSerial)\n return\n }\n\n if (imageRows) {\n var rowsToLoad = imageRows\n var rowsSerial = requestSerial\n imageArray = []\n selectedIndex = 0\n imagesLoaded = true\n opened = true\n Qt.callLater(function() {\n if (rowsSerial === root.requestSerial)\n root.loadRows(rowsToLoad, true)\n })\n return\n }\n\n imageArray = []\n selectedIndex = 0\n imagesLoaded = false\n opened = false\n startImageScan(requestSerial, imageDirs)\n }\n\n property var imageArray: []\n readonly property var matchingImageIndices: ImagePickerModel.matchingIndices(imageArray, filterText)\n onMatchingImageIndicesChanged: updateVisibleItems()\n onSelectedIndexChanged: {\n updateVisibleItems()\n introPrepareTimer.restart()\n }\n onThemeModeChanged: if (themeMode) introPrepareTimer.restart()\n\n Timer {\n id: introPrepareTimer\n interval: 75\n onTriggered: {\n if (root.opened && root.themeMode && !introPrepare.running) {\n introPrepare.theme = root.nameForPath(root.currentPath())\n introPrepare.command = [\"omarchy-theme-bg-boot-intro\", \"--prepare-theme\", root.nameForPath(root.currentPath())]\n introPrepare.running = true\n }\n }\n }\n\n Process {\n id: introPrepare\n property string theme: \"\"\n onExited: if (root.opened && root.themeMode && theme !== root.nameForPath(root.currentPath())) introPrepareTimer.restart()\n }\n\n function updateVisibleItems() {\n ImagePickerModel.syncWindow(visibleImages, ImagePickerModel.visibleWindow(matchingImageIndices, selectedIndex, previewRadius))\n }\n\n function enableNeighborsWhenReady() {\n for (var i = 0; i < imageCards.count; i++) {\n var item = imageCards.itemAt(i)\n if (item && item.selected && item.previewReady) neighborImagesEnabled = true\n }\n }\n\n ListModel { id: visibleImages }\n\n\n function currentThemePreview() {\n var name = String(themeNameFile.text() || \"\").trim()\n var images = ImagePickerModel.loadRows(themeRows)\n for (var i = 0; i < images.length; i++) {\n if (nameForPath(images[i].filePath) === name) return images[i].filePath\n }\n return \"\"\n }\n\n function openThemes() {\n if (themeRows) {\n openThemeRows()\n } else {\n // First open before the startup refresh has landed.\n themeOpenPending = true\n }\n refreshThemeRows()\n refreshExtraThemes()\n refreshStockThemes()\n }\n\n function openThemeRows() {\n openSelector(\"\", themeRows, currentThemePreview(), \"\", \"\", true, true)\n themeMode = true\n }\n\n // A refresh asked mid-refresh (a deletion finishing behind the open-time\n // one) queues a second pass instead of leaving the list stale.\n function refreshThemeRows() {\n if (themeRowsProc.running) { themeRowsProc.queued = true; return }\n themeRowsProc.running = true\n }\n\n function refreshExtraThemes() {\n if (extraThemesProc.running) { extraThemesProc.queued = true; return }\n extraThemesProc.running = true\n }\n\n function refreshStockThemes() {\n if (!stockThemesProc.running) stockThemesProc.running = true\n }\n\n function selectedThemeName() {\n return nameForPath(currentPath())\n }\n\n function canDeleteSelectedTheme() {\n return themeMode && !deleteThemeProc.running && !awaitingDeleteRefresh && stockThemesKnown && ImagePickerModel.canDeleteTheme(selectedThemeName(), extraThemeNames, stockThemeNames)\n }\n\n function requestDeleteSelectedTheme() {\n if (!canDeleteSelectedTheme()) return\n pendingDeleteTheme = selectedThemeName()\n deleteConfirm.selectedIndex = 1\n deleteConfirmOpen = true\n }\n\n function cancelDeleteTheme() {\n deleteConfirmOpen = false\n pendingDeleteTheme = \"\"\n }\n\n // Removal itself is omarchy-theme-remove's job (including its guards and\n // notification); the picker only refreshes its rows once it finishes.\n function confirmDeleteTheme() {\n var name = pendingDeleteTheme\n deleteConfirmOpen = false\n pendingDeleteTheme = \"\"\n if (!name || deleteThemeProc.running) return\n // Keep the user's place in the list once the deleted theme is gone.\n if (name === selectedThemeName()) deleteSelectionPath = ImagePickerModel.replacementSelectionPath(imageArray, selectedIndex, filterText)\n deleteThemeProc.command = [\"omarchy-theme-remove\", name]\n deleteThemeProc.running = true\n }\n\n function updateThemeRows(rows) {\n var changed = rows !== themeRows\n themeRows = rows\n\n if (themeOpenPending) {\n themeOpenPending = false\n if (rows) openThemeRows()\n } else if (changed && rows && themeMode && opened) {\n // A theme was added or removed since the rows were last read. Keep the\n // user's place in the carousel rather than jumping back to the current;\n // a just-deleted selection lands on the theme before it.\n selectedImage = deleteSelectionPath || currentPath() || currentThemePreview()\n deleteSelectionPath = \"\"\n awaitingDeleteRefresh = false\n imageRows = rows\n loadRows(rows, false)\n }\n }\n\n FileView {\n id: themeNameFile\n path: root.stateHome + \"/omarchy/current/theme.name\"\n watchChanges: true\n onFileChanged: reload()\n }\n\n Process {\n id: themeRowsProc\n property bool queued: false\n command: [root.omarchyPath + \"/bin/omarchy-theme-switcher\", \"--print-rows\"]\n stdout: StdioCollector {\n onStreamFinished: root.updateThemeRows(String(text || \"\").trim())\n }\n onExited: {\n if (queued) {\n queued = false\n running = true\n }\n }\n }\n\n // The same listing omarchy-theme-remove offers interactively: real\n // directories under the user themes path, never symlinked working copies.\n Process {\n id: extraThemesProc\n property bool queued: false\n command: [\"find\", root.userThemesPath, \"-mindepth\", \"1\", \"-maxdepth\", \"1\", \"-type\", \"d\", \"!\", \"-xtype\", \"l\", \"-printf\", \"%f\\n\"]\n stdout: StdioCollector {\n onStreamFinished: root.extraThemeNames = ImagePickerModel.parseThemeNames(String(text || \"\"))\n }\n onExited: {\n if (queued) {\n queued = false\n running = true\n }\n }\n }\n\n Process {\n id: stockThemesProc\n command: [\"find\", root.omarchyPath + \"/themes\", \"-mindepth\", \"1\", \"-maxdepth\", \"1\", \"-type\", \"d\", \"-printf\", \"%f\\n\"]\n stdout: StdioCollector {\n onStreamFinished: root.stockThemeNames = ImagePickerModel.parseThemeNames(String(text || \"\"))\n }\n // Until this lands, stockThemeNames is empty and an override would look\n // deletable: deletion stays disabled unless the listing succeeded.\n onExited: function(exitCode) { if (exitCode === 0) root.stockThemesKnown = true }\n }\n\n Process {\n id: deleteThemeProc\n onExited: function(exitCode) {\n if (exitCode === 0) root.awaitingDeleteRefresh = true\n else root.deleteSelectionPath = \"\"\n root.refreshExtraThemes()\n root.refreshThemeRows()\n }\n }\n\n Component.onCompleted: {\n refreshThemeRows()\n refreshExtraThemes()\n refreshStockThemes()\n }\n\n function startImageScan(serial, dirs) {\n if (loadImagesProc.running) {\n loadImagesProc.queuedSerial = serial\n loadImagesProc.queuedDirs = dirs\n return\n }\n\n loadImagesProc.activeSerial = serial\n loadImagesProc.queuedSerial = 0\n loadImagesProc.queuedDirs = \"\"\n loadImagesProc.command = [root.scriptPath(\"list.sh\"), dirs]\n loadImagesProc.running = true\n }\n\n function indexForSelectedImage(images) {\n return ImagePickerModel.indexForSelectedImage(images, selectedImage)\n }\n\n function selectedImageIndex() {\n return indexForSelectedImage(imageArray)\n }\n\n Process {\n id: loadImagesProc\n property int activeSerial: 0\n property int queuedSerial: 0\n property string queuedDirs: \"\"\n stdout: StdioCollector {\n waitForEnd: true\n onStreamFinished: {\n if (loadImagesProc.activeSerial === root.requestSerial)\n root.loadRows(String(text || \"\"), true)\n }\n }\n onExited: {\n var serial = queuedSerial\n var dirs = queuedDirs\n activeSerial = 0\n queuedSerial = 0\n queuedDirs = \"\"\n if (serial > 0 && serial === root.requestSerial)\n root.startImageScan(serial, dirs)\n }\n }\n\n // Lifecycle hooks invoked by omarchy-shell summon/hide. shell.summon(id,\n // payloadJson) hands the JSON to open() here; shell.hide(id) calls close().\n // The shell host owns the stable `image-selector` IPC target and forwards\n // those lower-level positional calls here.\n function open(payload) {\n var args = {}\n if (payload) {\n try { args = JSON.parse(payload) || {} } catch (e) { args = {} }\n }\n if (args.source === \"themes\") {\n openThemes()\n return\n }\n var dirs = String(args.imageDirs || imageDirs)\n var rows = String(args.imageRows || \"\")\n var sel = String(args.selectedImage || selectedImage)\n var selFile = String(args.selectionFile || \"\")\n var doneF = String(args.doneFile || \"\")\n var labels = args.showLabels === true || args.showLabels === \"true\"\n var filter = args.filterable === true || args.filterable === \"true\"\n openSelector(dirs, rows, sel, selFile, doneF, labels, filter)\n }\n\n function close() {\n cancel()\n }\n\n function preloadRows(nextImageRows, nextSelectedImage, nextShowLabels, nextFilterable) {\n // Theme/background set hooks can warm selector rows after a picker was\n // dismissed. Ignore those preloads while a user-visible request is open;\n // otherwise the preload resets layoutSettled without revealing again,\n // leaving the picker invisible behind its own open overlay.\n if (opened || requestActive) return\n\n requestSerial += 1\n imageRows = nextImageRows\n selectedImage = nextSelectedImage\n showLabels = nextShowLabels === true || nextShowLabels === \"true\"\n filterable = nextFilterable === true || nextFilterable === \"true\"\n filterText = \"\"\n layoutSettled = false\n\n if (imageRows && imageRows === loadedImageRows && imageArray.length > 0) {\n selectedIndex = selectedImageIndex()\n imagesLoaded = true\n } else if (imageRows) {\n loadRows(imageRows, false)\n }\n }\n\n Process {\n id: applyProc\n onExited: {\n if (root.applySerial === root.requestSerial)\n root.opened = false\n }\n }\n\n Process {\n id: releaseProc\n onExited: root.releaseNextDoneFile()\n }\n\n OverlayWindow {\n id: panel\n shown: root.opened\n shownKeyboardFocus: root.imagesLoaded ? WlrKeyboardFocus.Exclusive : WlrKeyboardFocus.None\n WlrLayershell.namespace: \"omarchy-image-selector\"\n\n MouseArea {\n anchors.fill: parent\n enabled: root.opened && root.imagesLoaded\n onClicked: root.cancel()\n }\n\n // Count presented frames while the card pre-renders below; two frames\n // prove its masked layers uploaded on this fresh surface.\n FrameAnimation {\n running: root.opened && !root.layoutSettled && root.renderedFrames < 2\n onTriggered: {\n root.renderedFrames += 1\n root.maybeReveal()\n }\n }\n\n // A preview stuck decoding (slow disk, huge original) must not hold an\n // invisible picker with the keyboard grabbed: reveal anyway shortly.\n Timer {\n interval: 400\n running: root.opened && root.imagesLoaded && !root.layoutSettled && root.imageArray.length > 0\n onTriggered: root.settleReveal()\n }\n\n Item {\n id: card\n visible: root.opened && root.imagesLoaded && root.imageArray.length > 0\n opacity: root.layoutSettled ? 1 : 0\n width: Math.min(parent.width - 80, root.expandedWidth + 13 * (root.sliceWidth + root.sliceSpacing) + 40)\n height: root.expandedHeight + Style.space(30) + root.bottomChromeHeight\n anchors.centerIn: parent\n\n MouseArea { anchors.fill: parent; enabled: root.layoutSettled; onClicked: {} }\n\n Item {\n id: carousel\n anchors.top: parent.top\n anchors.topMargin: Style.space(30)\n anchors.bottom: parent.bottom\n anchors.bottomMargin: root.bottomChromeHeight\n anchors.horizontalCenter: parent.horizontalCenter\n width: root.expandedWidth + 13 * (root.sliceWidth + root.sliceSpacing)\n clip: false\n focus: true\n\n readonly property real itemStep: root.sliceWidth + root.sliceSpacing\n readonly property real previewX: (width - root.expandedWidth) / 2\n\n Keys.priority: Keys.BeforeItem\n Keys.onPressed: function(event) {\n if (root.deleteConfirmOpen) {\n if (deleteConfirm.handleKey(event)) event.accepted = true\n return\n }\n // Nothing is visible before the reveal: only let the user back\n // out, never filter into a dead end or apply an unseen pick.\n if (!root.layoutSettled) {\n if (event.key === Qt.Key_Escape) {\n root.cancel()\n event.accepted = true\n }\n return\n }\n if (event.key === Qt.Key_Escape) {\n if (root.filterText) {\n root.updateFilter(\"\")\n } else {\n root.cancel()\n }\n event.accepted = true\n } else if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter) {\n root.applySelected()\n event.accepted = true\n } else if (event.key === Qt.Key_Delete && !(event.modifiers & (Qt.ControlModifier | Qt.AltModifier | Qt.MetaModifier))) {\n root.requestDeleteSelectedTheme()\n event.accepted = true\n } else if (root.filterable && Util.editsFilter(event, root.filterText)) {\n root.updateFilter(Util.editedFilter(event, root.filterText))\n event.accepted = true\n } else if (event.key === Qt.Key_Left || (event.key === Qt.Key_Tab && event.modifiers & Qt.ShiftModifier) || event.key === Qt.Key_Backtab) {\n root.selectAdjacent(-1)\n event.accepted = true\n } else if (event.key === Qt.Key_Right || event.key === Qt.Key_Tab) {\n root.selectAdjacent(1)\n event.accepted = true\n } else if (root.filterable && event.text && event.text.length === 1 && event.text.charCodeAt(0) >= 32 && event.text.charCodeAt(0) !== 127 && (event.modifiers === Qt.NoModifier || event.modifiers === Qt.ShiftModifier)) {\n root.updateFilter(root.filterText + event.text)\n event.accepted = true\n }\n }\n\n Component.onCompleted: forceActiveFocus()\n\n Repeater {\n id: imageCards\n model: visibleImages\n onCountChanged: root.maybeReveal()\n\n delegate: Item {\n id: item\n required property int imageIndex\n required property int relativeIndex\n\n readonly property var imageData: root.imageArray[imageIndex]\n readonly property string filePath: imageData ? imageData.filePath : \"\"\n readonly property string fileName: imageData ? imageData.fileName : \"\"\n readonly property string thumbnailPath: imageData ? imageData.thumbnailPath : \"\"\n\n readonly property bool selected: imageIndex === root.selectedIndex\n readonly property bool previewReady: image.status === Image.Ready || image.status === Image.Error\n readonly property bool previewSettled: !thumbnailPath || previewReady\n onPreviewSettledChanged: if (previewSettled) root.maybeReveal()\n onSelectedChanged: if (selected && previewReady) root.neighborImagesEnabled = true\n\n x: selected ? carousel.previewX : (relativeIndex < 0 ? carousel.previewX + relativeIndex * carousel.itemStep : carousel.previewX + root.expandedWidth + root.sliceSpacing + (relativeIndex - 1) * carousel.itemStep)\n width: selected ? root.expandedWidth : root.sliceWidth\n height: selected ? root.expandedHeight : root.sliceHeight\n y: selected ? 0 : (root.expandedHeight - root.sliceHeight) / 2\n z: selected ? 100 : 50 - Math.min(Math.abs(relativeIndex), 40)\n\n readonly property real skAbs: Math.abs(root.skewOffset)\n readonly property real topLeft: root.skewOffset >= 0 ? skAbs : 0\n readonly property real topRight: root.skewOffset >= 0 ? width : width - skAbs\n readonly property real bottomRight: root.skewOffset >= 0 ? width - skAbs : width\n readonly property real bottomLeft: root.skewOffset >= 0 ? 0 : skAbs\n\n Item {\n id: maskShape\n anchors.fill: parent\n visible: false\n layer.enabled: true\n\n Shape {\n anchors.fill: parent\n antialiasing: true\n preferredRendererType: Shape.CurveRenderer\n ShapePath {\n fillColor: \"white\"\n strokeColor: \"transparent\"\n startX: item.topLeft; startY: 0\n PathLine { x: item.topRight; y: 0 }\n PathLine { x: item.bottomRight; y: item.height }\n PathLine { x: item.bottomLeft; y: item.height }\n PathLine { x: item.topLeft; y: 0 }\n }\n }\n }\n\n Item {\n anchors.fill: parent\n layer.enabled: true\n layer.smooth: true\n layer.effect: MultiEffect {\n maskEnabled: true\n maskSource: maskShape\n maskThresholdMin: 0.3\n maskSpreadAtMin: 0.3\n }\n\n Rectangle { anchors.fill: parent; color: root.dimColor }\n\n Image {\n id: image\n anchors.fill: parent\n // Decode at the expanded card's physical size, off the GUI\n // thread. Keep that size during navigation to avoid reloads.\n // Departing cards release their images instead of retaining\n // every preview visited in a large collection.\n // Queue the selected preview first; neighbors must not delay\n // the image the user opened the picker to see.\n source: (item.selected || root.neighborImagesEnabled) && item.thumbnailPath ? Util.fileUrl(item.thumbnailPath) : \"\"\n sourceSize.width: Math.ceil(root.expandedWidth * Screen.devicePixelRatio)\n sourceSize.height: Math.ceil(root.expandedHeight * Screen.devicePixelRatio)\n fillMode: Image.PreserveAspectCrop\n asynchronous: true\n cache: false\n smooth: true\n opacity: status === Image.Ready ? 1 : 0\n onStatusChanged: if (item.selected && (status === Image.Ready || status === Image.Error)) root.neighborImagesEnabled = true\n }\n\n Rectangle {\n anchors.fill: parent\n color: Util.alpha(root.dimColor, item.selected ? 0 : 0.42)\n }\n }\n\n Shape {\n anchors.fill: parent\n antialiasing: true\n preferredRendererType: Shape.CurveRenderer\n ShapePath {\n fillColor: \"transparent\"\n strokeColor: item.selected ? root.selectedBorder : root.unselectedBorder\n strokeWidth: item.selected ? 3 : 1\n startX: item.topLeft; startY: 0\n PathLine { x: item.topRight; y: 0 }\n PathLine { x: item.bottomRight; y: item.height }\n PathLine { x: item.bottomLeft; y: item.height }\n PathLine { x: item.topLeft; y: 0 }\n }\n }\n\n MouseArea {\n anchors.fill: parent\n enabled: root.layoutSettled\n cursorShape: Qt.PointingHandCursor\n onClicked: item.selected ? root.applySelected() : root.select(item.imageIndex)\n }\n }\n }\n }\n\n Text {\n id: selectedLabel\n textFormat: Text.PlainText\n visible: root.showLabels\n anchors.top: carousel.bottom\n anchors.topMargin: Style.space(16)\n anchors.horizontalCenter: carousel.horizontalCenter\n width: root.expandedWidth\n text: root.currentLabel()\n color: root.foreground\n style: Text.Outline\n styleColor: Util.alpha(root.dimColor, 0.7)\n font.pixelSize: Style.font.display\n font.weight: Font.DemiBold\n horizontalAlignment: Text.AlignHCenter\n elide: Text.ElideRight\n }\n\n Text {\n textFormat: Text.PlainText\n visible: root.filterable && root.filterText\n anchors.top: selectedLabel.bottom\n anchors.topMargin: Style.space(8)\n anchors.horizontalCenter: carousel.horizontalCenter\n width: root.expandedWidth\n text: root.filterText\n color: root.foreground\n opacity: 0.85\n style: Text.Outline\n styleColor: Util.alpha(root.dimColor, 0.7)\n font.pixelSize: Style.font.title\n horizontalAlignment: Text.AlignHCenter\n elide: Text.ElideRight\n }\n }\n\n // Unlike the picker itself, the confirmation keeps the faded backdrop:\n // a destructive choice should take over the screen.\n ConfirmDialog {\n id: deleteConfirm\n anchors.fill: parent\n opened: root.deleteConfirmOpen\n z: 10\n message: \"Do you want to delete \" + (root.pendingDeleteTheme ? root.labelForPath(root.pendingDeleteTheme) : \"\") + \"?\"\n confirmText: \"Delete\"\n background: root.dimColor\n foreground: root.foreground\n onCanceled: root.cancelDeleteTheme()\n onConfirmed: root.confirmDeleteTheme()\n }\n }\n}\n```\n\n### ImagePickerModel.js\n```javascript\nfunction nameForPath(path) {\n return String(path || \"\").split(\"/\").pop().replace(/\\.[^/.]+$/, \"\")\n}\n\nfunction labelForPath(path) {\n return nameForPath(path).replace(/[-_]+/g, \" \").replace(/\\b\\w/g, function(match) { return match.toUpperCase() })\n}\n\n// Extra (user-installed) theme names, one per line, as listed from the user\n// themes directory: the set omarchy-theme-remove can delete.\nfunction parseThemeNames(text) {\n var names = []\n var lines = String(text || \"\").split(\"\\n\")\n for (var i = 0; i < lines.length; i++) {\n var name = lines[i].trim()\n if (name) names.push(name)\n }\n return names\n}\n\n// A user directory shadowing a stock theme holds customizations, not an\n// extra theme: removing it from here would silently revert to stock (and a\n// shadow can even list twice, once per preview extension), so only themes\n// with no stock twin can be deleted from the picker.\nfunction canDeleteTheme(name, extraNames, stockNames) {\n if (!name || !Array.isArray(extraNames) || extraNames.indexOf(name) === -1) return false\n return !Array.isArray(stockNames) || stockNames.indexOf(name) === -1\n}\n\n// Where selection lands when the selected image goes away: the previous\n// match in list order, or the next one when the first match is deleted.\nfunction replacementSelectionPath(images, selectedIndex, filterText) {\n var values = Array.isArray(images) ? images : []\n if (selectedIndex < 0 || selectedIndex >= values.length) return \"\"\n for (var i = selectedIndex - 1; i >= 0; i--) {\n if (itemMatches(values, i, filterText)) return values[i].filePath\n }\n for (var i = selectedIndex + 1; i < values.length; i++) {\n if (itemMatches(values, i, filterText)) return values[i].filePath\n }\n return \"\"\n}\n\nfunction loadRows(rows) {\n var images = []\n var seen = {}\n var paths = String(rows || \"\").split(\"\\n\")\n\n for (var i = 0; i < paths.length; i++) {\n var row = paths[i]\n if (!row) continue\n\n var columns = row.split(\"\\t\")\n var path = columns[0]\n if (!path) continue\n\n var fileName = path.split(\"/\").pop()\n if (seen[fileName]) continue\n seen[fileName] = true\n\n images.push({\n filePath: path,\n fileName: fileName,\n thumbnailPath: columns[1] || path\n })\n }\n\n return images\n}\n\nfunction itemMatches(images, index, filterText) {\n if (!Array.isArray(images) || index < 0 || index >= images.length) return false\n var needle = String(filterText || \"\").toLowerCase()\n if (!needle) return true\n\n var path = String(images[index].filePath || \"\")\n return nameForPath(path).toLowerCase().indexOf(needle) !== -1\n || labelForPath(path).toLowerCase().indexOf(needle) !== -1\n}\n\nfunction firstMatchingIndex(images, filterText) {\n var values = Array.isArray(images) ? images : []\n for (var i = 0; i < values.length; i++) {\n if (itemMatches(values, i, filterText)) return i\n }\n\n return -1\n}\n\nfunction filteredPosition(images, index, filterText) {\n if (!filterText) return index\n\n var position = 0\n for (var i = 0; i < index; i++) {\n if (itemMatches(images, i, filterText)) position++\n }\n\n return position\n}\n\nfunction selectedFilteredPosition(images, selectedIndex, filterText) {\n if (!filterText) return selectedIndex\n return itemMatches(images, selectedIndex, filterText) ? filteredPosition(images, selectedIndex, filterText) : 0\n}\n\nfunction indexForSelectedImage(images, selectedImage) {\n var values = Array.isArray(images) ? images : []\n for (var i = 0; i < values.length; i++) {\n if (values[i].filePath === selectedImage) return i\n }\n\n return 0\n}\n\nfunction nextSelectedIndexForFilter(images, selectedIndex, filterText) {\n if (itemMatches(images, selectedIndex, filterText)) return selectedIndex\n return firstMatchingIndex(images, filterText)\n}\n\nfunction matchingIndices(images, filterText) {\n var indices = []\n for (var i = 0; i < images.length; i++) {\n if (itemMatches(images, i, filterText)) indices.push(i)\n }\n return indices\n}\n\n// Keep the rendered carousel independent of the size of the collection.\nfunction visibleWindow(indices, selectedIndex, radius) {\n var position = indices.indexOf(selectedIndex)\n if (position < 0) position = 0\n var items = []\n for (var i = Math.max(0, position - radius); i < Math.min(indices.length, position + radius + 1); i++) {\n items.push({ imageIndex: indices[i], relativeIndex: i - position })\n }\n return items\n}\n\n// Preserve overlapping delegates as selection moves, including their decoded\n// images. Replacing the entire model on every keypress makes previews flicker.\nfunction syncWindow(model, items) {\n var wanted = {}\n for (var i = 0; i < items.length; i++) wanted[items[i].imageIndex] = true\n for (var i = model.count - 1; i >= 0; i--) {\n if (!wanted[model.get(i).imageIndex]) model.remove(i)\n }\n for (var i = 0; i < items.length; i++) {\n var existing = i\n while (existing < model.count && model.get(existing).imageIndex !== items[i].imageIndex) existing++\n if (existing === model.count) {\n model.insert(i, items[i])\n } else {\n if (existing !== i) model.move(existing, i, 1)\n model.setProperty(i, \"relativeIndex\", items[i].relativeIndex)\n }\n }\n}\n\nif (typeof module !== \"undefined\") {\n module.exports = {\n nameForPath: nameForPath,\n labelForPath: labelForPath,\n parseThemeNames: parseThemeNames,\n canDeleteTheme: canDeleteTheme,\n replacementSelectionPath: replacementSelectionPath,\n loadRows: loadRows,\n itemMatches: itemMatches,\n firstMatchingIndex: firstMatchingIndex,\n filteredPosition: filteredPosition,\n selectedFilteredPosition: selectedFilteredPosition,\n indexForSelectedImage: indexForSelectedImage,\n nextSelectedIndexForFilter: nextSelectedIndexForFilter,\n matchingIndices: matchingIndices,\n visibleWindow: visibleWindow,\n syncWindow: syncWindow\n }\n}\n```\n\n### list.sh\n```bash\n#!/bin/bash\n\nimage_dirs=${1:-}\ncache_dir=${XDG_CACHE_HOME:-$HOME/.cache}/omarchy/image-selector\nindex_file=\"$cache_dir/index.tsv\"\npending_video_file=$(mktemp)\n\nmkdir -p \"$cache_dir\"\ntrap 'rm -f \"$pending_video_file\"' EXIT\n\nis_video_path() {\n [[ ${1,,} =~ \\.(mp4|m4v|mov|webm|mkv|avi)$ ]]\n}\n\nthumbnail_path_for() {\n local image=\"$1\"\n local signature hash\n\n signature=$(stat -Lc '%s:%Y' \"$image\") || return\n hash=$(awk -F '\\t' -v path=\"$image\" -v sig=\"$signature\" '$1 == path && $2 == sig { print $3; exit }' \"$index_file\" 2>/dev/null)\n\n if [[ -z $hash ]]; then\n hash=$(printf '%s\\t%s' \"$image\" \"$signature\" | md5sum | cut -d ' ' -f 1)\n fi\n\n printf '%s/%s.jpg' \"$cache_dir\" \"$hash\"\n}\n\ngenerate_video_thumbnail() {\n local image=\"$1\"\n local thumbnail=\"$2\"\n local lock=\"$thumbnail.lock\"\n local lock_fd\n local tmp=\"$thumbnail.$$.jpg\"\n\n if [[ -d $lock ]] && (( $(date +%s) - $(stat -c '%Y' \"$lock\" 2>/dev/null || date +%s) > 120 )); then\n rmdir \"$lock\" 2>/dev/null\n fi\n\n exec {lock_fd}>\"$lock\" || return\n flock -w 30 \"$lock_fd\" || return\n rm -f \"$thumbnail\".*.jpg\n\n [[ -f $thumbnail ]] && return\n\n if timeout -k 5 10 ffmpegthumbnailer -i \"$image\" -o \"$tmp\" -s 1536 -q 8 {lock_fd}>&-; then\n mv -f \"$tmp\" \"$thumbnail\"\n else\n status=$?\n rm -f \"$tmp\" \"$thumbnail\"\n # Remember a rejected video so it costs nothing on the next scan; the key\n # covers size and mtime, so a repaired file starts clean. A timeout is\n # left to retry: the machine may only have been busy.\n (( status == 124 || status == 137 )) || : >\"$thumbnail.failed\"\n return 1\n fi\n}\n\ndrain_pending_video_thumbnails() {\n local video_jobs\n\n [[ -s $pending_video_file ]] || return 0\n\n video_jobs=$(( $(nproc) / 4 ))\n (( video_jobs > 0 )) || video_jobs=1\n export -f generate_video_thumbnail\n xargs -a \"$pending_video_file\" -0 -n 2 -P \"$video_jobs\" \\\n bash -c 'generate_video_thumbnail \"$1\" \"$2\"' _ >/dev/null 2>&1 || true\n}\n\nthumbnail_for() {\n local image=\"$1\"\n local thumbnail legacy_hash\n\n thumbnail=$(thumbnail_path_for \"$image\") || return\n\n if [[ ! -f $thumbnail ]] && ! is_video_path \"$image\"; then\n # Older on-demand picker code keyed fallback thumbnails by file content.\n # Keep finding those if a user still has them cached.\n legacy_hash=$(md5sum \"$image\" 2>/dev/null | cut -d ' ' -f 1)\n [[ -n $legacy_hash && -f $cache_dir/$legacy_hash.jpg ]] && thumbnail=\"$cache_dir/$legacy_hash.jpg\"\n fi\n\n if [[ -f $thumbnail ]]; then\n printf '%s' \"$thumbnail\"\n elif ! is_video_path \"$image\"; then\n printf '%s' \"$image\"\n fi\n}\n\nmapfile -d '' -t images < <(\n while IFS= read -r dir; do\n [[ -n $dir && -d $dir ]] || continue\n find -L \"$dir\" -maxdepth 1 -type f \\\n \\( -iname '*.jpg' -o -iname '*.jpeg' -o -iname '*.png' -o -iname '*.gif' -o -iname '*.bmp' -o -iname '*.webp' \\\n -o -iname '*.mp4' -o -iname '*.m4v' -o -iname '*.mov' -o -iname '*.webm' -o -iname '*.mkv' -o -iname '*.avi' \\) \\\n -print0 2>/dev/null\n done <<<\"$image_dirs\" | sort -z\n)\n\nfor image in \"${images[@]}\"; do\n if is_video_path \"$image\"; then\n thumbnail=$(thumbnail_path_for \"$image\") || continue\n [[ -f $thumbnail || -f $thumbnail.failed ]] || printf '%s\\0%s\\0' \"$image\" \"$thumbnail\" >>\"$pending_video_file\"\n fi\ndone\n\ndrain_pending_video_thumbnails\n\nfor image in \"${images[@]}\"; do\n thumbnail=$(thumbnail_for \"$image\")\n [[ -n $thumbnail ]] || continue\n printf '%s\\t%s\\n' \"$image\" \"$thumbnail\"\ndone\n```"}], "task": "build_from_spec", "meta": {"origin": "first-party", "repo": "https://github.com/basecamp/omarchy", "commit": "9480d1b6a98156314dbabe6bfef08f39f8b9cd07", "license": "MIT", "plugin_path": "shell/plugins/image-picker", "kinds": ["overlay"], "complexity": "large", "group": "1683ed85", "validator": "pass", "qmllint": "clean", "qml_files": 1, "chars": 41869, "tokens": 10155, "split": "train"}} {"messages": [{"role": "system", "content": "You are an Omarchy plugin expert. You write complete, valid Omarchy (Quattro / omarchy-shell, Quickshell QML) plugins. Manifests use schemaVersion 1, a namespaced id that never uses the reserved omarchy.* namespace, name, version, kinds (bar-widget|panel|overlay|menu|service|bar) with a matching safe relative entryPoints path for every kind, and no symlinks. Return every file in full as '### path' followed by a fenced code block."}, {"role": "user", "content": "I want an Omarchy overlay plugin named Image picker (id `acme.image-picker`): Image-grid selector overlay used for wallpapers, themes, and any other directory of images. Give me every file."}, {"role": "assistant", "content": "### manifest.json\n```json\n{\n \"schemaVersion\": 1,\n \"id\": \"acme.image-picker\",\n \"name\": \"Image picker\",\n \"version\": \"1.0.0\",\n \"author\": \"Omarchy\",\n \"description\": \"Image-grid selector overlay used for wallpapers, themes, and any other directory of images\",\n \"kinds\": [\n \"overlay\"\n ],\n \"keepLoaded\": true,\n \"entryPoints\": {\n \"overlay\": \"ImagePicker.qml\"\n }\n}\n```\n\n### ImagePicker.qml\n```qml\nimport Quickshell\nimport Quickshell.Io\nimport Quickshell.Wayland\nimport QtQuick\nimport QtQuick.Effects\nimport QtQuick.Shapes\nimport qs.Commons\nimport qs.Commons as Commons\nimport qs.Ui\nimport \"ImagePickerModel.js\" as ImagePickerModel\n\nItem {\n id: root\n\n // Injected by omarchy-shell; defaults to the session OMARCHY_PATH.\n property string omarchyPath: Quickshell.env(\"OMARCHY_PATH\")\n property string stateHome: Quickshell.env(\"HOME\") + \"/.local/state\"\n property string userThemesPath: Quickshell.env(\"HOME\") + \"/.config/omarchy/themes\"\n property string imageDirs: Quickshell.env(\"OMARCHY_IMAGE_SELECTOR_DIRS\") || Quickshell.env(\"OMARCHY_IMAGE_SELECTOR_DIR\") || Quickshell.env(\"OMARCHY_STOCK_BACKGROUNDS_DIR\") || (stateHome + \"/omarchy/current/theme/backgrounds\")\n property string imageRows: \"\"\n property string loadedImageRows: \"\"\n property string selectionFile: Quickshell.env(\"OMARCHY_IMAGE_SELECTOR_SELECTION_FILE\") || Quickshell.env(\"OMARCHY_BACKGROUND_SELECTION_FILE\")\n property string selectedImage: Quickshell.env(\"OMARCHY_IMAGE_SELECTOR_SELECTED\")\n property int selectedIndex: 0\n property bool imagesLoaded: false\n property bool opened: false\n property bool showLabels: false\n property bool filterable: false\n property bool layoutSettled: false\n property bool neighborImagesEnabled: false\n property int renderedFrames: 0\n property bool requestActive: false\n property int requestSerial: 0\n property int applySerial: 0\n property string doneFile: \"\"\n property string filterText: \"\"\n property var doneFilesToRelease: []\n // Themes open from rows the shell already holds, so the picker shows without\n // waiting on omarchy-theme-switcher; each open refreshes them behind it.\n property string themeRows: \"\"\n property bool themeMode: false\n property bool themeOpenPending: false\n property var extraThemeNames: []\n property var stockThemeNames: []\n property bool stockThemesKnown: false\n property bool awaitingDeleteRefresh: false\n property string pendingDeleteTheme: \"\"\n property string deleteSelectionPath: \"\"\n property bool deleteConfirmOpen: false\n // Bound to the central [image-picker] section in shell.toml via Commons.Color.qml.\n // `dimColor` tints unselected slices and text outlines against the desktop\n // behind the picker; it intentionally tracks the foundational background,\n // not a surface role.\n property color dimColor: Commons.Color.background\n property color foreground: Commons.Color.imagePicker.text\n property color selectedBorder: Commons.Color.imagePicker.selectedBorder\n property color unselectedBorder: Commons.Color.imagePicker.unselectedBorder\n property int expandedWidth: 768\n property int expandedHeight: 475\n property int sliceWidth: 108\n property int sliceHeight: 432\n property int sliceSpacing: -30\n property int skewOffset: 28\n property int bottomChromeHeight: showLabels ? (filterable ? 104 : 74) : (filterable ? 60 : 30)\n // Render only what fits on this display, plus one prefetch slice per side.\n readonly property int previewRadius: Math.max(1, Math.min(16, Math.ceil((panel.width - expandedWidth) / (2 * (sliceWidth + sliceSpacing))) + 1))\n onPreviewRadiusChanged: updateVisibleItems()\n\n onOpenedChanged: if (!opened) { layoutSettled = false; renderedFrames = 0; deleteConfirmOpen = false; pendingDeleteTheme = \"\"; deleteSelectionPath = \"\"; awaitingDeleteRefresh = false }\n\n function scriptPath(name) {\n return omarchyPath + \"/shell/plugins/image-picker/\" + name\n }\n\n function focusPicker() {\n if (root.opened && root.imagesLoaded && root.layoutSettled)\n carousel.forceActiveFocus()\n }\n\n function revealWhenSettled(serial) {\n Qt.callLater(function() {\n if (serial === root.requestSerial) root.maybeReveal()\n })\n }\n\n // The card renders at opacity 0 until every visible preview has decoded\n // and its masked layers have presented, so the picker lands in one\n // complete frame instead of flashing its images in as each asynchronous\n // decode and layer upload finishes.\n function allPreviewsSettled() {\n if (!opened || !imagesLoaded || layoutSettled || imageArray.length === 0 || imageCards.count === 0) return false\n for (var i = 0; i < imageCards.count; i++) {\n var item = imageCards.itemAt(i)\n if (!item || !item.previewSettled) return false\n }\n return true\n }\n\n function settleReveal() {\n if (!opened || !imagesLoaded || layoutSettled || imageArray.length === 0) return\n layoutSettled = true\n focusPicker()\n }\n\n function maybeReveal() {\n if (!allPreviewsSettled() || renderedFrames < 2) return\n // Confirm on the next tick: delegates inserted later in the same window\n // sync must not pop in after an early all-ready reading.\n Qt.callLater(function() {\n if (root.allPreviewsSettled() && root.renderedFrames >= 2) root.settleReveal()\n })\n }\n\n function currentPath() {\n if (imageArray.length === 0 || !itemMatches(selectedIndex)) return \"\"\n return imageArray[selectedIndex].filePath\n }\n\n function nameForPath(path) {\n return ImagePickerModel.nameForPath(path)\n }\n\n function labelForPath(path) {\n return ImagePickerModel.labelForPath(path)\n }\n\n function currentLabel() {\n var path = currentPath()\n if (!path) return filterText ? \"No matches\" : \"\"\n\n return labelForPath(path)\n }\n\n function itemMatches(index) {\n return ImagePickerModel.itemMatches(imageArray, index, filterText)\n }\n\n function firstMatchingIndex() {\n return ImagePickerModel.firstMatchingIndex(imageArray, filterText)\n }\n\n function select(index, immediate) {\n if (imageArray.length === 0) return\n if (index < 0) index = 0\n else if (index >= imageArray.length) index = imageArray.length - 1\n if (!itemMatches(index)) return\n if (index === selectedIndex && immediate !== true) return\n\n selectedIndex = index\n }\n\n function selectAdjacent(direction) {\n var count = imageArray.length\n if (count === 0) return\n\n var index = selectedIndex\n for (var i = 0; i < count; i++) {\n index = (index + direction + count) % count\n if (itemMatches(index)) {\n select(index)\n return\n }\n }\n }\n\n function updateFilter(nextFilterText) {\n filterText = nextFilterText\n\n if (!itemMatches(selectedIndex)) {\n var first = ImagePickerModel.nextSelectedIndexForFilter(imageArray, selectedIndex, filterText)\n if (first >= 0) selectedIndex = first\n }\n }\n\n function releaseNextDoneFile() {\n if (releaseProc.running || doneFilesToRelease.length === 0) return\n\n var path = doneFilesToRelease.shift()\n releaseProc.command = [\"bash\", \"-c\", \": > \" + Util.shellQuote(path)]\n releaseProc.running = true\n }\n\n function finishDoneFile(path) {\n if (!path) return\n doneFilesToRelease.push(path)\n releaseNextDoneFile()\n }\n\n function applySelected() {\n if (themeMode && (deleteThemeProc.running || awaitingDeleteRefresh)) return\n var path = currentPath()\n\n if (themeMode) {\n themeMode = false\n root.opened = false\n if (path) Util.execArgv([\"omarchy-theme-set\", nameForPath(path)])\n return\n }\n\n if (!path || !selectionFile) {\n cancel()\n return\n }\n\n var activeSelectionFile = selectionFile\n var activeDoneFile = doneFile\n applySerial = requestSerial\n requestActive = false\n selectionFile = \"\"\n doneFile = \"\"\n\n applyProc.command = [\"bash\", \"-c\", \"printf '%s\\\\n' \" + Util.shellQuote(path) + \" > \" + Util.shellQuote(activeSelectionFile) + \"; : > \" + Util.shellQuote(activeDoneFile)]\n applyProc.running = true\n }\n\n function cancel() {\n themeOpenPending = false\n\n if (requestActive)\n finishDoneFile(doneFile)\n\n requestActive = false\n selectionFile = \"\"\n doneFile = \"\"\n root.opened = false\n }\n\n function closeSelector(nextDoneFile) {\n requestSerial += 1\n themeOpenPending = false\n\n if (requestActive)\n finishDoneFile(doneFile)\n\n if (nextDoneFile && nextDoneFile !== doneFile)\n finishDoneFile(nextDoneFile)\n\n requestActive = false\n selectionFile = \"\"\n doneFile = \"\"\n filterText = \"\"\n root.opened = false\n }\n\n function loadRows(rows, reveal) {\n var newImages = ImagePickerModel.loadRows(rows)\n\n root.loadedImageRows = rows\n var nextIndex = root.indexForSelectedImage(newImages)\n root.selectedIndex = ImagePickerModel.nextSelectedIndexForFilter(newImages, nextIndex, root.filterText)\n root.neighborImagesEnabled = false\n root.imageArray = newImages\n root.imagesLoaded = true\n Qt.callLater(root.enableNeighborsWhenReady)\n\n if (reveal !== false) {\n root.opened = true\n root.revealWhenSettled(root.requestSerial)\n }\n }\n\n function openSelector(nextImageDirs, nextImageRows, nextSelectedImage, nextSelectionFile, nextDoneFile, nextShowLabels, nextFilterable) {\n deleteConfirmOpen = false\n pendingDeleteTheme = \"\"\n deleteSelectionPath = \"\"\n awaitingDeleteRefresh = false\n if (requestActive && doneFile && doneFile !== nextDoneFile)\n finishDoneFile(doneFile)\n\n requestSerial += 1\n themeMode = false\n themeOpenPending = false\n\n imageDirs = nextImageDirs\n imageRows = nextImageRows\n selectedImage = nextSelectedImage\n selectionFile = nextSelectionFile\n doneFile = nextDoneFile\n requestActive = !!doneFile\n showLabels = nextShowLabels === true || nextShowLabels === \"true\"\n filterable = nextFilterable === true || nextFilterable === \"true\"\n filterText = \"\"\n layoutSettled = false\n\n if (imageRows && imageRows === loadedImageRows && imageArray.length > 0) {\n root.select(root.selectedImageIndex(), true)\n imagesLoaded = true\n opened = true\n root.revealWhenSettled(requestSerial)\n return\n }\n\n if (imageRows) {\n var rowsToLoad = imageRows\n var rowsSerial = requestSerial\n imageArray = []\n selectedIndex = 0\n imagesLoaded = true\n opened = true\n Qt.callLater(function() {\n if (rowsSerial === root.requestSerial)\n root.loadRows(rowsToLoad, true)\n })\n return\n }\n\n imageArray = []\n selectedIndex = 0\n imagesLoaded = false\n opened = false\n startImageScan(requestSerial, imageDirs)\n }\n\n property var imageArray: []\n readonly property var matchingImageIndices: ImagePickerModel.matchingIndices(imageArray, filterText)\n onMatchingImageIndicesChanged: updateVisibleItems()\n onSelectedIndexChanged: {\n updateVisibleItems()\n introPrepareTimer.restart()\n }\n onThemeModeChanged: if (themeMode) introPrepareTimer.restart()\n\n Timer {\n id: introPrepareTimer\n interval: 75\n onTriggered: {\n if (root.opened && root.themeMode && !introPrepare.running) {\n introPrepare.theme = root.nameForPath(root.currentPath())\n introPrepare.command = [\"omarchy-theme-bg-boot-intro\", \"--prepare-theme\", root.nameForPath(root.currentPath())]\n introPrepare.running = true\n }\n }\n }\n\n Process {\n id: introPrepare\n property string theme: \"\"\n onExited: if (root.opened && root.themeMode && theme !== root.nameForPath(root.currentPath())) introPrepareTimer.restart()\n }\n\n function updateVisibleItems() {\n ImagePickerModel.syncWindow(visibleImages, ImagePickerModel.visibleWindow(matchingImageIndices, selectedIndex, previewRadius))\n }\n\n function enableNeighborsWhenReady() {\n for (var i = 0; i < imageCards.count; i++) {\n var item = imageCards.itemAt(i)\n if (item && item.selected && item.previewReady) neighborImagesEnabled = true\n }\n }\n\n ListModel { id: visibleImages }\n\n\n function currentThemePreview() {\n var name = String(themeNameFile.text() || \"\").trim()\n var images = ImagePickerModel.loadRows(themeRows)\n for (var i = 0; i < images.length; i++) {\n if (nameForPath(images[i].filePath) === name) return images[i].filePath\n }\n return \"\"\n }\n\n function openThemes() {\n if (themeRows) {\n openThemeRows()\n } else {\n // First open before the startup refresh has landed.\n themeOpenPending = true\n }\n refreshThemeRows()\n refreshExtraThemes()\n refreshStockThemes()\n }\n\n function openThemeRows() {\n openSelector(\"\", themeRows, currentThemePreview(), \"\", \"\", true, true)\n themeMode = true\n }\n\n // A refresh asked mid-refresh (a deletion finishing behind the open-time\n // one) queues a second pass instead of leaving the list stale.\n function refreshThemeRows() {\n if (themeRowsProc.running) { themeRowsProc.queued = true; return }\n themeRowsProc.running = true\n }\n\n function refreshExtraThemes() {\n if (extraThemesProc.running) { extraThemesProc.queued = true; return }\n extraThemesProc.running = true\n }\n\n function refreshStockThemes() {\n if (!stockThemesProc.running) stockThemesProc.running = true\n }\n\n function selectedThemeName() {\n return nameForPath(currentPath())\n }\n\n function canDeleteSelectedTheme() {\n return themeMode && !deleteThemeProc.running && !awaitingDeleteRefresh && stockThemesKnown && ImagePickerModel.canDeleteTheme(selectedThemeName(), extraThemeNames, stockThemeNames)\n }\n\n function requestDeleteSelectedTheme() {\n if (!canDeleteSelectedTheme()) return\n pendingDeleteTheme = selectedThemeName()\n deleteConfirm.selectedIndex = 1\n deleteConfirmOpen = true\n }\n\n function cancelDeleteTheme() {\n deleteConfirmOpen = false\n pendingDeleteTheme = \"\"\n }\n\n // Removal itself is omarchy-theme-remove's job (including its guards and\n // notification); the picker only refreshes its rows once it finishes.\n function confirmDeleteTheme() {\n var name = pendingDeleteTheme\n deleteConfirmOpen = false\n pendingDeleteTheme = \"\"\n if (!name || deleteThemeProc.running) return\n // Keep the user's place in the list once the deleted theme is gone.\n if (name === selectedThemeName()) deleteSelectionPath = ImagePickerModel.replacementSelectionPath(imageArray, selectedIndex, filterText)\n deleteThemeProc.command = [\"omarchy-theme-remove\", name]\n deleteThemeProc.running = true\n }\n\n function updateThemeRows(rows) {\n var changed = rows !== themeRows\n themeRows = rows\n\n if (themeOpenPending) {\n themeOpenPending = false\n if (rows) openThemeRows()\n } else if (changed && rows && themeMode && opened) {\n // A theme was added or removed since the rows were last read. Keep the\n // user's place in the carousel rather than jumping back to the current;\n // a just-deleted selection lands on the theme before it.\n selectedImage = deleteSelectionPath || currentPath() || currentThemePreview()\n deleteSelectionPath = \"\"\n awaitingDeleteRefresh = false\n imageRows = rows\n loadRows(rows, false)\n }\n }\n\n FileView {\n id: themeNameFile\n path: root.stateHome + \"/omarchy/current/theme.name\"\n watchChanges: true\n onFileChanged: reload()\n }\n\n Process {\n id: themeRowsProc\n property bool queued: false\n command: [root.omarchyPath + \"/bin/omarchy-theme-switcher\", \"--print-rows\"]\n stdout: StdioCollector {\n onStreamFinished: root.updateThemeRows(String(text || \"\").trim())\n }\n onExited: {\n if (queued) {\n queued = false\n running = true\n }\n }\n }\n\n // The same listing omarchy-theme-remove offers interactively: real\n // directories under the user themes path, never symlinked working copies.\n Process {\n id: extraThemesProc\n property bool queued: false\n command: [\"find\", root.userThemesPath, \"-mindepth\", \"1\", \"-maxdepth\", \"1\", \"-type\", \"d\", \"!\", \"-xtype\", \"l\", \"-printf\", \"%f\\n\"]\n stdout: StdioCollector {\n onStreamFinished: root.extraThemeNames = ImagePickerModel.parseThemeNames(String(text || \"\"))\n }\n onExited: {\n if (queued) {\n queued = false\n running = true\n }\n }\n }\n\n Process {\n id: stockThemesProc\n command: [\"find\", root.omarchyPath + \"/themes\", \"-mindepth\", \"1\", \"-maxdepth\", \"1\", \"-type\", \"d\", \"-printf\", \"%f\\n\"]\n stdout: StdioCollector {\n onStreamFinished: root.stockThemeNames = ImagePickerModel.parseThemeNames(String(text || \"\"))\n }\n // Until this lands, stockThemeNames is empty and an override would look\n // deletable: deletion stays disabled unless the listing succeeded.\n onExited: function(exitCode) { if (exitCode === 0) root.stockThemesKnown = true }\n }\n\n Process {\n id: deleteThemeProc\n onExited: function(exitCode) {\n if (exitCode === 0) root.awaitingDeleteRefresh = true\n else root.deleteSelectionPath = \"\"\n root.refreshExtraThemes()\n root.refreshThemeRows()\n }\n }\n\n Component.onCompleted: {\n refreshThemeRows()\n refreshExtraThemes()\n refreshStockThemes()\n }\n\n function startImageScan(serial, dirs) {\n if (loadImagesProc.running) {\n loadImagesProc.queuedSerial = serial\n loadImagesProc.queuedDirs = dirs\n return\n }\n\n loadImagesProc.activeSerial = serial\n loadImagesProc.queuedSerial = 0\n loadImagesProc.queuedDirs = \"\"\n loadImagesProc.command = [root.scriptPath(\"list.sh\"), dirs]\n loadImagesProc.running = true\n }\n\n function indexForSelectedImage(images) {\n return ImagePickerModel.indexForSelectedImage(images, selectedImage)\n }\n\n function selectedImageIndex() {\n return indexForSelectedImage(imageArray)\n }\n\n Process {\n id: loadImagesProc\n property int activeSerial: 0\n property int queuedSerial: 0\n property string queuedDirs: \"\"\n stdout: StdioCollector {\n waitForEnd: true\n onStreamFinished: {\n if (loadImagesProc.activeSerial === root.requestSerial)\n root.loadRows(String(text || \"\"), true)\n }\n }\n onExited: {\n var serial = queuedSerial\n var dirs = queuedDirs\n activeSerial = 0\n queuedSerial = 0\n queuedDirs = \"\"\n if (serial > 0 && serial === root.requestSerial)\n root.startImageScan(serial, dirs)\n }\n }\n\n // Lifecycle hooks invoked by omarchy-shell summon/hide. shell.summon(id,\n // payloadJson) hands the JSON to open() here; shell.hide(id) calls close().\n // The shell host owns the stable `image-selector` IPC target and forwards\n // those lower-level positional calls here.\n function open(payload) {\n var args = {}\n if (payload) {\n try { args = JSON.parse(payload) || {} } catch (e) { args = {} }\n }\n if (args.source === \"themes\") {\n openThemes()\n return\n }\n var dirs = String(args.imageDirs || imageDirs)\n var rows = String(args.imageRows || \"\")\n var sel = String(args.selectedImage || selectedImage)\n var selFile = String(args.selectionFile || \"\")\n var doneF = String(args.doneFile || \"\")\n var labels = args.showLabels === true || args.showLabels === \"true\"\n var filter = args.filterable === true || args.filterable === \"true\"\n openSelector(dirs, rows, sel, selFile, doneF, labels, filter)\n }\n\n function close() {\n cancel()\n }\n\n function preloadRows(nextImageRows, nextSelectedImage, nextShowLabels, nextFilterable) {\n // Theme/background set hooks can warm selector rows after a picker was\n // dismissed. Ignore those preloads while a user-visible request is open;\n // otherwise the preload resets layoutSettled without revealing again,\n // leaving the picker invisible behind its own open overlay.\n if (opened || requestActive) return\n\n requestSerial += 1\n imageRows = nextImageRows\n selectedImage = nextSelectedImage\n showLabels = nextShowLabels === true || nextShowLabels === \"true\"\n filterable = nextFilterable === true || nextFilterable === \"true\"\n filterText = \"\"\n layoutSettled = false\n\n if (imageRows && imageRows === loadedImageRows && imageArray.length > 0) {\n selectedIndex = selectedImageIndex()\n imagesLoaded = true\n } else if (imageRows) {\n loadRows(imageRows, false)\n }\n }\n\n Process {\n id: applyProc\n onExited: {\n if (root.applySerial === root.requestSerial)\n root.opened = false\n }\n }\n\n Process {\n id: releaseProc\n onExited: root.releaseNextDoneFile()\n }\n\n OverlayWindow {\n id: panel\n shown: root.opened\n shownKeyboardFocus: root.imagesLoaded ? WlrKeyboardFocus.Exclusive : WlrKeyboardFocus.None\n WlrLayershell.namespace: \"omarchy-image-selector\"\n\n MouseArea {\n anchors.fill: parent\n enabled: root.opened && root.imagesLoaded\n onClicked: root.cancel()\n }\n\n // Count presented frames while the card pre-renders below; two frames\n // prove its masked layers uploaded on this fresh surface.\n FrameAnimation {\n running: root.opened && !root.layoutSettled && root.renderedFrames < 2\n onTriggered: {\n root.renderedFrames += 1\n root.maybeReveal()\n }\n }\n\n // A preview stuck decoding (slow disk, huge original) must not hold an\n // invisible picker with the keyboard grabbed: reveal anyway shortly.\n Timer {\n interval: 400\n running: root.opened && root.imagesLoaded && !root.layoutSettled && root.imageArray.length > 0\n onTriggered: root.settleReveal()\n }\n\n Item {\n id: card\n visible: root.opened && root.imagesLoaded && root.imageArray.length > 0\n opacity: root.layoutSettled ? 1 : 0\n width: Math.min(parent.width - 80, root.expandedWidth + 13 * (root.sliceWidth + root.sliceSpacing) + 40)\n height: root.expandedHeight + Style.space(30) + root.bottomChromeHeight\n anchors.centerIn: parent\n\n MouseArea { anchors.fill: parent; enabled: root.layoutSettled; onClicked: {} }\n\n Item {\n id: carousel\n anchors.top: parent.top\n anchors.topMargin: Style.space(30)\n anchors.bottom: parent.bottom\n anchors.bottomMargin: root.bottomChromeHeight\n anchors.horizontalCenter: parent.horizontalCenter\n width: root.expandedWidth + 13 * (root.sliceWidth + root.sliceSpacing)\n clip: false\n focus: true\n\n readonly property real itemStep: root.sliceWidth + root.sliceSpacing\n readonly property real previewX: (width - root.expandedWidth) / 2\n\n Keys.priority: Keys.BeforeItem\n Keys.onPressed: function(event) {\n if (root.deleteConfirmOpen) {\n if (deleteConfirm.handleKey(event)) event.accepted = true\n return\n }\n // Nothing is visible before the reveal: only let the user back\n // out, never filter into a dead end or apply an unseen pick.\n if (!root.layoutSettled) {\n if (event.key === Qt.Key_Escape) {\n root.cancel()\n event.accepted = true\n }\n return\n }\n if (event.key === Qt.Key_Escape) {\n if (root.filterText) {\n root.updateFilter(\"\")\n } else {\n root.cancel()\n }\n event.accepted = true\n } else if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter) {\n root.applySelected()\n event.accepted = true\n } else if (event.key === Qt.Key_Delete && !(event.modifiers & (Qt.ControlModifier | Qt.AltModifier | Qt.MetaModifier))) {\n root.requestDeleteSelectedTheme()\n event.accepted = true\n } else if (root.filterable && Util.editsFilter(event, root.filterText)) {\n root.updateFilter(Util.editedFilter(event, root.filterText))\n event.accepted = true\n } else if (event.key === Qt.Key_Left || (event.key === Qt.Key_Tab && event.modifiers & Qt.ShiftModifier) || event.key === Qt.Key_Backtab) {\n root.selectAdjacent(-1)\n event.accepted = true\n } else if (event.key === Qt.Key_Right || event.key === Qt.Key_Tab) {\n root.selectAdjacent(1)\n event.accepted = true\n } else if (root.filterable && event.text && event.text.length === 1 && event.text.charCodeAt(0) >= 32 && event.text.charCodeAt(0) !== 127 && (event.modifiers === Qt.NoModifier || event.modifiers === Qt.ShiftModifier)) {\n root.updateFilter(root.filterText + event.text)\n event.accepted = true\n }\n }\n\n Component.onCompleted: forceActiveFocus()\n\n Repeater {\n id: imageCards\n model: visibleImages\n onCountChanged: root.maybeReveal()\n\n delegate: Item {\n id: item\n required property int imageIndex\n required property int relativeIndex\n\n readonly property var imageData: root.imageArray[imageIndex]\n readonly property string filePath: imageData ? imageData.filePath : \"\"\n readonly property string fileName: imageData ? imageData.fileName : \"\"\n readonly property string thumbnailPath: imageData ? imageData.thumbnailPath : \"\"\n\n readonly property bool selected: imageIndex === root.selectedIndex\n readonly property bool previewReady: image.status === Image.Ready || image.status === Image.Error\n readonly property bool previewSettled: !thumbnailPath || previewReady\n onPreviewSettledChanged: if (previewSettled) root.maybeReveal()\n onSelectedChanged: if (selected && previewReady) root.neighborImagesEnabled = true\n\n x: selected ? carousel.previewX : (relativeIndex < 0 ? carousel.previewX + relativeIndex * carousel.itemStep : carousel.previewX + root.expandedWidth + root.sliceSpacing + (relativeIndex - 1) * carousel.itemStep)\n width: selected ? root.expandedWidth : root.sliceWidth\n height: selected ? root.expandedHeight : root.sliceHeight\n y: selected ? 0 : (root.expandedHeight - root.sliceHeight) / 2\n z: selected ? 100 : 50 - Math.min(Math.abs(relativeIndex), 40)\n\n readonly property real skAbs: Math.abs(root.skewOffset)\n readonly property real topLeft: root.skewOffset >= 0 ? skAbs : 0\n readonly property real topRight: root.skewOffset >= 0 ? width : width - skAbs\n readonly property real bottomRight: root.skewOffset >= 0 ? width - skAbs : width\n readonly property real bottomLeft: root.skewOffset >= 0 ? 0 : skAbs\n\n Item {\n id: maskShape\n anchors.fill: parent\n visible: false\n layer.enabled: true\n\n Shape {\n anchors.fill: parent\n antialiasing: true\n preferredRendererType: Shape.CurveRenderer\n ShapePath {\n fillColor: \"white\"\n strokeColor: \"transparent\"\n startX: item.topLeft; startY: 0\n PathLine { x: item.topRight; y: 0 }\n PathLine { x: item.bottomRight; y: item.height }\n PathLine { x: item.bottomLeft; y: item.height }\n PathLine { x: item.topLeft; y: 0 }\n }\n }\n }\n\n Item {\n anchors.fill: parent\n layer.enabled: true\n layer.smooth: true\n layer.effect: MultiEffect {\n maskEnabled: true\n maskSource: maskShape\n maskThresholdMin: 0.3\n maskSpreadAtMin: 0.3\n }\n\n Rectangle { anchors.fill: parent; color: root.dimColor }\n\n Image {\n id: image\n anchors.fill: parent\n // Decode at the expanded card's physical size, off the GUI\n // thread. Keep that size during navigation to avoid reloads.\n // Departing cards release their images instead of retaining\n // every preview visited in a large collection.\n // Queue the selected preview first; neighbors must not delay\n // the image the user opened the picker to see.\n source: (item.selected || root.neighborImagesEnabled) && item.thumbnailPath ? Util.fileUrl(item.thumbnailPath) : \"\"\n sourceSize.width: Math.ceil(root.expandedWidth * Screen.devicePixelRatio)\n sourceSize.height: Math.ceil(root.expandedHeight * Screen.devicePixelRatio)\n fillMode: Image.PreserveAspectCrop\n asynchronous: true\n cache: false\n smooth: true\n opacity: status === Image.Ready ? 1 : 0\n onStatusChanged: if (item.selected && (status === Image.Ready || status === Image.Error)) root.neighborImagesEnabled = true\n }\n\n Rectangle {\n anchors.fill: parent\n color: Util.alpha(root.dimColor, item.selected ? 0 : 0.42)\n }\n }\n\n Shape {\n anchors.fill: parent\n antialiasing: true\n preferredRendererType: Shape.CurveRenderer\n ShapePath {\n fillColor: \"transparent\"\n strokeColor: item.selected ? root.selectedBorder : root.unselectedBorder\n strokeWidth: item.selected ? 3 : 1\n startX: item.topLeft; startY: 0\n PathLine { x: item.topRight; y: 0 }\n PathLine { x: item.bottomRight; y: item.height }\n PathLine { x: item.bottomLeft; y: item.height }\n PathLine { x: item.topLeft; y: 0 }\n }\n }\n\n MouseArea {\n anchors.fill: parent\n enabled: root.layoutSettled\n cursorShape: Qt.PointingHandCursor\n onClicked: item.selected ? root.applySelected() : root.select(item.imageIndex)\n }\n }\n }\n }\n\n Text {\n id: selectedLabel\n textFormat: Text.PlainText\n visible: root.showLabels\n anchors.top: carousel.bottom\n anchors.topMargin: Style.space(16)\n anchors.horizontalCenter: carousel.horizontalCenter\n width: root.expandedWidth\n text: root.currentLabel()\n color: root.foreground\n style: Text.Outline\n styleColor: Util.alpha(root.dimColor, 0.7)\n font.pixelSize: Style.font.display\n font.weight: Font.DemiBold\n horizontalAlignment: Text.AlignHCenter\n elide: Text.ElideRight\n }\n\n Text {\n textFormat: Text.PlainText\n visible: root.filterable && root.filterText\n anchors.top: selectedLabel.bottom\n anchors.topMargin: Style.space(8)\n anchors.horizontalCenter: carousel.horizontalCenter\n width: root.expandedWidth\n text: root.filterText\n color: root.foreground\n opacity: 0.85\n style: Text.Outline\n styleColor: Util.alpha(root.dimColor, 0.7)\n font.pixelSize: Style.font.title\n horizontalAlignment: Text.AlignHCenter\n elide: Text.ElideRight\n }\n }\n\n // Unlike the picker itself, the confirmation keeps the faded backdrop:\n // a destructive choice should take over the screen.\n ConfirmDialog {\n id: deleteConfirm\n anchors.fill: parent\n opened: root.deleteConfirmOpen\n z: 10\n message: \"Do you want to delete \" + (root.pendingDeleteTheme ? root.labelForPath(root.pendingDeleteTheme) : \"\") + \"?\"\n confirmText: \"Delete\"\n background: root.dimColor\n foreground: root.foreground\n onCanceled: root.cancelDeleteTheme()\n onConfirmed: root.confirmDeleteTheme()\n }\n }\n}\n```\n\n### ImagePickerModel.js\n```javascript\nfunction nameForPath(path) {\n return String(path || \"\").split(\"/\").pop().replace(/\\.[^/.]+$/, \"\")\n}\n\nfunction labelForPath(path) {\n return nameForPath(path).replace(/[-_]+/g, \" \").replace(/\\b\\w/g, function(match) { return match.toUpperCase() })\n}\n\n// Extra (user-installed) theme names, one per line, as listed from the user\n// themes directory: the set omarchy-theme-remove can delete.\nfunction parseThemeNames(text) {\n var names = []\n var lines = String(text || \"\").split(\"\\n\")\n for (var i = 0; i < lines.length; i++) {\n var name = lines[i].trim()\n if (name) names.push(name)\n }\n return names\n}\n\n// A user directory shadowing a stock theme holds customizations, not an\n// extra theme: removing it from here would silently revert to stock (and a\n// shadow can even list twice, once per preview extension), so only themes\n// with no stock twin can be deleted from the picker.\nfunction canDeleteTheme(name, extraNames, stockNames) {\n if (!name || !Array.isArray(extraNames) || extraNames.indexOf(name) === -1) return false\n return !Array.isArray(stockNames) || stockNames.indexOf(name) === -1\n}\n\n// Where selection lands when the selected image goes away: the previous\n// match in list order, or the next one when the first match is deleted.\nfunction replacementSelectionPath(images, selectedIndex, filterText) {\n var values = Array.isArray(images) ? images : []\n if (selectedIndex < 0 || selectedIndex >= values.length) return \"\"\n for (var i = selectedIndex - 1; i >= 0; i--) {\n if (itemMatches(values, i, filterText)) return values[i].filePath\n }\n for (var i = selectedIndex + 1; i < values.length; i++) {\n if (itemMatches(values, i, filterText)) return values[i].filePath\n }\n return \"\"\n}\n\nfunction loadRows(rows) {\n var images = []\n var seen = {}\n var paths = String(rows || \"\").split(\"\\n\")\n\n for (var i = 0; i < paths.length; i++) {\n var row = paths[i]\n if (!row) continue\n\n var columns = row.split(\"\\t\")\n var path = columns[0]\n if (!path) continue\n\n var fileName = path.split(\"/\").pop()\n if (seen[fileName]) continue\n seen[fileName] = true\n\n images.push({\n filePath: path,\n fileName: fileName,\n thumbnailPath: columns[1] || path\n })\n }\n\n return images\n}\n\nfunction itemMatches(images, index, filterText) {\n if (!Array.isArray(images) || index < 0 || index >= images.length) return false\n var needle = String(filterText || \"\").toLowerCase()\n if (!needle) return true\n\n var path = String(images[index].filePath || \"\")\n return nameForPath(path).toLowerCase().indexOf(needle) !== -1\n || labelForPath(path).toLowerCase().indexOf(needle) !== -1\n}\n\nfunction firstMatchingIndex(images, filterText) {\n var values = Array.isArray(images) ? images : []\n for (var i = 0; i < values.length; i++) {\n if (itemMatches(values, i, filterText)) return i\n }\n\n return -1\n}\n\nfunction filteredPosition(images, index, filterText) {\n if (!filterText) return index\n\n var position = 0\n for (var i = 0; i < index; i++) {\n if (itemMatches(images, i, filterText)) position++\n }\n\n return position\n}\n\nfunction selectedFilteredPosition(images, selectedIndex, filterText) {\n if (!filterText) return selectedIndex\n return itemMatches(images, selectedIndex, filterText) ? filteredPosition(images, selectedIndex, filterText) : 0\n}\n\nfunction indexForSelectedImage(images, selectedImage) {\n var values = Array.isArray(images) ? images : []\n for (var i = 0; i < values.length; i++) {\n if (values[i].filePath === selectedImage) return i\n }\n\n return 0\n}\n\nfunction nextSelectedIndexForFilter(images, selectedIndex, filterText) {\n if (itemMatches(images, selectedIndex, filterText)) return selectedIndex\n return firstMatchingIndex(images, filterText)\n}\n\nfunction matchingIndices(images, filterText) {\n var indices = []\n for (var i = 0; i < images.length; i++) {\n if (itemMatches(images, i, filterText)) indices.push(i)\n }\n return indices\n}\n\n// Keep the rendered carousel independent of the size of the collection.\nfunction visibleWindow(indices, selectedIndex, radius) {\n var position = indices.indexOf(selectedIndex)\n if (position < 0) position = 0\n var items = []\n for (var i = Math.max(0, position - radius); i < Math.min(indices.length, position + radius + 1); i++) {\n items.push({ imageIndex: indices[i], relativeIndex: i - position })\n }\n return items\n}\n\n// Preserve overlapping delegates as selection moves, including their decoded\n// images. Replacing the entire model on every keypress makes previews flicker.\nfunction syncWindow(model, items) {\n var wanted = {}\n for (var i = 0; i < items.length; i++) wanted[items[i].imageIndex] = true\n for (var i = model.count - 1; i >= 0; i--) {\n if (!wanted[model.get(i).imageIndex]) model.remove(i)\n }\n for (var i = 0; i < items.length; i++) {\n var existing = i\n while (existing < model.count && model.get(existing).imageIndex !== items[i].imageIndex) existing++\n if (existing === model.count) {\n model.insert(i, items[i])\n } else {\n if (existing !== i) model.move(existing, i, 1)\n model.setProperty(i, \"relativeIndex\", items[i].relativeIndex)\n }\n }\n}\n\nif (typeof module !== \"undefined\") {\n module.exports = {\n nameForPath: nameForPath,\n labelForPath: labelForPath,\n parseThemeNames: parseThemeNames,\n canDeleteTheme: canDeleteTheme,\n replacementSelectionPath: replacementSelectionPath,\n loadRows: loadRows,\n itemMatches: itemMatches,\n firstMatchingIndex: firstMatchingIndex,\n filteredPosition: filteredPosition,\n selectedFilteredPosition: selectedFilteredPosition,\n indexForSelectedImage: indexForSelectedImage,\n nextSelectedIndexForFilter: nextSelectedIndexForFilter,\n matchingIndices: matchingIndices,\n visibleWindow: visibleWindow,\n syncWindow: syncWindow\n }\n}\n```\n\n### list.sh\n```bash\n#!/bin/bash\n\nimage_dirs=${1:-}\ncache_dir=${XDG_CACHE_HOME:-$HOME/.cache}/omarchy/image-selector\nindex_file=\"$cache_dir/index.tsv\"\npending_video_file=$(mktemp)\n\nmkdir -p \"$cache_dir\"\ntrap 'rm -f \"$pending_video_file\"' EXIT\n\nis_video_path() {\n [[ ${1,,} =~ \\.(mp4|m4v|mov|webm|mkv|avi)$ ]]\n}\n\nthumbnail_path_for() {\n local image=\"$1\"\n local signature hash\n\n signature=$(stat -Lc '%s:%Y' \"$image\") || return\n hash=$(awk -F '\\t' -v path=\"$image\" -v sig=\"$signature\" '$1 == path && $2 == sig { print $3; exit }' \"$index_file\" 2>/dev/null)\n\n if [[ -z $hash ]]; then\n hash=$(printf '%s\\t%s' \"$image\" \"$signature\" | md5sum | cut -d ' ' -f 1)\n fi\n\n printf '%s/%s.jpg' \"$cache_dir\" \"$hash\"\n}\n\ngenerate_video_thumbnail() {\n local image=\"$1\"\n local thumbnail=\"$2\"\n local lock=\"$thumbnail.lock\"\n local lock_fd\n local tmp=\"$thumbnail.$$.jpg\"\n\n if [[ -d $lock ]] && (( $(date +%s) - $(stat -c '%Y' \"$lock\" 2>/dev/null || date +%s) > 120 )); then\n rmdir \"$lock\" 2>/dev/null\n fi\n\n exec {lock_fd}>\"$lock\" || return\n flock -w 30 \"$lock_fd\" || return\n rm -f \"$thumbnail\".*.jpg\n\n [[ -f $thumbnail ]] && return\n\n if timeout -k 5 10 ffmpegthumbnailer -i \"$image\" -o \"$tmp\" -s 1536 -q 8 {lock_fd}>&-; then\n mv -f \"$tmp\" \"$thumbnail\"\n else\n status=$?\n rm -f \"$tmp\" \"$thumbnail\"\n # Remember a rejected video so it costs nothing on the next scan; the key\n # covers size and mtime, so a repaired file starts clean. A timeout is\n # left to retry: the machine may only have been busy.\n (( status == 124 || status == 137 )) || : >\"$thumbnail.failed\"\n return 1\n fi\n}\n\ndrain_pending_video_thumbnails() {\n local video_jobs\n\n [[ -s $pending_video_file ]] || return 0\n\n video_jobs=$(( $(nproc) / 4 ))\n (( video_jobs > 0 )) || video_jobs=1\n export -f generate_video_thumbnail\n xargs -a \"$pending_video_file\" -0 -n 2 -P \"$video_jobs\" \\\n bash -c 'generate_video_thumbnail \"$1\" \"$2\"' _ >/dev/null 2>&1 || true\n}\n\nthumbnail_for() {\n local image=\"$1\"\n local thumbnail legacy_hash\n\n thumbnail=$(thumbnail_path_for \"$image\") || return\n\n if [[ ! -f $thumbnail ]] && ! is_video_path \"$image\"; then\n # Older on-demand picker code keyed fallback thumbnails by file content.\n # Keep finding those if a user still has them cached.\n legacy_hash=$(md5sum \"$image\" 2>/dev/null | cut -d ' ' -f 1)\n [[ -n $legacy_hash && -f $cache_dir/$legacy_hash.jpg ]] && thumbnail=\"$cache_dir/$legacy_hash.jpg\"\n fi\n\n if [[ -f $thumbnail ]]; then\n printf '%s' \"$thumbnail\"\n elif ! is_video_path \"$image\"; then\n printf '%s' \"$image\"\n fi\n}\n\nmapfile -d '' -t images < <(\n while IFS= read -r dir; do\n [[ -n $dir && -d $dir ]] || continue\n find -L \"$dir\" -maxdepth 1 -type f \\\n \\( -iname '*.jpg' -o -iname '*.jpeg' -o -iname '*.png' -o -iname '*.gif' -o -iname '*.bmp' -o -iname '*.webp' \\\n -o -iname '*.mp4' -o -iname '*.m4v' -o -iname '*.mov' -o -iname '*.webm' -o -iname '*.mkv' -o -iname '*.avi' \\) \\\n -print0 2>/dev/null\n done <<<\"$image_dirs\" | sort -z\n)\n\nfor image in \"${images[@]}\"; do\n if is_video_path \"$image\"; then\n thumbnail=$(thumbnail_path_for \"$image\") || continue\n [[ -f $thumbnail || -f $thumbnail.failed ]] || printf '%s\\0%s\\0' \"$image\" \"$thumbnail\" >>\"$pending_video_file\"\n fi\ndone\n\ndrain_pending_video_thumbnails\n\nfor image in \"${images[@]}\"; do\n thumbnail=$(thumbnail_for \"$image\")\n [[ -n $thumbnail ]] || continue\n printf '%s\\t%s\\n' \"$image\" \"$thumbnail\"\ndone\n```"}], "task": "build_from_spec", "meta": {"origin": "first-party", "repo": "https://github.com/basecamp/omarchy", "commit": "9480d1b6a98156314dbabe6bfef08f39f8b9cd07", "license": "MIT", "plugin_path": "shell/plugins/image-picker", "kinds": ["overlay"], "complexity": "large", "group": "1683ed85", "validator": "pass", "qmllint": "clean", "qml_files": 1, "chars": 41869, "tokens": 10155, "split": "train"}} {"messages": [{"role": "system", "content": "You are an Omarchy plugin expert. You write complete, valid Omarchy (Quattro / omarchy-shell, Quickshell QML) plugins. Manifests use schemaVersion 1, a namespaced id that never uses the reserved omarchy.* namespace, name, version, kinds (bar-widget|panel|overlay|menu|service|bar) with a matching safe relative entryPoints path for every kind, and no symlinks. Return every file in full as '### path' followed by a fenced code block."}, {"role": "user", "content": "Write a complete Omarchy plugin `acme.lock` called \"Lock Screen\" (service). Quickshell session lock with separate password and fingerprint PAM flows. (It's a third-party plugin, so don't use the reserved omarchy.* namespace.)"}, {"role": "assistant", "content": "### manifest.json\n```json\n{\n \"schemaVersion\": 1,\n \"id\": \"acme.lock\",\n \"name\": \"Lock Screen\",\n \"version\": \"1.0.0\",\n \"author\": \"Omarchy\",\n \"description\": \"Quickshell session lock with separate password and fingerprint PAM flows.\",\n \"omarchy\": {\n \"capabilities\": [\n \"authentication\"\n ]\n },\n \"kinds\": [\n \"service\"\n ],\n \"keepLoaded\": true,\n \"entryPoints\": {\n \"service\": \"Service.qml\"\n }\n}\n```\n\n### FingerprintModel.js\n```javascript\n// Back off missing prompts and fast device errors; ordinary mismatches\n// and a full scan window without a finger keep the normal swipe interval.\nvar MATCH_RETRY_MS = 250\nvar FAST_ERROR_MS = 2000\nvar NUDGE_COOLDOWN_MS = 2000\nvar IDLE_CLEAR_MS = 32000\nvar ERROR_RETRY_BASE_MS = 1000\n// Leave enough idle time for fprintd to exit and clear a wedged claim.\nvar FPRINTD_IDLE_EXIT_MS = 30000\nvar ERROR_RETRY_CAP_MS = 40000\nvar UNAVAILABLE_AFTER = 3\n// Abort before the D-Bus claim timeout, while allowing slow device opens.\nvar REACH_TIMEOUT_MS = 20000\n// Monotonic timers pause across suspend; a wall-clock gap detects resume.\nvar SLEEP_GAP_MS = 2000\n// Ignore transient misses while the asynchronous resume restart lands.\nvar RESUME_GRACE_MS = 5000\n\nfunction retryDelayMs(streak) {\n if (streak <= 0) return MATCH_RETRY_MS\n var delay = ERROR_RETRY_BASE_MS * Math.pow(2, streak - 1)\n return Math.min(delay, ERROR_RETRY_CAP_MS)\n}\n\n// Preserve the daemon idle window even under continuous user activity.\nfunction shouldNudge(nowMs, lastNudgeMs, lastSettleMs, currentIntervalMs) {\n if (currentIntervalMs <= MATCH_RETRY_MS) return false\n var sinceNudge = nowMs - lastNudgeMs\n var sinceSettle = nowMs - lastSettleMs\n // A backward clock step cannot count as a completed idle window.\n if (sinceNudge >= 0 && sinceNudge < Math.max(NUDGE_COOLDOWN_MS, currentIntervalMs)) return false\n if (sinceSettle < 0) sinceSettle = 0\n if (currentIntervalMs >= ERROR_RETRY_CAP_MS && sinceSettle < IDLE_CLEAR_MS) return false\n return true\n}\n\n\n// A failed probe is unknown, so it cannot disable authentication for the lock.\nfunction classifyProbe(text) {\n var s = String(text || \"\").trim()\n if (/^[ \\t]*-[ \\t]*#[0-9]+:/m.test(s)) return \"yes\"\n if (s === \"no\") return \"no\"\n if (/has no fingers enrolled/i.test(s)) return \"no\"\n return \"unknown\"\n}\n\n// Resume-time misses stay at the first tier while fprintd restarts.\nfunction nextStreak(streak, usableAttempt, inResumeGrace) {\n if (usableAttempt) return 0\n if (inResumeGrace) return 1\n return streak + 1\n}\n\n// Event-loop stalls may also open the grace window; retries remain paced.\nfunction spannedSleep(elapsedMs, expectedMs) {\n return elapsedMs > expectedMs + SLEEP_GAP_MS\n}\n\nfunction inResumeGrace(nowMs, resumedAtMs) {\n if (resumedAtMs <= 0) return false\n var elapsed = nowMs - resumedAtMs\n return elapsed >= 0 && elapsed < RESUME_GRACE_MS\n}\n\n// A few consecutive misses avoid reporting a single claim conflict.\nfunction isUnavailable(streak) {\n return streak >= UNAVAILABLE_AFTER\n}\n\nif (typeof module !== \"undefined\") {\n module.exports = {\n MATCH_RETRY_MS: MATCH_RETRY_MS,\n FAST_ERROR_MS: FAST_ERROR_MS,\n NUDGE_COOLDOWN_MS: NUDGE_COOLDOWN_MS,\n IDLE_CLEAR_MS: IDLE_CLEAR_MS,\n shouldNudge: shouldNudge,\n ERROR_RETRY_BASE_MS: ERROR_RETRY_BASE_MS,\n ERROR_RETRY_CAP_MS: ERROR_RETRY_CAP_MS,\n FPRINTD_IDLE_EXIT_MS: FPRINTD_IDLE_EXIT_MS,\n UNAVAILABLE_AFTER: UNAVAILABLE_AFTER,\n REACH_TIMEOUT_MS: REACH_TIMEOUT_MS,\n SLEEP_GAP_MS: SLEEP_GAP_MS,\n RESUME_GRACE_MS: RESUME_GRACE_MS,\n spannedSleep: spannedSleep,\n classifyProbe: classifyProbe,\n inResumeGrace: inResumeGrace,\n retryDelayMs: retryDelayMs,\n nextStreak: nextStreak,\n isUnavailable: isUnavailable\n }\n}\n```\n\n### LockFeedSurface.qml\n```qml\nimport QtQuick\nimport Owe.LockFeed\n\n// Loaded through a Loader from LockView, so a system without the module shows\n// no lock video instead of losing the whole lock screen.\nLockFeed {\n}\n```\n\n### LockView.qml\n```qml\nimport QtQuick\nimport QtQuick.Effects\nimport qs.Commons\nimport qs.Commons as Commons\nimport qs.Ui\n\nItem {\n id: root\n\n property string backgroundPath: \"\"\n property string videoPosterPath: \"\"\n property int backgroundVersion: 0\n property bool fingerprintConfigured: false\n property bool fingerprintUnavailable: false\n property bool authenticatingPassword: false\n property string failureMessage: \"\"\n property int failedAttempts: 0\n property bool inputEnabled: true\n property bool loadBackground: true\n // A locked session blanks the displays after a few seconds. Nothing is\n // visible from then until the user wakes it, so a video must not keep\n // decoding through what is usually the longest part of a lock.\n property bool displaysBlank: false\n property bool powerSaverActive: false\n property string passwordText: \"\"\n property bool syncingPasswordText: false\n\n readonly property string placeholderText: \"Enter Password\"\n readonly property int fieldWidth: 381\n readonly property int fieldHeight: 67\n readonly property int outlineThickness: 3\n readonly property int fieldFontSize: Math.round(Style.font.heading * 1.125)\n readonly property int passwordDotFontSize: Math.round(Style.font.heading * 1.33)\n readonly property int passwordDotLetterSpacing: Math.round(Style.font.heading * 0.19)\n // Space to keep clear on each side of the field for the fingerprint icon\n // (icon width plus a gap) so the centered dots never run under it.\n readonly property real fingerprintReserve: fingerprintConfigured ? Math.round(fingerprintIcon.implicitWidth + 12) : 0\n // Shrink the dots to fit once the password outgrows the field, so every\n // keystroke stays visible — otherwise long passwords clip with no feedback.\n readonly property real passwordDotScale: dotMetrics.advanceWidth > 0\n ? Math.min(1, (passwordInput.width - 4) / dotMetrics.advanceWidth)\n : 1\n readonly property bool showPasswordCursor: inputEnabled && !authenticatingPassword && failureMessage.length === 0\n readonly property bool errorState: failureMessage.length > 0\n readonly property var inputBorderSpec: errorState\n ? Border.surfaceSpec(\"lock\", \"border-error\", Commons.Color.lock.borderError, root.outlineThickness, \"border-alpha\")\n : Border.surfaceSpec(\"lock\", \"border-active\", Commons.Color.lock.borderActive, root.outlineThickness, \"border-alpha\")\n\n readonly property bool video: Util.isVideoPath(root.backgroundPath)\n readonly property bool feedActive: root.video && root.loadBackground && !root.displaysBlank && !root.powerSaverActive\n\n signal submitPassword(string password)\n signal passwordTextEdited(string password)\n signal clearFailureRequested()\n signal wakeRequested()\n\n function forcePasswordFocus() {\n passwordInput.forceActiveFocus()\n }\n\n function clearPassword() {\n passwordTextEdited(\"\")\n }\n\n // Waking a DPMS-blanked display can stall the compositor for seconds while\n // the monitor modesets, so the wake key's release arrives late and client-side\n // key repeat floods the field with that character. A held key has no business\n // typing a password; only holding Backspace/Delete to clear stays useful.\n function dropsAutoRepeat(key) {\n return key !== Qt.Key_Backspace && key !== Qt.Key_Delete\n }\n\n function syncPasswordText() {\n if (passwordInput.text === passwordText) return\n syncingPasswordText = true\n passwordInput.text = passwordText\n syncingPasswordText = false\n }\n\n onPasswordTextChanged: syncPasswordText()\n onInputEnabledChanged: {\n if (inputEnabled) Qt.callLater(forcePasswordFocus)\n }\n Component.onCompleted: {\n syncPasswordText()\n if (inputEnabled) Qt.callLater(forcePasswordFocus)\n }\n\n // Measures the masked password at full size; passwordDotScale compares this\n // against the field width to decide how far the dots must shrink to fit.\n TextMetrics {\n id: dotMetrics\n font.family: Style.font.family\n font.pixelSize: root.passwordDotFontSize\n font.letterSpacing: root.passwordDotLetterSpacing\n text: \"●\".repeat(passwordInput.text.length)\n }\n\n Rectangle {\n anchors.fill: parent\n color: Commons.Color.background\n\n BackgroundMedia {\n id: wallpaper\n objectName: \"lockWallpaper\"\n anchors.fill: parent\n path: root.loadBackground ? (root.video ? root.videoPosterPath : root.backgroundPath) : \"\"\n version: root.backgroundVersion\n // Decode only once sized, at the lock's own size: an unsized first\n // request decoded the file at its native resolution, then again once\n // sized. That size is what the lock service keeps decoded ahead of the\n // lock, so the first frame has the wallpaper.\n cached: true\n constrainDecode: true\n decodeSize: Qt.size(width, height)\n }\n\n MultiEffect {\n anchors.fill: wallpaper\n source: wallpaper\n autoPaddingEnabled: false\n blurEnabled: root.loadBackground && wallpaper.ready\n blur: 1.0\n blurMax: 128\n blurMultiplier: 1.25\n contrast: -0.08\n }\n\n // The cached poster stays behind the feed when policy pauses playback,\n // the module is unavailable, or a new connection has not received a frame.\n Loader {\n id: feedLoader\n objectName: \"lockFeedLoader\"\n anchors.fill: parent\n active: root.feedActive\n source: \"LockFeedSurface.qml\"\n visible: status === Loader.Ready\n }\n\n // The feed item cannot be sampled by MultiEffect on every renderer.\n // Keep video wallpapers visible and darken them slightly for legibility.\n Rectangle {\n anchors.fill: feedLoader\n visible: root.video\n color: \"#22000000\"\n }\n\n MouseArea {\n anchors.fill: parent\n hoverEnabled: true\n onClicked: { root.wakeRequested(); root.forcePasswordFocus() }\n onPositionChanged: root.wakeRequested()\n }\n\n BorderSurface {\n id: inputField\n width: root.fieldWidth\n height: root.fieldHeight\n anchors.centerIn: parent\n color: Commons.Color.lock.background\n borderSpec: root.inputBorderSpec\n radius: Style.cornerRadius\n clip: true\n\n TextInput {\n id: passwordInput\n anchors.fill: parent\n anchors.topMargin: inputField.borderTop\n // Reserve the fingerprint icon's width on both sides so the centered\n // dots stay symmetric and never slide under the icon as they grow.\n anchors.rightMargin: inputField.borderRight + 18 + root.fingerprintReserve\n anchors.bottomMargin: inputField.borderBottom\n anchors.leftMargin: inputField.borderLeft + 18 + root.fingerprintReserve\n verticalAlignment: TextInput.AlignVCenter\n horizontalAlignment: TextInput.AlignHCenter\n activeFocusOnPress: true\n clip: true\n enabled: root.inputEnabled && !root.authenticatingPassword\n readOnly: root.authenticatingPassword\n echoMode: TextInput.Password\n passwordCharacter: \"\\u25CF\"\n passwordMaskDelay: 0\n color: Commons.Color.lock.text\n selectionColor: Commons.Color.lock.selection\n selectedTextColor: Commons.Color.lock.text\n font.family: Style.font.family\n font.pixelSize: text.length > 0 ? Math.max(1, Math.floor(root.passwordDotFontSize * root.passwordDotScale)) : root.fieldFontSize\n font.letterSpacing: text.length > 0 ? root.passwordDotLetterSpacing * root.passwordDotScale : 0\n cursorVisible: activeFocus && root.showPasswordCursor && text.length > 0\n cursorDelegate: Rectangle {\n width: 2\n color: Commons.Color.lock.text\n visible: passwordInput.cursorVisible\n }\n\n onTextChanged: {\n if (!root.syncingPasswordText) root.passwordTextEdited(text)\n if (text.length > 0) {\n root.wakeRequested()\n }\n if (text.length > 0 && root.failureMessage.length > 0) root.clearFailureRequested()\n }\n\n onAccepted: {\n var submitted = root.passwordText\n root.passwordTextEdited(\"\")\n if (submitted.length > 0) root.submitPassword(submitted)\n }\n\n Keys.onPressed: function(event) {\n root.wakeRequested()\n if (event.isAutoRepeat && root.dropsAutoRepeat(event.key)) {\n event.accepted = true\n return\n }\n if (event.key === Qt.Key_Escape || (event.modifiers & Qt.ControlModifier && event.key === Qt.Key_U)) {\n root.passwordTextEdited(\"\")\n event.accepted = true\n }\n }\n }\n\n Text {\n textFormat: Text.PlainText\n anchors.fill: passwordInput\n text: root.authenticatingPassword ? \"Checking…\" : (root.failureMessage.length > 0 ? root.failureMessage : root.placeholderText)\n visible: passwordInput.text.length === 0\n color: root.authenticatingPassword ? Commons.Color.lock.text : (root.failureMessage.length > 0 ? Commons.Color.lock.textError : Commons.Color.lock.placeholder)\n font.family: Style.font.family\n font.pixelSize: root.fieldFontSize\n font.italic: !root.authenticatingPassword && root.failureMessage.length > 0\n horizontalAlignment: Text.AlignHCenter\n verticalAlignment: Text.AlignVCenter\n elide: Text.ElideRight\n }\n\n // Fingerprint hint pinned inside the field's right edge when a sensor is\n // enrolled, so the user knows they can touch to unlock instead of typing.\n // Matches hyprlock, which draws its fingerprint icon in the same spot.\n // A reader the shell cannot reach crosses out rather than disappears, so\n // it stops inviting touches that can never unlock.\n Text {\n id: fingerprintIcon\n objectName: \"fingerprintIndicator\"\n textFormat: Text.PlainText\n anchors.right: parent.right\n anchors.rightMargin: inputField.borderRight + 18\n anchors.verticalCenter: parent.verticalCenter\n visible: root.fingerprintConfigured\n text: root.fingerprintUnavailable ? \"󰺱\" : \"󰈷\"\n color: root.fingerprintUnavailable ? Commons.Color.lock.textError : Commons.Color.lock.placeholder\n font.family: Style.font.family\n font.pixelSize: Math.round(root.fieldFontSize * 1.1)\n horizontalAlignment: Text.AlignHCenter\n verticalAlignment: Text.AlignVCenter\n }\n }\n\n // The crossed-out icon has no meaning to a user who has never seen it — it\n // is not intuitive that it signals a broken reader — so the words carry the\n // explanation and the icon only reinforces it.\n Text {\n objectName: \"fingerprintUnavailableNotice\"\n textFormat: Text.PlainText\n anchors.top: inputField.bottom\n anchors.topMargin: 18\n anchors.horizontalCenter: inputField.horizontalCenter\n visible: root.fingerprintConfigured && root.fingerprintUnavailable\n text: \"Fingerprint reader unavailable\"\n color: Commons.Color.lock.textError\n font.family: Style.font.family\n font.pixelSize: Style.font.heading\n font.italic: true\n horizontalAlignment: Text.AlignHCenter\n }\n }\n}\n```\n\n### Service.qml\n```qml\nimport QtQuick\nimport Quickshell\nimport Quickshell.Io\nimport Quickshell.Services.Pam\nimport Quickshell.Wayland\nimport qs.Commons\nimport qs.Commons as Commons\nimport \"FingerprintModel.js\" as FingerprintModel\n\nItem {\n id: root\n\n property var shell: null\n property string omarchyPath: \"\"\n\n readonly property string home: Quickshell.env(\"HOME\")\n readonly property string stateHome: home + \"/.local/state\"\n readonly property string userName: Quickshell.env(\"USER\") || Quickshell.env(\"LOGNAME\")\n readonly property string currentBackgroundLink: stateHome + \"/omarchy/current/background\"\n\n property bool lockRequested: false\n property bool pendingSessionLock: false\n property bool authenticatingPassword: false\n property bool fingerprintAuthenticating: false\n property bool passwordPamConfigured: false\n property bool fingerprintConfigured: false\n property int fingerprintUnreachedStreak: 0\n property bool fingerprintAttemptReachedDevice: false\n property bool fingerprintAttemptFastError: false\n property double fingerprintAttemptPromptedAtMs: 0\n property double fingerprintLastNudgeMs: 0\n property double fingerprintLastSettleMs: 0\n property double fingerprintResumedAtMs: 0\n property int fingerprintProbeStreak: 0\n property bool previewVisible: false\n property string enteredPassword: \"\"\n property string pendingPassword: \"\"\n property string failureMessage: \"\"\n property int failedAttempts: 0\n property string backgroundPath: \"\"\n property string videoPosterPath: \"\"\n property int backgroundVersion: 0\n // The wallpaper file's mtime and size. The lock caches its wallpaper by\n // version, so a file overwritten in place must bump the version too.\n property string backgroundSignature: \"\"\n property string lastEvent: \"init\"\n property string lastEventAt: \"\"\n property bool displaysBlank: false\n // displaysBlank tracks what the lock asked for; Hyprland reports what each\n // panel actually did. While a video is on show the two are reconciled, so a\n // blank that failed keeps playing and a panel woken behind the lock's back\n // (a resume that kept the same outputs) resumes instead of freezing.\n property var monitorDpms: ({})\n property bool monitorDpmsKnown: false\n readonly property bool videoBackground: Util.isVideoPath(backgroundPath)\n property bool strandedLock: false\n property bool strandedLockResolved: false\n\n readonly property bool locked: lockRequested || sessionLock.locked || sessionLock.secure\n\n // Decisions read the lock state afresh. A property binding that missed a change\n // notification once reported locked after an unlock, and a lock request before\n // suspend then took that for done and never locked the session.\n function currentlyLocked() {\n return lockRequested || sessionLock.locked || sessionLock.secure\n }\n readonly property bool authenticating: authenticatingPassword || fingerprintAuthenticating\n readonly property var batteryService: shell && shell.services ? shell.firstPartyServiceFor(\"omarchy.battery\") : null\n readonly property bool powerSaverActive: batteryService ? batteryService.powerSaverOnBattery : false\n // A prompt clears the unavailable notice before the attempt finishes.\n readonly property bool fingerprintUnavailable: FingerprintModel.isUnavailable(fingerprintProbeStreak) || (fingerprintConfigured && (!fingerprintAttemptReachedDevice || fingerprintAttemptFastError) && FingerprintModel.isUnavailable(fingerprintUnreachedStreak))\n\n function realScreenCount() {\n var screens = Quickshell.screens || []\n var count = 0\n\n for (var i = 0; i < screens.length; i++) {\n var screen = screens[i]\n if (screen && screen.name && screen.width > 0 && screen.height > 0) count += 1\n }\n\n return count\n }\n\n function hasRealScreen() {\n return realScreenCount() > 0\n }\n\n function queueSessionLock() {\n pendingSessionLock = true\n if (!sessionLockStabilizeTimer.running) logEvent(\"lock-pending: screen-stabilizing\")\n sessionLockStabilizeTimer.restart()\n if (!pendingSessionLockTimer.running) pendingSessionLockTimer.start()\n }\n\n function requestSessionLock() {\n if (!lockRequested || sessionLock.locked || sessionLock.secure) return\n if (sessionLockStabilizeTimer.running) return\n\n if (!hasRealScreen()) {\n if (!pendingSessionLock || lastEvent !== \"lock-pending: no-real-screen\") logEvent(\"lock-pending: no-real-screen\")\n pendingSessionLock = true\n if (!pendingSessionLockTimer.running) pendingSessionLockTimer.start()\n return\n }\n\n pendingSessionLock = false\n pendingSessionLockTimer.stop()\n sessionLock.locked = true\n }\n\n // ext-session-lock outlives its client, and a restart carries no lock over, so\n // a session locked this early may be an orphan behind Hyprland's failsafe. It\n // may also be another shell's live lock, which Hyprland would let this one\n // take over and then strand on exit, so the helper answers undetermined while\n // another locker runs. Outputs are often still absent here, so ask until the\n // answer means something.\n function checkStrandedLock() {\n if (strandedLockResolved || strandedLockCheckProc.running) return\n\n // A lock this shell took is nobody's orphan.\n if (currentlyLocked()) {\n strandedLockResolved = true\n return\n }\n\n strandedLockCheckProc.running = true\n }\n\n function recoverStrandedLock() {\n if (!strandedLock || currentlyLocked() || !passwordPamConfigured) return\n\n strandedLock = false\n logEvent(\"lock-stranded: recovering\")\n beginLock()\n }\n\n function refreshBackground() {\n if (!readlinkProc.running) readlinkProc.running = true\n }\n\n function refreshPoster() {\n if (!root.videoBackground) {\n root.videoPosterPath = \"\"\n return\n }\n if (posterProc.running) return\n posterProc.sourcePath = root.backgroundPath\n posterProc.running = true\n }\n\n function refreshFingerprintStatus() {\n if (!fingerprintCheckProc.running) fingerprintCheckProc.running = true\n }\n\n // Only definitive enrollment results may disable authentication.\n function applyFingerprintProbe(text) {\n var status = FingerprintModel.classifyProbe(text)\n if (status === \"unknown\") {\n if (fingerprintConfigured) return\n fingerprintProbeStreak += 1\n if (lockRequested) {\n fingerprintRecheckTimer.interval = FingerprintModel.retryDelayMs(fingerprintProbeStreak)\n fingerprintRecheckTimer.restart()\n }\n return\n }\n fingerprintProbeStreak = 0\n fingerprintRecheckTimer.stop()\n fingerprintConfigured = status === \"yes\"\n if (lockRequested && fingerprintConfigured) {\n // A pending retry already owns the next attempt.\n if (!fingerprintRetryTimer.running) startFingerprint()\n } else if (!fingerprintConfigured) {\n // abort() delivers no completion signal, so close the attempt here\n // too; settle returns before arming a retry while unconfigured.\n if (fingerprintPam.active) fingerprintPam.abort()\n settleFingerprintAttempt()\n fingerprintRetryTimer.stop()\n }\n }\n\n function logEvent(event) {\n lastEvent = event\n lastEventAt = new Date().toISOString()\n console.log(\"omarchy lock \" + lastEventAt + \" \" + event)\n }\n\n function resetAuthenticationState() {\n enteredPassword = \"\"\n pendingPassword = \"\"\n failureMessage = \"\"\n failedAttempts = 0\n authenticatingPassword = false\n fingerprintAuthenticating = false\n fingerprintUnreachedStreak = 0\n fingerprintAttemptFastError = false\n fingerprintAttemptPromptedAtMs = 0\n fingerprintLastNudgeMs = 0\n fingerprintLastSettleMs = 0\n fingerprintResumedAtMs = 0\n fingerprintProbeStreak = 0\n fingerprintRecheckTimer.stop()\n fingerprintRetryTimer.stop()\n fingerprintReachTimer.stop()\n if (passwordPam.active) passwordPam.abort()\n if (fingerprintPam.active) fingerprintPam.abort()\n }\n\n function beginLock() {\n if (!passwordPamConfigured) {\n logEvent(\"lock-denied: missing-pam\")\n return false\n }\n\n resetAuthenticationState()\n lockRequested = true\n armBlankTimer()\n logEvent(\"lock-requested\")\n queueSessionLock()\n\n Qt.callLater(function() {\n root.refreshBackground()\n root.refreshFingerprintStatus()\n })\n\n return true\n }\n\n function finishUnlock() {\n if (!root.currentlyLocked()) return\n\n lockRequested = false\n pendingSessionLock = false\n sessionLockStabilizeTimer.stop()\n pendingSessionLockTimer.stop()\n resetAuthenticationState()\n idleBlankTimer.stop()\n sessionLock.locked = false\n logEvent(\"unlocked\")\n runWake()\n }\n\n function armBlankTimer() {\n idleBlankTimer.armedAt = Date.now()\n idleBlankTimer.restart()\n }\n\n function runWake() {\n root.displaysBlank = false\n root.monitorDpmsKnown = false\n if (!wakeProcess.running) wakeProcess.running = true\n if (lockRequested) armBlankTimer()\n nudgeFingerprint()\n }\n\n // User activity advances retries without recreating a busy retry loop.\n function nudgeFingerprint() {\n if (!lockRequested) return\n if (!fingerprintConfigured && fingerprintRecheckTimer.running) {\n var now = Date.now()\n if (FingerprintModel.shouldNudge(now, fingerprintLastNudgeMs, now - FingerprintModel.IDLE_CLEAR_MS, fingerprintRecheckTimer.interval)) {\n fingerprintLastNudgeMs = now\n fingerprintRecheckTimer.interval = FingerprintModel.MATCH_RETRY_MS\n fingerprintRecheckTimer.restart()\n }\n return\n }\n if (!fingerprintConfigured) return\n if (fingerprintPam.active || fingerprintAuthenticating) return\n if (!fingerprintRetryTimer.running) return\n var now = Date.now()\n if (!FingerprintModel.shouldNudge(now, fingerprintLastNudgeMs, fingerprintLastSettleMs, fingerprintRetryTimer.interval)) return\n fingerprintLastNudgeMs = now\n armFingerprintRetry(FingerprintModel.MATCH_RETRY_MS)\n }\n\n\n function armFingerprintRetry(delayMs) {\n fingerprintRetryTimer.interval = delayMs\n fingerprintRetryTimer.restart()\n }\n\n // Reset pre-sleep failures while the resume hook restarts fprintd.\n function noteFingerprintResumed() {\n var now = Date.now()\n if (FingerprintModel.inResumeGrace(now, fingerprintResumedAtMs)) return\n logEvent(\"fingerprint-resume: streak=\" + fingerprintUnreachedStreak)\n fingerprintResumedAtMs = now\n fingerprintUnreachedStreak = 0\n }\n\n // A suspended PAM conversation may be orphaned by the daemon restart.\n function restartFingerprintAfterSleep() {\n noteFingerprintResumed()\n if (fingerprintAuthenticating || fingerprintPam.active) {\n if (fingerprintPam.active) fingerprintPam.abort()\n settleFingerprintAttempt()\n return\n }\n if (!fingerprintRetryTimer.running) return\n armFingerprintRetry(FingerprintModel.MATCH_RETRY_MS)\n }\n\n function runBlank() {\n root.displaysBlank = true\n root.monitorDpmsKnown = false\n if (!blankProcess.running) blankProcess.running = true\n }\n\n function screenBlank(screenName) {\n var name = String(screenName || \"\")\n if (!monitorDpmsKnown || !(name in monitorDpms)) return displaysBlank\n return !monitorDpms[name]\n }\n\n function applyMonitorDpms(text) {\n var monitors\n try {\n monitors = JSON.parse(String(text || \"\"))\n } catch (error) {\n return\n }\n if (!Array.isArray(monitors)) return\n\n var dpms = {}\n for (var i = 0; i < monitors.length; i++) {\n var monitor = monitors[i]\n if (monitor && monitor.name && !monitor.disabled) dpms[String(monitor.name)] = !!monitor.dpmsStatus\n }\n monitorDpms = dpms\n monitorDpmsKnown = true\n }\n\n function submitPassword(value) {\n var password = String(value || \"\")\n if (!lockRequested || authenticatingPassword || password.length === 0) return\n\n runWake()\n pendingPassword = password\n failureMessage = \"\"\n authenticatingPassword = true\n\n if (!passwordPam.start()) {\n handlePasswordFailure()\n return\n }\n\n Qt.callLater(respondToPasswordPrompt)\n }\n\n function respondToPasswordPrompt() {\n if (!authenticatingPassword || !passwordPam.active || !passwordPam.responseRequired) return\n passwordPam.respond(pendingPassword)\n }\n\n function handlePasswordFailure() {\n if (!lockRequested) return\n\n authenticatingPassword = false\n enteredPassword = \"\"\n pendingPassword = \"\"\n failedAttempts += 1\n failureMessage = \"Authentication failed (\" + failedAttempts + \")\"\n runWake()\n }\n\n function startFingerprint() {\n if (!lockRequested || !sessionLock.secure || !fingerprintConfigured) return\n if (fingerprintPam.active || fingerprintAuthenticating) return\n\n fingerprintAuthenticating = true\n fingerprintAttemptReachedDevice = false\n fingerprintAttemptFastError = false\n fingerprintAttemptPromptedAtMs = 0\n if (!fingerprintPam.start()) {\n // Pace a failed start while checking whether its PAM configuration was\n // removed; a definitive \"no\" stops retries and hides the indicator.\n settleFingerprintAttempt()\n refreshFingerprintStatus()\n return\n }\n // Bound claims that never prompt; a normal verify waits for a finger\n // under pam_fprintd's own timeout after reaching the reader.\n fingerprintReachTimer.restart()\n }\n\n // A prompt proves the claim landed, so stop waiting for reachability.\n function noteFingerprintReachedDevice() {\n if (fingerprintAttemptReachedDevice) return\n fingerprintAttemptReachedDevice = true\n fingerprintAttemptPromptedAtMs = Date.now()\n fingerprintReachTimer.stop()\n }\n\n // abort() gives no completion signal; settle the attempt here.\n function timeoutFingerprintReach() {\n logEvent(\"fingerprint-reach-timeout\")\n if (fingerprintPam.active) fingerprintPam.abort()\n settleFingerprintAttempt()\n }\n\n // onError and onCompleted can both fire; settle each attempt once.\n function settleFingerprintAttempt(deviceError) {\n if (!fingerprintAuthenticating) return\n fingerprintAuthenticating = false\n fingerprintReachTimer.stop()\n if (!lockRequested || !fingerprintConfigured) return\n\n // An error can arrive before the sleep watcher notices the wall-clock gap.\n var now = Date.now()\n fingerprintAttemptFastError = !!deviceError && fingerprintAttemptReachedDevice && now - fingerprintAttemptPromptedAtMs < FingerprintModel.FAST_ERROR_MS\n var usableAttempt = fingerprintAttemptReachedDevice && !fingerprintAttemptFastError\n if (!usableAttempt && fingerprintSleepWatch.running\n && FingerprintModel.spannedSleep(now - fingerprintSleepWatch.lastTickMs, fingerprintSleepWatch.interval)) {\n noteFingerprintResumed()\n }\n\n // Reached attempts are the steady state (one per swipe window), so only\n // the misses and the recovery from them leave a trace.\n var previousStreak = fingerprintUnreachedStreak\n var inGrace = FingerprintModel.inResumeGrace(now, fingerprintResumedAtMs)\n fingerprintUnreachedStreak = FingerprintModel.nextStreak(previousStreak, usableAttempt, inGrace)\n if (!usableAttempt) {\n var crossed = !FingerprintModel.isUnavailable(previousStreak) && FingerprintModel.isUnavailable(fingerprintUnreachedStreak)\n logEvent((crossed ? \"fingerprint-unavailable\" : \"fingerprint-unreached\") + \": streak=\" + fingerprintUnreachedStreak)\n } else if (previousStreak > 0) {\n logEvent(\"fingerprint-recovered: streak=\" + previousStreak)\n }\n fingerprintLastSettleMs = now\n armFingerprintRetry(FingerprintModel.retryDelayMs(fingerprintUnreachedStreak))\n }\n\n function handleFingerprintFinished(result) {\n if (result === PamResult.Success && lockRequested) {\n // A match after a run of misses is the recovery too; the unlock resets\n // the streak without settling, so log it here or it leaves no trace.\n if (fingerprintUnreachedStreak > 0) logEvent(\"fingerprint-recovered: streak=\" + fingerprintUnreachedStreak)\n finishUnlock()\n } else {\n settleFingerprintAttempt(result === PamResult.Error)\n }\n }\n\n WlSessionLock {\n id: sessionLock\n\n locked: false\n\n onSecureStateChanged: {\n root.logEvent(\"secure=\" + secure)\n if (secure) {\n root.pendingSessionLock = false\n sessionLockStabilizeTimer.stop()\n pendingSessionLockTimer.stop()\n root.startFingerprint()\n }\n }\n\n onLockStateChanged: {\n root.logEvent(\"session-locked=\" + locked)\n\n if (locked) {\n root.pendingSessionLock = false\n sessionLockStabilizeTimer.stop()\n pendingSessionLockTimer.stop()\n }\n\n if (!locked && root.lockRequested) {\n root.lockRequested = false\n root.pendingSessionLock = false\n sessionLockStabilizeTimer.stop()\n pendingSessionLockTimer.stop()\n root.resetAuthenticationState()\n root.runWake()\n }\n }\n\n WlSessionLockSurface {\n id: lockSurface\n color: Commons.Color.background\n\n LockView {\n id: lockView\n anchors.fill: parent\n backgroundPath: root.backgroundPath\n videoPosterPath: root.videoPosterPath\n backgroundVersion: root.backgroundVersion\n fingerprintConfigured: root.fingerprintConfigured || root.fingerprintUnavailable\n fingerprintUnavailable: root.fingerprintUnavailable\n authenticatingPassword: root.authenticatingPassword\n failureMessage: root.failureMessage\n failedAttempts: root.failedAttempts\n inputEnabled: root.lockRequested\n loadBackground: root.locked\n displaysBlank: root.screenBlank(lockSurface.screen ? lockSurface.screen.name : \"\")\n powerSaverActive: root.powerSaverActive\n passwordText: root.enteredPassword\n onPasswordTextEdited: function(password) { root.enteredPassword = password }\n onSubmitPassword: function(password) { root.submitPassword(password) }\n onClearFailureRequested: root.failureMessage = \"\"\n onWakeRequested: root.runWake()\n }\n\n }\n }\n\n PanelWindow {\n id: previewWindow\n visible: root.previewVisible\n anchors { top: true; bottom: true; left: true; right: true }\n color: \"transparent\"\n WlrLayershell.namespace: \"omarchy-lock-preview\"\n WlrLayershell.layer: WlrLayer.Overlay\n WlrLayershell.keyboardFocus: WlrKeyboardFocus.Exclusive\n exclusionMode: ExclusionMode.Ignore\n\n LockView {\n anchors.fill: parent\n backgroundPath: root.backgroundPath\n videoPosterPath: root.videoPosterPath\n backgroundVersion: root.backgroundVersion\n fingerprintConfigured: root.fingerprintConfigured || root.fingerprintUnavailable\n fingerprintUnavailable: root.fingerprintUnavailable\n authenticatingPassword: false\n failureMessage: \"\"\n failedAttempts: 0\n inputEnabled: false\n loadBackground: root.previewVisible\n powerSaverActive: root.powerSaverActive\n passwordText: \"\"\n }\n\n MouseArea {\n anchors.fill: parent\n acceptedButtons: Qt.LeftButton | Qt.RightButton\n onClicked: root.previewVisible = false\n }\n }\n\n PamContext {\n id: passwordPam\n config: \"omarchy-lock-password\"\n user: root.userName\n\n onResponseRequiredChanged: root.respondToPasswordPrompt()\n onPamMessage: root.respondToPasswordPrompt()\n\n onCompleted: function(result) {\n root.authenticatingPassword = false\n root.pendingPassword = \"\"\n\n if (!root.lockRequested) return\n if (result === PamResult.Success) root.finishUnlock()\n else root.handlePasswordFailure()\n }\n\n onError: function(error) {\n root.handlePasswordFailure()\n }\n }\n\n PamContext {\n id: fingerprintPam\n config: \"omarchy-lock-fingerprint\"\n user: root.userName\n\n onPamMessage: {\n if (!messageIsError) root.noteFingerprintReachedDevice()\n }\n\n onCompleted: function(result) {\n root.handleFingerprintFinished(result)\n }\n\n onError: function(error) {\n root.settleFingerprintAttempt(true)\n }\n }\n\n // The lock only starts decoding its wallpaper once locked, and a machine\n // suspending right after locking froze that decode partway: waking showed\n // the password field on a bare background, then the wallpaper popped in.\n // Keep each screen's lock wallpaper decoded in the image cache ahead of\n // time, as the lock view requests it (same URL, the screen's logical size,\n // PreserveAspectCrop), so the lock draws it on its first frame.\n readonly property string lockWallpaperPath: videoBackground ? videoPosterPath : backgroundPath\n readonly property string lockWallpaperUrl: lockWallpaperPath && !Util.isVideoPath(lockWallpaperPath)\n ? Util.fileUrl(lockWallpaperPath) + (backgroundVersion ? \"?v=\" + backgroundVersion : \"\")\n : \"\"\n\n Variants {\n model: Quickshell.screens\n\n Image {\n required property var modelData\n visible: false\n source: root.lockWallpaperUrl\n sourceSize.width: modelData.width\n sourceSize.height: modelData.height\n fillMode: Image.PreserveAspectCrop\n asynchronous: true\n cache: true\n }\n }\n\n Timer {\n id: fingerprintRetryTimer\n interval: FingerprintModel.MATCH_RETRY_MS\n repeat: false\n onTriggered: root.startFingerprint()\n }\n\n // Detect resume both during an active attempt and during backoff.\n Timer {\n id: fingerprintSleepWatch\n interval: 1000\n repeat: true\n running: root.lockRequested && root.fingerprintConfigured\n property double lastTickMs: 0\n onRunningChanged: lastTickMs = Date.now()\n onTriggered: {\n var now = Date.now()\n var slept = FingerprintModel.spannedSleep(now - lastTickMs, interval)\n lastTickMs = now\n if (slept) root.restartFingerprintAfterSleep()\n }\n }\n\n Timer {\n id: fingerprintReachTimer\n interval: FingerprintModel.REACH_TIMEOUT_MS\n repeat: false\n onTriggered: root.timeoutFingerprintReach()\n }\n\n Process {\n id: readlinkProc\n command: [\"bash\", \"-c\", \"path=$(readlink -f -- \\\"$1\\\") && printf '%s\\\\n%s\\\\n' \\\"$path\\\" \\\"$(stat -Lc %Y:%s -- \\\"$path\\\" 2>/dev/null)\\\"\", \"_\", root.currentBackgroundLink]\n stdout: StdioCollector {\n waitForEnd: true\n onStreamFinished: {\n var lines = String(text || \"\").split(\"\\n\")\n var next = String(lines[0] || \"\").trim()\n var signature = String(lines[1] || \"\").trim()\n if (next !== root.backgroundPath) {\n root.videoPosterPath = \"\"\n root.backgroundPath = next\n root.backgroundSignature = signature\n root.backgroundVersion += 1\n } else if (signature !== root.backgroundSignature) {\n root.backgroundSignature = signature\n root.backgroundVersion += 1\n }\n root.refreshPoster()\n }\n }\n }\n\n Process {\n id: posterProc\n property string sourcePath: \"\"\n command: [\"bash\", Quickshell.env(\"OMARCHY_PATH\") + \"/shell/plugins/lock/poster.sh\", sourcePath]\n stdout: StdioCollector { id: posterOutput; waitForEnd: true }\n onExited: function(exitCode) {\n if (sourcePath !== root.backgroundPath) {\n root.refreshPoster()\n } else {\n root.videoPosterPath = exitCode === 0 ? String(posterOutput.text || \"\").trim() : \"\"\n }\n }\n }\n\n // Keep fprintd errors distinguishable from an explicit empty enrollment.\n Process {\n id: fingerprintCheckProc\n command: [\"bash\", \"-c\", \"if [[ -f /etc/pam.d/omarchy-lock-fingerprint ]] && command -v fprintd-list >/dev/null 2>&1; then LC_ALL=C fprintd-list \\\"$USER\\\" 2>&1; else echo no; fi\"]\n stdout: StdioCollector { id: fingerprintCheckStdout; waitForEnd: true }\n onExited: root.applyFingerprintProbe(fingerprintCheckStdout.text)\n }\n\n // Retries a probe that could not reach fprintd, paced like the attempt\n // retries so a daemon that stays unreachable is asked about ever less often.\n Timer {\n id: fingerprintRecheckTimer\n interval: FingerprintModel.ERROR_RETRY_BASE_MS\n repeat: false\n onTriggered: root.refreshFingerprintStatus()\n }\n\n Process {\n id: strandedLockCheckProc\n // $PPID is this shell: a crash re-execs in place, so its pid is the one to skip.\n command: [\"bash\", \"-c\", \"omarchy-hyprland-session-lock-stranded \\\"$PPID\\\"\"]\n onExited: function(exitCode) {\n // No output to read the lock off yet.\n if (exitCode === 2) return\n\n root.strandedLockResolved = true\n\n // A lock taken while this was in flight is this shell's own.\n root.strandedLock = exitCode === 0 && !root.currentlyLocked()\n root.recoverStrandedLock()\n }\n }\n\n Process {\n id: wakeProcess\n command: [\"bash\", \"-c\", \"omarchy-system-wake\"]\n }\n\n Process {\n id: blankProcess\n command: [\"bash\", \"-c\", \"omarchy-brightness-keyboard off; omarchy-brightness-display off\"]\n }\n\n // Quickshell exposes no DPMS signal, so the panel state is polled while a\n // video is the locked wallpaper. A wake or blank request drops the last\n // answer, so its optimistic state applies until the next poll confirms it.\n Process {\n id: monitorDpmsProcess\n command: [\"hyprctl\", \"monitors\", \"-j\"]\n stdout: StdioCollector {\n onStreamFinished: root.applyMonitorDpms(text)\n }\n }\n\n Timer {\n id: monitorDpmsTimer\n interval: 3000\n repeat: true\n triggeredOnStart: true\n running: root.locked && root.videoBackground\n onTriggered: {\n if (!monitorDpmsProcess.running) monitorDpmsProcess.running = true\n }\n onRunningChanged: {\n if (!running) root.monitorDpmsKnown = false\n }\n }\n\n Timer {\n id: idleBlankTimer\n interval: 5000\n repeat: false\n property double armedAt: 0\n onTriggered: {\n // A countdown frozen by suspend fires right after resume, which would\n // blank the freshly woken unlock screen under the user. Wall-clock time\n // exposes the gap: take a fresh run-up instead of blanking.\n if (Date.now() - armedAt > interval + 2000) {\n root.armBlankTimer()\n return\n }\n // Only a password check in flight should hold the display up. The\n // fingerprint PAM stays armed for the whole lock, so gating on\n // `authenticating` here would keep the panel lit until unlock.\n if (root.lockRequested && !root.authenticatingPassword) root.runBlank()\n }\n }\n\n Timer {\n id: sessionLockStabilizeTimer\n interval: 500\n repeat: false\n onTriggered: root.requestSessionLock()\n }\n\n Timer {\n id: pendingSessionLockTimer\n interval: 100\n repeat: true\n onTriggered: root.requestSessionLock()\n }\n\n Timer {\n id: strandedLockRetryTimer\n interval: 500\n repeat: true\n // Covers the compositor settling; screens coming back re-arm it.\n readonly property int budget: 20\n property int remaining: 20\n running: !root.strandedLockResolved && remaining > 0\n\n function rearm() {\n if (!root.strandedLockResolved) remaining = budget\n }\n\n onTriggered: {\n remaining -= 1\n root.checkStrandedLock()\n }\n }\n\n Connections {\n target: Quickshell\n function onScreensChanged() {\n // A panel coming back is a display turning on that runWake did not ask\n // for, so the blank state has to be given up here or a visible lock\n // wallpaper stays frozen until the next keypress.\n root.displaysBlank = false\n root.requestSessionLock()\n\n // A monitor still coming up has no workspace, so cannot answer yet.\n strandedLockRetryTimer.rearm()\n root.checkStrandedLock()\n }\n }\n\n onAuthenticatingPasswordChanged: {\n if (!lockRequested) return\n if (authenticatingPassword) idleBlankTimer.stop()\n else armBlankTimer()\n }\n\n FileView {\n path: \"/etc/pam.d/omarchy-lock-password\"\n watchChanges: true\n printErrors: false\n onLoaded: root.passwordPamConfigured = true\n onLoadFailed: root.passwordPamConfigured = false\n onFileChanged: reload()\n }\n\n // No lock before PAM is known good. An answer from before then may be stale --\n // the failsafe can be cleared from a TTY -- so re-ask rather than act on it.\n onPasswordPamConfiguredChanged: {\n if (!passwordPamConfigured) return\n\n strandedLock = false\n strandedLockResolved = false\n strandedLockRetryTimer.rearm()\n checkStrandedLock()\n }\n\n Component.onCompleted: {\n refreshBackground()\n refreshFingerprintStatus()\n checkStrandedLock()\n }\n\n ShellIpc {\n target: \"lock\"\n\n function lock(): string {\n if (!root.passwordPamConfigured) return \"missing-pam\"\n if (!root.currentlyLocked() && !root.beginLock()) return \"failed\"\n return \"ok\"\n }\n\n function isLocked(): string {\n return root.currentlyLocked() ? \"true\" : \"false\"\n }\n\n function status(): string {\n return JSON.stringify({\n locked: root.currentlyLocked(),\n requested: root.lockRequested,\n pending: root.pendingSessionLock,\n sessionLocked: sessionLock.locked,\n secure: sessionLock.secure,\n realScreens: root.realScreenCount(),\n passwordPam: root.passwordPamConfigured,\n fingerprint: root.fingerprintConfigured,\n fingerprintUnavailable: root.fingerprintUnavailable,\n authenticating: root.authenticating,\n lastEvent: root.lastEvent,\n lastEventAt: root.lastEventAt\n })\n }\n\n function preview(): string {\n root.refreshBackground()\n root.refreshFingerprintStatus()\n root.previewVisible = true\n return \"ok\"\n }\n\n function hidePreview(): string {\n root.previewVisible = false\n return \"ok\"\n }\n }\n}\n```\n\n### poster.sh\n```bash\n#!/bin/bash\n\n# One cached frame shared by all lock outputs, including when OWE is paused.\nset -euo pipefail\n\nsource_path=$1\ncache_dir=\"${XDG_CACHE_HOME:-$HOME/.cache}/omarchy/lock-poster\"\nsignature=$(stat -Lc '%s:%y:%z' \"$source_path\")\nkey=$(printf '%s\\n%s' \"$source_path\" \"$signature\" | sha256sum | cut -d ' ' -f 1)\nposter=\"$cache_dir/poster-$key.jpg\"\nmkdir -p \"$cache_dir\"\nexec {lock_fd}>\"$cache_dir/.lock\"\nflock -w 10 \"$lock_fd\"\n\nif [[ ! -s $poster ]]; then\n temporary=$(mktemp \"$cache_dir/.poster-XXXXXX.jpg\")\n trap 'rm -f \"$temporary\"' EXIT\n timeout -k 1 5 ffmpegthumbnailer -i \"$source_path\" -o \"$temporary\" -s 1920 -q 8 {lock_fd}>&-\n [[ -s $temporary ]]\n mv -f \"$temporary\" \"$poster\"\n find \"$cache_dir\" -maxdepth 1 -type f -name 'poster-*.jpg' ! -name \"poster-$key.jpg\" -delete\nfi\n\nprintf '%s\\n' \"$poster\"\n```"}], "task": "build_from_spec", "meta": {"origin": "first-party", "repo": "https://github.com/basecamp/omarchy", "commit": "9480d1b6a98156314dbabe6bfef08f39f8b9cd07", "license": "MIT", "plugin_path": "shell/plugins/lock", "kinds": ["service"], "complexity": "large", "group": "be0fe0eb", "validator": "pass", "qmllint": "clean", "qml_files": 3, "chars": 45720, "tokens": 10945, "split": "train"}} {"messages": [{"role": "system", "content": "You are an Omarchy plugin expert. You write complete, valid Omarchy (Quattro / omarchy-shell, Quickshell QML) plugins. Manifests use schemaVersion 1, a namespaced id that never uses the reserved omarchy.* namespace, name, version, kinds (bar-widget|panel|overlay|menu|service|bar) with a matching safe relative entryPoints path for every kind, and no symlinks. Return every file in full as '### path' followed by a fenced code block."}, {"role": "user", "content": "I want an Omarchy service plugin named Lock Screen (id `acme.lock`): Quickshell session lock with separate password and fingerprint PAM flows. Give me every file."}, {"role": "assistant", "content": "### manifest.json\n```json\n{\n \"schemaVersion\": 1,\n \"id\": \"acme.lock\",\n \"name\": \"Lock Screen\",\n \"version\": \"1.0.0\",\n \"author\": \"Omarchy\",\n \"description\": \"Quickshell session lock with separate password and fingerprint PAM flows.\",\n \"omarchy\": {\n \"capabilities\": [\n \"authentication\"\n ]\n },\n \"kinds\": [\n \"service\"\n ],\n \"keepLoaded\": true,\n \"entryPoints\": {\n \"service\": \"Service.qml\"\n }\n}\n```\n\n### FingerprintModel.js\n```javascript\n// Back off missing prompts and fast device errors; ordinary mismatches\n// and a full scan window without a finger keep the normal swipe interval.\nvar MATCH_RETRY_MS = 250\nvar FAST_ERROR_MS = 2000\nvar NUDGE_COOLDOWN_MS = 2000\nvar IDLE_CLEAR_MS = 32000\nvar ERROR_RETRY_BASE_MS = 1000\n// Leave enough idle time for fprintd to exit and clear a wedged claim.\nvar FPRINTD_IDLE_EXIT_MS = 30000\nvar ERROR_RETRY_CAP_MS = 40000\nvar UNAVAILABLE_AFTER = 3\n// Abort before the D-Bus claim timeout, while allowing slow device opens.\nvar REACH_TIMEOUT_MS = 20000\n// Monotonic timers pause across suspend; a wall-clock gap detects resume.\nvar SLEEP_GAP_MS = 2000\n// Ignore transient misses while the asynchronous resume restart lands.\nvar RESUME_GRACE_MS = 5000\n\nfunction retryDelayMs(streak) {\n if (streak <= 0) return MATCH_RETRY_MS\n var delay = ERROR_RETRY_BASE_MS * Math.pow(2, streak - 1)\n return Math.min(delay, ERROR_RETRY_CAP_MS)\n}\n\n// Preserve the daemon idle window even under continuous user activity.\nfunction shouldNudge(nowMs, lastNudgeMs, lastSettleMs, currentIntervalMs) {\n if (currentIntervalMs <= MATCH_RETRY_MS) return false\n var sinceNudge = nowMs - lastNudgeMs\n var sinceSettle = nowMs - lastSettleMs\n // A backward clock step cannot count as a completed idle window.\n if (sinceNudge >= 0 && sinceNudge < Math.max(NUDGE_COOLDOWN_MS, currentIntervalMs)) return false\n if (sinceSettle < 0) sinceSettle = 0\n if (currentIntervalMs >= ERROR_RETRY_CAP_MS && sinceSettle < IDLE_CLEAR_MS) return false\n return true\n}\n\n\n// A failed probe is unknown, so it cannot disable authentication for the lock.\nfunction classifyProbe(text) {\n var s = String(text || \"\").trim()\n if (/^[ \\t]*-[ \\t]*#[0-9]+:/m.test(s)) return \"yes\"\n if (s === \"no\") return \"no\"\n if (/has no fingers enrolled/i.test(s)) return \"no\"\n return \"unknown\"\n}\n\n// Resume-time misses stay at the first tier while fprintd restarts.\nfunction nextStreak(streak, usableAttempt, inResumeGrace) {\n if (usableAttempt) return 0\n if (inResumeGrace) return 1\n return streak + 1\n}\n\n// Event-loop stalls may also open the grace window; retries remain paced.\nfunction spannedSleep(elapsedMs, expectedMs) {\n return elapsedMs > expectedMs + SLEEP_GAP_MS\n}\n\nfunction inResumeGrace(nowMs, resumedAtMs) {\n if (resumedAtMs <= 0) return false\n var elapsed = nowMs - resumedAtMs\n return elapsed >= 0 && elapsed < RESUME_GRACE_MS\n}\n\n// A few consecutive misses avoid reporting a single claim conflict.\nfunction isUnavailable(streak) {\n return streak >= UNAVAILABLE_AFTER\n}\n\nif (typeof module !== \"undefined\") {\n module.exports = {\n MATCH_RETRY_MS: MATCH_RETRY_MS,\n FAST_ERROR_MS: FAST_ERROR_MS,\n NUDGE_COOLDOWN_MS: NUDGE_COOLDOWN_MS,\n IDLE_CLEAR_MS: IDLE_CLEAR_MS,\n shouldNudge: shouldNudge,\n ERROR_RETRY_BASE_MS: ERROR_RETRY_BASE_MS,\n ERROR_RETRY_CAP_MS: ERROR_RETRY_CAP_MS,\n FPRINTD_IDLE_EXIT_MS: FPRINTD_IDLE_EXIT_MS,\n UNAVAILABLE_AFTER: UNAVAILABLE_AFTER,\n REACH_TIMEOUT_MS: REACH_TIMEOUT_MS,\n SLEEP_GAP_MS: SLEEP_GAP_MS,\n RESUME_GRACE_MS: RESUME_GRACE_MS,\n spannedSleep: spannedSleep,\n classifyProbe: classifyProbe,\n inResumeGrace: inResumeGrace,\n retryDelayMs: retryDelayMs,\n nextStreak: nextStreak,\n isUnavailable: isUnavailable\n }\n}\n```\n\n### LockFeedSurface.qml\n```qml\nimport QtQuick\nimport Owe.LockFeed\n\n// Loaded through a Loader from LockView, so a system without the module shows\n// no lock video instead of losing the whole lock screen.\nLockFeed {\n}\n```\n\n### LockView.qml\n```qml\nimport QtQuick\nimport QtQuick.Effects\nimport qs.Commons\nimport qs.Commons as Commons\nimport qs.Ui\n\nItem {\n id: root\n\n property string backgroundPath: \"\"\n property string videoPosterPath: \"\"\n property int backgroundVersion: 0\n property bool fingerprintConfigured: false\n property bool fingerprintUnavailable: false\n property bool authenticatingPassword: false\n property string failureMessage: \"\"\n property int failedAttempts: 0\n property bool inputEnabled: true\n property bool loadBackground: true\n // A locked session blanks the displays after a few seconds. Nothing is\n // visible from then until the user wakes it, so a video must not keep\n // decoding through what is usually the longest part of a lock.\n property bool displaysBlank: false\n property bool powerSaverActive: false\n property string passwordText: \"\"\n property bool syncingPasswordText: false\n\n readonly property string placeholderText: \"Enter Password\"\n readonly property int fieldWidth: 381\n readonly property int fieldHeight: 67\n readonly property int outlineThickness: 3\n readonly property int fieldFontSize: Math.round(Style.font.heading * 1.125)\n readonly property int passwordDotFontSize: Math.round(Style.font.heading * 1.33)\n readonly property int passwordDotLetterSpacing: Math.round(Style.font.heading * 0.19)\n // Space to keep clear on each side of the field for the fingerprint icon\n // (icon width plus a gap) so the centered dots never run under it.\n readonly property real fingerprintReserve: fingerprintConfigured ? Math.round(fingerprintIcon.implicitWidth + 12) : 0\n // Shrink the dots to fit once the password outgrows the field, so every\n // keystroke stays visible — otherwise long passwords clip with no feedback.\n readonly property real passwordDotScale: dotMetrics.advanceWidth > 0\n ? Math.min(1, (passwordInput.width - 4) / dotMetrics.advanceWidth)\n : 1\n readonly property bool showPasswordCursor: inputEnabled && !authenticatingPassword && failureMessage.length === 0\n readonly property bool errorState: failureMessage.length > 0\n readonly property var inputBorderSpec: errorState\n ? Border.surfaceSpec(\"lock\", \"border-error\", Commons.Color.lock.borderError, root.outlineThickness, \"border-alpha\")\n : Border.surfaceSpec(\"lock\", \"border-active\", Commons.Color.lock.borderActive, root.outlineThickness, \"border-alpha\")\n\n readonly property bool video: Util.isVideoPath(root.backgroundPath)\n readonly property bool feedActive: root.video && root.loadBackground && !root.displaysBlank && !root.powerSaverActive\n\n signal submitPassword(string password)\n signal passwordTextEdited(string password)\n signal clearFailureRequested()\n signal wakeRequested()\n\n function forcePasswordFocus() {\n passwordInput.forceActiveFocus()\n }\n\n function clearPassword() {\n passwordTextEdited(\"\")\n }\n\n // Waking a DPMS-blanked display can stall the compositor for seconds while\n // the monitor modesets, so the wake key's release arrives late and client-side\n // key repeat floods the field with that character. A held key has no business\n // typing a password; only holding Backspace/Delete to clear stays useful.\n function dropsAutoRepeat(key) {\n return key !== Qt.Key_Backspace && key !== Qt.Key_Delete\n }\n\n function syncPasswordText() {\n if (passwordInput.text === passwordText) return\n syncingPasswordText = true\n passwordInput.text = passwordText\n syncingPasswordText = false\n }\n\n onPasswordTextChanged: syncPasswordText()\n onInputEnabledChanged: {\n if (inputEnabled) Qt.callLater(forcePasswordFocus)\n }\n Component.onCompleted: {\n syncPasswordText()\n if (inputEnabled) Qt.callLater(forcePasswordFocus)\n }\n\n // Measures the masked password at full size; passwordDotScale compares this\n // against the field width to decide how far the dots must shrink to fit.\n TextMetrics {\n id: dotMetrics\n font.family: Style.font.family\n font.pixelSize: root.passwordDotFontSize\n font.letterSpacing: root.passwordDotLetterSpacing\n text: \"●\".repeat(passwordInput.text.length)\n }\n\n Rectangle {\n anchors.fill: parent\n color: Commons.Color.background\n\n BackgroundMedia {\n id: wallpaper\n objectName: \"lockWallpaper\"\n anchors.fill: parent\n path: root.loadBackground ? (root.video ? root.videoPosterPath : root.backgroundPath) : \"\"\n version: root.backgroundVersion\n // Decode only once sized, at the lock's own size: an unsized first\n // request decoded the file at its native resolution, then again once\n // sized. That size is what the lock service keeps decoded ahead of the\n // lock, so the first frame has the wallpaper.\n cached: true\n constrainDecode: true\n decodeSize: Qt.size(width, height)\n }\n\n MultiEffect {\n anchors.fill: wallpaper\n source: wallpaper\n autoPaddingEnabled: false\n blurEnabled: root.loadBackground && wallpaper.ready\n blur: 1.0\n blurMax: 128\n blurMultiplier: 1.25\n contrast: -0.08\n }\n\n // The cached poster stays behind the feed when policy pauses playback,\n // the module is unavailable, or a new connection has not received a frame.\n Loader {\n id: feedLoader\n objectName: \"lockFeedLoader\"\n anchors.fill: parent\n active: root.feedActive\n source: \"LockFeedSurface.qml\"\n visible: status === Loader.Ready\n }\n\n // The feed item cannot be sampled by MultiEffect on every renderer.\n // Keep video wallpapers visible and darken them slightly for legibility.\n Rectangle {\n anchors.fill: feedLoader\n visible: root.video\n color: \"#22000000\"\n }\n\n MouseArea {\n anchors.fill: parent\n hoverEnabled: true\n onClicked: { root.wakeRequested(); root.forcePasswordFocus() }\n onPositionChanged: root.wakeRequested()\n }\n\n BorderSurface {\n id: inputField\n width: root.fieldWidth\n height: root.fieldHeight\n anchors.centerIn: parent\n color: Commons.Color.lock.background\n borderSpec: root.inputBorderSpec\n radius: Style.cornerRadius\n clip: true\n\n TextInput {\n id: passwordInput\n anchors.fill: parent\n anchors.topMargin: inputField.borderTop\n // Reserve the fingerprint icon's width on both sides so the centered\n // dots stay symmetric and never slide under the icon as they grow.\n anchors.rightMargin: inputField.borderRight + 18 + root.fingerprintReserve\n anchors.bottomMargin: inputField.borderBottom\n anchors.leftMargin: inputField.borderLeft + 18 + root.fingerprintReserve\n verticalAlignment: TextInput.AlignVCenter\n horizontalAlignment: TextInput.AlignHCenter\n activeFocusOnPress: true\n clip: true\n enabled: root.inputEnabled && !root.authenticatingPassword\n readOnly: root.authenticatingPassword\n echoMode: TextInput.Password\n passwordCharacter: \"\\u25CF\"\n passwordMaskDelay: 0\n color: Commons.Color.lock.text\n selectionColor: Commons.Color.lock.selection\n selectedTextColor: Commons.Color.lock.text\n font.family: Style.font.family\n font.pixelSize: text.length > 0 ? Math.max(1, Math.floor(root.passwordDotFontSize * root.passwordDotScale)) : root.fieldFontSize\n font.letterSpacing: text.length > 0 ? root.passwordDotLetterSpacing * root.passwordDotScale : 0\n cursorVisible: activeFocus && root.showPasswordCursor && text.length > 0\n cursorDelegate: Rectangle {\n width: 2\n color: Commons.Color.lock.text\n visible: passwordInput.cursorVisible\n }\n\n onTextChanged: {\n if (!root.syncingPasswordText) root.passwordTextEdited(text)\n if (text.length > 0) {\n root.wakeRequested()\n }\n if (text.length > 0 && root.failureMessage.length > 0) root.clearFailureRequested()\n }\n\n onAccepted: {\n var submitted = root.passwordText\n root.passwordTextEdited(\"\")\n if (submitted.length > 0) root.submitPassword(submitted)\n }\n\n Keys.onPressed: function(event) {\n root.wakeRequested()\n if (event.isAutoRepeat && root.dropsAutoRepeat(event.key)) {\n event.accepted = true\n return\n }\n if (event.key === Qt.Key_Escape || (event.modifiers & Qt.ControlModifier && event.key === Qt.Key_U)) {\n root.passwordTextEdited(\"\")\n event.accepted = true\n }\n }\n }\n\n Text {\n textFormat: Text.PlainText\n anchors.fill: passwordInput\n text: root.authenticatingPassword ? \"Checking…\" : (root.failureMessage.length > 0 ? root.failureMessage : root.placeholderText)\n visible: passwordInput.text.length === 0\n color: root.authenticatingPassword ? Commons.Color.lock.text : (root.failureMessage.length > 0 ? Commons.Color.lock.textError : Commons.Color.lock.placeholder)\n font.family: Style.font.family\n font.pixelSize: root.fieldFontSize\n font.italic: !root.authenticatingPassword && root.failureMessage.length > 0\n horizontalAlignment: Text.AlignHCenter\n verticalAlignment: Text.AlignVCenter\n elide: Text.ElideRight\n }\n\n // Fingerprint hint pinned inside the field's right edge when a sensor is\n // enrolled, so the user knows they can touch to unlock instead of typing.\n // Matches hyprlock, which draws its fingerprint icon in the same spot.\n // A reader the shell cannot reach crosses out rather than disappears, so\n // it stops inviting touches that can never unlock.\n Text {\n id: fingerprintIcon\n objectName: \"fingerprintIndicator\"\n textFormat: Text.PlainText\n anchors.right: parent.right\n anchors.rightMargin: inputField.borderRight + 18\n anchors.verticalCenter: parent.verticalCenter\n visible: root.fingerprintConfigured\n text: root.fingerprintUnavailable ? \"󰺱\" : \"󰈷\"\n color: root.fingerprintUnavailable ? Commons.Color.lock.textError : Commons.Color.lock.placeholder\n font.family: Style.font.family\n font.pixelSize: Math.round(root.fieldFontSize * 1.1)\n horizontalAlignment: Text.AlignHCenter\n verticalAlignment: Text.AlignVCenter\n }\n }\n\n // The crossed-out icon has no meaning to a user who has never seen it — it\n // is not intuitive that it signals a broken reader — so the words carry the\n // explanation and the icon only reinforces it.\n Text {\n objectName: \"fingerprintUnavailableNotice\"\n textFormat: Text.PlainText\n anchors.top: inputField.bottom\n anchors.topMargin: 18\n anchors.horizontalCenter: inputField.horizontalCenter\n visible: root.fingerprintConfigured && root.fingerprintUnavailable\n text: \"Fingerprint reader unavailable\"\n color: Commons.Color.lock.textError\n font.family: Style.font.family\n font.pixelSize: Style.font.heading\n font.italic: true\n horizontalAlignment: Text.AlignHCenter\n }\n }\n}\n```\n\n### Service.qml\n```qml\nimport QtQuick\nimport Quickshell\nimport Quickshell.Io\nimport Quickshell.Services.Pam\nimport Quickshell.Wayland\nimport qs.Commons\nimport qs.Commons as Commons\nimport \"FingerprintModel.js\" as FingerprintModel\n\nItem {\n id: root\n\n property var shell: null\n property string omarchyPath: \"\"\n\n readonly property string home: Quickshell.env(\"HOME\")\n readonly property string stateHome: home + \"/.local/state\"\n readonly property string userName: Quickshell.env(\"USER\") || Quickshell.env(\"LOGNAME\")\n readonly property string currentBackgroundLink: stateHome + \"/omarchy/current/background\"\n\n property bool lockRequested: false\n property bool pendingSessionLock: false\n property bool authenticatingPassword: false\n property bool fingerprintAuthenticating: false\n property bool passwordPamConfigured: false\n property bool fingerprintConfigured: false\n property int fingerprintUnreachedStreak: 0\n property bool fingerprintAttemptReachedDevice: false\n property bool fingerprintAttemptFastError: false\n property double fingerprintAttemptPromptedAtMs: 0\n property double fingerprintLastNudgeMs: 0\n property double fingerprintLastSettleMs: 0\n property double fingerprintResumedAtMs: 0\n property int fingerprintProbeStreak: 0\n property bool previewVisible: false\n property string enteredPassword: \"\"\n property string pendingPassword: \"\"\n property string failureMessage: \"\"\n property int failedAttempts: 0\n property string backgroundPath: \"\"\n property string videoPosterPath: \"\"\n property int backgroundVersion: 0\n // The wallpaper file's mtime and size. The lock caches its wallpaper by\n // version, so a file overwritten in place must bump the version too.\n property string backgroundSignature: \"\"\n property string lastEvent: \"init\"\n property string lastEventAt: \"\"\n property bool displaysBlank: false\n // displaysBlank tracks what the lock asked for; Hyprland reports what each\n // panel actually did. While a video is on show the two are reconciled, so a\n // blank that failed keeps playing and a panel woken behind the lock's back\n // (a resume that kept the same outputs) resumes instead of freezing.\n property var monitorDpms: ({})\n property bool monitorDpmsKnown: false\n readonly property bool videoBackground: Util.isVideoPath(backgroundPath)\n property bool strandedLock: false\n property bool strandedLockResolved: false\n\n readonly property bool locked: lockRequested || sessionLock.locked || sessionLock.secure\n\n // Decisions read the lock state afresh. A property binding that missed a change\n // notification once reported locked after an unlock, and a lock request before\n // suspend then took that for done and never locked the session.\n function currentlyLocked() {\n return lockRequested || sessionLock.locked || sessionLock.secure\n }\n readonly property bool authenticating: authenticatingPassword || fingerprintAuthenticating\n readonly property var batteryService: shell && shell.services ? shell.firstPartyServiceFor(\"omarchy.battery\") : null\n readonly property bool powerSaverActive: batteryService ? batteryService.powerSaverOnBattery : false\n // A prompt clears the unavailable notice before the attempt finishes.\n readonly property bool fingerprintUnavailable: FingerprintModel.isUnavailable(fingerprintProbeStreak) || (fingerprintConfigured && (!fingerprintAttemptReachedDevice || fingerprintAttemptFastError) && FingerprintModel.isUnavailable(fingerprintUnreachedStreak))\n\n function realScreenCount() {\n var screens = Quickshell.screens || []\n var count = 0\n\n for (var i = 0; i < screens.length; i++) {\n var screen = screens[i]\n if (screen && screen.name && screen.width > 0 && screen.height > 0) count += 1\n }\n\n return count\n }\n\n function hasRealScreen() {\n return realScreenCount() > 0\n }\n\n function queueSessionLock() {\n pendingSessionLock = true\n if (!sessionLockStabilizeTimer.running) logEvent(\"lock-pending: screen-stabilizing\")\n sessionLockStabilizeTimer.restart()\n if (!pendingSessionLockTimer.running) pendingSessionLockTimer.start()\n }\n\n function requestSessionLock() {\n if (!lockRequested || sessionLock.locked || sessionLock.secure) return\n if (sessionLockStabilizeTimer.running) return\n\n if (!hasRealScreen()) {\n if (!pendingSessionLock || lastEvent !== \"lock-pending: no-real-screen\") logEvent(\"lock-pending: no-real-screen\")\n pendingSessionLock = true\n if (!pendingSessionLockTimer.running) pendingSessionLockTimer.start()\n return\n }\n\n pendingSessionLock = false\n pendingSessionLockTimer.stop()\n sessionLock.locked = true\n }\n\n // ext-session-lock outlives its client, and a restart carries no lock over, so\n // a session locked this early may be an orphan behind Hyprland's failsafe. It\n // may also be another shell's live lock, which Hyprland would let this one\n // take over and then strand on exit, so the helper answers undetermined while\n // another locker runs. Outputs are often still absent here, so ask until the\n // answer means something.\n function checkStrandedLock() {\n if (strandedLockResolved || strandedLockCheckProc.running) return\n\n // A lock this shell took is nobody's orphan.\n if (currentlyLocked()) {\n strandedLockResolved = true\n return\n }\n\n strandedLockCheckProc.running = true\n }\n\n function recoverStrandedLock() {\n if (!strandedLock || currentlyLocked() || !passwordPamConfigured) return\n\n strandedLock = false\n logEvent(\"lock-stranded: recovering\")\n beginLock()\n }\n\n function refreshBackground() {\n if (!readlinkProc.running) readlinkProc.running = true\n }\n\n function refreshPoster() {\n if (!root.videoBackground) {\n root.videoPosterPath = \"\"\n return\n }\n if (posterProc.running) return\n posterProc.sourcePath = root.backgroundPath\n posterProc.running = true\n }\n\n function refreshFingerprintStatus() {\n if (!fingerprintCheckProc.running) fingerprintCheckProc.running = true\n }\n\n // Only definitive enrollment results may disable authentication.\n function applyFingerprintProbe(text) {\n var status = FingerprintModel.classifyProbe(text)\n if (status === \"unknown\") {\n if (fingerprintConfigured) return\n fingerprintProbeStreak += 1\n if (lockRequested) {\n fingerprintRecheckTimer.interval = FingerprintModel.retryDelayMs(fingerprintProbeStreak)\n fingerprintRecheckTimer.restart()\n }\n return\n }\n fingerprintProbeStreak = 0\n fingerprintRecheckTimer.stop()\n fingerprintConfigured = status === \"yes\"\n if (lockRequested && fingerprintConfigured) {\n // A pending retry already owns the next attempt.\n if (!fingerprintRetryTimer.running) startFingerprint()\n } else if (!fingerprintConfigured) {\n // abort() delivers no completion signal, so close the attempt here\n // too; settle returns before arming a retry while unconfigured.\n if (fingerprintPam.active) fingerprintPam.abort()\n settleFingerprintAttempt()\n fingerprintRetryTimer.stop()\n }\n }\n\n function logEvent(event) {\n lastEvent = event\n lastEventAt = new Date().toISOString()\n console.log(\"omarchy lock \" + lastEventAt + \" \" + event)\n }\n\n function resetAuthenticationState() {\n enteredPassword = \"\"\n pendingPassword = \"\"\n failureMessage = \"\"\n failedAttempts = 0\n authenticatingPassword = false\n fingerprintAuthenticating = false\n fingerprintUnreachedStreak = 0\n fingerprintAttemptFastError = false\n fingerprintAttemptPromptedAtMs = 0\n fingerprintLastNudgeMs = 0\n fingerprintLastSettleMs = 0\n fingerprintResumedAtMs = 0\n fingerprintProbeStreak = 0\n fingerprintRecheckTimer.stop()\n fingerprintRetryTimer.stop()\n fingerprintReachTimer.stop()\n if (passwordPam.active) passwordPam.abort()\n if (fingerprintPam.active) fingerprintPam.abort()\n }\n\n function beginLock() {\n if (!passwordPamConfigured) {\n logEvent(\"lock-denied: missing-pam\")\n return false\n }\n\n resetAuthenticationState()\n lockRequested = true\n armBlankTimer()\n logEvent(\"lock-requested\")\n queueSessionLock()\n\n Qt.callLater(function() {\n root.refreshBackground()\n root.refreshFingerprintStatus()\n })\n\n return true\n }\n\n function finishUnlock() {\n if (!root.currentlyLocked()) return\n\n lockRequested = false\n pendingSessionLock = false\n sessionLockStabilizeTimer.stop()\n pendingSessionLockTimer.stop()\n resetAuthenticationState()\n idleBlankTimer.stop()\n sessionLock.locked = false\n logEvent(\"unlocked\")\n runWake()\n }\n\n function armBlankTimer() {\n idleBlankTimer.armedAt = Date.now()\n idleBlankTimer.restart()\n }\n\n function runWake() {\n root.displaysBlank = false\n root.monitorDpmsKnown = false\n if (!wakeProcess.running) wakeProcess.running = true\n if (lockRequested) armBlankTimer()\n nudgeFingerprint()\n }\n\n // User activity advances retries without recreating a busy retry loop.\n function nudgeFingerprint() {\n if (!lockRequested) return\n if (!fingerprintConfigured && fingerprintRecheckTimer.running) {\n var now = Date.now()\n if (FingerprintModel.shouldNudge(now, fingerprintLastNudgeMs, now - FingerprintModel.IDLE_CLEAR_MS, fingerprintRecheckTimer.interval)) {\n fingerprintLastNudgeMs = now\n fingerprintRecheckTimer.interval = FingerprintModel.MATCH_RETRY_MS\n fingerprintRecheckTimer.restart()\n }\n return\n }\n if (!fingerprintConfigured) return\n if (fingerprintPam.active || fingerprintAuthenticating) return\n if (!fingerprintRetryTimer.running) return\n var now = Date.now()\n if (!FingerprintModel.shouldNudge(now, fingerprintLastNudgeMs, fingerprintLastSettleMs, fingerprintRetryTimer.interval)) return\n fingerprintLastNudgeMs = now\n armFingerprintRetry(FingerprintModel.MATCH_RETRY_MS)\n }\n\n\n function armFingerprintRetry(delayMs) {\n fingerprintRetryTimer.interval = delayMs\n fingerprintRetryTimer.restart()\n }\n\n // Reset pre-sleep failures while the resume hook restarts fprintd.\n function noteFingerprintResumed() {\n var now = Date.now()\n if (FingerprintModel.inResumeGrace(now, fingerprintResumedAtMs)) return\n logEvent(\"fingerprint-resume: streak=\" + fingerprintUnreachedStreak)\n fingerprintResumedAtMs = now\n fingerprintUnreachedStreak = 0\n }\n\n // A suspended PAM conversation may be orphaned by the daemon restart.\n function restartFingerprintAfterSleep() {\n noteFingerprintResumed()\n if (fingerprintAuthenticating || fingerprintPam.active) {\n if (fingerprintPam.active) fingerprintPam.abort()\n settleFingerprintAttempt()\n return\n }\n if (!fingerprintRetryTimer.running) return\n armFingerprintRetry(FingerprintModel.MATCH_RETRY_MS)\n }\n\n function runBlank() {\n root.displaysBlank = true\n root.monitorDpmsKnown = false\n if (!blankProcess.running) blankProcess.running = true\n }\n\n function screenBlank(screenName) {\n var name = String(screenName || \"\")\n if (!monitorDpmsKnown || !(name in monitorDpms)) return displaysBlank\n return !monitorDpms[name]\n }\n\n function applyMonitorDpms(text) {\n var monitors\n try {\n monitors = JSON.parse(String(text || \"\"))\n } catch (error) {\n return\n }\n if (!Array.isArray(monitors)) return\n\n var dpms = {}\n for (var i = 0; i < monitors.length; i++) {\n var monitor = monitors[i]\n if (monitor && monitor.name && !monitor.disabled) dpms[String(monitor.name)] = !!monitor.dpmsStatus\n }\n monitorDpms = dpms\n monitorDpmsKnown = true\n }\n\n function submitPassword(value) {\n var password = String(value || \"\")\n if (!lockRequested || authenticatingPassword || password.length === 0) return\n\n runWake()\n pendingPassword = password\n failureMessage = \"\"\n authenticatingPassword = true\n\n if (!passwordPam.start()) {\n handlePasswordFailure()\n return\n }\n\n Qt.callLater(respondToPasswordPrompt)\n }\n\n function respondToPasswordPrompt() {\n if (!authenticatingPassword || !passwordPam.active || !passwordPam.responseRequired) return\n passwordPam.respond(pendingPassword)\n }\n\n function handlePasswordFailure() {\n if (!lockRequested) return\n\n authenticatingPassword = false\n enteredPassword = \"\"\n pendingPassword = \"\"\n failedAttempts += 1\n failureMessage = \"Authentication failed (\" + failedAttempts + \")\"\n runWake()\n }\n\n function startFingerprint() {\n if (!lockRequested || !sessionLock.secure || !fingerprintConfigured) return\n if (fingerprintPam.active || fingerprintAuthenticating) return\n\n fingerprintAuthenticating = true\n fingerprintAttemptReachedDevice = false\n fingerprintAttemptFastError = false\n fingerprintAttemptPromptedAtMs = 0\n if (!fingerprintPam.start()) {\n // Pace a failed start while checking whether its PAM configuration was\n // removed; a definitive \"no\" stops retries and hides the indicator.\n settleFingerprintAttempt()\n refreshFingerprintStatus()\n return\n }\n // Bound claims that never prompt; a normal verify waits for a finger\n // under pam_fprintd's own timeout after reaching the reader.\n fingerprintReachTimer.restart()\n }\n\n // A prompt proves the claim landed, so stop waiting for reachability.\n function noteFingerprintReachedDevice() {\n if (fingerprintAttemptReachedDevice) return\n fingerprintAttemptReachedDevice = true\n fingerprintAttemptPromptedAtMs = Date.now()\n fingerprintReachTimer.stop()\n }\n\n // abort() gives no completion signal; settle the attempt here.\n function timeoutFingerprintReach() {\n logEvent(\"fingerprint-reach-timeout\")\n if (fingerprintPam.active) fingerprintPam.abort()\n settleFingerprintAttempt()\n }\n\n // onError and onCompleted can both fire; settle each attempt once.\n function settleFingerprintAttempt(deviceError) {\n if (!fingerprintAuthenticating) return\n fingerprintAuthenticating = false\n fingerprintReachTimer.stop()\n if (!lockRequested || !fingerprintConfigured) return\n\n // An error can arrive before the sleep watcher notices the wall-clock gap.\n var now = Date.now()\n fingerprintAttemptFastError = !!deviceError && fingerprintAttemptReachedDevice && now - fingerprintAttemptPromptedAtMs < FingerprintModel.FAST_ERROR_MS\n var usableAttempt = fingerprintAttemptReachedDevice && !fingerprintAttemptFastError\n if (!usableAttempt && fingerprintSleepWatch.running\n && FingerprintModel.spannedSleep(now - fingerprintSleepWatch.lastTickMs, fingerprintSleepWatch.interval)) {\n noteFingerprintResumed()\n }\n\n // Reached attempts are the steady state (one per swipe window), so only\n // the misses and the recovery from them leave a trace.\n var previousStreak = fingerprintUnreachedStreak\n var inGrace = FingerprintModel.inResumeGrace(now, fingerprintResumedAtMs)\n fingerprintUnreachedStreak = FingerprintModel.nextStreak(previousStreak, usableAttempt, inGrace)\n if (!usableAttempt) {\n var crossed = !FingerprintModel.isUnavailable(previousStreak) && FingerprintModel.isUnavailable(fingerprintUnreachedStreak)\n logEvent((crossed ? \"fingerprint-unavailable\" : \"fingerprint-unreached\") + \": streak=\" + fingerprintUnreachedStreak)\n } else if (previousStreak > 0) {\n logEvent(\"fingerprint-recovered: streak=\" + previousStreak)\n }\n fingerprintLastSettleMs = now\n armFingerprintRetry(FingerprintModel.retryDelayMs(fingerprintUnreachedStreak))\n }\n\n function handleFingerprintFinished(result) {\n if (result === PamResult.Success && lockRequested) {\n // A match after a run of misses is the recovery too; the unlock resets\n // the streak without settling, so log it here or it leaves no trace.\n if (fingerprintUnreachedStreak > 0) logEvent(\"fingerprint-recovered: streak=\" + fingerprintUnreachedStreak)\n finishUnlock()\n } else {\n settleFingerprintAttempt(result === PamResult.Error)\n }\n }\n\n WlSessionLock {\n id: sessionLock\n\n locked: false\n\n onSecureStateChanged: {\n root.logEvent(\"secure=\" + secure)\n if (secure) {\n root.pendingSessionLock = false\n sessionLockStabilizeTimer.stop()\n pendingSessionLockTimer.stop()\n root.startFingerprint()\n }\n }\n\n onLockStateChanged: {\n root.logEvent(\"session-locked=\" + locked)\n\n if (locked) {\n root.pendingSessionLock = false\n sessionLockStabilizeTimer.stop()\n pendingSessionLockTimer.stop()\n }\n\n if (!locked && root.lockRequested) {\n root.lockRequested = false\n root.pendingSessionLock = false\n sessionLockStabilizeTimer.stop()\n pendingSessionLockTimer.stop()\n root.resetAuthenticationState()\n root.runWake()\n }\n }\n\n WlSessionLockSurface {\n id: lockSurface\n color: Commons.Color.background\n\n LockView {\n id: lockView\n anchors.fill: parent\n backgroundPath: root.backgroundPath\n videoPosterPath: root.videoPosterPath\n backgroundVersion: root.backgroundVersion\n fingerprintConfigured: root.fingerprintConfigured || root.fingerprintUnavailable\n fingerprintUnavailable: root.fingerprintUnavailable\n authenticatingPassword: root.authenticatingPassword\n failureMessage: root.failureMessage\n failedAttempts: root.failedAttempts\n inputEnabled: root.lockRequested\n loadBackground: root.locked\n displaysBlank: root.screenBlank(lockSurface.screen ? lockSurface.screen.name : \"\")\n powerSaverActive: root.powerSaverActive\n passwordText: root.enteredPassword\n onPasswordTextEdited: function(password) { root.enteredPassword = password }\n onSubmitPassword: function(password) { root.submitPassword(password) }\n onClearFailureRequested: root.failureMessage = \"\"\n onWakeRequested: root.runWake()\n }\n\n }\n }\n\n PanelWindow {\n id: previewWindow\n visible: root.previewVisible\n anchors { top: true; bottom: true; left: true; right: true }\n color: \"transparent\"\n WlrLayershell.namespace: \"omarchy-lock-preview\"\n WlrLayershell.layer: WlrLayer.Overlay\n WlrLayershell.keyboardFocus: WlrKeyboardFocus.Exclusive\n exclusionMode: ExclusionMode.Ignore\n\n LockView {\n anchors.fill: parent\n backgroundPath: root.backgroundPath\n videoPosterPath: root.videoPosterPath\n backgroundVersion: root.backgroundVersion\n fingerprintConfigured: root.fingerprintConfigured || root.fingerprintUnavailable\n fingerprintUnavailable: root.fingerprintUnavailable\n authenticatingPassword: false\n failureMessage: \"\"\n failedAttempts: 0\n inputEnabled: false\n loadBackground: root.previewVisible\n powerSaverActive: root.powerSaverActive\n passwordText: \"\"\n }\n\n MouseArea {\n anchors.fill: parent\n acceptedButtons: Qt.LeftButton | Qt.RightButton\n onClicked: root.previewVisible = false\n }\n }\n\n PamContext {\n id: passwordPam\n config: \"omarchy-lock-password\"\n user: root.userName\n\n onResponseRequiredChanged: root.respondToPasswordPrompt()\n onPamMessage: root.respondToPasswordPrompt()\n\n onCompleted: function(result) {\n root.authenticatingPassword = false\n root.pendingPassword = \"\"\n\n if (!root.lockRequested) return\n if (result === PamResult.Success) root.finishUnlock()\n else root.handlePasswordFailure()\n }\n\n onError: function(error) {\n root.handlePasswordFailure()\n }\n }\n\n PamContext {\n id: fingerprintPam\n config: \"omarchy-lock-fingerprint\"\n user: root.userName\n\n onPamMessage: {\n if (!messageIsError) root.noteFingerprintReachedDevice()\n }\n\n onCompleted: function(result) {\n root.handleFingerprintFinished(result)\n }\n\n onError: function(error) {\n root.settleFingerprintAttempt(true)\n }\n }\n\n // The lock only starts decoding its wallpaper once locked, and a machine\n // suspending right after locking froze that decode partway: waking showed\n // the password field on a bare background, then the wallpaper popped in.\n // Keep each screen's lock wallpaper decoded in the image cache ahead of\n // time, as the lock view requests it (same URL, the screen's logical size,\n // PreserveAspectCrop), so the lock draws it on its first frame.\n readonly property string lockWallpaperPath: videoBackground ? videoPosterPath : backgroundPath\n readonly property string lockWallpaperUrl: lockWallpaperPath && !Util.isVideoPath(lockWallpaperPath)\n ? Util.fileUrl(lockWallpaperPath) + (backgroundVersion ? \"?v=\" + backgroundVersion : \"\")\n : \"\"\n\n Variants {\n model: Quickshell.screens\n\n Image {\n required property var modelData\n visible: false\n source: root.lockWallpaperUrl\n sourceSize.width: modelData.width\n sourceSize.height: modelData.height\n fillMode: Image.PreserveAspectCrop\n asynchronous: true\n cache: true\n }\n }\n\n Timer {\n id: fingerprintRetryTimer\n interval: FingerprintModel.MATCH_RETRY_MS\n repeat: false\n onTriggered: root.startFingerprint()\n }\n\n // Detect resume both during an active attempt and during backoff.\n Timer {\n id: fingerprintSleepWatch\n interval: 1000\n repeat: true\n running: root.lockRequested && root.fingerprintConfigured\n property double lastTickMs: 0\n onRunningChanged: lastTickMs = Date.now()\n onTriggered: {\n var now = Date.now()\n var slept = FingerprintModel.spannedSleep(now - lastTickMs, interval)\n lastTickMs = now\n if (slept) root.restartFingerprintAfterSleep()\n }\n }\n\n Timer {\n id: fingerprintReachTimer\n interval: FingerprintModel.REACH_TIMEOUT_MS\n repeat: false\n onTriggered: root.timeoutFingerprintReach()\n }\n\n Process {\n id: readlinkProc\n command: [\"bash\", \"-c\", \"path=$(readlink -f -- \\\"$1\\\") && printf '%s\\\\n%s\\\\n' \\\"$path\\\" \\\"$(stat -Lc %Y:%s -- \\\"$path\\\" 2>/dev/null)\\\"\", \"_\", root.currentBackgroundLink]\n stdout: StdioCollector {\n waitForEnd: true\n onStreamFinished: {\n var lines = String(text || \"\").split(\"\\n\")\n var next = String(lines[0] || \"\").trim()\n var signature = String(lines[1] || \"\").trim()\n if (next !== root.backgroundPath) {\n root.videoPosterPath = \"\"\n root.backgroundPath = next\n root.backgroundSignature = signature\n root.backgroundVersion += 1\n } else if (signature !== root.backgroundSignature) {\n root.backgroundSignature = signature\n root.backgroundVersion += 1\n }\n root.refreshPoster()\n }\n }\n }\n\n Process {\n id: posterProc\n property string sourcePath: \"\"\n command: [\"bash\", Quickshell.env(\"OMARCHY_PATH\") + \"/shell/plugins/lock/poster.sh\", sourcePath]\n stdout: StdioCollector { id: posterOutput; waitForEnd: true }\n onExited: function(exitCode) {\n if (sourcePath !== root.backgroundPath) {\n root.refreshPoster()\n } else {\n root.videoPosterPath = exitCode === 0 ? String(posterOutput.text || \"\").trim() : \"\"\n }\n }\n }\n\n // Keep fprintd errors distinguishable from an explicit empty enrollment.\n Process {\n id: fingerprintCheckProc\n command: [\"bash\", \"-c\", \"if [[ -f /etc/pam.d/omarchy-lock-fingerprint ]] && command -v fprintd-list >/dev/null 2>&1; then LC_ALL=C fprintd-list \\\"$USER\\\" 2>&1; else echo no; fi\"]\n stdout: StdioCollector { id: fingerprintCheckStdout; waitForEnd: true }\n onExited: root.applyFingerprintProbe(fingerprintCheckStdout.text)\n }\n\n // Retries a probe that could not reach fprintd, paced like the attempt\n // retries so a daemon that stays unreachable is asked about ever less often.\n Timer {\n id: fingerprintRecheckTimer\n interval: FingerprintModel.ERROR_RETRY_BASE_MS\n repeat: false\n onTriggered: root.refreshFingerprintStatus()\n }\n\n Process {\n id: strandedLockCheckProc\n // $PPID is this shell: a crash re-execs in place, so its pid is the one to skip.\n command: [\"bash\", \"-c\", \"omarchy-hyprland-session-lock-stranded \\\"$PPID\\\"\"]\n onExited: function(exitCode) {\n // No output to read the lock off yet.\n if (exitCode === 2) return\n\n root.strandedLockResolved = true\n\n // A lock taken while this was in flight is this shell's own.\n root.strandedLock = exitCode === 0 && !root.currentlyLocked()\n root.recoverStrandedLock()\n }\n }\n\n Process {\n id: wakeProcess\n command: [\"bash\", \"-c\", \"omarchy-system-wake\"]\n }\n\n Process {\n id: blankProcess\n command: [\"bash\", \"-c\", \"omarchy-brightness-keyboard off; omarchy-brightness-display off\"]\n }\n\n // Quickshell exposes no DPMS signal, so the panel state is polled while a\n // video is the locked wallpaper. A wake or blank request drops the last\n // answer, so its optimistic state applies until the next poll confirms it.\n Process {\n id: monitorDpmsProcess\n command: [\"hyprctl\", \"monitors\", \"-j\"]\n stdout: StdioCollector {\n onStreamFinished: root.applyMonitorDpms(text)\n }\n }\n\n Timer {\n id: monitorDpmsTimer\n interval: 3000\n repeat: true\n triggeredOnStart: true\n running: root.locked && root.videoBackground\n onTriggered: {\n if (!monitorDpmsProcess.running) monitorDpmsProcess.running = true\n }\n onRunningChanged: {\n if (!running) root.monitorDpmsKnown = false\n }\n }\n\n Timer {\n id: idleBlankTimer\n interval: 5000\n repeat: false\n property double armedAt: 0\n onTriggered: {\n // A countdown frozen by suspend fires right after resume, which would\n // blank the freshly woken unlock screen under the user. Wall-clock time\n // exposes the gap: take a fresh run-up instead of blanking.\n if (Date.now() - armedAt > interval + 2000) {\n root.armBlankTimer()\n return\n }\n // Only a password check in flight should hold the display up. The\n // fingerprint PAM stays armed for the whole lock, so gating on\n // `authenticating` here would keep the panel lit until unlock.\n if (root.lockRequested && !root.authenticatingPassword) root.runBlank()\n }\n }\n\n Timer {\n id: sessionLockStabilizeTimer\n interval: 500\n repeat: false\n onTriggered: root.requestSessionLock()\n }\n\n Timer {\n id: pendingSessionLockTimer\n interval: 100\n repeat: true\n onTriggered: root.requestSessionLock()\n }\n\n Timer {\n id: strandedLockRetryTimer\n interval: 500\n repeat: true\n // Covers the compositor settling; screens coming back re-arm it.\n readonly property int budget: 20\n property int remaining: 20\n running: !root.strandedLockResolved && remaining > 0\n\n function rearm() {\n if (!root.strandedLockResolved) remaining = budget\n }\n\n onTriggered: {\n remaining -= 1\n root.checkStrandedLock()\n }\n }\n\n Connections {\n target: Quickshell\n function onScreensChanged() {\n // A panel coming back is a display turning on that runWake did not ask\n // for, so the blank state has to be given up here or a visible lock\n // wallpaper stays frozen until the next keypress.\n root.displaysBlank = false\n root.requestSessionLock()\n\n // A monitor still coming up has no workspace, so cannot answer yet.\n strandedLockRetryTimer.rearm()\n root.checkStrandedLock()\n }\n }\n\n onAuthenticatingPasswordChanged: {\n if (!lockRequested) return\n if (authenticatingPassword) idleBlankTimer.stop()\n else armBlankTimer()\n }\n\n FileView {\n path: \"/etc/pam.d/omarchy-lock-password\"\n watchChanges: true\n printErrors: false\n onLoaded: root.passwordPamConfigured = true\n onLoadFailed: root.passwordPamConfigured = false\n onFileChanged: reload()\n }\n\n // No lock before PAM is known good. An answer from before then may be stale --\n // the failsafe can be cleared from a TTY -- so re-ask rather than act on it.\n onPasswordPamConfiguredChanged: {\n if (!passwordPamConfigured) return\n\n strandedLock = false\n strandedLockResolved = false\n strandedLockRetryTimer.rearm()\n checkStrandedLock()\n }\n\n Component.onCompleted: {\n refreshBackground()\n refreshFingerprintStatus()\n checkStrandedLock()\n }\n\n ShellIpc {\n target: \"lock\"\n\n function lock(): string {\n if (!root.passwordPamConfigured) return \"missing-pam\"\n if (!root.currentlyLocked() && !root.beginLock()) return \"failed\"\n return \"ok\"\n }\n\n function isLocked(): string {\n return root.currentlyLocked() ? \"true\" : \"false\"\n }\n\n function status(): string {\n return JSON.stringify({\n locked: root.currentlyLocked(),\n requested: root.lockRequested,\n pending: root.pendingSessionLock,\n sessionLocked: sessionLock.locked,\n secure: sessionLock.secure,\n realScreens: root.realScreenCount(),\n passwordPam: root.passwordPamConfigured,\n fingerprint: root.fingerprintConfigured,\n fingerprintUnavailable: root.fingerprintUnavailable,\n authenticating: root.authenticating,\n lastEvent: root.lastEvent,\n lastEventAt: root.lastEventAt\n })\n }\n\n function preview(): string {\n root.refreshBackground()\n root.refreshFingerprintStatus()\n root.previewVisible = true\n return \"ok\"\n }\n\n function hidePreview(): string {\n root.previewVisible = false\n return \"ok\"\n }\n }\n}\n```\n\n### poster.sh\n```bash\n#!/bin/bash\n\n# One cached frame shared by all lock outputs, including when OWE is paused.\nset -euo pipefail\n\nsource_path=$1\ncache_dir=\"${XDG_CACHE_HOME:-$HOME/.cache}/omarchy/lock-poster\"\nsignature=$(stat -Lc '%s:%y:%z' \"$source_path\")\nkey=$(printf '%s\\n%s' \"$source_path\" \"$signature\" | sha256sum | cut -d ' ' -f 1)\nposter=\"$cache_dir/poster-$key.jpg\"\nmkdir -p \"$cache_dir\"\nexec {lock_fd}>\"$cache_dir/.lock\"\nflock -w 10 \"$lock_fd\"\n\nif [[ ! -s $poster ]]; then\n temporary=$(mktemp \"$cache_dir/.poster-XXXXXX.jpg\")\n trap 'rm -f \"$temporary\"' EXIT\n timeout -k 1 5 ffmpegthumbnailer -i \"$source_path\" -o \"$temporary\" -s 1920 -q 8 {lock_fd}>&-\n [[ -s $temporary ]]\n mv -f \"$temporary\" \"$poster\"\n find \"$cache_dir\" -maxdepth 1 -type f -name 'poster-*.jpg' ! -name \"poster-$key.jpg\" -delete\nfi\n\nprintf '%s\\n' \"$poster\"\n```"}], "task": "build_from_spec", "meta": {"origin": "first-party", "repo": "https://github.com/basecamp/omarchy", "commit": "9480d1b6a98156314dbabe6bfef08f39f8b9cd07", "license": "MIT", "plugin_path": "shell/plugins/lock", "kinds": ["service"], "complexity": "large", "group": "be0fe0eb", "validator": "pass", "qmllint": "clean", "qml_files": 3, "chars": 45720, "tokens": 10945, "split": "train"}} {"messages": [{"role": "system", "content": "You are an Omarchy plugin expert. You write complete, valid Omarchy (Quattro / omarchy-shell, Quickshell QML) plugins. Manifests use schemaVersion 1, a namespaced id that never uses the reserved omarchy.* namespace, name, version, kinds (bar-widget|panel|overlay|menu|service|bar) with a matching safe relative entryPoints path for every kind, and no symlinks. Return every file in full as '### path' followed by a fenced code block."}, {"role": "user", "content": "Write a complete Omarchy plugin `acme.menu` called \"Omarchy menu\" (menu, bar-widget). Quickshell-powered Omarchy command menu. (It's a third-party plugin, so don't use the reserved omarchy.* namespace.)"}, {"role": "assistant", "content": "### manifest.json\n```json\n{\n \"schemaVersion\": 1,\n \"id\": \"acme.menu\",\n \"name\": \"Omarchy menu\",\n \"version\": \"1.0.0\",\n \"author\": \"Omarchy\",\n \"description\": \"Quickshell-powered Omarchy command menu\",\n \"kinds\": [\n \"menu\",\n \"bar-widget\"\n ],\n \"keepLoaded\": true,\n \"entryPoints\": {\n \"menu\": \"Menu.qml\",\n \"barWidget\": \"BarWidget.qml\"\n },\n \"barWidget\": {\n \"displayName\": \"Omarchy menu\",\n \"description\": \"Launches the Omarchy menu\",\n \"category\": \"Compositor\",\n \"allowMultiple\": false\n }\n}\n```\n\n### BarWidget.qml\n```qml\nimport QtQuick\nimport qs.Ui\n\nBarWidget {\n id: root\n moduleName: \"omarchy.menu\"\n\n implicitWidth: button.implicitWidth\n implicitHeight: button.implicitHeight\n\n BarIconButton {\n id: button\n anchors.fill: parent\n bar: root.bar\n text: \"\\ue900\"\n fontFamily: \"omarchy\"\n onPressed: function(button) {\n if (!root.bar) return\n if (button === Qt.RightButton) root.bar.run(\"xdg-terminal-exec\")\n else root.bar.run(\"omarchy-shell shell toggle omarchy.menu '{\\\"menu\\\":\\\"root\\\"}'\")\n }\n }\n}\n```\n\n### Menu.qml\n```qml\nimport Quickshell\nimport Quickshell.Io\nimport Quickshell.Wayland\nimport QtQuick\nimport qs.Commons\nimport qs.Commons as Commons\nimport qs.Ui\nimport \"MenuModel.js\" as MenuModel\n\nItem {\n id: root\n\n // Injected by omarchy-shell when this plugin is summoned.\n property string omarchyPath: Quickshell.env(\"OMARCHY_PATH\")\n property var shell: null\n property var manifest: null\n\n // Plugin lifecycle hooks. The host calls open(payloadJson) after\n // `omarchy-shell shell summon omarchy.menu ...` and close() when hidden.\n property string pendingInitialMenu: \"root\"\n\n function open(payloadJson) {\n var payload = ({})\n try { payload = JSON.parse(payloadJson || \"{}\") } catch (e) { payload = ({}) }\n\n if (payload.fontFamily) root.fontFamily = payload.fontFamily\n\n if (payload.mode === \"select\" || payload.mode === \"input\") {\n root.openDmenu(payload)\n } else {\n root.openRoute(payload.initialMenu || payload.menu || \"root\")\n }\n }\n\n function close() {\n root.cancel()\n }\n\n function refresh() {\n defaultMenuFile.reload()\n userMenuFile.reload()\n return \"ok\"\n }\n\n function ping() { return \"ok\" }\n\n property string fontFamily: Style.font.menuFamily\n // JSONC menu definitions. The shell parses both at startup and merges\n // the user file on top of the defaults, so the keybind → IPC → visible\n // path doesn't have to shell out to bash + jq on every open.\n property string defaultMenuPath: omarchyPath + \"/default/omarchy/omarchy-menu.jsonc\"\n property string userMenuPath: Quickshell.env(\"HOME\") + \"/.config/omarchy/extensions/omarchy-menu.jsonc\"\n property var defaultMenuItems: []\n property var userMenuItems: []\n property bool opened: false\n property string mode: \"menu\"\n readonly property bool dmenuActive: mode === \"select\" || mode === \"input\"\n property string dmenuPrompt: \"\"\n property var dmenuOptions: []\n property bool dmenuMultiple: false\n property var dmenuSelected: []\n // What the last confirmed change applied; a failed change returns the checks here.\n property var dmenuSaved: []\n property string dmenuChangeKey: \"\"\n property var dmenuOnChange: []\n property string selectionFile: \"\"\n property string doneFile: \"\"\n property int dmenuWidth: 300\n property int dmenuMaxHeight: 0\n property bool requestActive: false\n property bool rowsLoaded: false\n property string activeMenu: \"root\"\n property string filterText: \"\"\n property int selectedIndex: 0\n property bool cursorActive: false\n property int requestSerial: 0\n property int applySerial: 0\n property var items: ({})\n property var itemOrder: []\n property var navStack: []\n property var providersLoaded: ({})\n property var providerQueue: []\n property int providerRevision: 0\n\n // Shared application engine (entries, hidden filters, icons, launch,\n // removal), owned by the shell and also used by the standalone launcher.\n readonly property var appLibrary: root.shell ? root.shell.appLibrary : null\n property bool deleteConfirmOpen: false\n property var deleteTarget: null\n onOpenedChanged: if (!opened) { deleteConfirmOpen = false; deleteTarget = null }\n // Bound to the central [menu] section in shell.toml via Commons.Color.qml.\n // Each color already includes its alpha companion (composed in the\n // singleton), so consumers can drop them straight into a Rectangle.\n property color background: Commons.Color.menu.background\n property color foreground: Commons.Color.menu.text\n property color border: Commons.Color.menu.border\n property var borderSpec: Border.surfaceSpec(\"menu\", \"border\", border, Math.max(1, Style.space(2)))\n property color scrim: Commons.Color.menu.scrim\n property color selectedBackground: Commons.Color.menu.selectedBackground\n property color selectedText: Commons.Color.menu.selectedText\n property color selectedBorder: Commons.Color.menu.selectedBorder\n property var selectedBorderSpec: Border.surfaceSpec(\"menu\", \"selected-border\", selectedBorder, 0)\n readonly property real rowReservedBorderLeft: Border.left(selectedBorderSpec)\n readonly property real rowReservedBorderRight: Border.right(selectedBorderSpec)\n readonly property int cornerRadius: Style.cornerRadius\n property int contentMargin: Style.spacing.panelPadding\n property int headerHeight: Math.max(Style.space(34), Style.font.title + Style.spacing.controlPaddingY * 2)\n property int contentSpacing: Style.spacing.md\n property int baseRowHeight: Math.max(Style.space(50), Style.font.body + Style.spacing.rowPaddingX * 2)\n property int detailRowHeight: Math.max(Style.space(58), Style.font.body + Style.font.caption + Style.spacing.rowPaddingX * 2)\n // How much of the first hidden row stays visible at the fold — enough to\n // read as a cut-off row rather than a bottom border.\n property int rowPeek: Math.round(baseRowHeight * 0.55)\n property int rowSpacing: Style.spacing.xs\n property int dividerHeight: Style.space(17)\n property bool searchDivider: false\n property int layoutSerial: 0\n property int cardWidth: Math.min(root.dmenuActive ? Style.space(root.dmenuWidth) : ((root.activeMenu === \"trigger.capture.screenrecord\" || root.activeMenu === \"style.font\") ? Style.space(520) : Style.space(300)), panel.width - Style.gapsOut * 2)\n property int visibleRowsHeight: root.dmenuActive ? dmenuRowListHeight(layoutSerial, displayModel.count, filterText) : rowListHeight(layoutSerial, displayModel.count, filterText, searchDivider)\n property int cardHeight: root.dmenuActive\n ? Math.min(contentMargin * 2 + headerHeight + (mode === \"input\" ? 0 : contentSpacing + visibleRowsHeight), panel.height - Style.gapsOut * 2)\n : Math.min(contentMargin * 2 + headerHeight + contentSpacing + visibleRowsHeight, panel.height - Style.gapsOut * 2)\n\n function finishRequest(selection) {\n if (!root.requestActive || !root.doneFile) {\n root.opened = false\n return\n }\n\n var activeSelectionFile = root.selectionFile\n var activeDoneFile = root.doneFile\n root.requestActive = false\n root.selectionFile = \"\"\n root.doneFile = \"\"\n\n if (selection === null || selection === undefined) {\n resultProc.command = [\"bash\", \"-c\", \": > \" + Util.shellQuote(activeDoneFile)]\n } else {\n resultProc.command = [\"bash\", \"-c\", \"printf '%s\\\\n' \" + Util.shellQuote(selection) + \" > \" + Util.shellQuote(activeSelectionFile) + \"; : > \" + Util.shellQuote(activeDoneFile)]\n }\n resultProc.running = true\n }\n\n function runAction(action) {\n var command = String(action || \"\")\n if (!command) return\n\n var summon = MenuModel.summonAction(command)\n if (summon && root.shell && root.shell.summon(summon.id, summon.payload)) return\n\n Util.execDetached(command)\n }\n\n // Menu rows only surface their detail while a search is narrowing them;\n // dmenu rows carry caller-supplied subtext that must always be visible.\n function rowHeightForDetail(detail) {\n return (root.filterText || root.dmenuActive) && detail ? root.detailRowHeight : root.baseRowHeight\n }\n\n // Height the card can devote to rows before running off the screen — or\n // past the frozen top edge once a search has pinned the card in place.\n // Uses panel.cardTop rather than effectiveCardTop: the centered top is\n // derived from the card height, which this value feeds.\n function availableRowsHeight() {\n var top = panel.cardTop >= 0 ? panel.cardTop : Style.gapsOut\n var available = panel.height - top - Style.gapsOut - root.contentMargin * 2 - root.headerHeight - root.contentSpacing\n // The starting menu sets the ceiling along with the offset: drilling into\n // a longer submenu scrolls behind the fold instead of growing the card.\n if (panel.maxRowsHeight >= 0) available = Math.min(available, panel.maxRowsHeight)\n // A card that swallows the whole screen reads as a page, not a menu.\n return Math.min(available, Math.round(panel.height * 0.7))\n }\n\n // When every row fits, the list gets its full height. When they don't,\n // the card must end mid-row: a clipped row is what tells the eye there is\n // more below the fold, so never come out even on a row boundary.\n function foldedListHeight(totals, available) {\n var count = totals.length\n if (count === 0) return root.baseRowHeight\n if (totals[count - 1] <= available) return totals[count - 1]\n\n var peek = root.rowPeek\n var full = 0\n while (full < count && totals[full] <= available) full++\n while (full > 1 && totals[full - 1] + root.rowSpacing + peek > available) full--\n if (full < 1) return Math.max(available, root.baseRowHeight)\n\n return totals[full - 1] + root.rowSpacing + peek\n }\n\n function rowListHeight(_serial, _count, _filter, _divider) {\n if (displayModel.count === 0) return root.baseRowHeight\n\n var totals = []\n var total = 0\n var previousSection = \"\"\n\n for (var i = 0; i < displayModel.count; i++) {\n var row = displayModel.get(i)\n if (i > 0) total += root.rowSpacing\n if (row.section === \"drilldown\" && previousSection !== \"drilldown\") total += root.dividerHeight\n total += root.rowHeightForDetail(row.detail)\n previousSection = row.section\n totals.push(total)\n }\n\n return foldedListHeight(totals, availableRowsHeight())\n }\n\n function dmenuRowListHeight(_serial, _count, _filter) {\n if (root.mode === \"input\") return 0\n if (displayModel.count === 0) return root.baseRowHeight\n\n var available = availableRowsHeight()\n if (root.dmenuMaxHeight > 0) available = Math.min(available, Style.space(root.dmenuMaxHeight))\n\n var totals = []\n var total = 0\n for (var i = 0; i < displayModel.count; i++) {\n if (i > 0) total += root.rowSpacing\n total += root.rowHeightForDetail(displayModel.get(i).detail)\n totals.push(total)\n }\n\n return foldedListHeight(totals, available)\n }\n\n function item(id) {\n return root.items[id] || null\n }\n\n // ------------------------------------------------------------------\n // JSONC → normalized item array. Mirrors the bash bin's jq pipeline so\n // the on-disk authoring format stays untouched.\n // ------------------------------------------------------------------\n\n function stripJsonc(raw) {\n return MenuModel.stripJsonc(raw)\n }\n\n function normalizeAliases(value) {\n return MenuModel.normalizeAliases(value)\n }\n\n function normalizeItem(id, raw) {\n return MenuModel.normalizeItem(id, raw)\n }\n\n function parseMenuJsonc(raw) {\n return MenuModel.parseMenuJsonc(raw)\n }\n\n // Merge defaults + user extension. Later entries override earlier ones\n // on a per-key basis (so the user can tweak label/icon/action without\n // re-declaring the whole row).\n function rebuildItemsFromSources() {\n var mergedMenu = MenuModel.mergeMenuSources(root.defaultMenuItems, root.userMenuItems)\n root.providerRevision += 1\n root.providersLoaded = ({})\n root.providerQueue = []\n root.items = mergedMenu.items\n root.itemOrder = mergedMenu.itemOrder\n root.rowsLoaded = true\n root.evaluateGuards()\n if (root.opened) {\n root.rebuildDisplay()\n if (!root.dmenuActive) {\n if (root.filterText.trim()) root.loadProvidersForSearch()\n else root.loadProviderForMenu(root.activeMenu)\n }\n }\n }\n\n // Each known provider is a tiny bash one-liner that enumerates a list and\n // emits one tab-delimited row per item: `label\\tvalue\\tcurrent`. The shell\n // turns those into menu items children of `menuId`. A `volatile` provider\n // re-runs every time its submenu is entered, so a font installed since the\n // shell started shows up without restarting it.\n readonly property var providers: ({\n \"fonts\": {\n script: \"current=$(omarchy-font-current 2>/dev/null); omarchy-font-list 2>/dev/null | while read -r f; do [[ -z $f ]] && continue; printf '%s\\\\t%s\\\\t%s\\\\n' \\\"$f\\\" \\\"$f\\\" \\\"$current\\\"; done\",\n icon: \"\",\n volatile: true,\n actionFor: function(value) { return \"omarchy-font-set \" + Util.shellQuote(value) }\n },\n \"power-profiles\": {\n script: \"current=$(powerprofilesctl get 2>/dev/null); omarchy-powerprofiles-list 2>/dev/null | while read -r p; do [[ -z $p ]] && continue; printf '%s\\\\t%s\\\\t%s\\\\n' \\\"$p\\\" \\\"$p\\\" \\\"$current\\\"; done\",\n icon: \"\\udb81\\udc0b\",\n actionFor: function(value) { return \"omarchy-powerprofiles-set autodetect \" + Util.shellQuote(value) }\n }\n })\n\n function slugify(value) {\n return MenuModel.slugify(value)\n }\n\n // The apps provider is QML-native: rows come from the shared AppLibrary\n // (DesktopEntries) instead of a bash enumeration, so they carry image\n // icons, launch feedback, and uninstall support like the launcher.\n function mergeAppRows() {\n if (!root.appLibrary) return\n\n var rows = root.appLibrary.sortedEntries(\"\")\n var appRows = []\n for (var j = 0; j < rows.length; j++) {\n var entry = rows[j].entry\n var appId = String(entry.id || \"\")\n if (!appId) continue\n var subtext = root.appLibrary.entrySubtext(entry)\n var aliases = subtext ? [subtext] : []\n try {\n if (entry.keywords && typeof entry.keywords.join === \"function\") aliases = aliases.concat(entry.keywords)\n } catch (e) { }\n appRows.push({\n id: \"apps.\" + appId,\n parent: \"apps\",\n kind: \"app\",\n icon: \"\",\n appIcon: String(entry.icon || \"\"),\n appId: appId,\n label: root.appLibrary.entryName(entry),\n title: \"\",\n target: \"\",\n description: subtext,\n action: \"\",\n provider: \"\",\n aliases: aliases,\n when: \"\",\n checked: \"\",\n disabled: \"\",\n order: 0\n })\n }\n\n var merged = MenuModel.mergeAppRows(root.items, root.itemOrder, appRows)\n root.items = merged.items\n root.itemOrder = merged.itemOrder\n if (root.opened) root.rebuildDisplay()\n }\n\n function startProviderForMenu(id) {\n var entry = root.item(id)\n if (!entry || !entry.provider || root.providersLoaded[id]) return\n if (entry.provider === \"apps\") {\n root.providersLoaded[id] = true\n root.mergeAppRows()\n return\n }\n var spec = root.providers[entry.provider]\n if (!spec) return\n\n root.providersLoaded[id] = true\n providerProc.menuId = id\n providerProc.providerKey = entry.provider\n providerProc.revision = root.providerRevision\n providerProc.collected = \"\"\n providerProc.command = [\"bash\", \"-lc\", spec.script]\n providerProc.running = true\n }\n\n function mergeProviderRows(rows, menuId, providerKey) {\n var spec = root.providers[providerKey]\n if (!spec) return\n var lines = String(rows || \"\").split(\"\\n\")\n var providerRows = []\n var takenIds = ({})\n for (var i = 0; i < lines.length; i++) {\n var line = lines[i].trim()\n if (!line) continue\n var parts = line.split(\"\\t\")\n var label = parts[0] || \"\"\n var value = parts[1] || parts[0] || \"\"\n var current = parts[2] || \"\"\n if (!label) continue\n // Distinct values can slugify alike — Fira Code and Fira-Code both give\n // fira-code — and a repeated id is dropped, which would silently lose a\n // row from the list. Nudge it until it is the row's own.\n var rowId = menuId + \".\" + root.slugify(value)\n while (takenIds[rowId]) rowId += \"-\"\n takenIds[rowId] = true\n\n providerRows.push({\n id: rowId,\n parent: menuId,\n kind: \"action\",\n icon: (value === current) ? \"✓\" : (spec.icon || \"\"),\n label: label,\n title: \"\",\n target: \"\",\n description: \"\",\n action: spec.actionFor(value),\n provider: \"\",\n aliases: [],\n when: \"\",\n checked: \"\",\n disabled: \"\",\n order: 0\n })\n }\n var merged = MenuModel.swapProviderRows(root.items, root.itemOrder, menuId, providerRows)\n root.items = merged.items\n root.itemOrder = merged.itemOrder\n if (root.opened) root.rebuildDisplay()\n }\n\n function startNextProvider() {\n if (providerProc.running) return\n\n while (root.providerQueue.length > 0) {\n var id = root.providerQueue.shift()\n var entry = root.item(id)\n if (!entry || !entry.provider || root.providersLoaded[id]) continue\n\n root.startProviderForMenu(id)\n return\n }\n }\n\n // Entering a submenu is the one moment a volatile list is worth paying for\n // again: it may have been reshaped by the last pick from it. Search doesn't\n // invalidate, or every keystroke would restart the same enumeration.\n function invalidateVolatileProvider(id) {\n var entry = root.item(id)\n var spec = entry && entry.provider ? root.providers[entry.provider] : null\n if (spec && spec.volatile) root.providersLoaded[id] = false\n }\n\n function loadProviderForMenu(id) {\n var entry = root.item(id)\n if (!entry || !entry.provider || root.providersLoaded[id]) return\n\n // Native providers don't touch providerProc, so they never need to queue.\n if (entry.provider === \"apps\") {\n root.startProviderForMenu(id)\n return\n }\n\n if (providerProc.running) {\n if (root.providerQueue.indexOf(id) < 0) root.providerQueue = root.providerQueue.concat([id])\n return\n }\n\n root.startProviderForMenu(id)\n }\n\n function loadProvidersForSearch() {\n var active = root.item(root.activeMenu) ? root.activeMenu : \"root\"\n\n for (var i = 0; i < root.itemOrder.length; i++) {\n var entry = root.item(root.itemOrder[i])\n if (!entry || !entry.provider || root.providersLoaded[entry.id]) continue\n if (active !== \"root\" && entry.id !== active && !root.isDescendantOf(entry.id, active)) continue\n\n root.loadProviderForMenu(entry.id)\n }\n }\n\n function depthFor(id) {\n return MenuModel.depthFor(root.items, id)\n }\n\n function pathFor(id) {\n return MenuModel.pathFor(root.items, id)\n }\n\n function parentPathFor(id) {\n return MenuModel.parentPathFor(root.items, id)\n }\n\n function isDescendantOf(id, ancestorId) {\n return MenuModel.isDescendantOf(root.items, id, ancestorId)\n }\n\n function childCount(id) {\n return MenuModel.childCount(root.items, root.itemOrder, id)\n }\n\n // Guarded items are hidden when their `when:` evaluates false. Static\n // submenus are also hidden when none of their descendants are visible;\n // provider-backed menus stay visible because their rows load on demand.\n function isVisible(entry) {\n return MenuModel.isVisible(root.items, root.itemOrder, root.whenResults, entry)\n }\n\n // Label with the ✓ marker baked in when `checked:` or `disabled:` evaluated\n // truthy.\n function labelFor(entry) {\n return MenuModel.labelFor(entry, root.checkedResults, root.disabledResults)\n }\n\n function searchableToken(value) {\n return MenuModel.searchableToken(value)\n }\n\n function leafIdFor(id) {\n return MenuModel.leafIdFor(id)\n }\n\n function nameSearchText(entry) {\n return MenuModel.nameSearchText(entry)\n }\n\n function termInSearchWords(term, text) {\n return MenuModel.termInSearchWords(term, text)\n }\n\n function descriptionTextMatches(query, text) {\n return MenuModel.descriptionTextMatches(query, text)\n }\n\n // Rows whose `disabled:` evaluated truthy stay listed but dimmed, and the\n // cursor steps over them.\n function isDisabled(entry) {\n return MenuModel.isDisabled(root.disabledResults, entry)\n }\n\n // A disabled row earns its place in the submenu it belongs to, where the\n // list around it is the point. Search is a list of what you can do, so it\n // leaves them out.\n function matchesQuery(entry, query) {\n return MenuModel.matchesQuery(entry, query, root.isVisible(entry) && !root.isDisabled(entry))\n }\n\n function searchScore(entry, query) {\n return MenuModel.searchScore(root.items, entry, query)\n }\n\n function displayRow(entry, detail, score, section) {\n return MenuModel.displayRow(root.items, root.itemOrder, root.checkedResults, root.disabledResults, entry, detail, score, section)\n }\n\n function rowSelectable(index) {\n if (index < 0 || index >= displayModel.count) return false\n return !displayModel.get(index).disabled\n }\n\n // First selectable row at or past `from`, continuing in the direction of\n // travel and wrapping. -1 when every row is disabled, which leaves the menu\n // with no cursor at all rather than one parked on a row Enter won't run.\n function nextSelectable(from, direction) {\n var count = displayModel.count\n if (count === 0) return -1\n\n var step = direction < 0 ? -1 : 1\n var index = ((from % count) + count) % count\n for (var i = 0; i < count; i++) {\n if (root.rowSelectable(index)) return index\n index = (index + step + count) % count\n }\n\n return -1\n }\n\n // Park the cursor on a selectable row after the rows underneath it changed.\n // A menu with nothing selectable in it -- every app in it already installed\n // -- shows no cursor at all, and grows one the moment a row can take it.\n function settleCursor() {\n var target = root.nextSelectable(root.selectedIndex, 1)\n root.selectedIndex = target >= 0 ? target : 0\n root.cursorActive = target >= 0\n }\n\n function rebuildDmenuDisplay() {\n displayModel.clear()\n root.searchDivider = false\n\n if (root.mode === \"input\") {\n layoutSerial += 1\n return\n }\n\n if (root.dmenuMultiple && root.dmenuOnChange.length === 0) {\n displayModel.append({\n itemId: \"dmenu.apply\", disabled: false, kind: \"dmenu\", icon: \"\", iconFont: \"\",\n appIcon: \"\", appId: \"\", label: \"Apply\", target: \"\",\n detail: root.dmenuSelected.length + \" selected\", path: \"\", childCount: 0,\n action: \"\", provider: \"\", score: -1, section: \"\"\n })\n }\n var query = root.filterText.trim().toLowerCase()\n for (var i = 0; i < root.dmenuOptions.length; i++) {\n // An option is \"