hop
Hop: a small native macOS launcher. Clipboard history, find, on-device dictation and your coding agent behind one key.
Brought by drakestapleton
hop / Sources / FileIndex.swift
| 1 | import Foundation |
| 2 | import Darwin |
| 3 | |
| 4 | /// Hop's own file-name index. Spotlight is switched off on this Mac, so Hop walks the disk itself |
| 5 | /// at low I/O priority and keeps every path in one compact byte buffer (no per-file objects). |
| 6 | /// Searching is a plain byte scan, which is fast enough for a few hundred thousand paths. |
| 7 | final class FileIndex: @unchecked Sendable { |
| 8 | struct Hit: Identifiable, Hashable { |
| 9 | let id: String; let path: String; let score: Int |
| 10 | var machine: String? = nil // nil = this Mac |
| 11 | var isFolder: Bool { path.hasSuffix("/") } |
| 12 | init(id: String, score: Int) { self.id = id; self.path = id; self.score = score } |
| 13 | init(path: String, machine: String, score: Int) { |
| 14 | self.id = machine + ":" + path; self.path = path; self.score = score; self.machine = machine |
| 15 | } |
| 16 | } |
| 17 | |
| 18 | /// Same ranking as the local scan, for paths that come from another machine. The rules are Omega code |
| 19 | /// (`Omega/hopcore.om`, fn fscore), reached through OmegaCore. |
| 20 | static func score(path: String, terms: [String]) -> Int? { scores(paths: [path], terms: terms)[0] } |
| 21 | static func scores(paths: [String], terms: [String]) -> [Int?] { OmegaCore.shared.fileScores(paths: paths, terms: terms) } |
| 22 | |
| 23 | private let lock = NSLock() |
| 24 | private var blob = Data() // paths separated by \n |
| 25 | private var lower = Data() // same bytes with ASCII lower-cased (same offsets) |
| 26 | private(set) var count = 0 |
| 27 | private(set) var builtAt: Date? |
| 28 | private var building = false |
| 29 | private let roots: [String] |
| 30 | private let skip: Set<String> |
| 31 | private let fileOverride: URL? // tests point this at a throwaway file |
| 32 | private var file: URL { fileOverride ?? HopConfig.dir.appendingPathComponent("file-index.bin") } |
| 33 | |
| 34 | init(roots: [String], skipNames: [String], file: URL? = nil) { |
| 35 | self.roots = roots |
| 36 | self.skip = Set(skipNames) |
| 37 | self.fileOverride = file |
| 38 | let saved = self.file |
| 39 | if let d = try? Data(contentsOf: saved) { install(d, date: (try? saved.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate) } |
| 40 | } |
| 41 | |
| 42 | private func install(_ d: Data, date: Date?) { |
| 43 | // Nothing indexed (no roots, an empty folder, a folder that is not there): publish an empty index and stop. |
| 44 | // An empty buffer must never reach the in-place conversion below; in an optimised build that stopped Hop. |
| 45 | guard !d.isEmpty else { |
| 46 | lock.lock(); blob = Data(); lower = Data(); count = 0; builtAt = date; lock.unlock() |
| 47 | return |
| 48 | } |
| 49 | var low = Data(d) // its own storage, so the bytes below are changed in a buffer nobody else holds |
| 50 | low.withUnsafeMutableBytes { (p: UnsafeMutableRawBufferPointer) in |
| 51 | for i in 0..<p.count where p[i] >= 65 && p[i] <= 90 { p[i] += 32 } |
| 52 | } |
| 53 | let n = d.reduce(0) { $1 == 10 ? $0 + 1 : $0 } |
| 54 | lock.lock(); blob = d; lower = low; count = n; builtAt = date; lock.unlock() |
| 55 | } |
| 56 | |
| 57 | /// Rebuilds in the background at throttled disk priority so the Mac stays responsive. |
| 58 | func rebuild(completion: (@Sendable () -> Void)? = nil) { |
| 59 | lock.lock(); if building { lock.unlock(); return }; building = true; lock.unlock() |
| 60 | let roots = self.roots, skip = self.skip |
| 61 | Thread.detachNewThread { [weak self] in |
| 62 | Thread.current.qualityOfService = .background |
| 63 | setiopolicy_np(IOPOL_TYPE_DISK, IOPOL_SCOPE_THREAD, IOPOL_THROTTLE) |
| 64 | var out = Data(); out.reserveCapacity(32 << 20) |
| 65 | let keys: [URLResourceKey] = [.isDirectoryKey, .isPackageKey, .isSymbolicLinkKey] |
| 66 | var seen = 0 |
| 67 | for root in roots { |
| 68 | guard let en = FileManager.default.enumerator(at: URL(fileURLWithPath: root), includingPropertiesForKeys: keys, |
| 69 | options: [.skipsHiddenFiles], errorHandler: { _, _ in true }) else { continue } |
| 70 | for case let u as URL in en { |
| 71 | let name = u.lastPathComponent |
| 72 | let v = try? u.resourceValues(forKeys: Set(keys)) |
| 73 | if v?.isDirectory == true { |
| 74 | if skip.contains(name) || v?.isSymbolicLink == true { en.skipDescendants(); continue } |
| 75 | if v?.isPackage == true { en.skipDescendants() } // .app, .pages, ... count as one item |
| 76 | } |
| 77 | out.append(contentsOf: Array(u.path.utf8)); out.append(10) |
| 78 | seen += 1 |
| 79 | if seen >= 3_000_000 { break } |
| 80 | } |
| 81 | } |
| 82 | guard let self else { return } |
| 83 | try? out.write(to: self.file, options: .atomic) |
| 84 | try? FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: self.file.path) |
| 85 | self.install(out, date: Date()) |
| 86 | self.lock.lock(); self.building = false; self.lock.unlock() |
| 87 | completion?() |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | /// Every word must appear in the path; names that start with or contain the words rank first. |
| 92 | func search(_ query: String, limit: Int = 40) -> [Hit] { |
| 93 | let terms = query.lowercased().split(separator: " ").map { Array($0.utf8) }.filter { !$0.isEmpty } |
| 94 | guard !terms.isEmpty else { return [] } |
| 95 | lock.lock(); let b = blob, l = lower; lock.unlock() |
| 96 | let lead = terms.max { $0.count < $1.count }! |
| 97 | var hits: [Hit] = [] |
| 98 | l.withUnsafeBytes { (lp: UnsafeRawBufferPointer) in |
| 99 | b.withUnsafeBytes { (bp: UnsafeRawBufferPointer) in |
| 100 | guard let base = lp.baseAddress, lp.count > 0 else { return } |
| 101 | let n = lp.count |
| 102 | var pos = 0 |
| 103 | var scanned = 0 |
| 104 | while pos < n, scanned < 20_000 { |
| 105 | guard let m = lead.withUnsafeBufferPointer({ memmem(base + pos, n - pos, $0.baseAddress, $0.count) }) else { break } |
| 106 | let at = base.distance(to: UnsafeRawPointer(m)) |
| 107 | var s = at; while s > 0 && lp[s - 1] != 10 { s -= 1 } |
| 108 | var e = at; while e < n && lp[e] != 10 { e += 1 } |
| 109 | pos = e + 1; scanned += 1 |
| 110 | let line = UnsafeRawBufferPointer(rebasing: lp[s..<e]) |
| 111 | var nameStart = e; while nameStart > s && lp[nameStart - 1] != 47 { nameStart -= 1 } |
| 112 | let nameLine = UnsafeRawBufferPointer(rebasing: lp[nameStart..<e]) |
| 113 | var score = 0, ok = true |
| 114 | for t in terms { |
| 115 | if contains(nameLine, t) { score += startsWith(nameLine, t) ? 60 : 30 } |
| 116 | else if contains(line, t) { score += 5 } |
| 117 | else { ok = false; break } |
| 118 | } |
| 119 | if !ok { continue } |
| 120 | score -= (e - s) / 20 // shorter paths first |
| 121 | if nameLine.count == terms.reduce(0, { $0 + $1.count }) { score += 40 } // exact name |
| 122 | let path = String(decoding: UnsafeRawBufferPointer(rebasing: bp[s..<e]), as: UTF8.self) |
| 123 | if path.hasSuffix(".app") { score += 25 } |
| 124 | hits.append(Hit(id: path, score: score)) |
| 125 | } |
| 126 | } |
| 127 | } |
| 128 | return Array(hits.sorted { $0.score > $1.score }.prefix(limit)) |
| 129 | } |
| 130 | |
| 131 | private func contains(_ hay: UnsafeRawBufferPointer, _ needle: [UInt8]) -> Bool { |
| 132 | guard hay.count >= needle.count, let hb = hay.baseAddress else { return false } |
| 133 | return needle.withUnsafeBufferPointer { memmem(hb, hay.count, $0.baseAddress, $0.count) != nil } |
| 134 | } |
| 135 | private func startsWith(_ hay: UnsafeRawBufferPointer, _ needle: [UInt8]) -> Bool { |
| 136 | guard hay.count >= needle.count else { return false } |
| 137 | for i in 0..<needle.count where hay[i] != needle[i] { return false } |
| 138 | return true |
| 139 | } |
| 140 | } |