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 / Omega / tests / ui-clips / main.swift

81 lines · 5656 bytes Raw Blame History
1import AppKit
2import CryptoKit
3
4// The other side of the Omega panel's clipboard checks (Omega/tests/check-ui.sh), written with what Hop itself
5// uses: the Codable shape of Sources/Clipboard.swift and CryptoKit's AES.GCM (nonce + data + tag in one file).
6// ui-clips write DIR KEY [AGE [EXTRA]] a history of four things, the newest AGE seconds old, and EXTRA more texts
7// ui-clips read DIR KEY the history as Hop reads it back, one line a thing
8// ui-clips board-text TEXT put TEXT on the check's own pasteboard
9// ui-clips board-concealed TEXT the same, marked concealed as a password manager marks it
10// ui-clips board-picture put a small picture there
11// ui-clips board-clear
12struct ClipItem: Codable {
13 var id: UUID = UUID()
14 var date: Date
15 var text: String?
16 var imageFile: String?
17 var sourceApp: String?
18 var pinned: Bool = false
19}
20func fail(_ m: String) -> Never { FileHandle.standardError.write(Data((m + "\n").utf8)); exit(2) }
21
22let a = CommandLine.arguments
23guard a.count >= 2 else { fail("usage: ui-clips write|read|board-text|board-concealed|board-picture|board-clear ...") }
24let board = NSPasteboard(name: NSPasteboard.Name("com.aienos.hop.omega.check"))
25switch a[1] {
26case "board-clear": board.clearContents()
27case "board-text":
28 guard a.count >= 3 else { fail("board-text TEXT") }
29 board.clearContents(); board.setString(a[2], forType: .string)
30case "board-concealed":
31 guard a.count >= 3 else { fail("board-concealed TEXT") }
32 let concealed = NSPasteboard.PasteboardType("org.nspasteboard.ConcealedType")
33 board.clearContents(); board.declareTypes([.string, concealed], owner: nil)
34 board.setString(a[2], forType: .string); board.setString("", forType: concealed)
35case "board-picture":
36 // 3 by 2 pixels, drawn here, so that there is a real picture for AppKit to read
37 let rep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: 3, pixelsHigh: 2, bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true,
38 isPlanar: false, colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0)!
39 for x in 0..<3 { for y in 0..<2 { rep.setColor(NSColor(deviceRed: CGFloat(x) / 2, green: CGFloat(y), blue: 0.5, alpha: 1), atX: x, y: y) } }
40 board.clearContents(); board.setData(rep.representation(using: .png, properties: [:])!, forType: .png)
41case "write", "read":
42 guard a.count >= 4, let raw = Data(base64Encoded: a[3]), raw.count == 32 else { fail("\(a[1]) DIR KEY-IN-BASE64 ...") }
43 let dir = URL(fileURLWithPath: a[2]), key = SymmetricKey(data: raw), now = Date()
44 let images = dir.appendingPathComponent("clip-images"), file = dir.appendingPathComponent("clipboard.bin")
45 if a[1] == "write" {
46 let age = a.count > 4 ? Double(a[4]) ?? 20 : 20, extra = a.count > 5 ? Int(a[5]) ?? 0 : 0
47 // 70 bytes that stand for a picture: the panel unseals and pastes them as they are
48 let bytes = Data((0..<70).map { UInt8(($0 * 7 + 3) & 255) })
49 try! FileManager.default.createDirectory(at: images, withIntermediateDirectories: true)
50 try! AES.GCM.seal(bytes, using: key).combined!.write(to: images.appendingPathComponent("picture-1.bin"))
51 var items = [
52 ClipItem(date: now.addingTimeInterval(-age), text: "https://example.com/docs", sourceApp: "Safari"),
53 ClipItem(date: now.addingTimeInterval(-3000), text: " meeting notes\nline \"two\" with caf\u{e9} ", sourceApp: "Notes"),
54 ClipItem(date: now.addingTimeInterval(-5000), imageFile: "picture-1.bin"),
55 ClipItem(date: now.addingTimeInterval(-90000), text: "a pinned snippet", pinned: true),
56 ]
57 for k in 0..<extra { items.append(ClipItem(date: now.addingTimeInterval(-100000 - Double(k)), text: "filler \(k)")) }
58 let sealed = try! AES.GCM.seal(try! JSONEncoder().encode(items), using: key).combined!
59 try! sealed.write(to: file)
60 print("wrote \(items.count) items, \(sealed.count) bytes")
61 } else {
62 // exactly Hop's load: SealedBox(combined:), open, decode
63 guard let data = try? Data(contentsOf: file) else { print("no history"); exit(1) }
64 guard let box = try? AES.GCM.SealedBox(combined: data), let plain = try? AES.GCM.open(box, using: key) else { print("not sealed with this key"); exit(1) }
65 guard let items = try? JSONDecoder().decode([ClipItem].self, from: plain) else { print("not Hop's shape"); exit(1) }
66 let mode = (try? FileManager.default.attributesOfItem(atPath: file.path)[.posixPermissions] as? Int).map { String($0, radix: 8) } ?? "?"
67 print("items \(items.count) mode \(mode) fillers \(items.filter { ($0.text ?? "").hasPrefix("filler ") }.count)")
68 for it in items.prefix(6) {
69 var what = it.text.map { "text[\($0.replacingOccurrences(of: "\n", with: "\\n"))]" } ?? ""
70 if let f = it.imageFile {
71 // the picture as Hop would show it: unsealed, and something AppKit can read
72 let d = try? Data(contentsOf: images.appendingPathComponent(f))
73 let png = d.flatMap { try? AES.GCM.SealedBox(combined: $0) }.flatMap { try? AES.GCM.open($0, using: key) }
74 let size = png.flatMap { NSBitmapImageRep(data: $0) }.map { "\($0.pixelsWide)x\($0.pixelsHigh)" }
75 what = "picture[\(size ?? (png == nil ? "unreadable" : "\(png!.count) bytes"))]"
76 }
77 print("\(what) from[\(it.sourceApp ?? "")] pinned \(it.pinned) fresh \(abs(it.date.timeIntervalSince(now)) < 300) id \(it.id.uuidString.count)")
78 }
79 }
80default: fail("unknown: \(a[1])")
81}