Sources/OrgApp/Handoff.swift

89cd390831f813d3a7b29905803e98849b457be9
orgstar/Sources/OrgApp/Handoff.swift

253 lines · 11442 bytes

  1import Foundation
  2import OrgCore
  3
  4/// The open file and the caret's place in it, as Handoff passes them between orgstar on a Mac,
  5/// iPhone and iPad. Only where the file is and where the caret is go in the activity, never the
  6/// file's text.
  7///
  8/// A folder is found on the other device by its path in iCloud Drive (or another iCloud
  9/// container) when it is in iCloud, since that path is the same on every device; otherwise by
 10/// the added folder's name, since other providers (Dropbox, Working Copy, a local folder) put
 11/// the same folder at a different path on each device.
 12public struct HandoffPlace: Equatable, Sendable {
 13    /// The activity type, listed under `NSUserActivityTypes` in both apps' Info.plist.
 14    public static let activityType = "sh.krz.orgstar.editing"
 15
 16    /// The added folder's name.
 17    public var folder: String
 18    /// The file's path inside iCloud's containers (`com~apple~CloudDocs/org/todo.org`), when it
 19    /// is in iCloud.
 20    public var cloudPath: String?
 21    /// The file's path relative to the added folder.
 22    public var file: String
 23    /// The titles of the caret's heading and the headings above it, outermost first.
 24    public var outline: [String]
 25    /// The caret's heading's `ID`.
 26    public var id: String?
 27    /// The caret's line, from 1.
 28    public var line: Int
 29    /// The caret's heading's line, from 1; 0 before the first heading.
 30    public var headingLine: Int
 31
 32    public init(folder: String, cloudPath: String?, file: String, outline: [String], id: String?, line: Int, headingLine: Int) {
 33        self.folder = folder
 34        self.cloudPath = cloudPath
 35        self.file = file
 36        self.outline = outline
 37        self.id = id
 38        self.line = line
 39        self.headingLine = headingLine
 40    }
 41
 42    // MARK: - userInfo
 43
 44    public var userInfo: [String: Any] {
 45        var info: [String: Any] = ["folder": folder, "file": file, "outline": outline, "line": line, "headingLine": headingLine]
 46        if let cloudPath { info["cloudPath"] = cloudPath }
 47        if let id { info["id"] = id }
 48        return info
 49    }
 50
 51    public init?(userInfo: [AnyHashable: Any]?) {
 52        guard let info = userInfo, let folder = info["folder"] as? String, let file = info["file"] as? String,
 53              !file.isEmpty, !file.hasPrefix("/"), !file.split(separator: "/").contains("..") else { return nil }
 54        self.init(folder: folder, cloudPath: info["cloudPath"] as? String, file: file, outline: info["outline"] as? [String] ?? [],
 55                  id: info["id"] as? String, line: max(1, info["line"] as? Int ?? 1), headingLine: max(0, info["headingLine"] as? Int ?? 0))
 56    }
 57
 58    // MARK: - Advertising
 59
 60    /// Whether a file may be advertised: not an encrypted one.
 61    public static func advertises(_ path: String) -> Bool {
 62        !path.hasSuffix(".gpg")
 63    }
 64
 65    /// The place of `caret` in `text`, the file at `path` inside one of `roots`; nil when the
 66    /// file is in none of them or is encrypted.
 67    public static func make(path: String, text: String, caret: Int, roots: [String], settings: OrgSettings = .default) -> HandoffPlace? {
 68        guard advertises(path), let root = roots.filter({ inside(path, $0) }).max(by: { $0.count < $1.count }) else { return nil }
 69        let file = String(path.dropFirst(root.hasSuffix("/") ? root.count : root.count + 1))
 70        guard !file.isEmpty else { return nil }
 71        let model = DocumentModel(tree: OrgParser.parse(text, defaults: settings))
 72        let ns = text as NSString
 73        let caret = max(0, min(caret, ns.length))
 74        var outline: [String] = []
 75        var id: String?
 76        var headingLine = 0
 77        if let index = model.headings.lastIndex(where: { $0.headingRange.lowerBound <= caret }) {
 78            id = model.headings[index].id
 79            headingLine = line(of: model.headings[index].headingRange.lowerBound, in: ns)
 80            var next: Int? = index
 81            while let i = next {
 82                outline.insert(model.headings[i].title, at: 0)
 83                next = model.headings[i].parent
 84            }
 85        }
 86        return HandoffPlace(folder: (root as NSString).lastPathComponent, cloudPath: cloudPath(of: path), file: file,
 87                            outline: outline, id: id, line: line(of: caret, in: ns), headingLine: headingLine)
 88    }
 89
 90    /// `path` inside iCloud's containers: what follows `Mobile Documents/`, which is the same on
 91    /// a Mac (`~/Library/Mobile Documents`) and on iOS (`/var/mobile/Library/Mobile Documents`).
 92    public static func cloudPath(of path: String) -> String? {
 93        guard let range = path.range(of: "/Mobile Documents/") else { return nil }
 94        let rest = String(path[range.upperBound...])
 95        return rest.isEmpty ? nil : rest
 96    }
 97
 98    static func inside(_ path: String, _ root: String) -> Bool {
 99        path.hasPrefix(root.hasSuffix("/") ? root : root + "/")
100    }
101
102    /// The 1-based line of `offset`.
103    static func line(of offset: Int, in text: NSString) -> Int {
104        var line = 1
105        var index = 0
106        let end = min(offset, text.length)
107        while index < end {
108            let found = text.range(of: "\n", options: [], range: NSRange(location: index, length: end - index))
109            guard found.location != NSNotFound else { break }
110            line += 1
111            index = found.location + 1
112        }
113        return line
114    }
115
116    /// The offset where 1-based `line` starts, or the end of the text.
117    static func offset(ofLine line: Int, in text: NSString) -> Int {
118        var index = 0
119        var current = 1
120        while current < line {
121            let found = text.range(of: "\n", options: [], range: NSRange(location: index, length: text.length - index))
122            guard found.location != NSNotFound else { return text.length }
123            index = found.location + 1
124            current += 1
125        }
126        return index
127    }
128
129    // MARK: - Continuing
130
131    public enum Match: Equatable, Sendable {
132        /// The file on this device.
133        case file(String)
134        /// No added folder is the advertised one.
135        case noFolder
136        /// The folder is here, without the file (not synced yet, or since moved).
137        case noFile
138    }
139
140    /// The file on this device: in a root that has the same iCloud path, or else in a root with
141    /// the folder's name.
142    public func resolve(roots: [String], exists: (String) -> Bool = { FileManager.default.fileExists(atPath: $0) }) -> Match {
143        var candidates: [String] = []
144        if let cloudPath {
145            for root in roots {
146                guard let cloudRoot = Self.cloudPath(of: root), cloudPath.hasPrefix(cloudRoot + "/") else { continue }
147                candidates.append((root as NSString).appendingPathComponent(String(cloudPath.dropFirst(cloudRoot.count + 1))))
148            }
149        }
150        if candidates.isEmpty {
151            candidates = roots.filter { ($0 as NSString).lastPathComponent == folder }.map { ($0 as NSString).appendingPathComponent(file) }
152        }
153        guard !candidates.isEmpty else { return .noFolder }
154        return candidates.first(where: exists).map(Match.file) ?? .noFile
155    }
156
157    /// Where the caret goes in `text`, this device's copy of the file: the heading with the
158    /// `ID`, else the one at the outline path, at the same line within it; else the same line.
159    public func offset(in text: String, settings: OrgSettings = .default) -> Int {
160        let ns = text as NSString
161        let model = DocumentModel(tree: OrgParser.parse(text, defaults: settings))
162        var found: Int?
163        if let id { found = model.headings.firstIndex { $0.id == id } }
164        if found == nil, !outline.isEmpty {
165            var parent: Int?
166            for title in outline {
167                guard let next = model.headings.indices.first(where: { model.headings[$0].parent == parent && model.headings[$0].title == title }) else {
168                    parent = nil
169                    break
170                }
171                parent = next
172            }
173            found = parent
174        }
175        guard let found, headingLine > 0 else { return Self.offset(ofLine: line, in: ns) }
176        let start = model.headings[found].headingRange.lowerBound
177        // The caret was in the heading's own text, before the next heading.
178        let limit = found + 1 < model.headings.count ? max(start, model.headings[found + 1].headingRange.lowerBound - 1) : ns.length
179        let target = Self.line(of: start, in: ns) + max(0, line - headingLine)
180        return min(Self.offset(ofLine: target, in: ns), limit)
181    }
182}
183
184/// The activity that advertises the focused file to the other devices. `place` gives what to
185/// advertise when the file or the caret changes; the activity is current only while it gives
186/// one.
187@MainActor
188public final class HandoffAdvertiser {
189    public var place: () -> HandoffPlace? = { nil }
190    private var activity: NSUserActivity?
191    private var pending: Task<Void, Never>?
192
193    public init() {}
194
195    /// The file or caret changed: the activity follows a moment later, so typing and moving
196    /// the caret don't parse the file on every key.
197    public func changed() {
198        pending?.cancel()
199        pending = Task { [weak self] in
200            try? await Task.sleep(for: .milliseconds(700))
201            guard !Task.isCancelled else { return }
202            self?.update()
203        }
204    }
205
206    /// Advertises the place now, or stops advertising when there is none.
207    public func update() {
208        guard let place = place() else {
209            activity?.invalidate()
210            activity = nil
211            return
212        }
213        let activity = activity ?? NSUserActivity(activityType: HandoffPlace.activityType)
214        activity.title = (place.file as NSString).lastPathComponent
215        activity.isEligibleForHandoff = true
216        activity.isEligibleForSearch = false
217        activity.isEligibleForPublicIndexing = false
218        activity.userInfo = place.userInfo
219        activity.needsSave = true
220        self.activity = activity
221        activity.becomeCurrent()
222    }
223
224    /// Stops advertising.
225    public func stop() {
226        pending?.cancel()
227        activity?.invalidate()
228        activity = nil
229    }
230}
231
232extension HandoffPlace {
233    /// What to say when the file can't be continued here; nil when it can.
234    public func problem(_ match: Match) -> String? {
235        let name = (file as NSString).lastPathComponent
236        switch match {
237        case .file: return nil
238        case .noFolder: return String(localized: "Can't continue \(name): no folder named “\(folder)” is added on this device.", comment: "Handoff from another device")
239        case .noFile: return String(localized: "Can't continue \(name): it isn't in “\(folder)” on this device yet.", comment: "Handoff from another device")
240        }
241    }
242}
243
244extension DocumentSession {
245    /// The open file at `path`, or the focused one, and its caret, for Handoff; nil for a file
246    /// in none of `roots` or an encrypted one.
247    public func handoffPlace(_ path: String? = nil, roots: [String]) -> HandoffPlace? {
248        guard let path = path ?? self.path, let text = document(of: path)?.text else { return nil }
249        // The outline and ID could name decrypted headings.
250        guard !crypt.isPrivate(text, for: path) else { return nil }
251        return HandoffPlace.make(path: path, text: text, caret: caret(of: path) ?? 0, roots: roots, settings: defaults)
252    }
253}
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