hop
Hop: a small native macOS launcher. Clipboard history, find, on-device dictation and your coding agent behind one key.
Brought by drakestapleton
| 1 | import AppKit |
| 2 | import SwiftUI |
| 3 | |
| 4 | /// Things the one box can do that are not an app, a file or something copied. |
| 5 | enum SmartCommand: String, CaseIterable { |
| 6 | case settings = "Settings", reindex = "Rebuild file index", newChat = "New chat", quit = "Quit Hop" |
| 7 | var icon: String { |
| 8 | switch self { case .settings: "gearshape"; case .reindex: "arrow.triangle.2.circlepath"; case .newChat: "plus.bubble"; case .quit: "power" } |
| 9 | } |
| 10 | var keywords: [String] { |
| 11 | switch self { |
| 12 | case .settings: ["settings", "preferences", "config", "hop settings"] |
| 13 | case .reindex: ["rebuild file index", "reindex", "index files"] |
| 14 | case .newChat: ["new chat", "clear chat"] |
| 15 | case .quit: ["quit hop"] |
| 16 | } |
| 17 | } |
| 18 | } |
| 19 | |
| 20 | /// What Hop knows about the moment it was opened. Only this: which app was in front (its id, name and place on |
| 21 | /// disk), which app was in front before that, and the hour. No window titles, no screen contents, no new permission. |
| 22 | struct HopContext: Equatable { |
| 23 | var frontID = "" // bundle id of the app in front when Hop was opened |
| 24 | var frontName = "" |
| 25 | var frontPath = "" |
| 26 | var previousPath = "" // the app that was in front before that one |
| 27 | var hour = Calendar.current.component(.hour, from: Date()) |
| 28 | |
| 29 | private static let browsers: Set<String> = ["com.apple.Safari", "com.google.Chrome", "com.brave.Browser", "org.mozilla.firefox", |
| 30 | "company.thebrowser.Browser", "com.microsoft.edgemac", "com.operasoftware.Opera", "com.vivaldi.Vivaldi", "app.zen-browser.zen"] |
| 31 | var frontIsBrowser: Bool { Self.browsers.contains(frontID) } |
| 32 | } |
| 33 | |
| 34 | /// Which app you opened through Hop, from which app, at what hour. This is what lets the box offer an app before |
| 35 | /// you type. App paths and ids only; kept in `habits.json` next to Hop's other files, newest 400. |
| 36 | @MainActor |
| 37 | final class Habits { |
| 38 | static let shared = Habits() |
| 39 | struct Launch: Codable, Equatable { var app: String; var from: String; var hour: Int; var at: Date } |
| 40 | /// How much a habit lifts an app right now: `from` for "you open this from the app in front", `hour` for |
| 41 | /// "you open this around this time". |
| 42 | struct Lift: Equatable { var from = 0; var hour = 0; var total: Int { from + hour } } |
| 43 | |
| 44 | private(set) var launches: [Launch] = [] |
| 45 | private var file: URL { HopConfig.dir.appendingPathComponent("habits.json") } |
| 46 | |
| 47 | private init() { |
| 48 | if let d = try? Data(contentsOf: file), let v = try? JSONDecoder().decode([Launch].self, from: d) { launches = v } |
| 49 | } |
| 50 | |
| 51 | func record(app: String, context: HopContext, at: Date = Date()) { |
| 52 | launches.append(Launch(app: app, from: context.frontID, hour: Calendar.current.component(.hour, from: at), at: at)) |
| 53 | if launches.count > 400 { launches.removeFirst(launches.count - 400) } |
| 54 | if let d = try? JSONEncoder().encode(launches) { |
| 55 | try? d.write(to: file, options: .atomic) |
| 56 | try? FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: file.path) |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | /// A habit counts from the second time: one launch is not a pattern. The lift is the share of launches |
| 61 | /// from that app (up to 60), plus the share of launches within an hour of now (up to 25), that went to the |
| 62 | /// app. The rule is Omega code (`Omega/hopcore.om`, fn swlifts); this hands it the launches as numbers. |
| 63 | nonisolated static func lifts(apps: [String], context: HopContext, launches: [Launch]) -> [Lift] { |
| 64 | var place: [String: Int] = [:] |
| 65 | for (k, a) in apps.enumerated() where place[a] == nil { place[a] = k } |
| 66 | let front = !context.frontID.isEmpty |
| 67 | let v = SmartSuggest.lifts(hour: context.hour, hasFront: front, apps: apps.count, |
| 68 | launches: launches.map { (here: front && $0.from == context.frontID, hour: $0.hour, app: place[$0.app] ?? -1) }) |
| 69 | // The same app listed twice has the lift of its first place. |
| 70 | return apps.indices.map { k in let w = v[place[apps[k]] ?? k]; return Lift(from: w.from, hour: w.hour) } |
| 71 | } |
| 72 | nonisolated static func lift(app: String, context: HopContext, launches: [Launch]) -> Lift { |
| 73 | lifts(apps: [app], context: context, launches: launches)[0] |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | /// One line in the one box: what it is, how strongly it fits, and (for a guess) why Hop offers it. |
| 78 | struct SmartRow: Identifiable { |
| 79 | enum Kind { |
| 80 | case app(AppCatalog.App, running: Bool), file(FileIndex.Hit), clip(ClipItem), url(String), screen(Tab), command(SmartCommand), account(VaultEntry) |
| 81 | /// The one line for anything that is a message rather than a thing to open: a question and a request alike. |
| 82 | case agent |
| 83 | } |
| 84 | let id: String |
| 85 | let kind: Kind |
| 86 | let score: Int |
| 87 | var why = "" |
| 88 | } |
| 89 | |
| 90 | /// The one box: everything Hop can do, in one list, best guess first. No screen to pick. With nothing typed the |
| 91 | /// guesses come from the moment (the app in front, what was just copied, your habits); typing narrows the same list. |
| 92 | enum Smart { |
| 93 | /// A question for the model rather than a name to look up: it ends with "?", or starts with a question word |
| 94 | /// and runs to three words or more. Decided by Omega code (`Omega/hopcore.om`, fn qlike). |
| 95 | nonisolated static func questionLike(_ query: String) -> Bool { |
| 96 | OmegaText.questionLike(query) |
| 97 | } |
| 98 | |
| 99 | /// The address to open when the text is a web address ("https://…", or a bare "example.com/page"), else nil. |
| 100 | /// Not "app" as an ending: on a Mac "Notes.app" is an app, not a website (an address at a .app domain still |
| 101 | /// opens when typed with its scheme). The shape is decided by Omega code (`Omega/hopcore.om`, fn weba). |
| 102 | nonisolated static func webAddress(_ text: String) -> String? { |
| 103 | OmegaText.webAddress(text) |
| 104 | } |
| 105 | |
| 106 | private static let screenWords: [(Tab, [String])] = [ |
| 107 | (.clipboard, ["clipboard", "copied", "clipboard history"]), (.find, ["find", "files", "find files"]), |
| 108 | (.agent, ["agent", "ask", "chat"]), (.factory, ["factory", "stations", "queues", "droids"]), |
| 109 | (.accounts, ["accounts", "keys", "api keys", "passwords", "logins"]), (.voice, ["voice", "dictation", "microphone"])] |
| 110 | |
| 111 | /// Nothing typed: what you are most likely to want next, from the moment Hop was opened. Pure. |
| 112 | /// - latest: the thing copied most recently; `clips` is the whole history in the order it is shown |
| 113 | /// - recent: apps that were in front lately, newest first |
| 114 | /// - exclude: apps never offered (the one already in front, Hop itself) |
| 115 | nonisolated static func suggest(context: HopContext, apps: [AppCatalog.App], running: [String: String], recent: [String], |
| 116 | launches: [Habits.Launch], boost: (FileIndex.Hit) -> Int, latest: ClipItem?, clips: [ClipItem], |
| 117 | clipboardPaused: Bool, exclude: Set<String>, now: Date = Date()) -> [SmartRow] { |
| 118 | // What Hop knows about the moment, as plain numbers; what is offered and in which order is worked out by |
| 119 | // Omega code (SmartSuggest, `Omega/hopcore.om` fn swsuggest). |
| 120 | var input = SmartSuggest.Input() |
| 121 | var address: String? = nil |
| 122 | if let c = latest { |
| 123 | input.hasLatest = true |
| 124 | input.age = Int(now.timeIntervalSince(c.date).rounded(.down)) |
| 125 | if let text = c.text, let a = webAddress(text), text.lowercased().hasPrefix("http") { address = a; input.latestIsAddress = true } |
| 126 | } |
| 127 | input.frontIsBrowser = context.frontIsBrowser |
| 128 | let rest = Array(clips.filter({ $0.id != latest?.id }).prefix(20)) |
| 129 | input.rest = rest.count |
| 130 | input.paused = clipboardPaused |
| 131 | // Apps: the one you were just in, the ones you open from here or around now, the ones you use most, the open ones. |
| 132 | var byPath: [String: AppCatalog.App] = [:] |
| 133 | for a in apps { byPath[a.path] = a } |
| 134 | for (path, name) in running where byPath[path] == nil { byPath[path] = AppCatalog.App(path: path, name: name, alt: "") } |
| 135 | let skip = exclude.union(context.frontPath.isEmpty ? [] : [context.frontPath]) |
| 136 | let previous = recent.first { !skip.contains($0) } ?? "" |
| 137 | let paths = byPath.keys.filter { !skip.contains($0) }.sorted() // the order of their ids, which settles equal scores |
| 138 | let lifts = Habits.lifts(apps: paths, context: context, launches: launches) |
| 139 | input.apps = paths.enumerated().map { k, path in |
| 140 | SmartSuggest.App(liftFrom: lifts[k].from, liftHour: lifts[k].hour, used: boost(FileIndex.Hit(id: path, score: 0)), |
| 141 | running: running[path] != nil, previous: path == previous, |
| 142 | lately: recent.firstIndex(of: path).map { max(0, 10 - 2 * $0) } ?? 0) |
| 143 | } |
| 144 | return SmartSuggest.rows(input).compactMap { r -> SmartRow? in |
| 145 | switch r.kind { |
| 146 | case SmartSuggest.clip: |
| 147 | let c: ClipItem? = r.index == 0 ? latest : (r.index - 1 < rest.count ? rest[r.index - 1] : nil) |
| 148 | guard let c else { return nil } |
| 149 | return SmartRow(id: "clip:" + c.id.uuidString, kind: .clip(c), score: r.score, |
| 150 | why: r.why == 1 ? "You just copied this" : r.why == 2 ? "The last thing you copied" : "") |
| 151 | case SmartSuggest.address: |
| 152 | guard let address else { return nil } |
| 153 | return SmartRow(id: "url:" + address, kind: .url(address), score: r.score, why: "You copied a web address") |
| 154 | case SmartSuggest.app: |
| 155 | guard r.index < paths.count, let app = byPath[paths[r.index]] else { return nil } |
| 156 | let why = r.why == 4 ? "You often open this from \(context.frontName.isEmpty ? "here" : context.frontName)" |
| 157 | : r.why == 5 ? "You were just here" : r.why == 6 ? "You often open this around now" |
| 158 | : r.why == 7 ? "One of your most used" : "Running now" |
| 159 | return SmartRow(id: "app:" + app.path, kind: .app(app, running: running[app.path] != nil), score: r.score, why: why) |
| 160 | case SmartSuggest.screen: |
| 161 | return SmartRow(id: "screen:" + Tab.clipboard.rawValue, kind: .screen(.clipboard), score: r.score, why: "Clipboard history is paused. Open to see why.") |
| 162 | default: return nil |
| 163 | } |
| 164 | } |
| 165 | } |
| 166 | |
| 167 | /// Something typed: the same list, narrowed to what matches and ranked again. Pure. |
| 168 | /// - apps: matches from the app list, with how well each matched |
| 169 | /// - boost: how much the user's own use lifts a path (how often and how lately it was opened) |
| 170 | /// - searched: this Mac has finished searching its files for this text, so `files` is the whole answer |
| 171 | nonisolated static func rank(query: String, apps: [(app: AppCatalog.App, score: Int, running: Bool)], boost: (FileIndex.Hit) -> Int, |
| 172 | clips: [ClipItem], files: [FileIndex.Hit], accounts: [VaultEntry], tabs: [Tab], |
| 173 | enterSendsToAgent: Bool, context: HopContext = HopContext(), launches: [Habits.Launch] = [], |
| 174 | searched: Bool = true) -> [SmartRow] { |
| 175 | let q = query.trimmingCharacters(in: .whitespacesAndNewlines) |
| 176 | guard !q.isEmpty else { return [] } |
| 177 | let low = q.lowercased() |
| 178 | // What Hop knows about each candidate, as plain numbers; which rows show and in which order is worked out by |
| 179 | // Omega code (SmartRank, `Omega/hopcore.om` fn swrank). |
| 180 | var input = SmartRank.Input() |
| 181 | input.low = Array(low.utf8); input.lowCount = low.count |
| 182 | let lifts = Habits.lifts(apps: apps.map(\.app.path), context: context, launches: launches) |
| 183 | input.apps = apps.enumerated().map { k, a in |
| 184 | SmartRank.App(score: a.score, boost: boost(FileIndex.Hit(id: a.app.path, score: 0)), |
| 185 | lift: lifts[k].total, previous: a.app.path == context.previousPath) |
| 186 | } |
| 187 | // A web address typed with its scheme is plainly one. A bare one ("logo.ai", "example.com") may as well be a |
| 188 | // file name: it is offered only once the file search for it is done, and below every file when a file or folder |
| 189 | // has exactly that name, wherever it is. |
| 190 | let address = webAddress(q) |
| 191 | input.address = address == nil ? 0 : (address == q ? 1 : 2) |
| 192 | input.searched = searched |
| 193 | input.exactFile = files.contains { h in |
| 194 | let p = h.isFolder ? String(h.path.dropLast()) : h.path |
| 195 | return (p as NSString).lastPathComponent.lowercased() == low |
| 196 | } |
| 197 | let appPaths = Set(apps.map(\.app.path)) // an app already listed is not repeated as a file |
| 198 | input.files = files.map { SmartRank.File(score: $0.score, boost: boost($0), isApp: appPaths.contains($0.path)) } |
| 199 | let screens = screenWords.filter { tabs.contains($0.0) } |
| 200 | input.screens = screens.map { $0.1.map { Array($0.utf8) } } |
| 201 | input.commands = SmartCommand.allCases.map { $0.keywords.map { Array($0.utf8) } } |
| 202 | input.accounts = accounts.map { e in let a = e.account.lowercased(); return SmartRank.Account(contains: a.contains(low), prefix: a.hasPrefix(low)) } |
| 203 | input.clips = clips.prefix(8).map(\.pinned) // already filtered to the ones that contain every word typed; newest first |
| 204 | input.question = questionLike(q) |
| 205 | input.agentWanted = AppModel.sentenceGoesToAgent(q, enabled: enterSendsToAgent) |
| 206 | var agentListed = false // the core still ranks "ask" and "agent" apart; Hop shows one line, where the first of them stood |
| 207 | return SmartRank.rank(input).compactMap { r -> SmartRow? in |
| 208 | switch r.kind { |
| 209 | case SmartRank.app: |
| 210 | guard r.index < apps.count else { return nil } |
| 211 | return SmartRow(id: "app:" + apps[r.index].app.path, kind: .app(apps[r.index].app, running: apps[r.index].running), score: r.score) |
| 212 | case SmartRank.address: |
| 213 | guard let address else { return nil } |
| 214 | return SmartRow(id: "url:" + address, kind: .url(address), score: r.score) |
| 215 | case SmartRank.screen: |
| 216 | guard r.index < screens.count else { return nil } |
| 217 | return SmartRow(id: "screen:" + screens[r.index].0.rawValue, kind: .screen(screens[r.index].0), score: r.score) |
| 218 | case SmartRank.command: |
| 219 | guard r.index < SmartCommand.allCases.count else { return nil } |
| 220 | let c = SmartCommand.allCases[r.index] |
| 221 | return SmartRow(id: "cmd:" + c.rawValue, kind: .command(c), score: r.score) |
| 222 | case SmartRank.account: |
| 223 | guard r.index < accounts.count else { return nil } |
| 224 | return SmartRow(id: "account:" + accounts[r.index].account, kind: .account(accounts[r.index]), score: r.score) |
| 225 | case SmartRank.clip: |
| 226 | guard r.index < clips.count else { return nil } |
| 227 | return SmartRow(id: "clip:" + clips[r.index].id.uuidString, kind: .clip(clips[r.index]), score: r.score) |
| 228 | case SmartRank.file: |
| 229 | guard r.index < files.count else { return nil } |
| 230 | return SmartRow(id: "file:" + files[r.index].id, kind: .file(files[r.index]), score: r.score) |
| 231 | case SmartRank.ask, SmartRank.agent: |
| 232 | guard !agentListed else { return nil } |
| 233 | agentListed = true |
| 234 | return SmartRow(id: "agent", kind: .agent, score: r.score) |
| 235 | default: return nil |
| 236 | } |
| 237 | } |
| 238 | } |
| 239 | } |
| 240 | |
| 241 | extension AppModel { |
| 242 | /// True on the one box, whether or not something is typed. |
| 243 | var smartActive: Bool { tab == .all } |
| 244 | var smartTyped: Bool { !query.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } |
| 245 | /// With nothing typed there is no list: the home shows the first few guesses and nothing else. |
| 246 | nonisolated static let homeOffers = 3 |
| 247 | /// How many lines of `smartRows` are on show. The arrow keys and Enter reach only these. |
| 248 | var smartShown: Int { smartTyped ? smartRows.count : min(smartRows.count, Self.homeOffers) } |
| 249 | |
| 250 | /// Notes which app is in front, right before Hop's window appears. Hop's panel never becomes the front app, |
| 251 | /// so this is the app the user was in. Nothing about its windows or contents is read. |
| 252 | func captureContext() { |
| 253 | var c = HopContext() |
| 254 | let own = Bundle.main.bundlePath |
| 255 | if let f = NSWorkspace.shared.frontmostApplication, let path = f.bundleURL?.path, path != own { |
| 256 | c.frontID = f.bundleIdentifier ?? ""; c.frontName = f.localizedName ?? ""; c.frontPath = path |
| 257 | noteFront(path) |
| 258 | } |
| 259 | c.previousPath = recentApps.first { $0 != c.frontPath } ?? "" |
| 260 | context = c |
| 261 | refreshSmart() |
| 262 | } |
| 263 | |
| 264 | /// Keeps the short list of apps that were in front lately (in memory only, newest first). |
| 265 | func noteFront(_ path: String) { |
| 266 | guard path != Bundle.main.bundlePath else { return } |
| 267 | recentApps.removeAll { $0 == path } |
| 268 | recentApps.insert(path, at: 0) |
| 269 | if recentApps.count > 12 { recentApps.removeLast(recentApps.count - 12) } |
| 270 | } |
| 271 | |
| 272 | func refreshSmart() { |
| 273 | if let held = sendWhenSettled, held != query || !smartActive { sendWhenSettled = nil } // typed on, or left the box: that Enter is over |
| 274 | guard smartActive else { if !smartRows.isEmpty { smartRows = [] }; return } |
| 275 | let running = AppCatalog.runningNow() |
| 276 | let boost: (FileIndex.Hit) -> Int = { Recents.shared.boost($0) } |
| 277 | if smartTyped { |
| 278 | let matches = AppCatalog.match(query, apps: appCatalog.apps, running: running) |
| 279 | // File rows only once this Mac has searched for this very text: until then fileHits still holds the last |
| 280 | // search (or your most-used files), and Enter must not open one of those. |
| 281 | let searched = settledQuery == query |
| 282 | smartRows = Smart.rank(query: query, apps: matches, boost: boost, |
| 283 | clips: clipboard.lockReason == nil ? clipboard.search(query) : [], files: searched ? fileHits : [], accounts: vault, |
| 284 | tabs: tabs, enterSendsToAgent: config.enterSendsToAgent, context: context, launches: Habits.shared.launches, |
| 285 | searched: searched) |
| 286 | } else { |
| 287 | let open = clipboard.lockReason == nil |
| 288 | smartRows = Smart.suggest(context: context, apps: appCatalog.apps, running: running, recent: recentApps, |
| 289 | launches: Habits.shared.launches, boost: boost, latest: open ? clipboard.items.first : nil, |
| 290 | clips: open ? clipboard.search("") : [], clipboardPaused: !open, exclude: [Bundle.main.bundlePath]) |
| 291 | } |
| 292 | if selection >= smartShown { selection = 0 } |
| 293 | if sendWhenSettled != nil, settledQuery == query, !remotePending { // an Enter on the agent line that was waiting for the file search, here and on the other machines |
| 294 | sendWhenSettled = nil |
| 295 | if case .agent = smartRows.first?.kind { fixIt() } // a file turned up on top instead: the choice is the user's again |
| 296 | } |
| 297 | } |
| 298 | |
| 299 | /// Opens the app, or brings it to the front when it is already open. Remembered (how often, how lately, from |
| 300 | /// which app, at what hour), so it ranks higher next time and can be offered before anything is typed. |
| 301 | func launch(_ app: AppCatalog.App) { |
| 302 | Recents.shared.record(FileIndex.Hit(id: app.path, score: 0)) |
| 303 | Habits.shared.record(app: app.path, context: context) |
| 304 | if let dry = launchDryRun { query = ""; dry(app.path); refreshSmart(); return } |
| 305 | let cfg = NSWorkspace.OpenConfiguration() |
| 306 | cfg.activates = true |
| 307 | NSWorkspace.shared.openApplication(at: URL(fileURLWithPath: app.path), configuration: cfg) { _, error in |
| 308 | if let error { DispatchQueue.main.async { AppDelegate.log("open app failed: \(error.localizedDescription)") } } |
| 309 | } |
| 310 | query = "" |
| 311 | hide() |
| 312 | } |
| 313 | |
| 314 | func openWeb(_ address: String) { |
| 315 | if let dry = launchDryRun { query = ""; dry(address); return } |
| 316 | if let u = URL(string: address) { NSWorkspace.shared.open(u) } |
| 317 | query = "" |
| 318 | hide() |
| 319 | } |
| 320 | |
| 321 | func run(_ row: SmartRow, alt: Bool = false) { |
| 322 | switch row.kind { |
| 323 | case .app(let a, _): if alt { open(a.path, reveal: true) } else { launch(a) } |
| 324 | case .file(let h): open(h, reveal: alt) |
| 325 | case .clip(let c): if alt, let t = c.text, let address = Smart.webAddress(t) { openWeb(address) } else { paste(c) } |
| 326 | case .url(let address): openWeb(address) |
| 327 | case .screen(let t): query = ""; tab = t |
| 328 | case .command(let c): |
| 329 | query = "" |
| 330 | switch c { |
| 331 | case .settings: openSettings(); hide() |
| 332 | case .reindex: rebuildIndex() |
| 333 | case .newChat: newAgent(); tab = .agent |
| 334 | case .quit: quitApp() |
| 335 | } |
| 336 | case .account(let e): copySecret(e); query = ""; hide() |
| 337 | case .agent: |
| 338 | // As the top line it goes once this Mac and the other machines have finished looking for a file of that |
| 339 | // name: the text may yet turn out to be a file's name, here or there. The Enter is kept, not lost: it is |
| 340 | // carried out when the search is done, if the agent is still the top line (`sendWhenSettled`, in `refreshSmart`). |
| 341 | if smartRows.first?.id == row.id, settledQuery != query || remotePending { sendWhenSettled = query; return } |
| 342 | fixIt() |
| 343 | } |
| 344 | } |
| 345 | } |
| 346 | |
| 347 | // MARK: The list |
| 348 | struct SmartView: View { |
| 349 | @ObservedObject var m: AppModel |
| 350 | var body: some View { |
| 351 | VStack(spacing: 0) { |
| 352 | if m.smartRows.isEmpty { |
| 353 | Hint(lines: ["Type an app, a file, something you copied, or a question.", "As you use Hop it learns what you open from where, and offers it here before you type."]) |
| 354 | } else { |
| 355 | ScrollViewReader { proxy in |
| 356 | List(Array(m.smartRows.enumerated()), id: \.element.id) { i, row in |
| 357 | SmartRowView(m: m, row: row, selected: i == m.selection) |
| 358 | .id(i).contentShape(Rectangle()) |
| 359 | .onTapGesture(count: 2) { m.run(row) } |
| 360 | .onTapGesture { m.selection = i } |
| 361 | } |
| 362 | .listStyle(.plain).scrollContentBackground(.hidden) |
| 363 | .onChange(of: m.selection) { _, s in proxy.scrollTo(s) } |
| 364 | .safeAreaInset(edge: .bottom) { if !AXIsProcessTrusted(), m.clipboard.lockReason == nil { PastePermissionBar() } } |
| 365 | } |
| 366 | } |
| 367 | if !m.remoteNote.isEmpty { Text(m.remoteNote).font(.caption).foregroundStyle(.secondary).padding(.vertical, 4) } |
| 368 | CortexHits(m: m, c: m.cortex) |
| 369 | } |
| 370 | } |
| 371 | } |
| 372 | |
| 373 | /// What a line of the one box says and shows: its name, the small print, what Enter does, and its picture. |
| 374 | /// The list and the home screen's cards both read it from here. |
| 375 | @MainActor |
| 376 | struct SmartRowFace { |
| 377 | let m: AppModel |
| 378 | let row: SmartRow |
| 379 | |
| 380 | var title: String { |
| 381 | switch row.kind { |
| 382 | case .app(let a, _): a.name |
| 383 | case .file(let h): ((h.isFolder ? String(h.path.dropLast()) : h.path) as NSString).lastPathComponent |
| 384 | case .clip(let c): c.preview |
| 385 | case .url(let u): u |
| 386 | case .screen(let t): t.rawValue |
| 387 | case .command(let c): c.rawValue |
| 388 | case .account(let e): e.account |
| 389 | case .agent: "Agent: “\(m.query)”" |
| 390 | } |
| 391 | } |
| 392 | var detail: String { |
| 393 | if !row.why.isEmpty { return row.why } |
| 394 | switch row.kind { |
| 395 | case .app(let a, _): return (a.path as NSString).deletingLastPathComponent.replacingOccurrences(of: NSHomeDirectory(), with: "~") |
| 396 | case .file(let h): |
| 397 | return ((h.isFolder ? String(h.path.dropLast()) : h.path) as NSString).deletingLastPathComponent |
| 398 | .replacingOccurrences(of: m.config.machines.first { $0.name == h.machine }?.homeDir ?? NSHomeDirectory(), with: "~") |
| 399 | case .clip(let c): return [c.sourceApp, c.date.formatted(.relative(presentation: .named))].compactMap { $0 }.joined(separator: " · ") |
| 400 | case .url: return "Opens in your browser" |
| 401 | case .screen: return "Hop screen" |
| 402 | case .command: return "Hop" |
| 403 | case .account(let e): return [e.kind, e.note].filter { !$0.isEmpty }.joined(separator: " · ") |
| 404 | case .agent: return "Answers it, or does it for you." |
| 405 | } |
| 406 | } |
| 407 | /// What Enter does to this line. |
| 408 | var action: String { |
| 409 | switch row.kind { |
| 410 | case .app(_, let running): running ? "Switch to" : "Open" |
| 411 | case .file(let h): h.machine ?? "Open" |
| 412 | case .clip: "Paste" |
| 413 | case .url: "Open" |
| 414 | case .screen: "Show" |
| 415 | case .command: "Run" |
| 416 | case .account: "Copy key" |
| 417 | case .agent: "Agent" |
| 418 | } |
| 419 | } |
| 420 | var symbol: String? { |
| 421 | switch row.kind { |
| 422 | case .app, .file: nil |
| 423 | case .clip: "doc.on.clipboard" |
| 424 | case .url: "globe" |
| 425 | case .screen(let t): t.icon |
| 426 | case .command(let c): c.icon |
| 427 | case .account: "key" |
| 428 | case .agent: "wand.and.stars" |
| 429 | } |
| 430 | } |
| 431 | var tint: Color { |
| 432 | switch row.kind { case .agent: .purple; case .url: Spirit.accent; case .clip: .orange; default: .secondary } |
| 433 | } |
| 434 | @ViewBuilder var icon: some View { |
| 435 | if let symbol { Image(systemName: symbol).foregroundStyle(tint) } |
| 436 | else if case .file(let h) = row.kind, h.machine != nil { Image(systemName: h.isFolder ? "folder" : "doc").foregroundStyle(.secondary) } |
| 437 | else if case .file(let h) = row.kind { Image(nsImage: NSWorkspace.shared.icon(forFile: h.isFolder ? String(h.path.dropLast()) : h.path)).resizable() } |
| 438 | else if case .app(let a, _) = row.kind { Image(nsImage: NSWorkspace.shared.icon(forFile: a.path)).resizable() } |
| 439 | } |
| 440 | } |
| 441 | |
| 442 | struct SmartRowView: View { |
| 443 | @ObservedObject var m: AppModel |
| 444 | let row: SmartRow |
| 445 | let selected: Bool |
| 446 | |
| 447 | var body: some View { |
| 448 | let face = SmartRowFace(m: m, row: row) |
| 449 | // The agent line is reached with ⇧Enter from anywhere, as well as with Enter when it is the highlighted line. |
| 450 | let badge: String = { |
| 451 | if selected { return face.action + " ↩" } |
| 452 | if case .agent = row.kind { return "Agent ⇧↩" } |
| 453 | return face.action |
| 454 | }() |
| 455 | HStack(spacing: 10) { |
| 456 | face.icon.frame(width: 22, height: 22) |
| 457 | VStack(alignment: .leading, spacing: 1) { |
| 458 | Text(face.title).lineLimit(1).truncationMode(.tail) |
| 459 | if !face.detail.isEmpty { Text(face.detail).font(.caption).foregroundStyle(.secondary).lineLimit(1).truncationMode(.middle) } |
| 460 | } |
| 461 | Spacer() |
| 462 | Text(badge).font(.caption2.weight(.medium)) |
| 463 | .padding(.horizontal, 6).padding(.vertical, 2) |
| 464 | .background(face.tint.opacity(0.15), in: Capsule()) |
| 465 | } |
| 466 | .padding(.vertical, 5).padding(.horizontal, 8) |
| 467 | .background { |
| 468 | if selected { Spirit.glass(0.8, edge: Spirit.accent.opacity(0.55), radius: 8) } |
| 469 | } |
| 470 | } |
| 471 | } |