interplane.Get Omega
Read in your language

hop

Hop: a small native macOS launcher. Clipboard history, find, on-device dictation and your coding agent behind one key.

Brought by drakestapleton

branch main Branches Tags History

hop / Sources / main.swift

374 lines · 21480 bytes Raw Blame History
1import AppKit
2import SwiftUI
3import Carbon.HIToolbox
4import ServiceManagement
5import Combine
6
7// Hop started by itself to run a command as the leader of a process group of its own (`CommandRun`, ownGroup):
8// this process makes the group and becomes the command. Nothing else of Hop runs here.
9if CommandLine.arguments.count > 2, CommandLine.arguments[1] == "--hop-own-group" {
10 setpgid(0, 0)
11 let command = Array(CommandLine.arguments.dropFirst(2))
12 let argv: [UnsafeMutablePointer<CChar>?] = command.map { strdup($0) } + [nil]
13 execv(command[0], argv)
14 FileHandle.standardError.write(Data("could not start \(command[0]): \(String(cString: strerror(errno)))\n".utf8))
15 exit(127)
16}
17
18/// Floating panel that takes keyboard focus without pulling the previous app to the background,
19/// so "paste" lands back in whatever the user was typing in.
20final class HopPanel: NSPanel {
21 override var canBecomeKey: Bool { true }
22 override var canBecomeMain: Bool { false }
23}
24
25/// A global shortcut, checked before anything is registered. A shortcut with no Command, Control or Option would
26/// take a typing key away from every app on the Mac, so one typo in the config must never get that far.
27enum Hotkey {
28 static let fallback = "cmd+space"
29 struct Keys: Equatable { let code: UInt32; let mods: UInt32 }
30
31 private static let named: [String: Int] = ["space": kVK_Space, "return": kVK_Return, "tab": kVK_Tab, "escape": kVK_Escape,
32 "a": kVK_ANSI_A, "b": kVK_ANSI_B, "c": kVK_ANSI_C, "d": kVK_ANSI_D, "e": kVK_ANSI_E, "f": kVK_ANSI_F,
33 "g": kVK_ANSI_G, "h": kVK_ANSI_H, "i": kVK_ANSI_I, "j": kVK_ANSI_J, "k": kVK_ANSI_K, "l": kVK_ANSI_L,
34 "m": kVK_ANSI_M, "n": kVK_ANSI_N, "o": kVK_ANSI_O, "p": kVK_ANSI_P, "q": kVK_ANSI_Q, "r": kVK_ANSI_R,
35 "s": kVK_ANSI_S, "t": kVK_ANSI_T, "u": kVK_ANSI_U, "v": kVK_ANSI_V, "w": kVK_ANSI_W, "x": kVK_ANSI_X,
36 "y": kVK_ANSI_Y, "z": kVK_ANSI_Z, "0": kVK_ANSI_0, "1": kVK_ANSI_1, "2": kVK_ANSI_2, "3": kVK_ANSI_3,
37 "4": kVK_ANSI_4, "5": kVK_ANSI_5, "6": kVK_ANSI_6, "7": kVK_ANSI_7, "8": kVK_ANSI_8, "9": kVK_ANSI_9]
38 private static let functionKeys: [String: Int] = ["f1": kVK_F1, "f2": kVK_F2, "f3": kVK_F3, "f4": kVK_F4, "f5": kVK_F5,
39 "f6": kVK_F6, "f7": kVK_F7, "f8": kVK_F8, "f9": kVK_F9, "f10": kVK_F10, "f11": kVK_F11, "f12": kVK_F12, "f13": kVK_F13,
40 "f14": kVK_F14, "f15": kVK_F15, "f16": kVK_F16, "f17": kVK_F17, "f18": kVK_F18, "f19": kVK_F19, "f20": kVK_F20]
41
42 /// The keys for a shortcut written like "cmd+space", or why it is refused. Accepted only when every part is
43 /// understood, there is exactly one key, and either Command, Control or Option is held (Shift alone does not
44 /// count) or the key is a function key F1 to F20.
45 nonisolated static func check(_ spec: String) -> (keys: Keys?, why: String) {
46 let parts = spec.lowercased().split(separator: "+", omittingEmptySubsequences: false).map { $0.trimmingCharacters(in: .whitespaces) }
47 var mods = 0, code: Int?, function = false
48 for part in parts {
49 switch part {
50 case "cmd", "command": mods |= cmdKey
51 case "opt", "option", "alt": mods |= optionKey
52 case "ctrl", "control": mods |= controlKey
53 case "shift": mods |= shiftKey
54 default:
55 guard let k = named[part] ?? functionKeys[part] else { return (nil, part.isEmpty ? "a part of it is empty" : "“\(part)” is not a key Hop knows") }
56 guard code == nil else { return (nil, "it names more than one key") }
57 code = k; function = functionKeys[part] != nil
58 }
59 }
60 guard let code else { return (nil, "it names no key") }
61 guard function || mods & (cmdKey | controlKey | optionKey) != 0 else {
62 return (nil, "it has no Command, Control or Option, so it would take that key away from everything you type")
63 }
64 return (Keys(code: UInt32(code), mods: UInt32(mods)), "")
65 }
66
67 /// What Hop really registers for a configured value: the value itself when it is safe, otherwise the default
68 /// shortcut together with a message that names the refused value.
69 nonisolated static func resolve(_ spec: String) -> (use: String, keys: Keys, problem: String?) {
70 let r = check(spec)
71 if let k = r.keys { return (spec, k, nil) }
72 let standard = check(fallback).keys ?? Keys(code: UInt32(kVK_Space), mods: UInt32(cmdKey))
73 return (fallback, standard,
74 "config.json: the shortcut “\(spec)” was not used, because \(r.why). A shortcut needs Command, Control or Option (Shift alone is not enough), or must be a function key F1 to F20. Hop is using \(fallback) instead. Fix \"hotkey\" in Settings and reopen Hop.")
75 }
76}
77
78@MainActor
79final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate {
80 var panel: HopPanel!
81 var model: AppModel!
82 var status: NSStatusItem!
83 var hotKeyRef: EventHotKeyRef?
84 var dictationKeys: DictationKeys!
85 var dictationHUD: DictationHUD!
86 private var voiceHotKeys: [EventHotKeyRef] = []
87 private var keyTimer: Timer?
88
89 /// Hop has no menu bar, and macOS routes ⌘A, ⌘C, ⌘V, ⌘X and ⌘Z through the Edit menu. Without one the text
90 /// bar ignores them. This menu is never shown; it only gives those keys somewhere to land.
91 private func installEditMenu() {
92 let main = NSMenu(), editItem = NSMenuItem(), edit = NSMenu(title: "Edit")
93 func add(_ title: String, _ action: Selector, _ key: String, shift: Bool = false) {
94 let i = edit.addItem(withTitle: title, action: action, keyEquivalent: key)
95 if shift { i.keyEquivalentModifierMask = [.command, .shift] }
96 }
97 add("Undo", Selector(("undo:")), "z"); add("Redo", Selector(("redo:")), "z", shift: true)
98 edit.addItem(.separator())
99 add("Cut", #selector(NSText.cut(_:)), "x"); add("Copy", #selector(NSText.copy(_:)), "c")
100 add("Paste", #selector(NSText.paste(_:)), "v"); add("Select All", #selector(NSText.selectAll(_:)), "a")
101 editItem.submenu = edit; main.addItem(editItem)
102 NSApp.mainMenu = main
103 }
104
105 func applicationDidFinishLaunching(_ n: Notification) {
106 installEditMenu()
107 model = AppModel()
108 model.hide = { [weak self] in self?.hidePanel() }
109 model.openSettings = { [weak self] in self?.openSettings() }
110 model.quitApp = { NSApp.terminate(nil) }
111
112 panel = HopPanel(contentRect: NSRect(x: 0, y: 0, width: 820, height: 520),
113 styleMask: [.nonactivatingPanel, .titled, .fullSizeContentView, .resizable],
114 backing: .buffered, defer: false)
115 panel.titleVisibility = .hidden
116 panel.titlebarAppearsTransparent = true
117 panel.isMovableByWindowBackground = true
118 panel.level = .floating
119 panel.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary]
120 panel.hidesOnDeactivate = false
121 panel.isReleasedWhenClosed = false
122 panel.standardWindowButton(.closeButton)?.isHidden = true
123 panel.standardWindowButton(.miniaturizeButton)?.isHidden = true
124 panel.standardWindowButton(.zoomButton)?.isHidden = true
125 panel.delegate = self
126 // No grey box: the window itself is clear and the sky is drawn by RootView (SpiritField), to its own
127 // rounded shape. It stays a titled panel, which is what gives it the keyboard.
128 panel.isOpaque = false
129 panel.backgroundColor = .clear
130 panel.hasShadow = false
131 panel.appearance = NSAppearance(named: .darkAqua) // the sky is dark whatever the Mac's setting
132 panel.contentView = NSHostingView(rootView: RootView(m: model))
133 panel.setFrameAutosaveName("HopPanel")
134
135 status = NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength)
136 status.button?.image = NSImage(systemSymbolName: "bolt.horizontal.circle", accessibilityDescription: "Hop")
137 let menu = NSMenu()
138 menu.addItem(withTitle: "Open Hop (\(model.config.effectiveHotkey))", action: #selector(togglePanel), keyEquivalent: "")
139 menu.addItem(.separator())
140 menu.addItem(withTitle: "Rebuild file index", action: #selector(rebuildIndex), keyEquivalent: "")
141 menu.addItem(withTitle: "Allow paste into apps…", action: #selector(askAccessibility), keyEquivalent: "")
142 let login = NSMenuItem(title: "Open at login", action: #selector(toggleLogin(_:)), keyEquivalent: "")
143 login.state = SMAppService.mainApp.status == .enabled ? .on : .off
144 menu.addItem(login)
145 menu.addItem(withTitle: "Settings (edit config file)…", action: #selector(openSettings), keyEquivalent: ",")
146 menu.addItem(withTitle: "Clear clipboard history", action: #selector(clearClipboard), keyEquivalent: "")
147 if ((try? FileManager.default.contentsOfDirectory(atPath: HopConfig.dir.path)) ?? []).contains(where: { $0.hasPrefix("clipboard-legacy-") }) {
148 menu.addItem(withTitle: "Recover older clipboard history…", action: #selector(recoverClipboard), keyEquivalent: "")
149 }
150 menu.addItem(.separator())
151 menu.addItem(withTitle: "Quit Hop", action: #selector(quit), keyEquivalent: "q")
152 for i in menu.items { i.target = self }
153 status.menu = menu
154
155 if !CommandLine.arguments.contains("--no-global-hotkey") { registerHotKey(model.config.hotkey) } // a value that is not a safe shortcut is replaced there
156 // Dictation: the listening pill, the Fn key, and the shortcuts for the last dictation.
157 let d = model.dictation
158 dictationHUD = DictationHUD(d)
159 dictationKeys = DictationKeys(d)
160 d.isHopFront = { [weak self] in self?.panel.isKeyWindow ?? false }
161 d.showHop = { [weak self] in self?.showPanel(keepTab: true) }
162 if !CommandLine.arguments.contains("--no-global-hotkey") {
163 d.keysChanged = { [weak self] in self?.refreshDictationKeys() }
164 refreshDictationKeys()
165 keyTimer = Timer.scheduledTimer(withTimeInterval: 3, repeats: true) { [weak self] _ in // notices a permission granted later
166 MainActor.assumeIsolated { self?.model.dictation.autoSetup(); self?.refreshDictationKeys(); self?.logStatus() }
167 }
168 }
169 model.isPanelVisible = { [weak self] in self?.panel.isVisible ?? false }
170 // Menu bar icon tells the agent's state at a glance: working, done (not yet looked at), or idle.
171 model.$agentRunning.combineLatest(model.$agentUnseen).receive(on: RunLoop.main).sink { [weak self] running, unseen in
172 let name = running ? "wand.and.stars" : (unseen ? "checkmark.circle.fill" : "bolt.horizontal.circle")
173 self?.status.button?.image = NSImage(systemSymbolName: name, accessibilityDescription: running ? "Hop: agent working" : (unseen ? "Hop: agent finished" : "Hop"))
174 }.store(in: &watchers)
175 logStatus()
176 if CommandLine.arguments.contains("--factory"), model.config.factoryEnabled { model.tab = .factory; showPanel(keepTab: true) }
177 if CommandLine.arguments.contains("--show") { showPanel() } // started by `hop show`: the box was asked for
178 if CommandLine.arguments.contains("--uitest") { UITest.run(self) }
179 }
180 private var watchers = Set<AnyCancellable>()
181
182 func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
183 showPanel()
184 return true
185 }
186
187 func applicationWillTerminate(_ n: Notification) { model.tunnels.stopAll() }
188
189 // MARK: Panel
190 @objc func togglePanel() { panel.isVisible ? hidePanel() : showPanel() }
191
192 func showPanel(keepTab: Bool = false) {
193 if let screen = NSScreen.screens.first(where: { $0.frame.contains(NSEvent.mouseLocation) }) ?? NSScreen.main {
194 let f = panel.frame, v = screen.visibleFrame
195 panel.setFrameOrigin(NSPoint(x: v.midX - f.width / 2, y: v.maxY - f.height - v.height * 0.12))
196 }
197 if model.agentUnseen {
198 model.tab = .agent; model.agentUnseen = false // the agent finished while you were away: show its answer
199 } else if !keepTab && model.query.isEmpty && !model.agentRunning {
200 model.tab = .all // the one box, every time: what you copied, and anything you type
201 }
202 model.refreshApps() // an app installed since last time is there now
203 model.captureContext() // which app is in front, before Hop's window appears
204 panel.makeKeyAndOrderFront(nil)
205 model.panelShown = true
206 logStatus()
207 }
208
209 /// One line in hop.log on each open: which macOS permissions Hop has (states only, no content).
210 private var lastStatus = ""
211 func logStatus() {
212 let fda = FileManager.default.isReadableFile(atPath: NSHomeDirectory() + "/Library/Application Support/com.apple.TCC/TCC.db")
213 let v = model.dictation
214 let voice = !v.settings.enabled ? "off" : (!v.armed ? "standby(wispr)" : (dictationKeys?.running == true ? "listening-for-fn" : "no-key-permission"))
215 let s = "status dictation=\(voice) mic=\(SpeechEngine.microphoneAllowed ? "allowed" : (SpeechEngine.microphoneUndecided ? "not-asked" : "denied")) speech-model=\(v.modelReady ? "ready" : "loading") clipboard=\(model.clipboard.lockReason == nil ? "open" : "locked") paste=\(AXIsProcessTrusted() ? "allowed" : "not-allowed") full-disk=\(fda ? "yes" : "no") key-window=\(panel.isKeyWindow)"
216 if s != lastStatus { lastStatus = s; Self.log(s) }
217 }
218
219 func hidePanel() { panel.orderOut(nil); model.panelShown = false }
220
221 func windowDidResignKey(_ n: Notification) {
222 // Stay open while a confirmation dialog is up; otherwise get out of the way like Spotlight.
223 if NSApp.modalWindow == nil && panel.attachedSheet == nil && !UITest.active { hidePanel() }
224 }
225
226 // MARK: Hotkey
227 func registerHotKey(_ configured: String) {
228 let choice = Hotkey.resolve(configured) // never a bare typing key: see Hotkey
229 if choice.problem != nil { Self.log("hotkey: “\(configured)” refused; using \(choice.use)") } // the full message is in the window and in the settings: lines
230 let spec = choice.use, code = choice.keys.code, mods = choice.keys.mods
231 var spec2 = EventTypeSpec(eventClass: OSType(kEventClassKeyboard), eventKind: UInt32(kEventHotKeyPressed))
232 InstallEventHandler(GetApplicationEventTarget(), { _, event, _ -> OSStatus in
233 var hk = EventHotKeyID()
234 GetEventParameter(event, EventParamName(kEventParamDirectObject), EventParamType(typeEventHotKeyID), nil,
235 MemoryLayout<EventHotKeyID>.size, nil, &hk)
236 let which = hk.id
237 DispatchQueue.main.async { (NSApp.delegate as? AppDelegate)?.hotKeyPressed(which) }
238 return noErr
239 }, 1, &spec2, nil, nil)
240 let id = EventHotKeyID(signature: OSType(0x484F5021), id: 1) // 'HOP!'
241 let err = RegisterEventHotKey(code, mods, id, GetApplicationEventTarget(), 0, &hotKeyRef)
242 Self.log("hotkey \(spec): " + (err == noErr ? "registered" : "FAILED (OSStatus \(err))"))
243 if err != noErr {
244 let a = NSAlert()
245 a.messageText = "Hop couldn't use \(spec) as its shortcut"
246 a.informativeText = "Another app (maybe Raycast or Spotlight) already uses it. Pick a different one in Settings (\"hotkey\"), or turn it off in the other app. You can still open Hop from the menu bar icon."
247 a.runModal()
248 }
249 }
250
251 func hotKeyPressed(_ id: UInt32) {
252 switch id {
253 case 2: model.dictation.pasteLast()
254 case 3: model.dictation.copyLast()
255 case 4: model.dictation.polishSelection()
256 default: togglePanel()
257 }
258 }
259
260 /// Fn watching and the ⌃⌘V / ⌃⌘C / ⌥1 shortcuts are live only while Hop is the one handling dictation.
261 func refreshDictationKeys() {
262 dictationKeys.refresh()
263 let want = model.dictation.armed
264 if want && voiceHotKeys.isEmpty {
265 for (id, spec) in [(UInt32(2), "ctrl+cmd+v"), (3, "ctrl+cmd+c"), (4, "opt+1")] {
266 guard let k = Hotkey.check(spec).keys else { continue } // the same rule for every shortcut Hop registers
267 let code = k.code, mods = k.mods
268 var ref: EventHotKeyRef?
269 if RegisterEventHotKey(code, mods, EventHotKeyID(signature: OSType(0x484F5021), id: id), GetApplicationEventTarget(), 0, &ref) == noErr, let ref {
270 voiceHotKeys.append(ref)
271 }
272 }
273 } else if !want && !voiceHotKeys.isEmpty {
274 voiceHotKeys.forEach { UnregisterEventHotKey($0) }; voiceHotKeys = []
275 }
276 }
277
278 /// One-line status log at ~/Library/Application Support/Hop/hop.log (no content, just events).
279 static func log(_ s: String) {
280 let line = "\(Date().formatted(.iso8601)) \(s)\n"
281 let url = HopConfig.dir.appendingPathComponent("hop.log")
282 if let h = try? FileHandle(forWritingTo: url) { h.seekToEndOfFile(); h.write(Data(line.utf8)); try? h.close() }
283 else { try? Data(line.utf8).write(to: url) }
284 }
285
286 // MARK: Menu actions
287 @objc func rebuildIndex() { model.rebuildIndex() }
288 @objc func askAccessibility() {
289 let opts = [kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: true] as CFDictionary
290 _ = AXIsProcessTrustedWithOptions(opts)
291 }
292 @objc func toggleLogin(_ item: NSMenuItem) {
293 do {
294 if SMAppService.mainApp.status == .enabled { try SMAppService.mainApp.unregister(); item.state = .off }
295 else { try SMAppService.mainApp.register(); item.state = .on }
296 } catch {
297 let a = NSAlert(); a.messageText = "Couldn't change Open at login"; a.informativeText = error.localizedDescription; a.runModal()
298 }
299 }
300 @objc func openSettings() {
301 model.config.save()
302 NSWorkspace.shared.open([HopConfig.url], withApplicationAt: URL(fileURLWithPath: "/System/Applications/TextEdit.app"),
303 configuration: NSWorkspace.OpenConfiguration())
304 }
305 @objc func clearClipboard() { model.clipboard.clearUnpinned() }
306 @objc func recoverClipboard() {
307 let n = model.clipboard.recoverLegacy()
308 let a = NSAlert(); a.messageText = n > 0 ? "Brought back \(n) older clipboard items" : "Nothing was brought back"
309 a.informativeText = n > 0 ? "They are in the Clipboard list now." : "macOS did not release the old key, or there were no older items that are not already in the list."
310 a.runModal()
311 }
312 @objc func quit() { NSApp.terminate(nil) }
313}
314
315// The UI tests answer Hop's own questions and change settings, so they never run against real settings.
316if (CommandLine.arguments.contains("--uitest") || CommandLine.arguments.contains("--selftest-flow")), let refusal = UITest.refusal() {
317 FileHandle.standardError.write(Data((refusal + "\n").utf8))
318 exit(2)
319}
320
321// Typed alone in a terminal, hop opens the box of the Hop that is running, or starts Hop (`hop show`). Opened as
322// an app there is no terminal on its input and output, and Hop starts here as it always did.
323let typedAlone = CommandLine.arguments.count == 1 && isatty(0) == 1 && isatty(1) == 1
324if typedAlone || (CommandLine.arguments.count > 1 && Cli.commands.contains(CommandLine.arguments[1])) {
325 let cmd = typedAlone ? "show" : CommandLine.arguments[1], rest = Array(CommandLine.arguments.dropFirst(2))
326 Task { @MainActor in exit(await Cli.main(cmd, rest)) }
327 RunLoop.main.run()
328}
329
330// A word that is no command, or a --option the app does not have, is a slip of the finger in a terminal, not a
331// reason to start a second Hop. Single-dash arguments are left to macOS (-AppleLanguages and the like).
332if CommandLine.arguments.count > 1 {
333 let first = CommandLine.arguments[1]
334 let slip = !first.hasPrefix("-") ? first : CommandLine.arguments.dropFirst().first { $0.hasPrefix("--") && !Cli.appFlags.contains($0) }
335 if let slip {
336 FileHandle.standardError.write(Data("hop: no command or option named \"\(slip)\". Run: hop help\n".utf8))
337 exit(2)
338 }
339}
340
341// Only the rows about who Hop picks to answer (own model first, the next mind, Stronger, who answered), against
342// stub servers on loopback and stand-in tools.
343if CommandLine.arguments.contains("--selftest-ask") {
344 Task { @MainActor in exit(await AskRouteChecks.runAlone()) }
345 RunLoop.main.run()
346}
347
348if CommandLine.arguments.contains("--selftest-pick") {
349 Task { @MainActor in exit(await PickChecks.runAlone()) }
350 RunLoop.main.run()
351}
352
353if CommandLine.arguments.contains("--selftest") {
354 Task { @MainActor in exit(await SelfTest.run()) }
355 RunLoop.main.run()
356}
357
358if CommandLine.arguments.contains("--selftest-flow") {
359 Task { @MainActor in
360 NSApplication.shared.setActivationPolicy(.prohibited)
361 UITest.active = true
362 exit(await UITest.flowChecks(AppModel(startServices: false)))
363 }
364 RunLoop.main.run()
365}
366
367MainActor.assumeIsolated {
368 FactoryMetrics.begin()
369 let app = NSApplication.shared
370 let delegate = AppDelegate() // stays alive for the life of app.run()
371 app.delegate = delegate
372 app.setActivationPolicy(.accessory)
373 app.run()
374}