Sources/OrgstarMobile/SpotlightIndexer.swift

3a5c6a6f0e1b65f57e3697195747679128581b57
orgstar/Sources/OrgstarMobile/SpotlightIndexer.swift

91 lines · 3991 bytes

 1#if os(iOS)
 2import CoreSpotlight
 3import Foundation
 4import OrgApp
 5import OrgCore
 6import UniformTypeIdentifiers
 7
 8/// The workspace's org files in Spotlight with what the Mac's importer gives it: the text,
 9/// title, author, description, tags and headings. A file is indexed again when it changes.
10@MainActor
11final class SpotlightIndexer {
12    private struct State: Codable {
13        /// Also kept as the index's client state; the system deleting the index (as it does
14        /// when the app is installed again) takes it away, and every file is indexed again.
15        var generation = UUID()
16        /// Modification dates of the files as indexed.
17        var stamps: [String: Date] = [:]
18    }
19
20    private let index = CSSearchableIndex(name: "files")
21    private let stateFile = WorkspaceModel.defaultDirectory.appendingPathComponent("spotlight.json")
22    private var state: State
23    /// Files to index once the running update finishes; a batch can't start while one is open.
24    private var waiting: [FileEntry]?
25    private var running = false
26
27    init() {
28        state = (try? JSONDecoder().decode(State.self, from: Data(contentsOf: stateFile))) ?? State()
29    }
30
31    func update(_ files: [FileEntry]) async {
32        let interval = Perf.begin("spotlight.update")
33        defer { interval.end("\(files.count) files") }
34        guard !running else { return waiting = files }
35        running = true
36        defer { running = false }
37        var next: [FileEntry]? = files
38        while let files = next {
39            await index(files)
40            next = waiting
41            waiting = nil
42        }
43    }
44
45    /// Opens a batch with the changes; `endBatch` commits them. Not async: in a batch the
46    /// calls' completion handlers wait for the batch to end.
47    private func submit(_ items: [CSSearchableItem], removing gone: [String]) {
48        index.beginBatch()
49        if !items.isEmpty { index.indexSearchableItems(items, completionHandler: nil) }
50        if !gone.isEmpty { index.deleteSearchableItems(withIdentifiers: gone, completionHandler: nil) }
51    }
52
53    private func index(_ files: [FileEntry]) async {
54        let generation = Data(state.generation.uuidString.utf8)
55        let stamps = (try? await index.fetchLastClientState()) == generation ? state.stamps : [:]
56        var current: [String: Date] = [:]
57        var items: [CSSearchableItem] = []
58        for file in files where file.kind == .org {
59            guard let date = (try? FileManager.default.attributesOfItem(atPath: file.path))?[.modificationDate] as? Date else { continue }
60            if stamps[file.path] == date {
61                current[file.path] = date
62            } else if let text = try? String(contentsOfFile: file.path, encoding: .utf8) {
63                items.append(Self.item(file, text: text))
64                current[file.path] = date
65            }
66        }
67        let gone = stamps.keys.filter { current[$0] == nil }
68        guard !items.isEmpty || !gone.isEmpty else { return }
69        submit(items, removing: gone)
70        do {
71            try await index.endBatch(withClientState: generation)
72        } catch {
73            return
74        }
75        state.stamps = current
76        try? JSONEncoder().encode(state).write(to: stateFile, options: .atomic)
77    }
78
79    private static func item(_ file: FileEntry, text: String) -> CSSearchableItem {
80        let summary = FileSummary(text)
81        let attributes = CSSearchableItemAttributeSet(contentType: .text)
82        attributes.title = summary.title ?? (file.name as NSString).deletingPathExtension
83        attributes.displayName = attributes.title
84        attributes.contentDescription = summary.description ?? file.relativePath
85        attributes.textContent = text
86        if let author = summary.author { attributes.authorNames = [author] }
87        attributes.keywords = summary.tags + summary.headings
88        return CSSearchableItem(uniqueIdentifier: file.path, domainIdentifier: "files", attributeSet: attributes)
89    }
90}
91#endif
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form