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 / Clipboard.swift

217 lines · 10356 bytes Raw Blame History
1import AppKit
2import CryptoKit
3
4struct ClipItem: Codable, Identifiable, Hashable {
5 var id: UUID = UUID()
6 var date: Date
7 var text: String?
8 var imageFile: String? // file name inside the images folder (encrypted PNG)
9 var sourceApp: String?
10 var pinned: Bool = false
11
12 var preview: String {
13 if let t = text { return t.trimmingCharacters(in: .whitespacesAndNewlines).replacingOccurrences(of: "\n", with: " ⏎ ") }
14 return "Image"
15 }
16}
17
18/// Watches the system clipboard and keeps an encrypted history on disk.
19/// Items marked concealed or transient (password managers do this) are never stored.
20@MainActor
21final class ClipboardStore: ObservableObject {
22 @Published private(set) var items: [ClipItem] = []
23 @Published private(set) var lockReason: String?
24 private var lastChange = NSPasteboard.general.changeCount
25 private var timer: Timer?
26 private var key: SymmetricKey?
27 private let limit: Int
28 private var ignoreNextChange = false
29
30 private static let skipTypes: Set<String> = [
31 "org.nspasteboard.ConcealedType", "org.nspasteboard.TransientType",
32 "org.nspasteboard.AutoGeneratedType", "com.agilebits.onepassword",
33 "com.typeit4me.clipping", "de.petermaurer.TransientPasteboardType",
34 ]
35 private var file: URL { HopConfig.dir.appendingPathComponent("clipboard.bin") }
36 private var imageDir: URL {
37 let d = HopConfig.dir.appendingPathComponent("clip-images", isDirectory: true)
38 try? FileManager.default.createDirectory(at: d, withIntermediateDirectories: true)
39 return d
40 }
41
42 init(limit: Int, enabled: Bool = true) {
43 self.limit = max(50, limit)
44 if enabled { unlock(allowInteraction: false) }
45 }
46
47 /// Adds text that did not come through the system clipboard (a dictation), so it can be found and pasted again.
48 func record(_ text: String, from source: String) {
49 guard key != nil, !text.isEmpty else { return }
50 items.removeAll { $0.text == text && !$0.pinned }
51 items.insert(ClipItem(date: Date(), text: text, sourceApp: source), at: 0)
52 trim(); save()
53 }
54
55 /// Brings back history saved before the key moved (one macOS approval). Text items only; nothing is deleted.
56 @discardableResult
57 func recoverLegacy() -> Int {
58 guard let key else { return 0 }
59 guard let oldKey = try? Vault.legacyStorageKey(allowInteraction: true) else { return 0 }
60 let files = ((try? FileManager.default.contentsOfDirectory(at: HopConfig.dir, includingPropertiesForKeys: nil)) ?? [])
61 .filter { $0.lastPathComponent.hasPrefix("clipboard-legacy-") && $0.pathExtension == "bin" }
62 var added = 0
63 for f in files {
64 guard let data = try? Data(contentsOf: f), let box = try? AES.GCM.SealedBox(combined: data),
65 let plain = try? AES.GCM.open(box, using: oldKey),
66 let old = try? JSONDecoder().decode([ClipItem].self, from: plain) else { continue }
67 for it in old where it.text != nil && !items.contains(where: { $0.text == it.text }) { items.append(it); added += 1 }
68 }
69 _ = key
70 items.sort { $0.date > $1.date }
71 save()
72 return added
73 }
74
75 /// UI self-test only: show made-up items in memory. Nothing is read from or written to disk (no key is set).
76 func showTestItems(_ texts: [String]) {
77 timer?.invalidate(); timer = nil; key = nil
78 items = texts.map { ClipItem(date: Date(), text: $0, sourceApp: "Test") }
79 lockReason = nil
80 }
81
82 func unlock(allowInteraction: Bool) {
83 timer?.invalidate(); timer = nil; key = nil
84 let others = NSRunningApplication.runningApplications(withBundleIdentifier: "com.aienos.hop")
85 .contains { $0.processIdentifier != ProcessInfo.processInfo.processIdentifier && !$0.isTerminated }
86 guard !others else {
87 items = []
88 lockReason = "Another Hop copy is running. Close it before unlocking clipboard history; two copies must not overwrite the same history."
89 return
90 }
91 do {
92 let available = try Vault.storageKey(allowInteraction: allowInteraction)
93 let loaded = try load(using: available)
94 key = available; items = loaded; lockReason = nil
95 lastChange = NSPasteboard.general.changeCount
96 timer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true) { [weak self] _ in
97 MainActor.assumeIsolated { self?.poll() }
98 }
99 timer?.tolerance = 0.2
100 } catch {
101 items = []
102 lockReason = error.localizedDescription
103 }
104 }
105
106 private func poll() {
107 guard let key else { return }
108 let pb = NSPasteboard.general
109 guard pb.changeCount != lastChange else { return }
110 lastChange = pb.changeCount
111 if ignoreNextChange { ignoreNextChange = false; return }
112 let types = Set((pb.types ?? []).map(\.rawValue))
113 if !types.isDisjoint(with: Self.skipTypes) { return }
114 let app = NSWorkspace.shared.frontmostApplication?.localizedName
115 if let s = pb.string(forType: .string), !s.isEmpty {
116 guard s.utf8.count <= 512_000 else { return }
117 if let i = items.firstIndex(where: { $0.text == s }) {
118 var it = items.remove(at: i); it.date = Date(); items.insert(it, at: 0)
119 } else {
120 items.insert(ClipItem(date: Date(), text: s, sourceApp: app), at: 0)
121 }
122 } else if let img = NSImage(pasteboard: pb), let tiff = img.tiffRepresentation,
123 let rep = NSBitmapImageRep(data: tiff), let png = rep.representation(using: .png, properties: [:]),
124 png.count <= 20_000_000 {
125 let name = UUID().uuidString + ".bin"
126 if let sealed = try? AES.GCM.seal(png, using: key).combined {
127 try? sealed.write(to: imageDir.appendingPathComponent(name), options: .atomic)
128 items.insert(ClipItem(date: Date(), imageFile: name, sourceApp: app), at: 0)
129 }
130 } else { return }
131 trim(); save()
132 }
133
134 func image(for item: ClipItem) -> NSImage? {
135 guard let key, let f = item.imageFile, let d = try? Data(contentsOf: imageDir.appendingPathComponent(f)),
136 let box = try? AES.GCM.SealedBox(combined: d), let png = try? AES.GCM.open(box, using: key) else { return nil }
137 return NSImage(data: png)
138 }
139
140 /// Puts an item back on the clipboard (without re-recording it as new).
141 func copy(_ item: ClipItem) {
142 guard key != nil else { return }
143 let pb = NSPasteboard.general
144 pb.clearContents()
145 if let t = item.text { pb.setString(t, forType: .string) }
146 else if let img = image(for: item) { pb.writeObjects([img]) }
147 ignoreNextChange = true
148 if let i = items.firstIndex(of: item) { var it = items.remove(at: i); it.date = Date(); items.insert(it, at: 0) }
149 save()
150 }
151
152 func togglePin(_ item: ClipItem) {
153 guard key != nil else { return }
154 guard let i = items.firstIndex(of: item) else { return }
155 items[i].pinned.toggle(); save()
156 }
157
158 func delete(_ item: ClipItem) {
159 guard key != nil else { return }
160 if let f = item.imageFile { try? FileManager.default.removeItem(at: imageDir.appendingPathComponent(f)) }
161 items.removeAll { $0.id == item.id }; save()
162 }
163
164 func clearUnpinned() {
165 guard key != nil else { return }
166 for it in items where !it.pinned { if let f = it.imageFile { try? FileManager.default.removeItem(at: imageDir.appendingPathComponent(f)) } }
167 items.removeAll { !$0.pinned }; save()
168 }
169
170 func search(_ q: String) -> [ClipItem] { Self.search(q, in: items) }
171
172 private func trim() {
173 var unpinned = items.filter { !$0.pinned }
174 guard unpinned.count > limit else { return }
175 let drop = unpinned[limit...]
176 for it in drop { if let f = it.imageFile { try? FileManager.default.removeItem(at: imageDir.appendingPathComponent(f)) } }
177 let dropIDs = Set(drop.map(\.id))
178 unpinned.removeAll { dropIDs.contains($0.id) }
179 items.removeAll { dropIDs.contains($0.id) }
180 }
181
182 private func save() {
183 guard let key, let d = try? JSONEncoder().encode(items), let sealed = try? AES.GCM.seal(d, using: key).combined else { return }
184 try? sealed.write(to: file, options: .atomic)
185 try? FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: file.path)
186 }
187
188 private func load(using key: SymmetricKey) throws -> [ClipItem] {
189 let data: Data
190 do { data = try Data(contentsOf: file) }
191 catch let error as NSError where error.domain == NSCocoaErrorDomain && error.code == NSFileReadNoSuchFileError { return [] }
192 let box = try AES.GCM.SealedBox(combined: data)
193 let plain = try AES.GCM.open(box, using: key)
194 return try JSONDecoder().decode([ClipItem].self, from: plain)
195 }
196
197 /// What is saved, for reading only (`hop clip`, `hop status`): nil when no history file exists. Nothing is
198 /// written, moved or unlocked here, so it is safe while Hop itself is running (Hop replaces the file whole).
199 nonisolated static func saved() throws -> [ClipItem]? {
200 let file = HopConfig.dir.appendingPathComponent("clipboard.bin")
201 guard FileManager.default.fileExists(atPath: file.path) else { return nil }
202 guard let key = try Vault.readStorageKey() else { throw Vault.StorageError.missingHistoricalKey }
203 let plain = try AES.GCM.open(AES.GCM.SealedBox(combined: Data(contentsOf: file)), using: key)
204 return try JSONDecoder().decode([ClipItem].self, from: plain)
205 }
206
207 /// The order and the match Hop's Clipboard screen uses: pinned first, then newest; every word must be in the text.
208 nonisolated static func search(_ q: String, in items: [ClipItem]) -> [ClipItem] {
209 let sorted = items.filter(\.pinned) + items.filter { !$0.pinned }
210 let terms = q.lowercased().split(separator: " ").map(String.init)
211 if terms.isEmpty { return sorted }
212 return sorted.filter { it in
213 let hay = (it.text ?? "image").lowercased()
214 return terms.allSatisfy { hay.contains($0) }
215 }
216 }
217}