Commit 3aa264c947

3aa264c947476955d58c5cccc70e97072bb47877

parent: 5b5584bafa

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-26 09:01 UTC

Handoff of the open file and caret between Mac, iPhone and iPad

The editor advertises an NSUserActivity (sh.krz.orgstar.editing) with the
added folder's name, the file's path in iCloud when it is in iCloud, its
path in the folder, and the caret's heading (ID and outline path) and
line; never the file's text, and never for a .org.gpg file. The
receiving app finds the folder by its iCloud path, else by name, opens
the file in the editor at the heading or line, and says when it has no
such folder or file.

Closes #93

Layout: unified · split

Changed files (15)
Sources/OrgApp/Handoff.swift added +251 · view
@@ -0,0 +1,251 @@
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 return HandoffPlace.make(path: path, text: text, caret: caret(of: path) ?? 0, roots: roots, settings: defaults)
250 }
251}
Sources/Orgstar/ContentView.swift +16 · view
@@ -372,6 +372,8 @@ struct ContentView: View {
372 clock.remindAtEffort(session) 372 clock.remindAtEffort(session)
373 commands.knownTags = { [index = workspace.index] in (try? index.tags()) ?? [] } 373 commands.knownTags = { [index = workspace.index] in (try? index.tags()) ?? [] }
374 commands.completionIndex = workspace.index 374 commands.completionIndex = workspace.index
375 commands.handoff.place = { [weak session, weak workspace] in workspace.flatMap { session?.handoffPlace(roots: $0.rootPaths) } }
376 commands.continueHandoff = continueHandoff
375 commands.mainWindowOpen = true 377 commands.mainWindowOpen = true
376 commands.whatsNew = WhatsNew.pending(firstLaunch: noFolders && !welcomeShown) 378 commands.whatsNew = WhatsNew.pending(firstLaunch: noFolders && !welcomeShown)
377 if noFolders, !welcomeShown { 379 if noFolders, !welcomeShown {
@@ -512,6 +514,10 @@ struct ContentView: View {
512 } 514 }
513 session.reveal(request.offset) 515 session.reveal(request.offset)
514 } 516 }
517 // Handoff follows the focused file and its caret, and takes over again when the app does.
518 .onChange(of: session.path, initial: true) { commands.handoff.changed() }
519 .onChange(of: commands.selection) { commands.handoff.changed() }
520 .onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ in commands.handoff.update() }
515 .onChange(of: commands.focusSearch) { _, focus in 521 .onChange(of: commands.focusSearch) { _, focus in
516 if focus { 522 if focus {
517 searchFocused = true 523 searchFocused = true
@@ -580,6 +586,8 @@ struct ContentView: View {
580 // Files handed over at launch open after the restored buffers, and show. 586 // Files handed over at launch open after the restored buffers, and show.
581 for path in AppDelegate.pendingOpens { session.open(path) } 587 for path in AppDelegate.pendingOpens { session.open(path) }
582 AppDelegate.pendingOpens = [] 588 AppDelegate.pendingOpens = []
589 for place in AppDelegate.pendingHandoffs { continueHandoff(place) }
590 AppDelegate.pendingHandoffs = []
583 #if APPSTORE 591 #if APPSTORE
584 for link in AppDelegate.pendingLinks { commands.handle(protocolURL: link) } 592 for link in AppDelegate.pendingLinks { commands.handle(protocolURL: link) }
585 AppDelegate.pendingLinks = [] 593 AppDelegate.pendingLinks = []
@@ -1296,6 +1304,14 @@ struct ContentView: View {
1296 } 1304 }
1297 } 1305 }
1298 1306
1307 /// A file continued from another device, at the caret's heading or line there.
1308 private func continueHandoff(_ place: HandoffPlace) {
1309 let match = place.resolve(roots: workspace.rootPaths)
1310 guard case .file(let path) = match else { return commands.show(place.problem(match) ?? "") }
1311 let offset = session.text(of: path).map { place.offset(in: $0, settings: session.defaults) } ?? 0
1312 commands.jump(path: path, offset: offset)
1313 }
1314
1299 /// Runs a command from a key, the palette or the Org menu. 1315 /// Runs a command from a key, the palette or the Org menu.
1300 private func perform(_ id: String) { 1316 private func perform(_ id: String) {
1301 if hiddenCommandIDs.contains(id) { 1317 if hiddenCommandIDs.contains(id) {
Sources/Orgstar/OrgstarApp.swift +24 · view
@@ -77,6 +77,10 @@ final class AppCommands {
77 77
78 /// The editor's selection, for the modeline. 78 /// The editor's selection, for the modeline.
79 var selection = NSRange(location: 0, length: 0) 79 var selection = NSRange(location: 0, length: 0)
80 /// The focused file and caret, advertised for Handoff.
81 @ObservationIgnored let handoff = HandoffAdvertiser()
82 /// Opens a file continued from another device; the main window sets it.
83 @ObservationIgnored var continueHandoff: ((HandoffPlace) -> Void)?
80 var keyHints: [KeyHint] = [] 84 var keyHints: [KeyHint] = []
81 /// A question a command asked, answered in the echo area. 85 /// A question a command asked, answered in the echo area.
82 private(set) var prompt: PromptRequest? 86 private(set) var prompt: PromptRequest?
@@ -270,6 +274,26 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent
270 /// org-protocol and orgstar:// links that arrive before the window is ready. 274 /// org-protocol and orgstar:// links that arrive before the window is ready.
271 static var pendingLinks: [String] = [] 275 static var pendingLinks: [String] = []
272 276
277 /// Files continued from another device before the window is ready.
278 static var pendingHandoffs: [HandoffPlace] = []
279
280 func application(_ application: NSApplication, willContinueUserActivityWithType userActivityType: String) -> Bool {
281 userActivityType == HandoffPlace.activityType
282 }
283
284 /// Handoff from an iPhone, iPad or another Mac.
285 func application(_ application: NSApplication, continue userActivity: NSUserActivity,
286 restorationHandler: @escaping ([any NSUserActivityRestoring]) -> Void) -> Bool {
287 guard userActivity.activityType == HandoffPlace.activityType, let place = HandoffPlace(userInfo: userActivity.userInfo) else { return false }
288 if let handler = commands?.continueHandoff {
289 NSApp.activate()
290 handler(place)
291 } else {
292 Self.pendingHandoffs.append(place)
293 }
294 return true
295 }
296
273 func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { true } 297 func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { true }
274 298
275 func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply { 299 func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
Sources/OrgstarMobile/EditorScreen.swift +4 · view
@@ -316,6 +316,7 @@ struct EditorScreen: View {
316 // A pane command moved focus here. 316 // A pane command moved focus here.
317 .onChange(of: isFocused) { 317 .onChange(of: isFocused) {
318 countVersions() 318 countVersions()
319 if isFocused { model.handoffPath = path }
319 guard isFocused, let textView, !textView.isFirstResponder else { return } 320 guard isFocused, let textView, !textView.isFirstResponder else { return }
320 editor?.focus(textView) 321 editor?.focus(textView)
321 textView.becomeFirstResponder() 322 textView.becomeFirstResponder()
@@ -334,6 +335,7 @@ struct EditorScreen: View {
334 .onDisappear { 335 .onDisappear {
335 // Typing the reader shows next, and a save, don't wait for the autosave delay. 336 // Typing the reader shows next, and a save, don't wait for the autosave delay.
336 if session.dirtyPaths.contains(path) { _ = session.save(path) } 337 if session.dirtyPaths.contains(path) { _ = session.save(path) }
338 if model.handoffPath == path { model.handoffPath = nil }
337 } 339 }
338 } 340 }
339 341
@@ -401,6 +403,7 @@ struct EditorScreen: View {
401 session.focused = pane 403 session.focused = pane
402 bind(editor) 404 bind(editor)
403 editor.focus(view) 405 editor.focus(view)
406 model.handoffPath = path
404 } 407 }
405 // A kept editor missed settings changed while it was off screen. 408 // A kept editor missed settings changed while it was off screen.
406 editor.options = editorOptions 409 editor.options = editorOptions
@@ -442,6 +445,7 @@ struct EditorScreen: View {
442 editor.createID = { [weak session] item in session.flatMap { CompletionSources.createID(item, session: $0) } } 445 editor.createID = { [weak session] item in session.flatMap { CompletionSources.createID(item, session: $0) } }
443 editor.otherBuffers = { [weak session, path] in session.map { CompletionSources.otherBuffers($0, excluding: path) } ?? [] } 446 editor.otherBuffers = { [weak session, path] in session.map { CompletionSources.otherBuffers($0, excluding: path) } ?? [] }
444 editor.onChange = { [weak session] in session?.bufferChanged(path) } 447 editor.onChange = { [weak session] in session?.bufferChanged(path) }
448 editor.onSelect = { [weak model] in model?.handoff.changed() }
445 editor.onMessage = { message = $0 } 449 editor.onMessage = { message = $0 }
446 editor.onPrompt = { prompt, reply in self.prompt = PromptRequest(prompt: prompt, reply: reply) } 450 editor.onPrompt = { prompt, reply in self.prompt = PromptRequest(prompt: prompt, reply: reply) }
447 editor.onLink = { link in follow(link) } 451 editor.onLink = { link in follow(link) }
Sources/OrgstarMobile/MobileEditor.swift +3 · view
@@ -110,6 +110,8 @@ final class MobileEditor: NSObject, DocumentBuffer {
110 var onColumnView: ((ColumnView.View) -> Void)? 110 var onColumnView: ((ColumnView.View) -> Void)?
111 /// Commands the app runs, as `app.clock.in`. 111 /// Commands the app runs, as `app.clock.in`.
112 var onAppCommand: ((String) -> Void)? 112 var onAppCommand: ((String) -> Void)?
113 /// The caret or selection moved.
114 var onSelect: (() -> Void)?
113 /// Where paste looks for an image; scripts checking the app set another. 115 /// Where paste looks for an image; scripts checking the app set another.
114 static var pasteboard = UIPasteboard.general 116 static var pasteboard = UIPasteboard.general
115 /// Files dropped at the caret; nil leaves them to the text view. 117 /// Files dropped at the caret; nil leaves them to the text view.
@@ -734,6 +736,7 @@ extension MobileEditor: UITextViewDelegate {
734 if textView.isFirstResponder { focus(textView) } 736 if textView.isFirstResponder { focus(textView) }
735 guard textView === self.textView else { return } 737 guard textView === self.textView else { return }
736 selectionChanged() 738 selectionChanged()
739 onSelect?()
737 if let open = completionList, textView.selectedRange.location != open.completion.range.upperBound { refreshCompletion() } 740 if let open = completionList, textView.selectedRange.location != open.completion.range.upperBound { refreshCompletion() }
738 } 741 }
739 742
Sources/OrgstarMobile/MobileModel.swift +10 · view
@@ -47,6 +47,12 @@ final class MobileModel {
47 var watchCaptures = 0 47 var watchCaptures = 0
48 /// Reminders for the agenda, with `agenda-reminders`. 48 /// Reminders for the agenda, with `agenda-reminders`.
49 let reminderLists = ReminderLists() 49 let reminderLists = ReminderLists()
50 /// The file and caret of the editor on screen, advertised for Handoff.
51 @ObservationIgnored let handoff = HandoffAdvertiser()
52 /// The file of the editor on screen; nil when none is.
53 @ObservationIgnored var handoffPath: String? {
54 didSet { if handoffPath != oldValue { handoff.changed() } }
55 }
50 56
51 struct AgendaDays: Equatable { 57 struct AgendaDays: Equatable {
52 let start: Int 58 let start: Int
@@ -99,6 +105,10 @@ final class MobileModel {
99 watchConfig() 105 watchConfig()
100 // `org-clock-out-when-done`, and the reminder when the Effort runs out. 106 // `org-clock-out-when-done`, and the reminder when the Effort runs out.
101 clock.notifications = SystemReminderCenter() 107 clock.notifications = SystemReminderCenter()
108 handoff.place = { [weak self] in
109 guard let self, let path = self.handoffPath, let workspace = self.workspace else { return nil }
110 return self.session.handoffPlace(path, roots: workspace.rootPaths)
111 }
102 session.textChanged = { [weak self] path in 112 session.textChanged = { [weak self] path in
103 guard let self else { return } 113 guard let self else { return }
104 _ = self.clock.textChanged(path, self.session) 114 _ = self.clock.textChanged(path, self.session)
Sources/OrgstarMobile/OrgstarMobileApp.swift +13 · view
@@ -409,6 +409,9 @@ struct RootView: View {
409 .onContinueUserActivity(CSSearchableItemActionType) { activity in 409 .onContinueUserActivity(CSSearchableItemActionType) { activity in
410 if let path = activity.userInfo?[CSSearchableItemActivityIdentifier] as? String { model.openRequest = .file(path) } 410 if let path = activity.userInfo?[CSSearchableItemActivityIdentifier] as? String { model.openRequest = .file(path) }
411 } 411 }
412 .onContinueUserActivity(HandoffPlace.activityType) { activity in
413 if let place = HandoffPlace(userInfo: activity.userInfo) { continueHandoff(place) }
414 }
412 .onChange(of: scenePhase) { _, phase in 415 .onChange(of: scenePhase) { _, phase in
413 // Unsaved edits are written before the app may be stopped. 416 // Unsaved edits are written before the app may be stopped.
414 if phase == .background { 417 if phase == .background {
@@ -422,6 +425,7 @@ struct RootView: View {
422 } 425 }
423 takeShared() 426 takeShared()
424 model.reloadConfig() 427 model.reloadConfig()
428 model.handoff.update()
425 Task { await workspace.refresh() } 429 Task { await workspace.refresh() }
426 } 430 }
427 .onOpenURL(perform: handle) 431 .onOpenURL(perform: handle)
@@ -480,6 +484,15 @@ struct RootView: View {
480 } 484 }
481 } 485 }
482 486
487 /// A file continued from another device, in the editor at the caret's heading or line there.
488 private func continueHandoff(_ place: HandoffPlace) {
489 let match = place.resolve(roots: workspace.rootPaths)
490 guard case .file(let path) = match else { return message = place.problem(match) }
491 let offset = session.text(of: path).map { place.offset(in: $0, settings: session.defaults) } ?? 0
492 tab = .agenda
493 agendaPath.append(EditorRoute(path: path, offset: offset))
494 }
495
483 /// A tab or sidebar row; on iPhone, search is pushed on the agenda. 496 /// A tab or sidebar row; on iPhone, search is pushed on the agenda.
484 private func show(_ destination: AppTab) { 497 private func show(_ destination: AppTab) {
485 if destination == .search, sizeClass != .regular { 498 if destination == .search, sizeClass != .regular {
Tests/OrgAppTests/HandoffTests.swift added +99 · view
@@ -0,0 +1,99 @@
1import Foundation
2import Testing
3@testable import OrgApp
4
5struct HandoffTests {
6 static let text = """
7 #+TITLE: Notes
8 * Work
9 ** Project
10 :PROPERTIES:
11 :ID: project-1
12 :END:
13 first line
14 second line
15 ** Other
16 * Home
17
18 """
19
20 @Test func placeRoundTripsThroughUserInfo() throws {
21 let path = "/Users/a/Library/Mobile Documents/com~apple~CloudDocs/org/notes/todo.org"
22 let caret = (Self.text as NSString).range(of: "second").location + 3
23 let place = try #require(HandoffPlace.make(path: path, text: Self.text, caret: caret, roots: ["/Users/a/Library/Mobile Documents/com~apple~CloudDocs/org"]))
24 #expect(place.folder == "org")
25 #expect(place.file == "notes/todo.org")
26 #expect(place.cloudPath == "com~apple~CloudDocs/org/notes/todo.org")
27 #expect(place.outline == ["Work", "Project"])
28 #expect(place.id == "project-1")
29 #expect(place.line == 8)
30 #expect(place.headingLine == 3)
31 // Through a property list, as Handoff sends it.
32 let data = try PropertyListSerialization.data(fromPropertyList: place.userInfo, format: .binary, options: 0)
33 let info = try #require(try PropertyListSerialization.propertyList(from: data, format: nil) as? [AnyHashable: Any])
34 #expect(HandoffPlace(userInfo: info) == place)
35 #expect(!place.userInfo.values.contains { ($0 as? String)?.contains("second line") == true })
36 }
37
38 @Test func nothingIsAdvertisedOutsideTheFoldersOrForEncryptedFiles() {
39 #expect(HandoffPlace.make(path: "/elsewhere/a.org", text: "", caret: 0, roots: ["/org"]) == nil)
40 #expect(HandoffPlace.make(path: "/org/secret.org.gpg", text: "", caret: 0, roots: ["/org"]) == nil)
41 #expect(HandoffPlace.make(path: "/org/a.org", text: "", caret: 0, roots: ["/org"])?.file == "a.org")
42 // The innermost of nested roots.
43 #expect(HandoffPlace.make(path: "/org/work/a.org", text: "", caret: 0, roots: ["/org", "/org/work"])?.folder == "work")
44 }
45
46 @Test func userInfoMustNameAFileInsideTheFolder() {
47 #expect(HandoffPlace(userInfo: ["folder": "org", "file": "../etc/passwd"]) == nil)
48 #expect(HandoffPlace(userInfo: ["folder": "org", "file": "/etc/passwd"]) == nil)
49 #expect(HandoffPlace(userInfo: ["folder": "org"]) == nil)
50 #expect(HandoffPlace(userInfo: nil) == nil)
51 #expect(HandoffPlace(userInfo: ["folder": "org", "file": "a.org"])?.line == 1)
52 }
53
54 @Test func iCloudFoldersMatchByTheirPathInICloud() {
55 let place = HandoffPlace(folder: "org", cloudPath: "com~apple~CloudDocs/org/notes/todo.org", file: "notes/todo.org",
56 outline: [], id: nil, line: 1, headingLine: 0)
57 let phone = "/private/var/mobile/Library/Mobile Documents/com~apple~CloudDocs/org"
58 #expect(place.resolve(roots: [phone], exists: { _ in true }) == .file(phone + "/notes/todo.org"))
59 // A root higher up in iCloud Drive holds the file too.
60 let drive = "/private/var/mobile/Library/Mobile Documents/com~apple~CloudDocs"
61 #expect(place.resolve(roots: [drive], exists: { _ in true }) == .file(drive + "/org/notes/todo.org"))
62 // Another iCloud folder named org is not this one, so the name decides only without a match.
63 let other = "/private/var/mobile/Library/Mobile Documents/com~apple~CloudDocs/archive/org"
64 #expect(place.resolve(roots: [other, phone], exists: { _ in true }) == .file(phone + "/notes/todo.org"))
65 }
66
67 @Test func otherFoldersMatchByName() {
68 let place = HandoffPlace(folder: "notes", cloudPath: nil, file: "a/b.org", outline: [], id: nil, line: 1, headingLine: 0)
69 let root = "/private/var/mobile/Containers/Shared/AppGroup/1234/File Provider Storage/notes"
70 #expect(place.resolve(roots: ["/x/org", root], exists: { _ in true }) == .file(root + "/a/b.org"))
71 #expect(place.resolve(roots: ["/x/org"], exists: { _ in true }) == .noFolder)
72 #expect(place.resolve(roots: [root], exists: { _ in false }) == .noFile)
73 // Two folders of that name: the one with the file.
74 #expect(place.resolve(roots: ["/y/notes", root], exists: { $0.hasPrefix(root) }) == .file(root + "/a/b.org"))
75 // An iCloud file on a device without that iCloud folder still matches by name.
76 let cloud = HandoffPlace(folder: "notes", cloudPath: "com~apple~CloudDocs/notes/a/b.org", file: "a/b.org", outline: [], id: nil, line: 1, headingLine: 0)
77 #expect(cloud.resolve(roots: [root], exists: { _ in true }) == .file(root + "/a/b.org"))
78 }
79
80 @Test func caretGoesToTheHeadingByIDThenOutlineThenLine() {
81 let place = HandoffPlace(folder: "org", cloudPath: nil, file: "a.org", outline: ["Work", "Project"], id: "project-1", line: 8, headingLine: 3)
82 let ns = Self.text as NSString
83 let second = ns.range(of: "second line").location
84 #expect(place.offset(in: Self.text) == second)
85 // Lines added above the heading on this device: the heading is found by ID.
86 let moved = "* New\nnew text\n" + Self.text
87 #expect(place.offset(in: moved) == (moved as NSString).range(of: "second line").location)
88 // Without the ID, by the outline path.
89 var byOutline = place
90 byOutline.id = "gone"
91 #expect(byOutline.offset(in: moved) == (moved as NSString).range(of: "second line").location)
92 // Neither: the same line.
93 let unrelated = HandoffPlace(folder: "org", cloudPath: nil, file: "a.org", outline: ["Nope"], id: nil, line: 3, headingLine: 2)
94 #expect(unrelated.offset(in: Self.text) == ns.range(of: "** Project").location)
95 // A line past the heading's text stays in it.
96 let long = HandoffPlace(folder: "org", cloudPath: nil, file: "a.org", outline: ["Work", "Project"], id: nil, line: 40, headingLine: 3)
97 #expect(long.offset(in: Self.text) == ns.range(of: "** Other").location - 1)
98 }
99}
docs/manual/guide/01-files-and-folders.org +13 · view
@@ -332,6 +332,19 @@ The Mac App Store version can't run git and has no Git pane.
332 332
333Files in iCloud Drive that aren't downloaded to the Mac show in the sidebar with a cloud icon and grey text, with the tooltip "Downloading from iCloud". orgstar asks iCloud to download them, and indexes them and lets you open them when they arrive. Files iCloud removes from the Mac to save space keep their index entries until they are back, so search and the agenda still find them. 333Files in iCloud Drive that aren't downloaded to the Mac show in the sidebar with a cloud icon and grey text, with the tooltip "Downloading from iCloud". orgstar asks iCloud to download them, and indexes them and lets you open them when they arrive. Files iCloud removes from the Mac to save space keep their index entries until they are back, so search and the agenda still find them.
334 334
335* Handoff
336
337A file open in the editor can be continued on another Mac, iPhone or iPad signed in to the same Apple Account, with Handoff turned on in each device's settings. The other device shows orgstar's icon in the Dock or the app switcher; choosing it opens the same file in its editor, at the same place.
338
339What is passed is where the file is and where the caret is, never the file's text:
340
341- the name of the added folder the file is in, the file's path inside iCloud when it is in iCloud Drive, and its path inside the folder;
342- the caret's heading (its =ID= when it has one, and the titles of it and the headings above it) and line.
343
344The other device looks for the file in its own added folders. A folder in iCloud Drive is matched by its path in iCloud Drive, which is the same on every device, so it is found even when another folder has the same name; an added folder higher up in iCloud Drive holds the file too. Any other folder, such as one kept by Dropbox, Syncthing or Working Copy, is at a different path on each device and is matched by its name: add it with the same name on both. The caret goes to the heading with that =ID=, or else the heading at that outline path, on the same line within it as on the other device; when neither is found, to the same line of the file. When the device has no folder of that name, or the folder doesn't have the file yet, orgstar says so and opens nothing.
345
346Only files in an added folder are offered, and never an encrypted =.org.gpg= file. On iPhone and iPad, the editor offers its file; the reader and the agenda don't.
347
335* Encodings and line endings 348* Encodings and line endings
336 349
337orgstar edits UTF-8 files, with or without a byte order mark. 350orgstar edits UTF-8 files, with or without a byte order mark.
docs/manual/guide/14-ios.org +4 · view
@@ -512,6 +512,10 @@ These settings from =config.toml= apply on iOS:
512 512
513=capture.toml= and =views.toml= in the folder apply too. =keymap= and =keymap.toml= apply with a hardware keyboard. Other settings, including =save=, don't apply on iOS. See [[file:13-configuration.org][Configuration]]. 513=capture.toml= and =views.toml= in the folder apply too. =keymap= and =keymap.toml= apply with a hardware keyboard. Other settings, including =save=, don't apply on iOS. See [[file:13-configuration.org][Configuration]].
514 514
515* Handoff
516
517The file open in the editor is offered to your other devices through Handoff, and a file offered by a Mac, iPhone or iPad opens here in the editor at the same heading or line, when an added folder holds it. See [[file:01-files-and-folders.org][Files and folders]], Handoff, for how folders are matched.
518
515* Spotlight and Quick Look 519* Spotlight and Quick Look
516 520
517orgstar adds the org files in your folders to Spotlight with their title (=#+TITLE=, else the file name), author, description, tags, headings and text. A file is indexed again when it changes. Tap a Spotlight result to open the file in orgstar's reader. 521orgstar adds the org files in your folders to Spotlight with their title (=#+TITLE=, else the file name), author, description, tags, headings and text. A file is indexed again when it changes. Tap a Spotlight result to open the file in orgstar's reader.
ios/Orgstar/Info.plist +4 · view
@@ -60,6 +60,10 @@
60 <string>The agenda shows your reminders alongside your Org entries. orgstar only reads them.</string> 60 <string>The agenda shows your reminders alongside your Org entries. orgstar only reads them.</string>
61 <key>NSSupportsLiveActivities</key> 61 <key>NSSupportsLiveActivities</key>
62 <true/> 62 <true/>
63 <key>NSUserActivityTypes</key>
64 <array>
65 <string>sh.krz.orgstar.editing</string>
66 </array>
63 <key>UIApplicationSceneManifest</key> 67 <key>UIApplicationSceneManifest</key>
64 <dict> 68 <dict>
65 <key>UIApplicationSupportsMultipleScenes</key> 69 <key>UIApplicationSupportsMultipleScenes</key>
ios/OrgstarMac/Info.plist +4 · view
@@ -82,6 +82,10 @@
82 <string>NSApplication</string> 82 <string>NSApplication</string>
83 <key>NSRemindersFullAccessUsageDescription</key> 83 <key>NSRemindersFullAccessUsageDescription</key>
84 <string>The agenda shows your reminders alongside your Org entries. orgstar only reads them.</string> 84 <string>The agenda shows your reminders alongside your Org entries. orgstar only reads them.</string>
85 <key>NSUserActivityTypes</key>
86 <array>
87 <string>sh.krz.orgstar.editing</string>
88 </array>
85 <key>UTImportedTypeDeclarations</key> 89 <key>UTImportedTypeDeclarations</key>
86 <array> 90 <array>
87 <dict> 91 <dict>
l10n/Localizable.xcstrings +70 · view
@@ -7390,6 +7390,76 @@
7390 } 7390 }
7391 } 7391 }
7392 }, 7392 },
7393 "Can't continue %@: it isn't in “%@” on this device yet.": {
7394 "comment": "Handoff from another device",
7395 "localizations": {
7396 "de": {
7397 "stringUnit": {
7398 "state": "translated",
7399 "value": "%1$@ kann nicht fortgesetzt werden: Die Datei ist auf diesem Gerät noch nicht in „%2$@“."
7400 }
7401 },
7402 "es": {
7403 "stringUnit": {
7404 "state": "translated",
7405 "value": "No se puede continuar %1$@: todavía no está en «%2$@» en este dispositivo."
7406 }
7407 },
7408 "fr": {
7409 "stringUnit": {
7410 "state": "translated",
7411 "value": "Impossible de continuer %1$@ : le fichier n’est pas encore dans « %2$@ » sur cet appareil."
7412 }
7413 },
7414 "ja": {
7415 "stringUnit": {
7416 "state": "translated",
7417 "value": "%1$@を続けられません:このデバイスの「%2$@」にはまだありません。"
7418 }
7419 },
7420 "pt-BR": {
7421 "stringUnit": {
7422 "state": "translated",
7423 "value": "Não é possível continuar %1$@: ele ainda não está em “%2$@” neste dispositivo."
7424 }
7425 }
7426 }
7427 },
7428 "Can't continue %@: no folder named “%@” is added on this device.": {
7429 "comment": "Handoff from another device",
7430 "localizations": {
7431 "de": {
7432 "stringUnit": {
7433 "state": "translated",
7434 "value": "%1$@ kann nicht fortgesetzt werden: Auf diesem Gerät ist kein Ordner namens „%2$@“ hinzugefügt."
7435 }
7436 },
7437 "es": {
7438 "stringUnit": {
7439 "state": "translated",
7440 "value": "No se puede continuar %1$@: no hay ninguna carpeta llamada «%2$@» añadida en este dispositivo."
7441 }
7442 },
7443 "fr": {
7444 "stringUnit": {
7445 "state": "translated",
7446 "value": "Impossible de continuer %1$@ : aucun dossier nommé « %2$@ » n’est ajouté sur cet appareil."
7447 }
7448 },
7449 "ja": {
7450 "stringUnit": {
7451 "state": "translated",
7452 "value": "%1$@を続けられません:このデバイスには「%2$@」という名前のフォルダが追加されていません。"
7453 }
7454 },
7455 "pt-BR": {
7456 "stringUnit": {
7457 "state": "translated",
7458 "value": "Não é possível continuar %1$@: nenhuma pasta chamada “%2$@” foi adicionada neste dispositivo."
7459 }
7460 }
7461 }
7462 },
7393 "Can't export %@: %@": { 7463 "Can't export %@: %@": {
7394 "comment": "Echo area: file name, then the reason", 7464 "comment": "Echo area: file name, then the reason",
7395 "localizations": { 7465 "localizations": {
scripts/build-app.sh +2 · view
@@ -159,6 +159,8 @@ ${feed_keys}
159 <true/> 159 <true/>
160 <key>NSPrincipalClass</key> 160 <key>NSPrincipalClass</key>
161 <string>NSApplication</string> 161 <string>NSApplication</string>
162 <key>NSUserActivityTypes</key>
163 <array><string>sh.krz.orgstar.editing</string></array>
162</dict> 164</dict>
163</plist> 165</plist>
164EOF 166EOF
scripts/build-ios-app.sh +2 · view
@@ -110,6 +110,8 @@ cat > "$app/Info.plist" <<PLIST
110 <array><string>org-protocol</string></array> 110 <array><string>org-protocol</string></array>
111 </dict> 111 </dict>
112 </array> 112 </array>
113 <key>NSUserActivityTypes</key>
114 <array><string>sh.krz.orgstar.editing</string></array>
113</dict> 115</dict>
114</plist> 116</plist>
115PLIST 117PLIST
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