diff --git a/Backend.qml b/Backend.qml index 65eba4a..719dc52 100644 --- a/Backend.qml +++ b/Backend.qml @@ -12,6 +12,7 @@ import "core/FleaSearch.js" as FleaSearch import "core/Frecency.js" as Frecency import "core/OmarchyMenu.js" as OmarchyMenu import "core/RootSearch.js" as RootSearch +import "core/Quicklinks.js" as Quicklinks import "core/Calculator.js" as Calculator import "core/ClipboardHistory.js" as ClipboardHistory import "core/Themes.js" as Themes @@ -35,7 +36,7 @@ Item { readonly property var registry: Rpc.createRegistry() readonly property double startedAt: Date.now() - readonly property var deps: ({ Ranker: Ranker, Frecency: Frecency, OmarchyMenu: OmarchyMenu }) + readonly property var deps: ({ Ranker: Ranker, Frecency: Frecency, OmarchyMenu: OmarchyMenu, Quicklinks: Quicklinks }) property var candidates: [] property var candidatesById: ({}) @@ -114,6 +115,7 @@ Item { for (var i = 0; i < apps.length; i++) if (apps[i] && apps[i].id) next.push(RootSearch.appCandidate(apps[i])) next = next.concat(RootSearch.menuCandidates(menuSource.tree, menuSource.guards, menuSource.providerItems, backend.deps)) for (var b = 0; b < RootSearch.BUILTINS.length; b++) next.push(RootSearch.builtinCandidate(RootSearch.BUILTINS[b])) + if (quicklinksStore.loaded) next = next.concat(Quicklinks.list(quicklinksStore.doc).map(Quicklinks.toCandidate)) // A built-in that replaces an Omarchy command hides that command. var superseded = ({}) RootSearch.BUILTINS.forEach(function(d) { (d.supersedes || []).forEach(function(id) { superseded[id] = true }) }) @@ -512,10 +514,13 @@ Item { return { close: true } } backend.recordVisit(id, query) + if (candidate.run.quicklinks) return backend.quicklinksCommand(candidate.run.quicklinks) if (candidate.run.push && candidate.run.push.kind === "theme") themeSource.refresh() if (candidate.run.push) return { push: candidate.run.push } if (candidate.run.summon) backend.summonPlugin(candidate.run.summon, candidate.run.payload || "{}") return { close: true } + case "quicklink": + return backend.openQuicklink(candidate.quicklinkId, (data && data.arguments) || {}, query) case "fallback": Util.execArgv(["omarchy-launch-browser", RootSearch.fallbackUrl(candidate, query)]) return { close: true } @@ -544,6 +549,21 @@ Item { case "open-in-omarchy-menu": backend.summonPlugin("omarchy.menu", JSON.stringify({ menu: backend.omarchyRouteFor(candidate) })) return { close: true } + case "edit-quicklink": + var editing = Quicklinks.get(quicklinksStore.doc, candidate.quicklinkId) + return { push: backend.quicklinkForm("Edit Quicklink", editing) } + case "copy-link": + clipboard.copy(Quicklinks.get(quicklinksStore.doc, candidate.quicklinkId).link) + return { close: true, hud: "Copied to Clipboard" } + case "delete-quicklink": + // The confirm alert, as for the other destructive actions [O]. + if (!(data && data.confirmed)) return { confirm: { + title: "Delete Quicklink", destructive: true, primary: "Delete", + message: "Delete “" + candidate.title + "”? This also removes its alias, favourite and ranking." + } } + var deleted = backend.callSync("quicklinks.delete", { id: candidate.quicklinkId }) + if (!deleted.ok) throw new Error(deleted.error) + return { toast: { style: "success", title: "Quicklink deleted" } } case "copy-command": case "copy-id": clipboard.copy(action === "copy-id" ? candidate.appId + ".desktop" : candidate.action) @@ -583,6 +603,172 @@ Item { throw new Error("Unknown action " + action) } + // ------------------------------------------------------------ quicklinks + + function installedApps() { + // Every app with a desktop entry, even one hidden from search; not + // NoDisplay handlers, which are not meant to be launched by hand. + return Quicklinks.installedApps((DesktopEntries.applications.values || []).filter(function(e) { return !e.noDisplay })) + } + + // Month and day names for {date}; "" is the system locale. + function localeNames(name) { + var locale = name ? Qt.locale(name) : Qt.locale() + return { + month: function(i, long) { return locale.monthName(i, long ? Locale.LongFormat : Locale.ShortFormat) }, + day: function(i, long) { return locale.dayName(i, long ? Locale.LongFormat : Locale.ShortFormat) } + } + } + + // The Name / Link / Open With form; `item` is null when creating. + function quicklinkForm(title, item) { + var value = item || {} + return { + kind: "quicklink-form", + title: title, + quicklinkId: item && item.id ? item.id : "", + focus: 0, + fields: [ + { key: "name", label: "Name", value: value.name || "", placeholder: "Quicklink name" }, + { key: "link", label: "Link", value: value.link || "", placeholder: "https://google.com/search?q={argument}" }, + { key: "openWith", label: "Open With", value: value.openWith || "", picker: true } + ] + } + } + + function quicklinksCommand(name) { + if (name === "create") { + // A URL or path on the clipboard fills an untouched form when it arrives. + if (!pasteProc.running) backend.paste(false, function(text) { + var suggested = Quicklinks.suggestion(text) + if (suggested) backend.emit("quicklinks.autofill", suggested) + }) + return { push: backend.quicklinkForm("Create Quicklink", null) } + } + if (name === "search") return { push: { kind: "quicklinks", title: "Search Quicklinks" } } + if (name === "import") return { push: { kind: "quicklink-import", title: "Import Quicklinks" } } + return backend.exportQuicklinks() + } + + function storeQuicklinks(doc) { + // Only items: the store keeps schemaVersion and schemaHistory beside them. + if (!quicklinksStore.update(function(stored) { stored.items = doc.items })) throw new Error("quicklinks are read-only: " + (quicklinksStore.lastError || "written by a newer build")) + backend.rebuildCandidates() + } + + // Arguments first (a form), then the clipboard or selection, then open. + // values come from the launcher's argument pills, by name. + function openQuicklink(id, values, query) { + var item = Quicklinks.get(quicklinksStore.doc, id) + if (!item) return { toast: { style: "failure", title: "Quicklink not found" } } + var parsed = Quicklinks.parseLink(item.link) + if (parsed.error) return { toast: { style: "failure", title: parsed.error } } + var missing = parsed.arguments.some(function(a) { return !a.defaultValue && !String(values[a.name] || "").trim() }) + if (!missing) return backend.launchQuicklink(item, values, query) + // `omacast run` without values: the launcher focuses the empty pill. + return { arguments: { id: "quicklink:" + item.id, title: item.name } } + } + + function launchQuicklink(item, values, query) { + var parsed = Quicklinks.parseLink(item.link) + var args = parsed.error ? parsed : Quicklinks.argumentValues(parsed, values) + if (args.error) return { toast: { style: "failure", title: args.error } } + var ctx = { now: Date.now(), values: args.values, clipboard: "", selection: "", uuid: Quicklinks.randomUuid(), names: backend.localeNames } + if (!parsed.needsClipboard && !parsed.needsSelection) return backend.finishLaunch(item, ctx, query) + if (pasteProc.running) return { toast: { style: "failure", title: "Still reading the clipboard" } } + // Read what the link needs, then open. The launcher has closed by then, + // so a failure becomes a notification. + var notifyFailure = function(title, message) { + backend.log("warning", "quicklinks", title + ": " + message) + Quickshell.execDetached(["notify-send", "--app-name=omacast", title, message]) + } + var opened = function() { + var outcome = backend.finishLaunch(item, ctx, query) + if (!outcome.toast) return + notifyFailure(item.name, outcome.toast.title) + } + var withSelection = function() { + if (!parsed.needsSelection) { opened(); return } + backend.paste(true, function(text) { ctx.selection = text; opened() }) + } + if (parsed.needsClipboard) backend.paste(false, function(text, ok) { + if (!ok) return notifyFailure(item.name, "The clipboard has no text to put in the link") + ctx.clipboard = text + withSelection() + }) + else withSelection() + return { close: true } + } + + // Reads the clipboard (or the primary selection) as text: done(text, ok), + // where ok is false when it is empty, not text, or the read timed out. + function paste(primary, done) { + pasteProc.collected = "" + pasteProc.done = done + pasteProc.command = ["timeout", "2", "wl-paste"].concat(primary ? ["--primary"] : []).concat(["--no-newline", "--type", "text"]) + pasteProc.running = true + } + + function finishLaunch(item, ctx, query) { + var expanded = Quicklinks.expand(item.link, ctx) + if (expanded.error) return { toast: { style: "failure", title: expanded.error } } + var argv = Quicklinks.openArgv(expanded.url, item.openWith, backend.paths.home) + if (!argv) return { toast: { style: "failure", title: "Cannot open " + expanded.url } } + backend.recordVisit("quicklink:" + item.id, query) + Util.execArgv(argv) + return { close: true } + } + + function exportQuicklinks() { + var rows = Quicklinks.exportList(quicklinksStore.doc) + if (rows.length === 0) return { toast: { style: "failure", title: "No quicklinks to export" } } + if (exportProc.running) return { toast: { style: "failure", title: "Already exporting" } } + exportProc.payload = JSON.stringify(rows, null, 2) + "\n" + exportProc.count = rows.length + exportProc.running = true + return { toast: { style: "success", title: "Exporting…" } } + } + + // A path the user typed, read synchronously; "" when it cannot be read. + function readTextFile(path) { + importFile.failed = "" + if (importFile.path === path) importFile.reload() + else importFile.path = path + var text = importFile.text() + if (importFile.failed) throw new Error("Cannot read " + path + ": " + importFile.failed) + return text + } + + // From a file (sync), or from the clipboard: then {pending: true} and the + // result arrives as quicklinks.imported. Either way {ok, title, added, …}. + function importQuicklinks(input) { + var path = String(input || "").trim() + if (path === "~" || path.indexOf("~/") === 0) path = backend.paths.home + path.slice(1) + if (path && path.charAt(0) !== "/") throw new Error("Type a full path, starting with / or ~") + if (path) return backend.importText(backend.readTextFile(path), path + " is empty") + if (pasteProc.running) throw new Error("Still reading the clipboard") + backend.paste(false, function(text) { + var outcome + try { outcome = backend.importText(text, "The clipboard is empty") } + catch (e) { outcome = { ok: false, title: String(e.message || e) } } + backend.emit("quicklinks.imported", outcome) + }) + return { pending: true, ok: true, title: "Reading the clipboard…" } + } + + function importText(text, emptyMessage) { + if (!String(text || "").trim()) throw new Error(emptyMessage) + var r = Quicklinks.importText(quicklinksStore.doc, text, { apps: backend.installedApps(), now: Date.now() }) + if (r.error) throw new Error(r.error) + if (r.added > 0) backend.storeQuicklinks(r.doc) + var parts = [r.added + " imported"] + if (r.duplicates) parts.push(r.duplicates + " already saved") + if (r.withoutApp) parts.push(r.withoutApp + " set to the default app") + if (r.failed.length) parts.push("skipped " + r.failed.join(", ")) + return { ok: r.added > 0 || r.failed.length === 0, title: parts.join(" · "), added: r.added, duplicates: r.duplicates, withoutApp: r.withoutApp, failed: r.failed } + } + + // ------------------------------------------------------------- services function registerServices() { Rpc.register(backend.registry, "system", { @@ -595,6 +781,8 @@ Item { workMs: Date.now() - t0, settings: { loaded: settingsStore.loaded, readOnly: settingsStore.readOnly, error: settingsStore.lastError }, frecency: { loaded: frecencyStore.loaded, readOnly: frecencyStore.readOnly, error: frecencyStore.lastError }, + quicklinks: { loaded: quicklinksStore.loaded, readOnly: quicklinksStore.readOnly, error: quicklinksStore.lastError }, + // Kept for Phase 0 callers. loaded: settingsStore.loaded, readOnly: settingsStore.readOnly, error: settingsStore.lastError } }, @@ -662,6 +850,7 @@ Item { if (data && data.fleaHits) ctx.fleaHits = data.fleaHits var sections if (view && view.kind === "menu") sections = RootSearch.submenuSections(backend.candidates, view.menuId, query, ctx, backend.deps) + else if (view && view.kind === "quicklinks") sections = RootSearch.quicklinkSections(backend.candidates, query, ctx, backend.deps) else if (view && view.kind === "theme") sections = Themes.sections(themeSource.themes, themeSource.current, query) else if (view && view.kind === "clipboard") sections = ClipboardHistory.sections(backend.clipboardEntries(), query, String(data && data.filter || "all"), ctx.nowMs) @@ -694,6 +883,8 @@ Item { } if (rowId.indexOf("emoji:") === 0) return Emoji.actionsFor(backend.emojiCandidate(rowId).candidate, backend.emojiState().tone) var candidate = backend.decorated(rowId) + if (!candidate && (rowId === "url:open" || rowId === "url:create")) + return RootSearch.actionsFor({ kind: rowId === "url:open" ? "url-open" : "url-create", title: rowId === "url:open" ? "Open in Browser" : "Create Quicklink" }) if (!candidate) { var fallback = RootSearch.FALLBACKS.filter(function(f) { return f.id === data.id })[0] if (!fallback) throw new Error("Unknown command " + (data && data.id)) @@ -747,6 +938,15 @@ Item { Util.execArgv(["omarchy-launch-browser", RootSearch.fallbackUrl(fallback, data.query)]) return { close: true } } + // So are the rows for a typed web address. + var url = data && (data.id === "url:open" || data.id === "url:create") ? Quicklinks.webAddress(data.query) : "" + if (url && data.id === "url:open") { + var argv = Quicklinks.openArgv(url, "", backend.paths.home) + if (!argv) return { toast: { style: "failure", title: "Cannot open " + url } } + Util.execArgv(argv) + return { close: true } + } + if (url) return { push: backend.quicklinkForm("Create Quicklink", Quicklinks.suggestion(data.query)) } // The calculator row is the query itself, evaluated again. if (data && data.id === RootSearch.CALCULATOR_ID) { var calc = backend.calculate(String(data.query || "")) @@ -768,6 +968,46 @@ Item { getSearchHistory: function() { return frecencyStore.loaded ? frecencyStore.doc.searchHistory : [] } }) + Rpc.register(backend.registry, "quicklinks", { + list: function() { return Quicklinks.list(quicklinksStore.doc) }, + get: function(data) { return Quicklinks.get(quicklinksStore.doc, String(data && data.id || "")) }, + openWithChoices: function(data) { return Quicklinks.openWithChoices(backend.installedApps(), data && data.query, data && data.current) }, + openWithLabel: function(data) { return Quicklinks.openWithLabel(backend.installedApps(), String(data && data.id || "")) }, + // {name, link, iconName?, openWith?} + save: function(data) { + var r = Quicklinks.save(quicklinksStore.doc, data || {}, { apps: backend.installedApps(), now: Date.now() }) + if (r.error) throw new Error(r.error) + backend.storeQuicklinks(r.doc) + return r.item + }, + // {id, name, link, iconName?, openWith?} + update: function(data) { + var r = Quicklinks.update(quicklinksStore.doc, String(data && data.id || ""), data || {}, { apps: backend.installedApps(), now: Date.now() }) + if (r.error) throw new Error(r.error) + backend.storeQuicklinks(r.doc) + return r.item + }, + // Also forgets its alias, favourite slot and ranking. + "delete": function(data) { + var id = String(data && data.id || "") + var r = Quicklinks.remove(quicklinksStore.doc, id) + if (r.error) throw new Error(r.error) + backend.storeQuicklinks(r.doc) + if (settingsStore.doc.commands["quicklink:" + id]) backend.updateCommand("quicklink:" + id, function() { return {} }) + frecencyStore.update(function(doc) { delete doc.items["quicklink:" + id] }) + return null + }, + // {path?}: a JSON file, or the clipboard when empty. + "import": function(data) { return backend.importQuicklinks(data && data.path) }, + "export": function() { return backend.exportQuicklinks() }, + // {id, values?, query?} + open: function(data) { + var item = Quicklinks.get(quicklinksStore.doc, String(data && data.id || "")) + if (!item) throw new Error("Quicklink not found") + return backend.launchQuicklink(item, (data && data.values) || {}, String(data && data.query || "")) + } + }) + // Names from Raycast's calculator namespace (ref 02 §2). Rpc.register(backend.registry, "calculator", { calculate: function(data) { return backend.calculate(String(data && data.query || "")) }, @@ -863,7 +1103,7 @@ Item { function onValuesChanged() { rebuildTimer.restart() } } - Component.onDestruction: { settingsStore.flush(); frecencyStore.flush(); calculatorStore.flush(); emojiStore.flush(); clipboardStore.flush() } + Component.onDestruction: { settingsStore.flush(); frecencyStore.flush(); calculatorStore.flush(); quicklinksStore.flush(); emojiStore.flush(); clipboardStore.flush() } onNotification: function(method, data) { if (method === "window.visibilityChanged" && data && data.visible) { menuSource.refresh() @@ -993,10 +1233,66 @@ Item { onMessage: function(level, text, metadata) { backend.log(level, "calculator", text, metadata) } } + JsonStore { + id: quicklinksStore + ready: backend.directoriesReady + path: backend.paths.db + "/" + Schema.documents.quicklinks.file + migrations: Schema.documents.quicklinks.migrations + onMessage: function(level, text, metadata) { backend.log(level, "store", text, metadata) } + } + + // wl-paste goes through the data-control protocol, so it works while the + // launcher is unfocused or closed. Quickshell.clipboardText would not. + Process { + id: pasteProc + property var done: null + property string collected: "" + stdout: SplitParser { onRead: function(line) { pasteProc.collected += line + "\n" } } + onExited: function(exitCode) { + var done = pasteProc.done + pasteProc.done = null + if (done) done(exitCode === 0 ? pasteProc.collected.replace(/\n$/, "") : "", exitCode === 0) + } + } + + // Export: a JSON file in Downloads (or home), also put on the clipboard. + // The JSON goes through stdin, so no file contents reach an argv. + Process { + id: exportProc + property string payload: "" + property int count: 0 + stdinEnabled: true + command: ["sh", "-c", "d=$(xdg-user-dir DOWNLOAD 2>/dev/null); [ -d \"$d\" ] || d=$HOME; f=\"$d/omacast-quicklinks-$(date +%F).json\"; cat > \"$f\" && wl-copy --type text/plain < \"$f\" && printf %s \"$f\""] + property string path: "" + property string errors: "" + stdout: SplitParser { onRead: function(line) { exportProc.path = line } } + stderr: SplitParser { onRead: function(line) { exportProc.errors = line } } + onStarted: { exportProc.write(exportProc.payload); exportProc.stdinEnabled = false } + onExited: function(exitCode) { + exportProc.stdinEnabled = true + var where = exportProc.path.replace(backend.paths.home, "~") + backend.emit("quicklinks.exported", exitCode === 0 + ? { ok: true, title: "Exported " + exportProc.count + (exportProc.count === 1 ? " quicklink" : " quicklinks") + " to " + where + " and the clipboard" } + : { ok: false, title: "Export failed: " + (exportProc.errors || "exit " + exitCode) }) + exportProc.path = "" + exportProc.errors = "" + } + } + + FileView { + id: importFile + property string failed: "" + blockAllReads: true + printErrors: false + onLoadFailed: function(error) { importFile.failed = FileViewError.toString(error) } + } + + // Bumped whenever ranking inputs change, so views re-query. readonly property int dataRevision: candidatesRevision + (settingsStore.loaded ? 1 : 0) + (frecencyStore.loaded ? 1 : 0) property int storeRevision: 0 Connections { target: settingsStore; function onChanged() { backend.storeRevision++ } } Connections { target: frecencyStore; function onChanged() { backend.storeRevision++ } } + Connections { target: quicklinksStore; function onChanged() { backend.storeRevision++; rebuildTimer.restart() } } Connections { target: calculatorStore; function onChanged() { backend.storeRevision++ } } Connections { target: emojiStore; function onChanged() { backend.storeRevision++ } } diff --git a/CLAUDE.md b/CLAUDE.md index f0dfa48..4e63d1b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -131,7 +131,7 @@ Works: - **Ctrl+P** opens the root dropdown (All / Applications / Commands); emacs Ctrl+P = up only works inside popups. - **Ctrl+T** opens the toast's actions (Copy Error Message on failures, Undo after Disable Command). **Ctrl+Shift+K** opens the About panel for the selected row. - **Argument pills:** "Search Google" / "Search DuckDuckGo" take a query in a pill after the search text (Tab in, Shift+Tab out). - - **Alerts:** Shut Down, Restart, Log Out and Delete All Entries ask first (↵ confirms, Esc cancels). `omacast run` skips the alert. + - **Alerts:** Shut Down, Restart, Log Out, Delete All Entries and Delete Quicklink ask first (↵ confirms, Esc cancels). `omacast run` skips the alert. - **Feedback:** toasts in the footer and a HUD through Omarchy's OSD when the window closes; static footer "Loading…" appears only after 500 ms of visible loading, yields to toasts and resets on hide. The header divider stays still. - **Window behaviour:** - The `escapeKeyBehavior` setting works both ways. @@ -158,6 +158,7 @@ Works: - **Clipboard History** (Phase 3, SPEC §5.3/§8.2, `core/ClipboardHistory.js`, `builtin:clipboard-history`, global shortcut `omacast:clipboard`): `services/ClipboardWatcher.qml` runs one `wl-paste --watch` whose constant bash script skips `CLIPBOARD_STATE != data` and `x-kde-passwordManagerHint`, prefers an `image/*` offer, keeps `text/uri-list` for `file://` copies, and prints one JSON line per copy. Images and text ≥ 30,720 bytes go to `~/.local/share/omacast/clipboard/` by MD5; short text travels in the JSON line. The backend adds the source (`ToplevelManager.activeToplevel` + `DesktopEntries.heuristicLookup`), drops disabled apps (`clipboardDisabledApplications`), dedups by hash (copy count, last copied), and prunes by `clipboardHistoryDuration` (default `P1W`, pins kept) plus a 1000-unpinned cap [D], deleting orphaned files. The first line after the watcher starts is skipped if already known, and our own writes from the history (5 s hash window) don't count as copies. UI: 40/60 list/detail (`ui/DetailPane.qml`: text, image or colour swatch, then Information rows), sections Pinned/Today/Yesterday/Earlier [I], type dropdown on Ctrl+P. Actions: Paste (↵, via `ClipboardWriter.copyFile` for files), Copy (Ctrl+↵), Open link/file (Ctrl+O), Pin (Ctrl+Shift+P), Delete (Ctrl+D), Delete All unpinned (Ctrl+Shift+D, confirmed). RPC: `clipboard.getAll|getDetail|copy|paste|pin|unpin|delete|deleteAll`. Not done: OCR, Paste Sequentially, rich-text representations (only plain text, URI lists and one image type are kept), edit/rename, Save as Snippet, moving pins, image dimensions. `omacast:clipboard` toggles: a second press closes the view. - **Switch Theme** (`builtin:switch-theme`, `core/Themes.js`, `services/ThemeSource.qml`; Raycast's command name, Omarchy's themes [D]): the list is Omarchy's own picker rows (`omarchy-theme-switcher --print-rows`, "\t", ~40 ms), reloaded on each push; the current theme is the watched `~/.local/state/omarchy/current/theme.name`. List/detail layout with the preview image (a video preview falls back to its thumbnail), opens on the current theme, ↵ runs `omarchy-theme-set `. Rows have no icon (`iconless` in ResultRow). BUILTINS `supersedes: ["omarchy:appearance.theme"]` drops Omarchy's theme picker from the candidates. Global shortcut `omacast:theme` toggles it (README shows binding it to Super+Ctrl+T in place of Omarchy's theme menu). RPC: `themes.getAll|getDetail`. Not done: live preview while moving through the list, palette swatches. - **Script Commands** (SPEC §9.9, `core/ScriptCommands.js`): `services/ScriptCommandSource.qml` scans `~/.config/omacast/script-commands` on every open (executable, ≤ 2 MB, no `.template.`, first 60 lines), and `services/ScriptRunner.qml` runs each one under `bash -lc` from its `currentDirectoryPath`. Text, password and dropdown arguments are pills (`←`/`→` cycle a dropdown). `silent` closes and shows a HUD with the last output line; `compact` shows "Running…" then a toast (a HUD if the window closed). `needsConfirmation` uses the alert. Not yet: the `fullOutput` output view and `inline` refresh (both run as `compact`), image icons (emoji only), a settings list of folders, Create/Reload commands. +- **Quicklinks** (SPEC §8.4): Create / Search / Import / Export Quicklinks, Create Quicklink or Open in Browser for a typed web address, arguments in the same pills as the web searches (Tab into them, ↑/↓ steps an option, ↵ opens), Create Quicklink filled from a URL or path on the clipboard, Open With from installed apps, and Edit (Ctrl+E), Copy Link (Ctrl+Shift+C) and Delete (Ctrl+D, the Linux key in SPEC §10.3, confirmed through the alert) actions. Placeholders follow SPEC §8.3 except clipboard history, snippets and the calculator. - **Latency:** show → mapped in 59–66 ms, hide in 24–42 ms on Omarchy 4.0.6 (`tests/smoke.sh`; it was 37–44 ms on the old `OverlayWindow`). - **Tests:** root search, calculator and privacy coverage (`node --test tests/*.test.js`). diff --git a/Launcher.qml b/Launcher.qml index 27cc0af..a2044c7 100644 --- a/Launcher.qml +++ b/Launcher.qml @@ -71,6 +71,10 @@ Item { root.show() launcher.popToRoot() launcher.push(outcome.push) + } else if (outcome.arguments) { + root.show() + launcher.popToRoot() + launcher.promptArguments(outcome.arguments) } else if (outcome.close) { root.hide() if (outcome.hud) launcher.hud(outcome.hud) diff --git a/README.md b/README.md index d580440..7dfb726 100644 --- a/README.md +++ b/README.md @@ -226,9 +226,10 @@ monitor-input-cycle "$1" && echo "Switching display" | `Ctrl+↑` / `Ctrl+↓` | Jump between sections | | `↑` on an empty search | Search history | | `Ctrl+P` | Filter dropdown (All / Applications / Commands; types in Clipboard History) | -| `Tab` / `Shift+Tab` | Into and out of an argument pill | +| `Tab` / `Shift+Tab` | Into and out of an argument pill, and between a quicklink's arguments | | `Ctrl+Shift+F` | Add to or remove from favorites (`Ctrl+Alt+↑↓` to reorder) | | `Ctrl+Shift+C` | Copy (the command, desktop id, answer or name) | +| `Ctrl+E` / `Ctrl+D` | Edit / delete a quicklink | | `Alt+Shift+D` | Disable a command | | `Ctrl+T` | Actions for the current toast (Undo, Copy Error Message) | | `Ctrl+Shift+K` | About the selected result | @@ -349,6 +350,7 @@ Done: - [x] Emoji & Symbols - [x] Switch Theme - [x] Script Commands (arguments, confirmation) +- [x] Quicklinks Next: @@ -358,7 +360,6 @@ Next: Later: -- [ ] Quicklinks - [ ] Snippets and text expansion - [ ] Running Raycast extensions built from the open-source [`raycast/extensions`](https://github.com/raycast/extensions) repo - [ ] Window management and a window switcher diff --git a/SPEC.md b/SPEC.md index a7b9fba..9a11188 100644 --- a/SPEC.md +++ b/SPEC.md @@ -520,6 +520,7 @@ Grammar: `{keyword opt="v" opt2='v' | modifier | modifier}`. Quotes accepted: `" - Shown in root search with inline argument pills. Can be a fallback command. - Settings: Show Link Previews, Pass Selected Text as Argument. - **Import/Export** JSON: `[{name, link, openWith?}]` [I, keep compatible with Raycast's documented format]. +- Quickshell build [D, 2026-10-20]: `db/quicklinks.json`, `core/Quicklinks.js`. Arguments use the same argument pills as the web-search builtins (§12 Phase 1 leftovers): a quicklink candidate's `arguments` carry `{name, placeholder, required}` plus `defaultValue` and `options`; an argument with a default is optional and shows the default as its placeholder; an option argument steps through its options with ↑/↓ [D]. Delete Quicklink goes through the confirm alert. Web links open through `omarchy-launch-browser`, other links through `xdg-open`, a chosen app through `gtk-launch`. Create Quicklink fills an untouched form from a URL or path on the clipboard. localhost, loopback and private IPv4 hosts open as http. Values in a file-path link (`/…`, `~/…`) are not encoded. `{selection}` is the primary selection. `{clipboard offset=N}` waits for clipboard history; `{browser-tab}` is refused. No favicons, tags or link previews yet. Export writes `~/Downloads/omacast-quicklinks-.json` and copies it; import reads a file path or the clipboard. ### 8.5 Window management maths [O command list, I geometry] - Work area = monitor geometry minus reserved space (Hyprland `monitors -j` `reserved`; KDE/X11 `_NET_WORKAREA`). @@ -799,7 +800,7 @@ Repo layout [D]: - **Ctrl+P dropdown.** Ctrl+P is always `toggleFilter`, so emacs Ctrl+P = up is dropped in the list (it still moves up inside popups). Raycast's root has no dropdown; ours filters root search by type (All / Applications / Commands, `RootSearch.FILTERS`), hides the Calculator and fallback sections while filtered, and resets on pop-to-root. - **Ctrl+T** opens the toast's actions. Failure toasts offer "Copy Error Message"; "Disable Command" offers "Undo". - **Ctrl+Shift+K** About panel: `rootSearch.getItemInfo` → `RootSearch.aboutFor`. - - **Argument pills.** Builtins may declare `arguments` (`{name, placeholder, required}`). "Search Google" and "Search DuckDuckGo" are root commands with a `query` argument. Tab enters the pills, Shift+Tab / Backspace on an empty pill goes back, ↵ with an empty required argument focuses it. + - **Argument pills.** Builtins and quicklinks may declare `arguments` (`{name, placeholder, required}`). "Search Google" and "Search DuckDuckGo" are root commands with a `query` argument. Tab enters the pills, Shift+Tab / Backspace on an empty pill goes back, ↵ with an empty required argument focuses it. - **Alerts.** `rootSearch.performAction` returns `{confirm}` for Shut Down / Restart / Log Out and Delete All Entries until called with `confirmed: true`. `omacast run` is explicit and skips it. - **Keystroke buffering: won't do.** A parked surface conflicts with Omarchy's remap-on-open design (note above). - **"fir" → Firefox:** on a list where another title starts with "Fire", the literal port ties at score 8 and the collator decides until Firefox has been launched once (`tests/ranker.test.js`). diff --git a/core/Quicklinks.js b/core/Quicklinks.js new file mode 100644 index 0000000..93c135c --- /dev/null +++ b/core/Quicklinks.js @@ -0,0 +1,599 @@ +// Quicklinks (SPEC §8.4): the saved-link library, placeholder expansion +// (SPEC §8.3), web-address detection, and how a link is opened. +// A document is { items: [{id, name, link, iconName, openWith, createdAt, updatedAt}] }. + +var NAME_MAX = 200 // [D] long enough for any row title +var ARGUMENTS_MAX = 3 // [O] ref 02 §5.2 +var KEYWORDS = ["argument", "clipboard", "selection", "uuid", "datetime", "date", "time", "day"] +// Refused in quicklinks: browser-tab and cursor [O] ref 02 §6; snippet and +// calculator until those features exist, and ai (no AI features) [D]. +var REFUSED = ["browser-tab", "cursor", "snippet", "calculator", "ai"] +var MODIFIERS = ["uppercase", "lowercase", "trim", "percent-encode", "json-stringify", "raw"] +var QUOTES = { "\"": "\"", "'": "'", "`": "`", "“": "”", "‘": "’" } +var OFFSET = /^([+-])(\d+)([mhHdDMyY])$/ + +// ---------------------------------------------------------------- library + +function list(doc) { + return (doc && Array.isArray(doc.items) ? doc.items : []).filter(function(item) { + return item && typeof item.id === "string" && typeof item.name === "string" && typeof item.link === "string" + }) +} + +function get(doc, id) { + var items = list(doc) + for (var i = 0; i < items.length; i++) if (items[i].id === id) return items[i] + return null +} + +function nameTaken(doc, name, exceptId) { + var wanted = String(name).trim().toLowerCase() + return list(doc).some(function(item) { return item.id !== exceptId && item.name.trim().toLowerCase() === wanted }) +} + +function newId(doc, now) { + var id = "ql-" + now.toString(36) + while (get(doc, id)) id += "x" + return id +} + +// Checks one {name, link, iconName?, openWith?}. ctx.apps is the desktop +// catalog (installedApps); an empty one means it has not loaded, so only +// the id's shape is checked. ctx.keepOpenWith is allowed even if uninstalled. +function validate(input, ctx) { + var name = String(input && input.name != null ? input.name : "").trim() + var link = String(input && input.link != null ? input.link : "").trim() + if (!name) return { error: "A quicklink needs a name" } + if (name.length > NAME_MAX) return { error: "That name is too long" } + if (!link) return { error: "A quicklink needs a link" } + var refused = refusedTarget(link) + if (refused) return { error: refused } + var parsed = parseLink(link) + if (parsed.error) return { error: parsed.error } + var openWith = String(input.openWith || "").trim() + if (openWith && !(ctx && ctx.keepOpenWith === openWith)) { + if (!isDesktopId(openWith)) return { error: "Open With must be a desktop id such as firefox.desktop" } + var apps = (ctx && ctx.apps) || [] + if (apps.length) { + var app = findApp(apps, openWith) + if (!app) return { error: openWith + " is not installed" } + openWith = app.id + } + } + return { error: "", item: { name: name, link: link, iconName: String(input.iconName || "").trim(), openWith: openWith } } +} + +function save(doc, input, ctx) { + var checked = validate(input, ctx) + if (checked.error) return { error: checked.error } + if (nameTaken(doc, checked.item.name, "")) return { error: "A quicklink named " + checked.item.name + " already exists" } + var now = ctx.now + var item = Object.assign({ id: newId(doc, now) }, checked.item, { createdAt: now, updatedAt: now }) + return { error: "", item: item, doc: { items: list(doc).concat([item]) } } +} + +function update(doc, id, input, ctx) { + var current = get(doc, id) + if (!current) return { error: "Quicklink not found" } + var checked = validate(input, Object.assign({}, ctx, { keepOpenWith: current.openWith })) + if (checked.error) return { error: checked.error } + if (nameTaken(doc, checked.item.name, id)) return { error: "A quicklink named " + checked.item.name + " already exists" } + var item = Object.assign({ id: id }, checked.item, { createdAt: current.createdAt, updatedAt: ctx.now }) + return { error: "", item: item, doc: { items: list(doc).map(function(it) { return it.id === id ? item : it }) } } +} + +function remove(doc, id) { + if (!get(doc, id)) return { error: "Quicklink not found" } + return { error: "", doc: { items: list(doc).filter(function(it) { return it.id !== id }) } } +} + +// Raycast's export format [I]: [{name, link, iconName?, openWith?}]. +// [D] A row with the same name and link as a saved one is a duplicate. +function importText(doc, text, ctx) { + var rows + try { rows = JSON.parse(String(text || "")) } catch (e) { return { error: "That is not valid JSON" } } + if (!Array.isArray(rows)) return { error: "Import expects a JSON array" } + var next = { items: list(doc) } + var added = 0, duplicates = 0, withoutApp = 0, failed = [] + for (var i = 0; i < rows.length; i++) { + var row = rows[i] + var label = row && typeof row.name === "string" && row.name.trim() ? row.name.trim() : "row " + (i + 1) + if (!row || typeof row !== "object" || Array.isArray(row)) { failed.push(label); continue } + var same = list(next).some(function(it) { return it.name === String(row.name).trim() && it.link === String(row.link).trim() }) + if (same) { duplicates++; continue } + // [D] A Raycast export names macOS apps; keep the link, open it with the default. + var apps = ctx.apps || [] + var openWith = String(row.openWith || "").trim() + if (openWith && !(isDesktopId(openWith) && (!apps.length || findApp(apps, openWith)))) { + openWith = "" + withoutApp++ + } + var saved = save(next, Object.assign({}, row, { openWith: openWith }), { apps: apps, now: ctx.now + i }) + if (saved.error) { failed.push(label); continue } + next = saved.doc + added++ + } + return { error: "", doc: next, added: added, duplicates: duplicates, withoutApp: withoutApp, failed: failed } +} + +function exportList(doc) { + return list(doc).map(function(item) { + var row = { name: item.name, link: item.link } + if (item.iconName) row.iconName = item.iconName + if (item.openWith) row.openWith = item.openWith + return row + }) +} + +function toCandidate(item) { + var parsed = parseLink(item.link) + return { + id: "quicklink:" + item.id, + type: "quicklink", + kind: "quicklink", + title: item.name, + subtitle: item.link, + keywords: [], + typeLabel: "Quicklink", + glyph: item.iconName ? "" : "", // nf-fa-link + iconName: item.iconName || "", + quicklinkId: item.id, + // [O] Up to 3 arguments become argument pills after the search text. + // Pills read {placeholder, required}; a default makes one optional. + arguments: parsed.error ? [] : parsed.arguments.map(function(a) { + return { + name: a.name, defaultValue: a.defaultValue, options: a.options, required: !a.defaultValue, + placeholder: a.options.length ? a.name + " ▾" : (a.defaultValue || a.name) + } + }), + rootSearch: { when: "searching" } // [O] Search Quicklinks lists them all + } +} + +// ----------------------------------------------------------- placeholders + +// Index of the "}" that closes the placeholder at `start`, or -1 when +// there is none on that line: then "{" is literal text [O]. Quotes may hide "}". +function placeholderEnd(text, start) { + var close = "" + for (var i = start + 1; i < text.length; i++) { + var ch = text.charAt(i) + if (close) { + if (ch === "\\") i++ + else if (ch === close) close = "" + } else if (ch === "\n") return -1 + else if (QUOTES[ch]) close = QUOTES[ch] + else if (ch === "}") return i + } + return -1 +} + +// Splits on spaces and "|" outside quotes. Returns {words, modifiers}; a +// word that starts with a quote is marked `quoted` (a value, never key=value). +function tokenize(inner) { + var words = [], modifiers = [], buf = "", quoted = false, inPipe = false + function flush() { + if (!buf && !quoted) return + if (inPipe) modifiers.push(buf) + else words.push({ text: buf, quoted: quoted }) + buf = "" + quoted = false + } + for (var i = 0; i < inner.length; i++) { + var ch = inner.charAt(i) + if (QUOTES[ch]) { + var close = QUOTES[ch] + if (!buf) quoted = true + for (i++; i < inner.length && inner.charAt(i) !== close; i++) { + if (inner.charAt(i) === "\\" && i + 1 < inner.length) i++ + buf += inner.charAt(i) + } + } else if (ch === " ") flush() + else if (ch === "|") { flush(); inPipe = true } + else buf += ch + } + flush() + return { words: words, modifiers: modifiers } +} + +// "a, b, Title: value" -> [{title, value}], with "\" escapes [O]. +function parseOptions(text) { + var out = [], buf = "" + for (var i = 0; i <= text.length; i++) { + var ch = text.charAt(i) + if (ch === "\\" && i + 1 < text.length) { buf += text.charAt(++i); continue } + if (ch !== "," && i < text.length) { buf += ch; continue } + var item = buf.trim() + buf = "" + if (!item) continue + var colon = item.indexOf(":") + out.push(colon < 0 ? { title: item, value: item } : { title: item.slice(0, colon).trim(), value: item.slice(colon + 1).trim() }) + } + return out +} + +function parsePlaceholder(inner) { + var head = inner.split(/[ |]/)[0] + var keyword = head.toLowerCase() + for (var r = 0; r < REFUSED.length; r++) { + if (keyword === REFUSED[r] || keyword.indexOf(REFUSED[r] + ".") === 0) return { error: "Quicklinks cannot use {" + head + "}" } + } + var tokens = tokenize(inner) + for (var m = 0; m < tokens.modifiers.length; m++) { + if (MODIFIERS.indexOf(tokens.modifiers[m]) < 0) return { error: "Unknown modifier " + tokens.modifiers[m] } + } + head = keyword + if (KEYWORDS.indexOf(head) < 0) { + // [O] Any other {word} or {word:default} is an argument (legacy form). + var legacy = inner.split("|")[0].trim() + if (!legacy || legacy.indexOf("=") >= 0) return { error: "Unknown placeholder {" + inner + "}" } + var colon = legacy.indexOf(":") + var name = colon < 0 ? legacy : legacy.slice(0, colon).trim() + return { kind: "argument", name: name, defaultValue: colon < 0 ? "" : legacy.slice(colon + 1).trim(), options: [], modifiers: tokens.modifiers } + } + var attrs = {}, positional = [] + for (var w = 1; w < tokens.words.length; w++) { + var word = tokens.words[w] + var eq = word.quoted ? -1 : word.text.indexOf("=") + if (eq > 0) attrs[word.text.slice(0, eq)] = word.text.slice(eq + 1) + else positional.push(word.text) + } + var out = { kind: head, modifiers: tokens.modifiers, attrs: attrs } + if (head === "argument") { + out.name = attrs.name || "argument" + out.defaultValue = attrs["default"] || "" + out.options = attrs.options ? parseOptions(attrs.options) : [] + } else if (head === "clipboard" && attrs.offset && attrs.offset !== "0") { + return { error: "{clipboard offset} needs clipboard history, which is not built yet" } + } else if (head === "date" || head === "time" || head === "datetime" || head === "day") { + // [O] Legacy {date "format" +1d}: a quoted format and offsets. + var offsets = attrs.offset ? attrs.offset.trim().split(/\s+/) : [] + for (var q = 0; q < positional.length; q++) { + if (/^[+-]\d/.test(positional[q])) offsets.push(positional[q]) + else if (!attrs.format) attrs.format = positional[q] + } + for (var o = 0; o < offsets.length; o++) if (!OFFSET.test(offsets[o])) return { error: "Bad date offset " + offsets[o] } + out.offsets = offsets + } + return out +} + +// Walks the link once. `visit(placeholder)` returns the text to put in its +// place, or {error}. Literal text goes through `literal`. +function walk(link, visit, literal) { + var out = "" + for (var i = 0; i < link.length;) { + var start = link.indexOf("{", i) + if (start < 0) { out += literal(link.slice(i)); break } + out += literal(link.slice(i, start)) + var end = placeholderEnd(link, start) + if (end < 0) { out += literal("{"); i = start + 1; continue } + var placeholder = parsePlaceholder(link.slice(start + 1, end)) + if (placeholder.error) return { error: placeholder.error } + var value = visit(placeholder) + if (value && value.error) return { error: value.error } + out += value + i = end + 1 + } + return { error: "", text: out } +} + +// What opening a link needs: its arguments (merged by name, max 3) and +// whether it reads the clipboard or the selection. +function parseLink(link) { + var args = [], needs = { clipboard: false, selection: false } + var result = walk(String(link || ""), function(p) { + if (p.kind === "clipboard" || p.kind === "selection") needs[p.kind] = true + if (p.kind !== "argument") return "" + var known = args.filter(function(a) { return a.name === p.name })[0] + if (!known) args.push({ name: p.name, defaultValue: p.defaultValue, options: p.options }) + else { + if (!known.defaultValue) known.defaultValue = p.defaultValue + if (!known.options.length) known.options = p.options + } + return "" + }, function() { return "" }) + if (result.error) return { error: result.error } + if (args.length > ARGUMENTS_MAX) return { error: "A quicklink can have at most " + ARGUMENTS_MAX + " arguments" } + return { error: "", arguments: args, needsClipboard: needs.clipboard, needsSelection: needs.selection } +} + +// Fills defaults, trims, and checks required arguments and options. +// An option matches its title or its value, ignoring case. +function argumentValues(parsed, given) { + var out = {} + for (var i = 0; i < parsed.arguments.length; i++) { + var arg = parsed.arguments[i] + var text = String(given && given[arg.name] != null ? given[arg.name] : "").trim() || arg.defaultValue + if (!text) return { error: arg.name + " is required" } + if (arg.options.length) { + var wanted = text.toLowerCase() + var hit = arg.options.filter(function(o) { return o.title.toLowerCase() === wanted || o.value.toLowerCase() === wanted })[0] + if (!hit) return { error: text + " is not one of " + arg.options.map(function(o) { return o.title }).join(", ") } + text = hit.value + } + out[arg.name] = text + } + return { error: "", values: out } +} + +// ctx: {now, values, clipboard, selection, uuid, names}. names(locale) +// gives month and day names, "" meaning the system locale (QML passes +// Qt.locale); without it, English. +// [I] Substituted values are percent-encoded unless `| raw`, except in a +// file path, which xdg-open needs as written. +function expand(link, ctx) { + var text = String(link || "").trim() + var path = isPath(text) + var result = walk(text, function(p) { + var value + if (p.kind === "argument") value = ctx.values[p.name] || "" + else if (p.kind === "clipboard") value = ctx.clipboard || "" + else if (p.kind === "selection") value = ctx.selection || "" + else if (p.kind === "uuid") value = ctx.uuid || "" + else value = dateText(p, ctx) + var raw = path + for (var i = 0; i < p.modifiers.length; i++) { + var m = p.modifiers[i] + if (m === "uppercase") value = value.toUpperCase() + else if (m === "lowercase") value = value.toLowerCase() + else if (m === "trim") value = value.trim() + else if (m === "json-stringify") value = JSON.stringify(value) + else if (m === "percent-encode") { value = encodeURIComponent(value); raw = true } + else if (m === "raw") raw = true + } + return raw ? value : encodeURIComponent(value) + }, function(part) { return path ? part : part.replace(/ /g, "%20") }) + if (result.error) return { error: result.error } + if (!result.text.trim()) return { error: "The link is empty after its placeholders are filled in" } + var refused = refusedTarget(result.text) + if (refused) return { error: refused } + return { error: "", url: result.text } +} + +// --------------------------------------------------------------- dates + +var MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] +var DAYS = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] +var ENGLISH = { + month: function(i, long) { return long ? MONTHS[i] : MONTHS[i].slice(0, 3) }, + day: function(i, long) { return long ? DAYS[i] : DAYS[i].slice(0, 3) } +} +// ICU pattern letters we support, longest first. +var TOKENS = ["yyyy", "yy", "y", "MMMM", "MMM", "MM", "M", "dd", "d", "EEEE", "EEE", "EE", "E", "HH", "H", "hh", "h", "mm", "m", "ss", "s", "a"] + +function shifted(now, offsets) { + var date = new Date(now) + for (var i = 0; i < offsets.length; i++) { + var m = OFFSET.exec(offsets[i]) + var n = (m[1] === "-" ? -1 : 1) * parseInt(m[2], 10) + var unit = m[3] + if (unit === "m") date.setMinutes(date.getMinutes() + n) + else if (unit === "h" || unit === "H") date.setHours(date.getHours() + n) + else if (unit === "d" || unit === "D") date.setDate(date.getDate() + n) + else if (unit === "M") date.setMonth(date.getMonth() + n) + else date.setFullYear(date.getFullYear() + n) + } + return date +} + +function pad(n, width) { + var s = String(n) + while (s.length < width) s = "0" + s + return s +} + +function formatDate(date, pattern, names) { + var out = "" + for (var i = 0; i < pattern.length;) { + if (pattern.charAt(i) === "'") { + var close = pattern.indexOf("'", i + 1) + out += close === i + 1 ? "'" : pattern.slice(i + 1, close < 0 ? pattern.length : close) + i = close < 0 ? pattern.length : close + 1 + continue + } + var token = TOKENS.filter(function(t) { return pattern.substr(i, t.length) === t })[0] + if (!token) { out += pattern.charAt(i++); continue } + var h12 = date.getHours() % 12 || 12 + var values = { + yyyy: pad(date.getFullYear(), 4), yy: pad(date.getFullYear() % 100, 2), y: date.getFullYear(), + MMMM: names.month(date.getMonth(), true), MMM: names.month(date.getMonth(), false), + MM: pad(date.getMonth() + 1, 2), M: date.getMonth() + 1, dd: pad(date.getDate(), 2), d: date.getDate(), + EEEE: names.day(date.getDay(), true), EEE: names.day(date.getDay(), false), + EE: names.day(date.getDay(), false), E: names.day(date.getDay(), false), + HH: pad(date.getHours(), 2), H: date.getHours(), hh: pad(h12, 2), h: h12, + mm: pad(date.getMinutes(), 2), m: date.getMinutes(), ss: pad(date.getSeconds(), 2), s: date.getSeconds(), + a: date.getHours() < 12 ? "AM" : "PM" + } + out += values[token] + i += token.length + } + return out +} + +// [I] Defaults follow Raycast's medium styles: "20 Oct 2026", "14:05". +function dateText(p, ctx) { + var date = shifted(ctx.now, p.offsets) + var names = ctx.names ? ctx.names(p.attrs.locale || "") : ENGLISH + if (p.attrs.format) return formatDate(date, p.attrs.format, names) + if (p.kind === "day") return formatDate(date, "EEEE", names) + if (p.kind === "time") return formatDate(date, "HH:mm", names) + if (p.kind === "datetime") return formatDate(date, "d MMM yyyy HH:mm", names) + return formatDate(date, "d MMM yyyy", names) +} + +// ------------------------------------------------------- web addresses + +// [D] A bare host needs a two-letter country TLD, an IDN TLD, or one of +// these common longer ones, so "vs.code" or "node.js" stay searches. Any +// other TLD works with its scheme (https://example.museum). +var LONG_TLDS = ["com", "net", "org", "edu", "gov", "mil", "int", "info", "biz", "dev", "app", "xyz", "online", "site", "store", "shop", "tech", "blog", "cloud", "page", "wiki", "news", "design", "club", "live", "life", "world", "space", "website", "email", "link", "art", "pro", "name", "mobi", "codes", "software", "systems", "social", "media", "studio", "agency", "digital", "network", "games", "tools", "host", "lol", "one", "top", "fun", "run", "build", "chat", "zone", "today", "academy", "school", "photo", "photos", "travel", "music", "video", "tv", "work", "works", "company", "solutions", "services", "group", "team", "eu", "asia", "moe", "museum", "coop", "aero", "jobs", "berlin", "london", "nyc", "paris", "tokyo"] +// A last label that is a common file extension is a file, not a TLD. +var FILE_EXTENSIONS = ["json", "md", "js", "ts", "txt", "pdf", "png", "jpg", "jpeg", "gif", "svg", "html", "css", "xml", "sh", "py", "rs", "qml", "zip", "tar", "gz", "conf", "toml", "yaml", "yml", "log", "lock"] +// Zero-width and bidi controls make a host look like another one. +var HIDDEN_CHARS = /[᠎​-‏‪-‮⁠⁦-⁩]/ + +function isPath(text) { + return /^[\/~]/.test(text) +} + +function isHost(host) { + if (/^localhost$/i.test(host)) return true + if (/^\d{1,3}(\.\d{1,3}){3}$/.test(host)) return host.split(".").every(function(n) { return Number(n) <= 255 }) + if (HIDDEN_CHARS.test(host)) return false + var labels = host.split(".") + if (labels.length < 2) return false + if (!labels.every(function(l) { return /^[^\s\-_.:@\/][^\s_.:@\/]{0,62}$/.test(l) && !/-$/.test(l) })) return false + var tld = labels[labels.length - 1].toLowerCase() + return /^([a-z]{2}|xn--[a-z0-9-]+|[^\x00-\x7f]{2,})$/.test(tld) ? FILE_EXTENSIONS.indexOf(tld) < 0 : LONG_TLDS.indexOf(tld) >= 0 +} + +// "github.com/x", "localhost:3000", "1.2.3.4" -> a full http(s) URL, or "". +// [D] localhost is http; every other bare host is https. +// Dev servers and routers rarely serve TLS: localhost, loopback and private +// IPv4 ranges open as http [D]. +function isLocalHost(host) { + if (/^localhost$/i.test(host)) return true + if (!/^\d{1,3}(\.\d{1,3}){3}$/.test(host)) return false + return /^(127|10)\./.test(host) || /^192\.168\./.test(host) || /^172\.(1[6-9]|2\d|3[01])\./.test(host) +} + +function bareWebUrl(text) { + var m = /^([^\/?#:\s]+)(?::(\d{1,5}))?([\/?#][^\s]*)?$/.exec(String(text || "")) + if (!m || !isHost(m[1])) return "" + if (m[2] !== undefined && !(Number(m[2]) >= 1 && Number(m[2]) <= 65535)) return "" + return (isLocalHost(m[1]) ? "http://" : "https://") + m[0] +} + +// A root-search query that is an address: scheme://…, mailto:/tel:, or a bare host. +function webAddress(query) { + var q = String(query || "").trim() + if (!q || /\s/.test(q)) return "" + if (/^[a-z][a-z0-9+.-]*:\/\/\S+$/i.test(q) || /^(mailto|tel):\S+$/i.test(q)) return refusedTarget(q) ? "" : q + return bareWebUrl(q) +} + +// A starting name and link for Create Quicklink from a typed query or the +// clipboard [O: Raycast autofills from a URL or file path in the +// clipboard]: a web address named after its host, or a path named after its +// last part. Anything else gives null. +function suggestion(text) { + var q = String(text || "").trim() + if (!q || q.length > 2048 || /\s/.test(q.replace(/ /g, ""))) return null + if ((q.charAt(0) === "/" || q.indexOf("~/") === 0) && q.length > 2) { + var parts = q.replace(/\/+$/, "").split("/") + return { name: parts[parts.length - 1], link: q } + } + var url = webAddress(q) + if (!url || refusedTarget(url)) return null + if (/^(mailto|tel):/i.test(url)) return { name: url.slice(url.indexOf(":") + 1), link: url } + var host = url.replace(/^[a-z][a-z0-9+.-]*:(\/\/)?/i, "").split(/[\/?#]/)[0].replace(/^[^@]*@/, "").replace(/^www\./i, "") + return { name: host || url, link: url } +} + +// ------------------------------------------------------------- opening + +function refusedTarget(target) { + var text = String(target || "").trim() + if (/^javascript:/i.test(text)) return "Links cannot use javascript:" + // xdg-utils' xdg-open has no "--", so a leading "-" would be read as an option. + if (text.charAt(0) === "-") return "A link cannot start with -" + return "" +} + +// The argv that opens `url`. http(s) and bare hosts go through Omarchy's +// browser launcher, like the web-search fallbacks; anything else (a path, +// spotify://, mailto:) through xdg-open; a chosen app through gtk-launch. +function openArgv(url, openWith, home) { + var target = String(url || "").trim() + if (refusedTarget(target)) return null + if (target === "~" || target.indexOf("~/") === 0) target = home + target.slice(1) + var bare = isPath(target) ? "" : bareWebUrl(target) + if (bare) target = bare + if (openWith) return isDesktopId(openWith) ? ["uwsm-app", "--", "gtk-launch", openWith, target] : null + if (/^https?:\/\//i.test(target)) return ["omarchy-launch-browser", target] + return ["xdg-open", target] +} + +// ----------------------------------------------------------- open with + +function isDesktopId(id) { + return /^[A-Za-z0-9][A-Za-z0-9_.+-]*\.desktop$/.test(String(id || "")) +} + +// Quickshell DesktopEntry objects -> [{id: "x.desktop", name, icon}], by name. +function installedApps(entries) { + var out = [] + for (var i = 0; i < (entries || []).length; i++) { + var e = entries[i] + if (!e || !e.id) continue + var id = /\.desktop$/.test(e.id) ? String(e.id) : e.id + ".desktop" + if (isDesktopId(id) && !out.some(function(a) { return a.id === id })) out.push({ id: id, name: String(e.name || id), icon: String(e.icon || "") }) + } + return out.sort(function(a, b) { return a.name.toLowerCase() < b.name.toLowerCase() ? -1 : (a.name.toLowerCase() > b.name.toLowerCase() ? 1 : 0) }) +} + +// An exact id, or the only one that matches ignoring case. +function findApp(apps, id) { + var exact = apps.filter(function(a) { return a.id === id }) + if (exact.length) return exact[0] + var folded = apps.filter(function(a) { return a.id.toLowerCase() === String(id).toLowerCase() }) + return folded.length === 1 ? folded[0] : null +} + +var DEFAULT_APP = "Default" + +function openWithLabel(apps, id) { + if (!id) return DEFAULT_APP + var app = findApp(apps, id) + return app ? app.name : (apps.length ? id + " (not installed)" : id) +} + +// Picker rows: Default, then a saved app that is gone, then installed apps. +function openWithChoices(apps, query, current) { + var q = String(query || "").trim().toLowerCase() + var match = function(text) { return !q || text.toLowerCase().indexOf(q) >= 0 } + var rows = [] + if (match(DEFAULT_APP)) rows.push({ id: "", title: DEFAULT_APP, subtitle: "Browser for web links, xdg-open for the rest", glyph: "", iconName: "" }) + if (current && !findApp(apps, current) && match(current)) rows.push({ id: current, title: openWithLabel(apps, current), subtitle: "", glyph: "", iconName: "" }) + for (var i = 0; i < apps.length; i++) { + if (match(apps[i].name + " " + apps[i].id)) rows.push({ id: apps[i].id, title: apps[i].name, subtitle: "", glyph: "", iconName: apps[i].icon }) + } + return rows +} + +function randomUuid() { + return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) { + var r = Math.floor(Math.random() * 16) + return (c === "x" ? r : (r & 3) | 8).toString(16) + }) +} + +if (typeof module !== "undefined") { + module.exports = { + NAME_MAX: NAME_MAX, + list: list, + get: get, + save: save, + update: update, + remove: remove, + importText: importText, + exportList: exportList, + toCandidate: toCandidate, + suggestion: suggestion, + parseLink: parseLink, + argumentValues: argumentValues, + expand: expand, + formatDate: formatDate, + bareWebUrl: bareWebUrl, + webAddress: webAddress, + refusedTarget: refusedTarget, + openArgv: openArgv, + isDesktopId: isDesktopId, + installedApps: installedApps, + findApp: findApp, + openWithLabel: openWithLabel, + openWithChoices: openWithChoices, + randomUuid: randomUuid + } +} diff --git a/core/RootSearch.js b/core/RootSearch.js index 3a2a78a..3018578 100644 --- a/core/RootSearch.js +++ b/core/RootSearch.js @@ -68,7 +68,12 @@ var BUILTINS = [ keywords: ["calculator", "calc", "math", "history", "conversions"], run: { push: { kind: "calculator-history", title: "Calculator History" } }, rootSearch: { when: "always" } - } + }, + // Quicklinks (SPEC §8.4), named as in Raycast [O]. + { id: "builtin:create-quicklink", title: "Create Quicklink", subtitle: "Quicklinks", keywords: ["link", "bookmark", "url"], glyph: "", run: { quicklinks: "create" } }, + { id: "builtin:search-quicklinks", title: "Search Quicklinks", subtitle: "Quicklinks", keywords: ["link", "bookmark"], glyph: "", run: { quicklinks: "search" } }, + { id: "builtin:import-quicklinks", title: "Import Quicklinks", subtitle: "Quicklinks", keywords: ["link", "json"], glyph: "", run: { quicklinks: "import" } }, + { id: "builtin:export-quicklinks", title: "Export Quicklinks", subtitle: "Quicklinks", keywords: ["link", "json", "backup"], glyph: "", run: { quicklinks: "export" } } ] function words(value) { @@ -233,6 +238,19 @@ function rankOptions(ctx) { return { sensitivity: ctx.sensitivity || "medium", nowMs: ctx.nowMs, fleaHits: ctx.fleaHits || null } } +// [O] A query that is a web address offers to open it or save it. +function urlRows(url) { + return [ + { id: "url:open", kind: "url-open", title: "Open in Browser" }, + { id: "url:create", kind: "url-create", title: "Create Quicklink" } + ].map(function(r) { + return { + candidate: { id: r.id, type: "command", kind: r.kind, title: r.title, subtitle: url, typeLabel: "Link", glyph: "", url: url, rootSearch: { when: "searching" } }, + record: null + } + }) +} + function fallbackRows(query) { return FALLBACKS.map(function(f) { return { @@ -321,6 +339,8 @@ function rootSections(candidates, query, ctx, deps) { var sections = [] if (ctx.calculation && !filtered) sections.push({ id: "calculator", title: "Calculator", rows: [{ candidate: calculatorCandidate(ctx.calculation), record: null }] }) if (results.length > 0) sections.push({ id: "results", title: "Results", rows: results }) + var url = deps.Quicklinks && !filtered ? deps.Quicklinks.webAddress(q) : "" + if (url) sections.push({ id: "url", title: "Link", rows: urlRows(url) }) if (!filtered) sections.push({ id: "fallback-commands", title: "Use “" + q + "” with…", rows: fallbackRows(q) }) return sections } @@ -363,6 +383,19 @@ function submenuSections(candidates, menuId, query, ctx, deps) { return ranked.length ? [{ id: "results", title: "Results", rows: ranked }] : [] } +// Search Quicklinks: every quicklink by name, or ranked while searching. +function quicklinkSections(candidates, query, ctx, deps) { + var q = String(query || "").trim() + var inside = [] + for (var i = 0; i < candidates.length; i++) if (candidates[i].type === "quicklink") inside.push(decorate(candidates[i], ctx, deps)) + if (!q) { + inside.sort(function(a, b) { return a.title.toLowerCase() < b.title.toLowerCase() ? -1 : (a.title.toLowerCase() > b.title.toLowerCase() ? 1 : 0) }) + return inside.length ? [{ id: "quicklinks", title: "", rows: inside.map(function(c) { return { candidate: c, record: null } }) }] : [] + } + var ranked = deps.Ranker.rank(inside, q, rankOptions(ctx)) + return ranked.length ? [{ id: "results", title: "Results", rows: ranked }] : [] +} + function actionsFor(candidate) { if (candidate.kind === "calculator" || candidate.kind === "calculator-history") { // ↵ copies, Ctrl ↵ pastes (SPEC §8 Calculator) [O]; delete keys are @@ -387,6 +420,9 @@ function actionsFor(candidate) { case "omarchy-action": primary = { id: "open", title: "Run", icon: "" }; break case "omarchy-menu": case "omarchy-link": primary = { id: "open", title: "Open Menu", icon: "" }; break + case "quicklink": primary = { id: "open", title: "Open Quicklink", icon: "" }; break + case "url-open": + case "url-create": primary = { id: "open", title: candidate.title, icon: "" }; break case "fallback": primary = { id: "open", title: candidate.title, icon: "" }; break case "script": primary = { id: "open", title: "Run Script", icon: "\uf120" }; break default: primary = { id: "open", title: "Open Command", icon: "" } @@ -397,10 +433,14 @@ function actionsFor(candidate) { if (candidate.kind && candidate.kind.indexOf("omarchy-") === 0) list.push({ id: "open-in-omarchy-menu", title: "Open in Omarchy Menu", shortcut: "Ctrl ↵", section: "primary", icon: "" }) - if (candidate.kind === "fallback") return list + if (candidate.kind === "fallback" || candidate.kind === "url-open" || candidate.kind === "url-create") return list if (candidate.kind === "app") list.push({ id: "open-new", title: "Open New Window", shortcut: "Shift ↵", section: "primary", icon: "" }) if (candidate.kind === "app") list.push({ id: "copy-id", title: "Copy Desktop ID", shortcut: "Ctrl Shift C", section: "copy", icon: "" }) + if (candidate.kind === "quicklink") { + list.push({ id: "edit-quicklink", title: "Edit Quicklink", shortcut: "Ctrl E", section: "primary", icon: "" }) + list.push({ id: "copy-link", title: "Copy Link", shortcut: "Ctrl Shift C", section: "copy", icon: "" }) + } if (candidate.kind === "omarchy-action") list.push({ id: "copy-command", title: "Copy Command", shortcut: "Ctrl Shift C", section: "copy", icon: "" }) if (candidate.favoriteOrder === null || candidate.favoriteOrder === undefined) { @@ -413,7 +453,8 @@ function actionsFor(candidate) { list.push({ id: "set-alias", title: candidate.alias ? "Change Alias" : "Set Alias", shortcut: "", section: "configure", icon: "" }) if (candidate.alias) list.push({ id: "remove-alias", title: "Remove Alias", shortcut: "", section: "configure", icon: "" }) if (candidate.frecency > 1) list.push({ id: "reset-ranking", title: "Reset Ranking", shortcut: "", section: "configure", icon: "" }) - list.push({ id: "disable", title: "Disable Command", shortcut: "Alt Shift D", section: "delete", icon: "" }) + if (candidate.kind === "quicklink") list.push({ id: "delete-quicklink", title: "Delete Quicklink", shortcut: "Ctrl D", section: "delete", icon: "" }) + else list.push({ id: "disable", title: "Disable Command", shortcut: "Alt Shift D", section: "delete", icon: "" }) return list } @@ -528,6 +569,7 @@ if (typeof module !== "undefined") { decorate: decorate, rootSections: rootSections, submenuSections: submenuSections, + quicklinkSections: quicklinkSections, actionsFor: actionsFor, reorderFavorites: reorderFavorites, fallbackUrl: fallbackUrl diff --git a/core/Schema.js b/core/Schema.js index 4ffd1ed..ead543b 100644 --- a/core/Schema.js +++ b/core/Schema.js @@ -46,6 +46,19 @@ var calculatorMigrations = [ } ] +// Saved quicklinks (SPEC §8.4), in the shape Quicklinks.js reads: +// items [{id, name, link, iconName, openWith, createdAt, updatedAt}]. +var quicklinksMigrations = [ + { + version: 1, + name: "quicklinks", + up: function(doc) { + doc.items = Array.isArray(doc.items) ? doc.items : [] + return doc + } + } +] + // Clipboard History (SPEC §8.2): ClipboardHistory.add entries, newest first. var clipboardMigrations = [ { @@ -88,6 +101,7 @@ var documents = { settings: { file: "settings.json", migrations: settingsMigrations }, frecency: { file: "frecency.json", migrations: frecencyMigrations }, calculator: { file: "calculator.json", migrations: calculatorMigrations }, + quicklinks: { file: "quicklinks.json", migrations: quicklinksMigrations }, emoji: { file: "emoji.json", migrations: emojiMigrations }, clipboard: { file: "clipboard.json", migrations: clipboardMigrations } } @@ -150,6 +164,7 @@ if (typeof module !== "undefined") { module.exports = { settingsMigrations: settingsMigrations, frecencyMigrations: frecencyMigrations, + quicklinksMigrations: quicklinksMigrations, calculatorMigrations: calculatorMigrations, clipboardMigrations: clipboardMigrations, emojiMigrations: emojiMigrations, diff --git a/tests/quicklinks.test.js b/tests/quicklinks.test.js new file mode 100644 index 0000000..78dfc52 --- /dev/null +++ b/tests/quicklinks.test.js @@ -0,0 +1,191 @@ +const test = require("node:test") +const assert = require("node:assert/strict") +const Q = require("../core/Quicklinks.js") +const Migrate = require("../core/Migrate.js") +const Schema = require("../core/Schema.js") + +const NOW = new Date(2026, 9, 20, 9, 5, 7).getTime() // Tue 20 Oct 2026 09:05:07, local time +const apps = Q.installedApps([ + { id: "firefox", name: "Firefox", icon: "firefox" }, + { id: "chromium.desktop", name: "Chromium", icon: "chromium" }, + { id: "org.gnome.Nautilus", name: "Files", icon: "nautilus" } +]) +const ctx = { apps, now: NOW } + +function saved(input) { + const r = Q.save({ items: [] }, input, ctx) + assert.equal(r.error, "") + return r +} + +function expand(link, values, extra) { + const parsed = Q.parseLink(link) + assert.equal(parsed.error, "", parsed.error) + const args = Q.argumentValues(parsed, values || {}) + assert.equal(args.error, "", args.error) + return Q.expand(link, Object.assign({ now: NOW, values: args.values }, extra || {})) +} + +test("a new quicklinks document migrates to an empty library", () => { + const r = Migrate.migrate(null, Schema.documents.quicklinks.migrations, 1) + assert.deepEqual(r.doc.items, []) +}) + +test("save, update and remove keep names unique ignoring case", () => { + const first = saved({ name: " GitHub ", link: "github.com" }) + assert.equal(first.item.name, "GitHub") + assert.match(Q.save(first.doc, { name: "github", link: "x.com" }, ctx).error, /already exists/) + const second = Q.save(first.doc, { name: "Docs", link: "https://docs.example.com" }, { apps, now: NOW + 1 }) + assert.match(Q.update(second.doc, second.item.id, { name: "GITHUB", link: "y.com" }, ctx).error, /already exists/) + const renamed = Q.update(second.doc, first.item.id, { name: "GitHub Home", link: "github.com" }, { apps, now: NOW + 2 }) + assert.equal(renamed.item.createdAt, NOW) + assert.equal(renamed.item.updatedAt, NOW + 2) + assert.deepEqual(Q.list(Q.remove(renamed.doc, first.item.id).doc).map((i) => i.name), ["Docs"]) +}) + +test("save refuses empty fields, javascript:, a leading dash and bad placeholders", () => { + assert.match(Q.save({}, { name: "", link: "x.com" }, ctx).error, /name/) + assert.match(Q.save({}, { name: "a", link: " " }, ctx).error, /link/) + assert.match(Q.save({}, { name: "a", link: "javascript:alert(1)" }, ctx).error, /javascript/) + assert.match(Q.save({}, { name: "a", link: "--help" }, ctx).error, /cannot start with -/) + assert.match(Q.save({}, { name: "a", link: "https://x.com/{browser-tab.url}" }, ctx).error, /cannot use \{browser-tab.url\}/) + assert.match(Q.save({}, { name: "a", link: "https://x.com/{cursor}" }, ctx).error, /cannot use/) + assert.match(Q.save({}, { name: "a", link: "https://x.com/{clipboard offset=1}" }, ctx).error, /clipboard history/) + assert.match(Q.save({}, { name: "a", link: "https://x.com/{a}{b}{c}{d}" }, ctx).error, /at most 3/) + assert.match(Q.save({}, { name: "a", link: "https://x.com/{argument | shout}" }, ctx).error, /Unknown modifier/) +}) + +test("Open With takes an installed desktop id, and keeps a saved one that is gone", () => { + assert.equal(saved({ name: "a", link: "x.com", openWith: "FIREFOX.desktop" }).item.openWith, "firefox.desktop") + assert.match(Q.save({}, { name: "a", link: "x.com", openWith: "vlc.desktop" }, ctx).error, /not installed/) + assert.match(Q.save({}, { name: "a", link: "x.com", openWith: "rm -rf" }, ctx).error, /desktop id/) + // Before the app catalog loads, any well-formed id is accepted. + assert.equal(Q.save({}, { name: "a", link: "x.com", openWith: "vlc.desktop" }, { apps: [], now: NOW }).error, "") + const old = Q.save({}, { name: "a", link: "x.com", openWith: "vlc.desktop" }, { apps: [], now: NOW }) + assert.equal(Q.update(old.doc, old.item.id, { name: "b", link: "x.com", openWith: "vlc.desktop" }, ctx).error, "") + assert.equal(Q.openWithLabel(apps, "vlc.desktop"), "vlc.desktop (not installed)") + assert.equal(Q.openWithLabel(apps, ""), "Default") + assert.deepEqual(Q.openWithChoices(apps, "", "vlc.desktop").map((r) => r.title), ["Default", "vlc.desktop (not installed)", "Chromium", "Files", "Firefox"]) + assert.deepEqual(Q.openWithChoices(apps, "fire", "").map((r) => r.id), ["firefox.desktop"]) +}) + +test("import reads Raycast's export, skips duplicates and reports bad rows", () => { + const start = saved({ name: "GitHub", link: "github.com" }).doc + const text = JSON.stringify([ + { name: "GitHub", link: "github.com" }, + { name: "Maps", link: "https://maps.google.com/?q={query}", openWith: "com.google.Chrome" }, + { name: "Files", link: "~/Notes", openWith: "org.gnome.Nautilus.desktop" }, + { name: "Broken", link: "" }, + "nope" + ]) + const r = Q.importText(start, text, ctx) + assert.equal(r.added, 2) + assert.equal(r.duplicates, 1) + assert.equal(r.withoutApp, 1) + assert.deepEqual(r.failed, ["Broken", "row 5"]) + assert.deepEqual(Q.exportList(r.doc), [ + { name: "GitHub", link: "github.com" }, + { name: "Maps", link: "https://maps.google.com/?q={query}" }, + { name: "Files", link: "~/Notes", openWith: "org.gnome.Nautilus.desktop" } + ]) + assert.match(Q.importText(start, "{", ctx).error, /valid JSON/) + assert.match(Q.importText(start, "{}", ctx).error, /array/) +}) + +test("arguments merge by name, take defaults, and match options", () => { + const link = "https://x.com/{argument name=lang options=\"English: en, French: fr\"}/{argument name=\"search term\" default=\"hello world\"}/{lang}" + const parsed = Q.parseLink(link) + assert.deepEqual(parsed.arguments.map((a) => a.name), ["lang", "search term"]) + assert.match(Q.argumentValues(parsed, {}).error, /lang is required/) + assert.match(Q.argumentValues(parsed, { lang: "de" }).error, /not one of English, French/) + assert.equal(expand(link, { lang: "french" }).url, "https://x.com/fr/hello%20world/fr") +}) + +test("values are percent-encoded in URLs, raw on request, and raw in file paths", () => { + assert.equal(expand("https://x.com/?q={query}", { query: "a&b c" }).url, "https://x.com/?q=a%26b%20c") + assert.equal(expand("https://x.com/{path | raw}", { path: "a/b" }).url, "https://x.com/a/b") + assert.equal(expand("~/Notes/{argument}", { argument: "todo list.md" }).url, "~/Notes/todo list.md") + assert.equal(expand("{q | uppercase}.com", { q: "Hi" }).url, "HI.com") + assert.equal(expand("https://x.com/{q:fallback}").url, "https://x.com/fallback") + assert.equal(expand("https://x.com/{\"literal").url, "https://x.com/{\"literal") +}) + +test("an expansion that leaves nothing or a leading dash is refused with its reason", () => { + assert.match(expand("{clipboard}", {}, { clipboard: "" }).error, /empty after/) + assert.match(expand("{clipboard | raw}", {}, { clipboard: "-rf" }).error, /cannot start with -/) + assert.equal(expand("https://x.com/?q={selection}", {}, { selection: "hi" }).url, "https://x.com/?q=hi") + assert.equal(Q.parseLink("{selection}{clipboard}").needsSelection, true) +}) + +test("dates use ICU patterns, offsets and localized names", () => { + assert.equal(expand("{date}").url, "20%20Oct%202026") + assert.equal(expand("{time | raw}").url, "09:05") + assert.equal(expand("{date format=\"EEE, d MMMM yy\" | raw}").url, "Tue, 20 October 26") + assert.equal(expand("{date format=\"EEEE 'at' h a\" | raw}").url, "Tuesday at 9 AM") + assert.equal(expand("{date \"yyyy-MM-dd\" +1D | raw}").url, "2026-10-21") + assert.equal(expand("{date format=\"yyyy-MM-dd HH:mm\" offset=\"-1M +2h -5m\" | raw}").url, "2026-09-20 11:00") + assert.equal(expand("{day | raw}").url, "Tuesday") + const names = (locale) => ({ month: () => locale + "-month", day: () => locale + "-day" }) + assert.equal(expand("{date format=\"EEEE MMMM\" locale=fr | raw}", {}, { names }).url, "fr-day fr-month") + assert.match(Q.parseLink("{date +1w}").error, /Bad date offset/) +}) + +test("web addresses: real hosts are detected, abbreviations and files are not", () => { + assert.equal(Q.webAddress("github.com/x"), "https://github.com/x") + assert.equal(Q.webAddress("localhost:3000"), "http://localhost:3000") + assert.equal(Q.webAddress("1.2.3.4"), "https://1.2.3.4") + assert.equal(Q.webAddress("bbc.co.uk"), "https://bbc.co.uk") + assert.equal(Q.webAddress("https://example.museum"), "https://example.museum") + assert.equal(Q.webAddress("spotify://track/1"), "spotify://track/1") + for (const q of ["e.g", "a.m", "vs.code", "node.js", "notes.md", "github", "1.2.3.999", "two words.com", "x.com:99999", "goo​gle.com"]) { + assert.equal(Q.webAddress(q), "", q) + } +}) + +test("web links and bare hosts open in the browser, others with xdg-open or the chosen app", () => { + assert.deepEqual(Q.openArgv("github.com", "", "/home/u"), ["omarchy-launch-browser", "https://github.com"]) + assert.deepEqual(Q.openArgv("https://github.com", "", "/home/u"), ["omarchy-launch-browser", "https://github.com"]) + assert.deepEqual(Q.openArgv("~/Notes/a b.md", "", "/home/u"), ["xdg-open", "/home/u/Notes/a b.md"]) + assert.deepEqual(Q.openArgv("mailto:a@b.co", "", "/home/u"), ["xdg-open", "mailto:a@b.co"]) + assert.deepEqual(Q.openArgv("github.com", "chromium.desktop", "/home/u"), ["uwsm-app", "--", "gtk-launch", "chromium.desktop", "https://github.com"]) + assert.equal(Q.openArgv("-x", "", "/home/u"), null) + assert.equal(Q.openArgv("x.com", "bad id", "/home/u"), null) +}) + +test("a quicklink becomes a root-search candidate", () => { + const c = Q.toCandidate(saved({ name: "GitHub", link: "github.com" }).item) + assert.equal(c.type, "quicklink") + assert.equal(c.title, "GitHub") + assert.match(c.id, /^quicklink:ql-/) + assert.deepEqual(c.arguments, []) + const withArgs = Q.toCandidate(saved({ name: "DDG", link: "https://duckduckgo.com/?q={query}&kl={argument name=region default=wt-wt}" }).item) + assert.deepEqual(withArgs.arguments.map((a) => [a.name, a.defaultValue]), [["query", ""], ["region", "wt-wt"]]) +}) + +test("local addresses open as http, javascript:// is not an address, keywords ignore case", () => { + assert.equal(Q.webAddress("127.0.0.1:3000"), "http://127.0.0.1:3000") + assert.equal(Q.webAddress("192.168.1.1"), "http://192.168.1.1") + assert.equal(Q.webAddress("172.20.0.5/admin"), "http://172.20.0.5/admin") + assert.equal(Q.webAddress("8.8.8.8"), "https://8.8.8.8") + assert.equal(Q.webAddress("10.tv"), "https://10.tv") + assert.equal(Q.webAddress("127.example.com"), "https://127.example.com") + assert.equal(Q.webAddress("javascript://x"), "") + assert.equal(Q.parseLink("https://x.com/{UUID}").arguments.length, 0) +}) + +test("Create Quicklink suggests a name and link from a URL or path, nothing else", () => { + assert.deepEqual(Q.suggestion("https://www.github.com/x?y=1"), { name: "github.com", link: "https://www.github.com/x?y=1" }) + assert.deepEqual(Q.suggestion(" github.com "), { name: "github.com", link: "https://github.com" }) + assert.deepEqual(Q.suggestion("~/Notes/a b.md"), { name: "a b.md", link: "~/Notes/a b.md" }) + assert.deepEqual(Q.suggestion("mailto:a@b.co"), { name: "a@b.co", link: "mailto:a@b.co" }) + for (const t of ["", "hello world", "e.g", "javascript:alert(1)", "two\nlines.com"]) assert.equal(Q.suggestion(t), null, t) +}) + +test("quicklink arguments use the argument-pill shape", () => { + const RS = require("../core/RootSearch.js") + const c = Q.toCandidate({ id: "a", name: "Repo", link: "https://github.com/{argument name=owner}/{argument name=repo default=oma-cast}?tab={argument name=tab options=\"Code,Issues\"}" }) + assert.deepEqual(c.arguments.map((a) => [a.name, a.required, a.placeholder]), [["owner", true, "owner"], ["repo", false, "oma-cast"], ["tab", true, "tab ▾"]]) + assert.equal(RS.missingArgument(c.arguments, { repo: "x" }), 0) + assert.equal(RS.missingArgument(c.arguments, { owner: "basecamp" }), 2) + assert.equal(RS.missingArgument(c.arguments, { owner: "basecamp", tab: "Issues" }), -1) +}) diff --git a/tests/rootsearch.test.js b/tests/rootsearch.test.js index f745aa4..01d6cd4 100644 --- a/tests/rootsearch.test.js +++ b/tests/rootsearch.test.js @@ -134,6 +134,28 @@ test("fallback URLs encode the query", () => { assert.equal(RS.fallbackUrl(RS.FALLBACKS[0], " a&b c "), "https://www.google.com/search?q=a%26b%20c") }) +test("a web address offers Open in Browser and Create Quicklink before the fallbacks", () => { + const Quicklinks = require("../core/Quicklinks.js") + const sections = RS.rootSections(candidates(), "github.com/x", ctx(), Object.assign({ Quicklinks }, deps)) + const link = sections.find((s) => s.id === "url") + assert.deepEqual(titles(link), ["Open in Browser", "Create Quicklink"]) + assert.equal(link.rows[0].candidate.url, "https://github.com/x") + assert.equal(sections[sections.length - 1].id, "fallback-commands") + assert.equal(RS.rootSections(candidates(), "vs.code", ctx(), Object.assign({ Quicklinks }, deps)).some((s) => s.id === "url"), false) +}) + +test("quicklinks are searched from the root and listed by name in Search Quicklinks", () => { + const Quicklinks = require("../core/Quicklinks.js") + const links = [{ id: "a", name: "Maps", link: "x.com" }, { id: "b", name: "GitHub", link: "github.com" }].map(Quicklinks.toCandidate) + const all = candidates().concat(links) + assert.equal(RS.rootSections(all, "", ctx(), deps).some((s) => s.rows.some((r) => r.candidate.type === "quicklink")), false) + assert.equal(titles(RS.rootSections(all, "github", ctx(), deps)[0])[0], "GitHub") + assert.deepEqual(titles(RS.quicklinkSections(all, "", ctx(), deps)[0]), ["GitHub", "Maps"]) + assert.deepEqual(titles(RS.quicklinkSections(all, "map", ctx(), deps)[0]), ["Maps"]) + const actions = RS.actionsFor(RS.decorate(links[0], ctx(), deps)).map((a) => a.id) + assert.deepEqual(actions, ["open", "edit-quicklink", "copy-link", "favorite-add", "set-alias", "delete-quicklink"]) +}) + test("web searches take an inline argument", () => { const google = results("google")[0].rows[0].candidate assert.equal(google.id, "builtin:google-search") diff --git a/ui/LauncherWindow.qml b/ui/LauncherWindow.qml index 1071842..a46cc9d 100644 --- a/ui/LauncherWindow.qml +++ b/ui/LauncherWindow.qml @@ -145,6 +145,7 @@ PanelWindow { property var argValues: ({}) property int argFocus: -1 property string argsForId: "" + property var pendingPrompt: null // Navigation bindings (ref 04 §2.8): emacs moves with Ctrl+N (Ctrl+P is the // dropdown); vim-motions with Ctrl+J/K, which moves the action panel to @@ -155,13 +156,28 @@ PanelWindow { readonly property bool atRoot: window.stack.length === 1 readonly property bool compact: window.general.windowMode === "compact" && window.atRoot && !window.query - readonly property string placeholder: window.view.kind === "alias" ? "Type an alias, then press ↵" - : window.view.kind === "menu" ? "Search " + window.view.title + "…" - : window.view.kind === "calculator-history" ? "Search calculations…" - : window.clipboardView ? "Type to filter entries…" - : window.view.kind === "theme" ? "Search themes…" - : window.grid ? "Search Emoji & Symbols…" - : "Search for apps and commands…" + // Editor views (alias, quicklink form, import) take the header text as + // input instead of searching; a form edits its focused field there. + readonly property bool editor: ["alias", "quicklink-form", "quicklink-import"].indexOf(window.view.kind) >= 0 + readonly property bool formActive: window.view.kind === "quicklink-form" + readonly property var focusedField: window.view.kind === "quicklink-form" ? window.view.fields[window.view.focus] : null + // The Open With field filters installed apps instead of taking text. + readonly property bool pickingApp: !!(window.focusedField && window.focusedField.picker) + readonly property bool pickedSelected: window.pickingApp && !!window.selectedRow && window.selectedRow.itemId === (window.focusedField.value || "") + readonly property string placeholder: { + var kind = window.view.kind + if (kind === "alias") return "Type an alias, then press ↵" + if (kind === "quicklink-import") return "Path to a JSON file, or ↵ to import the clipboard" + if (window.pickingApp) return "Search apps…" + if (window.focusedField) return window.focusedField.placeholder || window.focusedField.label + if (kind === "quicklinks") return "Search quicklinks…" + if (kind === "menu") return "Search " + window.view.title + "…" + if (kind === "calculator-history") return "Search calculations…" + if (window.clipboardView) return "Type to filter entries…" + if (kind === "theme") return "Search themes…" + if (window.grid) return "Search Emoji & Symbols…" + return "Search for apps and commands…" + } readonly property int cardWidth: Math.min(px(750), width - Style.gapsOut * 2) readonly property int fullHeight: Math.min(px(475), height - Style.gapsOut * 2) @@ -249,6 +265,7 @@ PanelWindow { window.searchSerial++ window.backend.cancelSearch() window.searchPending = false + window.pendingPrompt = null window.closePopups() var seconds = Number(window.general.popToRootTimeout) if (!(seconds > 0)) window.popToRoot() @@ -289,7 +306,7 @@ PanelWindow { saved[saved.length - 1] = Object.assign({}, window.view, { query: window.query, selectedIndex: window.selectedIndex }) window.stack = saved.concat([next]) if (next.kind === "clipboard") window.clipboardFilter = "all" - window.query = next.kind === "alias" ? (next.value || "") : "" + window.query = next.kind === "alias" ? (next.value || "") : (next.fields ? window.fieldText(next.fields[0]) : "") window.rebuild(true) } @@ -318,7 +335,8 @@ PanelWindow { pointerGate.reset() var keepId = !resetSelection && window.selectedRow ? window.selectedRow.itemId : "" window.searchPending = false - if (window.view.kind === "alias") { Rows.update(rows, []); window.select(-1); return } + if (window.pickingApp) { window.fillOpenWithRows(); return } + if (window.editor) { Rows.update(rows, []); window.select(-1); return } window.searchPending = true var revision = window.backend.candidatesRevision window.backend.searchAsync({ query: window.query, view: window.view, filter: window.activeFilter }, function(result) { @@ -330,7 +348,9 @@ PanelWindow { } function applySearch(result, keepId, restoreIndex) { + if (window.pendingPrompt && window.query !== window.pendingPrompt.title) window.pendingPrompt = null if (!result.ok) { + window.pendingPrompt = null Rows.update(rows, []) window.showToast("failure", result.error) window.select(-1) @@ -363,6 +383,7 @@ PanelWindow { Rows.update(rows, next) if (restoreIndex >= 0 && restoreIndex < rows.count && window.isSelectable(restoreIndex)) window.select(restoreIndex) else window.select(keepIndex >= 0 ? keepIndex : window.nextSelectable(-1, 1), keepIndex >= 0 ? keepColumn : 0) + window.takePendingPrompt() } function rowData(c, kind) { @@ -489,10 +510,7 @@ PanelWindow { if (!window.selectedRow) return window.actionPanelOpen = false // ↵ on a command with an empty required argument focuses that pill. - if (actionId === "open" && window.argDefs.length) { - var missing = RootSearch.missingArgument(window.argDefs, window.argValues) - if (missing >= 0) { window.argFocus = missing; return } - } + if (actionId === "open" && window.focusMissingArgument()) return window.request({ id: window.selectedRow.itemId, action: actionId, query: window.query, arguments: window.argValues }) } @@ -501,6 +519,7 @@ PanelWindow { if (!r.ok) { window.showToast("failure", r.error); return } var outcome = r.data || {} if (outcome.confirm) { window.alert = { spec: outcome.confirm, payload: payload }; return } + if (outcome.arguments) { window.focusMissingArgument(); return } if (outcome.push) { window.push(outcome.push); return } if (outcome.close) { if (outcome.hud) window.hud(outcome.hud) @@ -591,7 +610,26 @@ PanelWindow { if (action.done) window.showToast("success", action.done) } - // Typing, Tab and Backspace while an argument pill has focus. + // Focus the first required argument still empty; true when there is one. + function focusMissingArgument() { + if (!window.argDefs.length) return false + var missing = RootSearch.missingArgument(window.argDefs, window.argValues) + if (missing < 0) return false + window.argFocus = missing + return true + } + + // A quicklink argument with options steps through them with ↑/↓ [D]. + function stepOption(def, value, direction) { + var options = def.options + var current = String(value || "").toLowerCase() + var at = -1 + for (var i = 0; i < options.length; i++) if (options[i].title.toLowerCase() === current || options[i].value.toLowerCase() === current) at = i + var next = at < 0 ? (direction > 0 ? 0 : options.length - 1) : (at + direction + options.length) % options.length + return options[next].title + } + + // Typing, Tab, Backspace and option ↑/↓ while an argument pill has focus. function handleArgumentKey(event, shift) { var def = window.argDefs[window.argFocus] var value = window.argValues[def.name] || "" @@ -601,6 +639,10 @@ PanelWindow { values[def.name] = next window.argValues = values } + if (def.options && def.options.length && (key === Qt.Key_Up || key === Qt.Key_Down) && !(event.modifiers & (Qt.ControlModifier | Qt.AltModifier))) { + set(window.stepOption(def, value, key === Qt.Key_Down ? 1 : -1)) + return true + } if (key === Qt.Key_Tab || key === Qt.Key_Backtab) { var step = shift || key === Qt.Key_Backtab ? -1 : 1 var next = window.argFocus + step @@ -616,11 +658,168 @@ PanelWindow { if (key === Qt.Key_Backspace) { set(""); return true } return window.isTyping(event) } - if (Util.editsFilter(event, value)) { set(Util.editedFilter(event, value)); return true } + // editsFilter skips an empty value; an edit key there must not fall through to the search text. + if (Util.editsFilter(event, value || " ")) { if (value) set(Util.editedFilter(event, value)); return true } if (window.isTyping(event)) { set(value + event.text); return true } return false } + // --------------------------------------------------------------- forms + + // The header text for a field: its value, except the picker, which starts + // with an empty search. + function fieldText(field) { + return field && !field.picker ? String(field.value || "") : "" + } + + function replaceView(changes) { + var stack = window.stack.slice() + stack[stack.length - 1] = Object.assign({}, window.view, changes) + window.stack = stack + } + + // Copy the header into the focused field's value. + function stashField() { + if (!window.formActive || window.pickingApp) return + var fields = window.view.fields.map(function(f) { return Object.assign({}, f) }) + fields[window.view.focus].value = window.query + window.replaceView({ fields: fields }) + } + + function setFormFocus(index) { + if (!window.formActive || index < 0 || index >= window.view.fields.length) return + window.stashField() + window.replaceView({ focus: index }) + window.query = window.fieldText(window.view.fields[index]) + window.rebuild(true) + } + + // Fill a new, untouched Create Quicklink form from the clipboard. + function autofillQuicklink(suggested) { + if (!window.formActive || window.view.quicklinkId) return + window.stashField() + var fields = window.view.fields.map(function(f) { return Object.assign({}, f) }) + if (fields.some(function(f) { return f.value })) return + fields.forEach(function(f) { if (f.key === "name" || f.key === "link") f.value = suggested[f.key] || "" }) + window.replaceView({ fields: fields }) + if (!window.pickingApp) window.query = window.fieldText(fields[window.view.focus]) + } + + function formValues() { + window.stashField() + var out = ({}) + for (var i = 0; i < window.view.fields.length; i++) out[window.view.fields[i].key] = window.view.fields[i].value + return out + } + + function fillOpenWithRows() { + var current = window.focusedField.value || "" + var r = window.backend.callSync("quicklinks.openWithChoices", { query: window.query, current: current }) + var choices = r.ok ? r.data : [] + var next = [] + var keep = -1 + for (var i = 0; i < choices.length; i++) { + if (choices[i].id === current) keep = next.length + next.push(window.rowData(choices[i], "item")) + } + Rows.update(rows, next) + window.select(!window.query && keep >= 0 ? keep : window.nextSelectable(-1, 1)) + } + + // ↵ in Open With picks the highlighted app; ↵ on the app already chosen saves. + function chooseOpenWith() { + if (!window.selectedRow) return + if (window.pickedSelected) { window.saveQuicklink(); return } + var fields = window.view.fields.map(function(f) { return Object.assign({}, f) }) + fields[window.view.focus].value = window.selectedRow.itemId + window.replaceView({ fields: fields }) + window.query = "" + window.rebuild(true) + } + + function openWithText(id) { + var r = window.backend.callSync("quicklinks.openWithLabel", { id: id || "" }) + return r.ok ? String(r.data) : String(id || "") + } + + function saveQuicklink() { + var data = window.formValues() + var editing = !!window.view.quicklinkId + if (editing) data.id = window.view.quicklinkId + var r = window.backend.callSync(editing ? "quicklinks.update" : "quicklinks.save", data) + if (!r.ok) { window.showToast("failure", r.error); return } + window.pop() + window.showToast("success", editing ? "Quicklink saved" : "Quicklink created") + window.rebuild(false) + } + + // `omacast run quicklink:` for a link with arguments: find its row + // and put the cursor in its first empty pill. + function promptArguments(target) { + window.pendingPrompt = { id: String(target.id || ""), title: String(target.title || "") } + if (window.query === window.pendingPrompt.title) window.rebuild(true) + else window.setQuery(window.pendingPrompt.title) + } + + function takePendingPrompt() { + var target = window.pendingPrompt + if (!target) return + window.pendingPrompt = null + for (var i = 0; i < rows.count; i++) { + if (rows.get(i).itemId === target.id) { window.select(i); window.focusMissingArgument(); return } + } + window.showToast("failure", "Cannot find " + target.title) + } + + function importQuicklinks() { + var r = window.backend.callSync("quicklinks.import", { path: window.query }) + if (!r.ok) { window.showToast("failure", r.error); return } + window.pop() + window.showToast(r.data.ok ? "success" : "failure", r.data.title) + window.rebuild(false) + } + + function isTab(event) { return event.key === Qt.Key_Tab && !(event.modifiers & Qt.ShiftModifier) } + function isBacktab(event) { return event.key === Qt.Key_Backtab || (event.key === Qt.Key_Tab && (event.modifiers & Qt.ShiftModifier) !== 0) } + + // Keys inside an editor view; true when handled. + function handleEditorKey(event, key, ctrl, enter) { + var kind = window.view.kind + if (kind === "alias") { + if (enter) { window.saveAlias(); return true } + return key === Qt.Key_Space + } + if (kind === "quicklink-import") { + if (enter) { window.importQuicklinks(); return true } + return false + } + var focus = window.view.focus + var last = window.view.fields.length - 1 + if (enter && ctrl) { window.saveQuicklink(); return true } + if (window.isTab(event)) { window.setFormFocus(focus + 1); return true } + if (window.isBacktab(event)) { window.setFormFocus(focus - 1); return true } + if (window.pickingApp) { + if (enter) { window.chooseOpenWith(); return true } + var dir = window.direction(event, ctrl, false, true) + if (dir > 0) { window.move(1); return true } + if (dir < 0) { + if (window.selectedIndex === window.nextSelectable(-1, 1)) window.setFormFocus(focus - 1) + else window.move(-1) + return true + } + if (Util.editsFilter(event, window.query || " ")) { + if (window.query) window.setQuery(Util.editedFilter(event, window.query)) + return true + } + if (window.isTyping(event)) { window.setQuery(window.query + event.text); return true } + return true + } + if (enter) { if (focus >= last) window.saveQuicklink(); else window.setFormFocus(focus + 1); return true } + if (key === Qt.Key_Down) { window.setFormFocus(focus + 1); return true } + if (key === Qt.Key_Up) { window.setFormFocus(focus - 1); return true } + return false + } + function saveAlias() { var r = window.backend.callSync("settings.updateCommandSettings", { commandId: window.view.commandId, alias: window.query }) if (!r.ok) { window.showToast("failure", r.error); return } @@ -656,7 +855,7 @@ PanelWindow { if (window.query === next) return window.query = next window.historyIndex = -1 - window.rebuild(true) + if (!window.editor || window.pickingApp) window.rebuild(true) } function pasteClipboard() { @@ -721,7 +920,7 @@ PanelWindow { window.popToRoot() return } - if (window.query && window.view.kind !== "alias") window.setQuery("") + if (window.query && (!window.editor || window.pickingApp)) window.setQuery("") else if (!window.atRoot) window.pop() else window.dismissRequested() } @@ -767,7 +966,8 @@ PanelWindow { if (window.alert) { if (key === Qt.Key_Escape) window.alert = null - else if (enter) window.confirmAlert() + // A held Enter that opened the alert must not also confirm it. + else if (enter && !event.isAutoRepeat) window.confirmAlert() return true } if (key === Qt.Key_Escape) { window.handleEscape(shift); return true } @@ -800,9 +1000,8 @@ PanelWindow { return window.handlePopupKey(event, actionPanel.item, ctrl, alt) } - if (window.view.kind === "alias") { - if (enter) { window.saveAlias(); return true } - if (key === Qt.Key_Space) return true + if (window.editor) { + if (window.handleEditorKey(event, key, ctrl, enter)) return true } else { if (ctrl && shift && key === Qt.Key_K) { window.toggleAbout(); return true } if (window.isActionPanelKey(ctrl, alt, shift, key)) { window.toggleActionPanel(); return true } @@ -834,9 +1033,10 @@ PanelWindow { if (key === Qt.Key_PageUp) { window.move(-8); return true } if (key === Qt.Key_PageDown) { window.move(8); return true } if (ctrl && shift && key === Qt.Key_F) { window.performIfOffered(["favorite-add", "favorite-remove"]); return true } - if (ctrl && shift && key === Qt.Key_C) { window.performIfOffered(["copy-command", "copy-id", "copy-question-answer", "copy-name"]); return true } + if (ctrl && shift && key === Qt.Key_C) { window.performIfOffered(["copy-command", "copy-id", "copy-question-answer", "copy-name", "copy-link"]); return true } if (ctrl && shift && key === Qt.Key_D) { window.performIfOffered(["delete-all-entries", "clear-recent"]); return true } - if (ctrl && key === Qt.Key_D) { window.performIfOffered(["delete-entry", "remove-recent"]); return true } + if (ctrl && key === Qt.Key_D) { window.performIfOffered(["delete-entry", "remove-recent", "delete-quicklink"]); return true } + if (ctrl && !shift && key === Qt.Key_E && window.performIfOffered(["edit-quicklink"])) return true if (alt && shift && key === Qt.Key_D) { window.performIfOffered(["disable"]); return true } if (ctrl && key >= Qt.Key_1 && key <= Qt.Key_9) { var target = window.nthItem(key - Qt.Key_0) @@ -848,7 +1048,7 @@ PanelWindow { if (Util.editsFilter(event, window.query)) { window.setQuery(Util.editedFilter(event, window.query)); return true } // Super+Backspace (Omarchy's delete to line start) arrives raw under the submap: clear the query. if (key === Qt.Key_Backspace && window.superOnly(event)) { window.setQuery(""); return true } - if (key === Qt.Key_Backspace && !window.query && !window.atRoot) { window.pop(); return true } + if (key === Qt.Key_Backspace && !window.query && !window.atRoot && !window.formActive) { window.pop(); return true } if (window.isTyping(event)) { window.setQuery(window.query + event.text); return true } return false } @@ -860,15 +1060,20 @@ PanelWindow { Connections { target: window.backend - function onCandidatesRevisionChanged() { if (window.shown && !window.actionPanelOpen && !window.alert) window.rebuild(false) } - // Exchange rates or zone offsets arrived: re-evaluate a calculation on screen. - function onCalculatorRevisionChanged() { if (window.shown && !window.actionPanelOpen && window.query) window.rebuild(false) } - // A copy, pin or delete: refresh an open Clipboard History. - function onNotification(method) { + function onCandidatesRevisionChanged() { if (window.shown && !window.actionPanelOpen && !window.alert && (!window.editor || window.pickingApp)) window.rebuild(false) } + function onNotification(method, data) { + if (method === "quicklinks.autofill") window.autofillQuicklink(data) + if (method === "quicklinks.exported" || method === "quicklinks.imported") { + if (window.shown) window.showToast(data.ok ? "success" : "failure", data.title) + else window.hud(data.title) + } + // A copy, pin or delete: refresh an open Clipboard History. if (method !== "clipboard.stateChanged" && method !== "themes.changed") return window.clipboardRevision++ if (window.shown && window.splitView && !window.actionPanelOpen && !window.alert) window.rebuild(false) } + // Exchange rates or zone offsets arrived: re-evaluate a calculation on screen. + function onCalculatorRevisionChanged() { if (window.shown && !window.actionPanelOpen && window.query) window.rebuild(false) } } @@ -986,7 +1191,7 @@ PanelWindow { Row { id: pills - visible: window.argDefs.length > 0 && window.view.kind !== "alias" + visible: window.argDefs.length > 0 && !window.editor x: queryText.x + (window.query ? queryText.width : 0) + window.px(10) anchors.verticalCenter: parent.verticalCenter spacing: window.px(6) @@ -1019,7 +1224,7 @@ PanelWindow { readonly property string shownValue: dropdown ? ScriptCommands.optionTitle(pill.modelData, pill.value) : pill.modelData.type === "password" ? "•".repeat(pill.value.length) : pill.value text: (dropdown && pill.focused ? "‹ " : "") - + (shownValue || (pill.modelData.placeholder + (pill.modelData.required ? "" : " (optional)"))) + + (shownValue || (pill.modelData.placeholder + (pill.modelData.required || pill.modelData.defaultValue ? "" : " (optional)"))) + (dropdown && pill.focused ? " ›" : "") opacity: pill.value ? 1 : 0.5 color: window.look.foreground @@ -1118,16 +1323,79 @@ PanelWindow { anchors.leftMargin: card.borderLeft + window.px(8) anchors.rightMargin: card.borderRight + window.px(8) + // The form's fields; the focused one shows the header text. + Column { + id: formColumn + visible: window.formActive + anchors.left: parent.left + anchors.right: parent.right + anchors.top: parent.top + anchors.topMargin: window.px(8) + spacing: window.px(2) + + Repeater { + model: window.formActive ? window.view.fields : [] + delegate: Item { + required property var modelData + required property int index + readonly property bool focused: index === window.view.focus + width: formColumn.width + height: window.px(40) + + Rectangle { + anchors.fill: parent + radius: Math.max(Style.cornerRadius, window.px(6)) + color: parent.focused ? window.look.selectedBackground : "transparent" + } + Text { + id: fieldLabel + anchors.left: parent.left + anchors.leftMargin: window.px(12) + anchors.verticalCenter: parent.verticalCenter + width: window.px(110) + textFormat: Text.PlainText + text: modelData.label + color: window.look.foreground + opacity: 0.55 + font.family: window.look.fontFamily + font.pixelSize: Math.round(Style.font.body * window.zoom) + elide: Text.ElideRight + } + Text { + anchors.left: fieldLabel.right + anchors.leftMargin: window.px(8) + anchors.right: parent.right + anchors.rightMargin: window.px(12) + anchors.verticalCenter: parent.verticalCenter + textFormat: Text.PlainText + readonly property string value: modelData.picker ? (window.backend.candidatesRevision, window.openWithText(modelData.value)) + : (parent.focused ? window.query : String(modelData.value || "")) + text: value || modelData.placeholder || "" + opacity: value ? 1 : 0.4 + color: window.look.foreground + font.family: window.look.fontFamily + font.pixelSize: Math.round(Style.font.title * window.zoom) + elide: Text.ElideRight + } + MouseArea { + anchors.fill: parent + cursorShape: Qt.PointingHandCursor + onClicked: window.setFormFocus(index) + } + } + } + } + ListView { id: list anchors.left: parent.left - anchors.top: parent.top + anchors.top: window.formActive ? formColumn.bottom : parent.top anchors.bottom: parent.bottom // Clipboard History is list on the left, detail on the right (ref 04 §2 master-detail). width: window.splitView ? Math.round(parent.width * 0.4) : parent.width anchors.topMargin: window.px(4) anchors.bottomMargin: window.px(4) - visible: window.view.kind !== "alias" + visible: !window.editor || window.pickingApp clip: true model: rows reuseItems: true @@ -1145,8 +1413,13 @@ PanelWindow { zoom: window.zoom selectedColumn: window.selectedColumn columns: Emoji.COLUMNS - onHovered: function(i, item, mouse) { if (!window.actionPanelOpen && pointerGate.moved(item, mouse)) window.select(i, item.isGrid ? item.columnAt(mouse.x) : undefined) } - onClicked: function(i, column) { if (window.grid) window.select(i, column); window.perform("open", i) } + // Hover doesn't move the selection while a pill is being typed in. + onHovered: function(i, item, mouse) { if (!window.actionPanelOpen && window.argFocus < 0 && pointerGate.moved(item, mouse)) window.select(i, item.isGrid ? item.columnAt(mouse.x) : undefined) } + onClicked: function(i, column) { + if (window.pickingApp) { window.select(i); window.chooseOpenWith(); return } + if (window.grid) window.select(i, column) + window.perform("open", i) + } } } @@ -1164,7 +1437,7 @@ PanelWindow { Column { anchors.centerIn: parent spacing: window.px(8) - visible: window.view.kind === "alias" || rows.count === 0 + visible: !window.formActive && (window.editor || rows.count === 0) Logo { anchors.horizontalCenter: parent.horizontalCenter @@ -1183,8 +1456,9 @@ PanelWindow { Text { anchors.horizontalCenter: parent.horizontalCenter textFormat: Text.PlainText - text: window.view.kind === "alias" ? window.view.title + text: window.editor ? window.view.title : window.view.kind === "calculator-history" && !window.query ? "No Calculations Yet" + : window.view.kind === "quicklinks" && !window.query ? "No Quicklinks Yet" : window.clipboardView && !window.query && window.clipboardFilter === "all" ? "No Clipboard Entries" : (window.backend.ready ? "No results" : "Loading…") color: window.look.foreground @@ -1194,10 +1468,17 @@ PanelWindow { Text { anchors.horizontalCenter: parent.horizontalCenter textFormat: Text.PlainText - text: window.view.kind === "alias" ? "Typing the alias exactly in the root search puts this command on top. Leave it empty to remove it." - : window.view.kind === "calculator-history" && !window.query ? "Type a calculation in the root search, then copy or paste the answer." - : window.clipboardView && !window.query && window.clipboardFilter === "all" - ? (window.backend.config.clipboardHistory ? "Copy something and it shows up here." : "Recording is off: clipboardHistory is false in config.json.") : "" + text: { + switch (window.view.kind) { + case "alias": return "Typing the alias exactly in the root search puts this command on top. Leave it empty to remove it." + case "quicklink-import": return "Reads a JSON array of {name, link} rows, as Raycast exports them. Rows already saved are skipped." + case "calculator-history": return window.query ? "" : "Type a calculation in the root search, then copy or paste the answer." + case "quicklinks": return window.query ? "" : "Run Create Quicklink, or type a web address in the root search." + case "clipboard": return window.query || window.clipboardFilter !== "all" ? "" + : window.backend.config.clipboardHistory ? "Copy something and it shows up here." : "Recording is off: clipboardHistory is false in config.json." + } + return "" + } visible: text.length > 0 color: window.look.foreground opacity: 0.55 @@ -1280,6 +1561,9 @@ PanelWindow { window.selectedRow window.backend.storeRevision if (window.view.kind === "alias") return { title: "Save Alias", shortcut: "↵" } + if (window.pickingApp) return { title: window.pickedSelected ? "Save Quicklink" : "Select App", shortcut: "↵" } + if (window.view.kind === "quicklink-form") return { title: window.view.focus >= window.view.fields.length - 1 ? "Save Quicklink" : "Next Field", shortcut: "↵" } + if (window.view.kind === "quicklink-import") return { title: window.query ? "Import File" : "Import Clipboard", shortcut: "↵" } var list = window.actionsForSelected() return list.length ? list[0] : null } @@ -1306,14 +1590,14 @@ PanelWindow { zoom: window.zoom } Rectangle { - visible: window.view.kind !== "alias" + visible: !window.editor anchors.verticalCenter: parent.verticalCenter width: 1 height: window.px(14) color: Util.alpha(window.look.foreground, 0.2) } Text { - visible: window.view.kind !== "alias" + visible: !window.editor anchors.verticalCenter: parent.verticalCenter textFormat: Text.PlainText text: "Actions" @@ -1323,7 +1607,7 @@ PanelWindow { font.pixelSize: Math.round(Style.font.bodySmall * window.zoom) } KeyHint { - visible: window.view.kind !== "alias" + visible: !window.editor anchors.verticalCenter: parent.verticalCenter keys: window.actionPanelKeys color: window.look.foreground