iPad multi-window !296

merged merged by cmc on 2026-10-11 17:07 UTC · krz/orgstar:issue-64 into main

12 files changed, +560 −144

Layout: unified · split

Sources/OrgApp/DocumentSession.swift +6
@@ -213,6 +213,12 @@ public final class DocumentSession {
213 213
214 public func isOpen(_ path: String) -> Bool { entry(path) != nil } 214 public func isOpen(_ path: String) -> Bool { entry(path) != nil }
215 215
216 /// The document of an open file, whichever pane shows it.
217 public func document(of path: String) -> DocumentState? { entry(path)?.buffer.document }
218
219 /// Whether `buffer` is the live state of `path`, as `attach` made it.
220 public func isAttached(_ buffer: DocumentBuffer, for path: String) -> Bool { entry(path)?.buffer === buffer }
221
216 /// The caret of an open file. 222 /// The caret of an open file.
217 public func caret(of path: String) -> Int? { entry(path)?.buffer.selection.first?.lowerBound } 223 public func caret(of path: String) -> Int? { entry(path)?.buffer.selection.first?.lowerBound }
218 224
Sources/OrgstarMobile/EditorScreen.swift +171 −64
@@ -16,7 +16,20 @@ struct EditorScreen: View {
16 let offset: Int? 16 let offset: Int?
17 let workspace: WorkspaceModel 17 let workspace: WorkspaceModel
18 let session: DocumentSession 18 let session: DocumentSession
19 /// The pane this screen shows its file in, from a split; nil makes one for the screen.
20 var givenPane: EditorPane? = nil
21 /// In a split, the focused pane shows the toolbar and the split the title.
22 var inSplit = false
23 var isFocused = true
24 /// Focus came to this screen's pane.
25 var onFocus: () -> Void = {}
26 /// The pane commands (`app.split-right` …), which the split runs.
27 var onPaneCommand: ((String) -> Void)? = nil
19 @State private var editor: MobileEditor? 28 @State private var editor: MobileEditor?
29 /// This screen's view of the editor.
30 @State private var textView: UITextView?
31 @State private var holder = PaneHolder()
32 @Environment(\.horizontalSizeClass) private var sizeClass
20 @State private var prompt: PromptRequest? 33 @State private var prompt: PromptRequest?
21 @State private var message: String? 34 @State private var message: String?
22 @State private var sheet: Sheet? 35 @State private var sheet: Sheet?
@@ -80,21 +93,26 @@ struct EditorScreen: View {
80 } 93 }
81 } 94 }
82 95
96 private var pane: EditorPane? { givenPane ?? holder.pane }
97
98 /// The pane commands, as the Mac's View menu has them.
99 static let paneCommands = ["app.split-right", "app.split-below", "app.pane-next", "app.pane-close", "app.pane-only"]
100
83 var body: some View { 101 var body: some View {
84 Group { 102 Group {
85 if let editor { 103 if let editor, let textView {
86 EditorTextView(editor: editor, palette: { sheet = .palette }) 104 EditorTextView(editor: editor, view: textView, palette: { sheet = .palette })
87 .ignoresSafeArea(.container, edges: .bottom) 105 .ignoresSafeArea(.container, edges: .bottom)
88 } else { 106 } else {
89 ProgressView() 107 ProgressView()
90 } 108 }
91 } 109 }
92 .navigationTitle(session.bufferName(path) + (session.dirtyPaths.contains(path) ? " •" : "")) 110 .modifier(EditorTitle(title: session.bufferName(path) + (session.dirtyPaths.contains(path) ? " •" : ""), shown: !inSplit))
93 .navigationBarTitleDisplayMode(.inline)
94 .toolbar(.hidden, for: .tabBar) 111 .toolbar(.hidden, for: .tabBar)
95 .toolbar { 112 .toolbar {
113 if !inSplit || isFocused {
96 ToolbarItemGroup(placement: .primaryAction) { 114 ToolbarItemGroup(placement: .primaryAction) {
97 if session.conflict != nil { 115 if pane?.conflict != nil {
98 Button("Conflict", systemImage: "exclamationmark.triangle") { sheet = .conflict } 116 Button("Conflict", systemImage: "exclamationmark.triangle") { sheet = .conflict }
99 } 117 }
100 Button("Undo", systemImage: "arrow.uturn.backward") { editor?.run("edit.undo") } 118 Button("Undo", systemImage: "arrow.uturn.backward") { editor?.run("edit.undo") }
@@ -145,11 +163,23 @@ struct EditorScreen: View {
145 Button("Encrypt Tagged Entries…", systemImage: "lock.rectangle.stack") { crypt("app.crypt.encrypt-entries") } 163 Button("Encrypt Tagged Entries…", systemImage: "lock.rectangle.stack") { crypt("app.crypt.encrypt-entries") }
146 Button("Forget Encryption Passphrase", systemImage: "key.slash") { crypt("app.crypt.forget-passphrase") } 164 Button("Forget Encryption Passphrase", systemImage: "key.slash") { crypt("app.crypt.forget-passphrase") }
147 } 165 }
148 if let text = session.document?.text, session.path == path { ExportMenu(path: path, text: text) { message = $0 } } 166 if let text = session.document(of: path)?.text { ExportMenu(path: path, text: text) { message = $0 } }
149 Button("Sync Conflict Copies", systemImage: "doc.on.doc") { sheet = .syncCopies } 167 Button("Sync Conflict Copies", systemImage: "doc.on.doc") { sheet = .syncCopies }
150 Button("Recovered Versions", systemImage: "clock.arrow.circlepath") { sheet = .recovery } 168 Button("Recovered Versions", systemImage: "clock.arrow.circlepath") { sheet = .recovery }
169 if onPaneCommand != nil, sizeClass == .regular {
170 Menu("Panes", systemImage: "rectangle.split.2x1") {
171 Button("Split Pane Right", systemImage: "rectangle.split.2x1") { onPaneCommand?("app.split-right") }
172 Button("Split Pane Below", systemImage: "rectangle.split.1x2") { onPaneCommand?("app.split-below") }
173 if inSplit {
174 Button("Next Pane", systemImage: "arrow.right.square") { onPaneCommand?("app.pane-next") }
175 Button("Close Pane", systemImage: "xmark.square") { onPaneCommand?("app.pane-close") }
176 Button("Close Other Panes", systemImage: "square") { onPaneCommand?("app.pane-only") }
177 }
178 }
179 }
151 } 180 }
152 } 181 }
182 }
153 } 183 }
154 .safeAreaInset(edge: .top) { 184 .safeAreaInset(edge: .top) {
155 VStack(spacing: 0) { 185 VStack(spacing: 0) {
@@ -183,7 +213,7 @@ struct EditorScreen: View {
183 } 213 }
184 }) { sheet in 214 }) { sheet in
185 switch sheet { 215 switch sheet {
186 case .palette: if let editor { CommandPalette(editor: editor) { chosen = $0 } } 216 case .palette: if let editor { CommandPalette(editor: editor, panes: onPaneCommand != nil && sizeClass == .regular, split: inSplit) { chosen = $0 } }
187 case .conflict: ConflictSheet(session: session) 217 case .conflict: ConflictSheet(session: session)
188 case .syncCopies: SyncConflictSheet(session: session) { message = $0 } 218 case .syncCopies: SyncConflictSheet(session: session) { message = $0 }
189 case .recovery: RecoverySheet(session: session) { message = $0 } 219 case .recovery: RecoverySheet(session: session) { message = $0 }
@@ -249,15 +279,21 @@ struct EditorScreen: View {
249 defaultFilename: exportedTable?.type == .tabSeparatedText ? "table.tsv" : "table.csv") { result in 279 defaultFilename: exportedTable?.type == .tabSeparatedText ? "table.tsv" : "table.csv") { result in
250 if case .failure(let error) = result { message = error.localizedDescription } else { message = "Export done." } 280 if case .failure(let error) = result { message = error.localizedDescription } else { message = "Export done." }
251 } 281 }
252 .onChange(of: session.conflict) { _, conflict in 282 .onChange(of: pane?.conflict) { _, conflict in
253 if conflict != nil, session.path == path { sheet = .conflict } 283 if conflict != nil, isFocused { sheet = .conflict }
254 } 284 }
255 .onChange(of: session.lastError) { _, error in 285 .onChange(of: session.lastError) { _, error in
256 if let error { message = error; session.lastError = nil } 286 if let error { message = error; session.lastError = nil }
257 } 287 }
258 .onAppear(perform: start) 288 .onAppear(perform: start)
259 .onChange(of: session.revealRequest?.id) { 289 // A pane command moved focus here.
260 if let offset = session.revealRequest?.offset, session.path == path { editor?.reveal(offset) } 290 .onChange(of: isFocused) {
291 guard isFocused, let textView, !textView.isFirstResponder else { return }
292 editor?.focus(textView)
293 textView.becomeFirstResponder()
294 }
295 .onChange(of: pane?.revealRequest?.id) {
296 if let offset = pane?.revealRequest?.offset, pane?.path == path { editor?.reveal(offset) }
261 } 297 }
262 .onChange(of: model.settingsVersion) { 298 .onChange(of: model.settingsVersion) {
263 editor?.options = editorOptions 299 editor?.options = editorOptions
@@ -309,69 +345,108 @@ struct EditorScreen: View {
309 } 345 }
310 346
311 private func start() { 347 private func start() {
312 if session.path != path { session.open(path) } 348 let pane: EditorPane
313 if editor == nil, let document = session.document { 349 if let existing = self.pane {
314 let editor = MobileEditor( 350 pane = existing
315 document: document, editable: document.isEditable, options: editorOptions, theme: model.theme, 351 } else {
316 showMarkup: model.showMarkup, baseDirectory: URL(fileURLWithPath: path).deletingLastPathComponent() 352 pane = session.makePane()
317 ) 353 holder.pane = pane
318 editor.knownTags = { [index = workspace.index] in (try? index.tags()) ?? [] } 354 let store = model.editors, path = path
319 editor.onChange = { [weak session] in session?.bufferChanged(path) } 355 holder.release = { [weak session] in
320 editor.onMessage = { message = $0 } 356 store.release(pane.id, path: path)
321 editor.onPrompt = { prompt, reply in self.prompt = PromptRequest(prompt: prompt, reply: reply) } 357 session?.closePane(pane)
322 editor.onLink = { link in follow(link) }
323 editor.onEditBlock = { edit in sheet = .block(edit) }
324 editor.onColumnView = { view in sheet = .columns(view) }
325 editor.onTangle = { scope in message = session.tangle(scope) }
326 editor.onBabel = { job in run(job) }
327 editor.onRefreshSetup = { session.refreshSetup() }
328 editor.onAgenda = { start, count in model.agendaRequest = .init(start: start, count: count) }
329 editor.keymap = model.keymap
330 editor.modal = model.modalKeys
331 editor.onAppCommand = { id in
332 if id == "app.save" {
333 _ = session.save(path)
334 } else if ["app.refile", "app.refile.copy", "app.refile.goto"].contains(id) {
335 sheet = .refile(id)
336 } else if id == "app.table-import" {
337 importingTable = true
338 } else if id == "app.table-export" {
339 exportTable(csv: true)
340 } else if id == "app.plot" {
341 plotTable()
342 } else if id.hasPrefix("app.crypt.") {
343 crypt(id)
344 } else if id.hasPrefix("app.attach.") {
345 attachActions.run(id)
346 } else if id.hasPrefix("app.dailies.") || id.hasPrefix("app.node.") {
347 roamActions.run(id)
348 } else if id == "app.backlinks" {
349 sheet = .backlinks
350 } else if id == "app.toggle-markup" {
351 model.showMarkup.toggle()
352 } else if MobileEditor.linkCommands.contains(id) {
353 link(id)
354 } else if !MobileClock.run(id, model: model, workspace: workspace, show: { message = $0 }) {
355 message = "Not available on iOS yet"
356 }
357 } 358 }
358 self.editor = editor
359 } 359 }
360 if let editor { session.attach(editor) } 360 if pane.path != path { session.open(path, in: pane) }
361 if let offset { editor?.reveal(offset) } 361 model.editors.prune(session)
362 if session.conflict != nil { 362 guard let editor = model.editors.editor(for: path, session: session, make: makeEditor) else { return }
363 let view = model.editors.view(for: pane.id, of: editor)
364 editor.onFocus[ObjectIdentifier(view)] = { [weak session] in
365 session?.focused = pane
366 bind(editor)
367 onFocus()
368 }
369 // A pane a split adds leaves focus where it was, as `split-window` does.
370 if isFocused {
371 session.focused = pane
372 bind(editor)
373 editor.focus(view)
374 }
375 self.editor = editor
376 textView = view
377 if let offset { editor.reveal(offset) }
378 if pane.conflict != nil {
363 sheet = .conflict 379 sheet = .conflict
364 } else if case let copies = session.syncConflictCopies().count, copies > 0 { 380 } else if case let copies = session.syncConflictCopies().count, copies > 0 {
365 message = "\(copies) sync conflict \(copies == 1 ? "copy" : "copies") of this file; More › Sync Conflict Copies compares them." 381 message = "\(copies) sync conflict \(copies == 1 ? "copy" : "copies") of this file; More › Sync Conflict Copies compares them."
366 } 382 }
367 } 383 }
384
385 private func makeEditor() -> MobileEditor? {
386 guard let document = session.document(of: path) else { return nil }
387 return MobileEditor(
388 document: document, editable: document.isEditable, options: editorOptions, theme: model.theme,
389 showMarkup: model.showMarkup, baseDirectory: URL(fileURLWithPath: path).deletingLastPathComponent()
390 )
391 }
392
393 /// The editor's callbacks go to this screen: it's shown here, or its view here took focus.
394 private func bind(_ editor: MobileEditor) {
395 editor.knownTags = { [index = workspace.index] in (try? index.tags()) ?? [] }
396 editor.onChange = { [weak session] in session?.bufferChanged(path) }
397 editor.onMessage = { message = $0 }
398 editor.onPrompt = { prompt, reply in self.prompt = PromptRequest(prompt: prompt, reply: reply) }
399 editor.onLink = { link in follow(link) }
400 editor.onEditBlock = { edit in sheet = .block(edit) }
401 editor.onColumnView = { view in sheet = .columns(view) }
402 editor.onTangle = { scope in message = session.tangle(scope) }
403 editor.onBabel = { job in run(job) }
404 editor.onRefreshSetup = { session.refreshSetup() }
405 editor.onAgenda = { start, count in model.agendaRequest = .init(start: start, count: count) }
406 editor.keymap = model.keymap
407 editor.modal = model.modalKeys
408 editor.onAppCommand = { id in
409 if Self.paneCommands.contains(id) {
410 if let onPaneCommand { onPaneCommand(id) } else { message = "Not available here" }
411 } else if id == "app.save" {
412 _ = session.save(path)
413 } else if ["app.refile", "app.refile.copy", "app.refile.goto"].contains(id) {
414 sheet = .refile(id)
415 } else if id == "app.table-import" {
416 importingTable = true
417 } else if id == "app.table-export" {
418 exportTable(csv: true)
419 } else if id == "app.plot" {
420 plotTable()
421 } else if id.hasPrefix("app.crypt.") {
422 crypt(id)
423 } else if id.hasPrefix("app.attach.") {
424 attachActions.run(id)
425 } else if id.hasPrefix("app.dailies.") || id.hasPrefix("app.node.") {
426 roamActions.run(id)
427 } else if id == "app.backlinks" {
428 sheet = .backlinks
429 } else if id == "app.toggle-markup" {
430 model.showMarkup.toggle()
431 } else if MobileEditor.linkCommands.contains(id) {
432 link(id)
433 } else if !MobileClock.run(id, model: model, workspace: workspace, show: { message = $0 }) {
434 message = "Not available on iOS yet"
435 }
436 }
437 }
368} 438}
369 439
370extension EditorScreen { 440extension EditorScreen {
371 /// Follows a link; files the editor doesn't open show in Quick Look. 441 /// Follows a link; files the editor doesn't open show in Quick Look.
372 private func follow(_ link: OrgLink) { 442 private func follow(_ link: OrgLink) {
373 switch session.follow(link, workspace: workspace, isText: { _ in false }) { 443 switch session.follow(link, workspace: workspace, isText: { _ in false }) {
374 case .shown: message = session.path == path ? nil : "Opened \((session.path.map { ($0 as NSString).lastPathComponent }) ?? "")" 444 case .shown:
445 // A link to another file shows it on its own screen; this pane keeps its file.
446 guard let pane, let target = pane.path, target != path else { message = nil; return }
447 let caret = session.caret(of: target) ?? 0
448 session.open(path, in: pane)
449 model.openRequest = .offset(target, caret)
375 case .openExternally(let url): if url.isFileURL { previewed = url } else { openURL(url) } 450 case .openExternally(let url): if url.isFileURL { previewed = url } else { openURL(url) }
376 case .message(let text): message = text 451 case .message(let text): message = text
377 } 452 }
@@ -511,6 +586,8 @@ extension EditorScreen {
511/// The editor's text view, with the Org key bar over the keyboard. 586/// The editor's text view, with the Org key bar over the keyboard.
512struct EditorTextView: UIViewRepresentable { 587struct EditorTextView: UIViewRepresentable {
513 let editor: MobileEditor 588 let editor: MobileEditor
589 /// This pane's view of the editor.
590 let view: UITextView
514 let palette: () -> Void 591 let palette: () -> Void
515 592
516 func makeUIView(context: Context) -> UITextView { 593 func makeUIView(context: Context) -> UITextView {
@@ -518,9 +595,9 @@ struct EditorTextView: UIViewRepresentable {
518 bar.view.frame = CGRect(x: 0, y: 0, width: 400, height: 48) 595 bar.view.frame = CGRect(x: 0, y: 0, width: 400, height: 48)
519 bar.view.backgroundColor = .clear 596 bar.view.backgroundColor = .clear
520 bar.sizingOptions = [] 597 bar.sizingOptions = []
521 editor.textView.inputAccessoryView = bar.view 598 view.inputAccessoryView = bar.view
522 context.coordinator.bar = bar 599 context.coordinator.bar = bar
523 return editor.textView 600 return view
524 } 601 }
525 602
526 func updateUIView(_ view: UITextView, context: Context) {} 603 func updateUIView(_ view: UITextView, context: Context) {}
@@ -770,6 +847,9 @@ struct CodeTextView: UIViewRepresentable {
770/// Every command that applies at the caret, by name. 847/// Every command that applies at the caret, by name.
771struct CommandPalette: View { 848struct CommandPalette: View {
772 let editor: MobileEditor 849 let editor: MobileEditor
850 /// The pane commands are offered (on iPad), and those for more than one pane.
851 var panes = false
852 var split = false
773 /// Called with the chosen command before the palette closes. 853 /// Called with the chosen command before the palette closes.
774 let choose: (String) -> Void 854 let choose: (String) -> Void
775 @State private var query = "" 855 @State private var query = ""
@@ -832,7 +912,9 @@ struct CommandPalette: View {
832 .onAppear { 912 .onAppear {
833 guard applicable == nil else { return } 913 guard applicable == nil else { return }
834 let context = editor.editContext() 914 let context = editor.editContext()
835 applicable = (Self.viewCommands + Commands.everything.map { ($0.id, $0.title) }) 915 let paneCommands: [(id: String, title: String)] = !panes ? [] : [("app.split-right", "Split Pane Right"), ("app.split-below", "Split Pane Below")]
916 + (split ? [("app.pane-next", "Next Pane"), ("app.pane-close", "Close Pane"), ("app.pane-only", "Close Other Panes")] : [])
917 applicable = paneCommands.map { ($0.id, $0.title, editor.keymap.keyLabels(for: $0.id).first) } + (Self.viewCommands + Commands.everything.map { ($0.id, $0.title) })
836 .filter { editor.applies($0.id, in: context) } 918 .filter { editor.applies($0.id, in: context) }
837 .map { ($0.id, $0.title, editor.keymap.keyLabels(for: $0.id).first) } 919 .map { ($0.id, $0.title, editor.keymap.keyLabels(for: $0.id).first) }
838 } 920 }
@@ -912,4 +994,29 @@ struct CryptScreen: View {
912 _ = editor.perform(PrecomputedEdit(EditResult(baseRevision: context.revision, edits: TextEdit.between(context.text, new), selection: [caret..<caret]))) 994 _ = editor.perform(PrecomputedEdit(EditResult(baseRevision: context.revision, edits: TextEdit.between(context.text, new), selection: [caret..<caret])))
913 } 995 }
914} 996}
997/// The pane an editor screen made for itself, closed with the screen.
998@MainActor
999final class PaneHolder {
1000 var pane: EditorPane?
1001 nonisolated(unsafe) var release: (() -> Void)?
1002
1003 deinit {
1004 guard let release else { return }
1005 Task { @MainActor in release() }
1006 }
1007}
1008
1009/// The screen's title, unless a split shows the focused pane's.
1010private struct EditorTitle: ViewModifier {
1011 let title: String
1012 let shown: Bool
1013
1014 func body(content: Content) -> some View {
1015 if shown {
1016 content.navigationTitle(title).navigationBarTitleDisplayMode(.inline)
1017 } else {
1018 content
1019 }
1020 }
1021}
915#endif 1022#endif
Sources/OrgstarMobile/EditorSplitScreen.swift added +131
@@ -0,0 +1,131 @@
1#if os(iOS)
2import OrgApp
3import SwiftUI
4import UIKit
5
6/// An editor's panes in a scene, as a Mac window has them: one to start, split right or below
7/// (`app.split-right`, `app.split-below`), each showing a buffer in its own view, with its own
8/// caret and scroll, over the buffer every scene shares.
9@MainActor
10@Observable
11final class EditorSplit {
12 private(set) var layout: PaneLayout
13 private(set) var panes: [PaneID: EditorPane] = [:]
14 private(set) var paths: [PaneID: String] = [:]
15 var focused: PaneID
16 @ObservationIgnored nonisolated(unsafe) private var release: (() -> Void)?
17
18 init(path: String, session: DocumentSession, store: MobileEditorStore) {
19 let pane = session.makePane()
20 layout = .pane(pane.id)
21 focused = pane.id
22 panes = [pane.id: pane]
23 paths = [pane.id: path]
24 release = { [weak self, weak session] in
25 guard let self, let session else { return }
26 for (id, pane) in panes {
27 if let path = paths[id] { store.release(id, path: path) }
28 session.closePane(pane)
29 }
30 }
31 }
32
33 deinit {
34 guard let release else { return }
35 Task { @MainActor in release() }
36 }
37
38 var isSplit: Bool { layout.panes.count > 1 }
39
40 /// Runs a pane command; false when it does nothing here.
41 func run(_ id: String, session: DocumentSession, store: MobileEditorStore) -> String? {
42 switch id {
43 case "app.split-right", "app.split-below":
44 guard let path = paths[focused] else { return nil }
45 let pane = session.makePane()
46 panes[pane.id] = pane
47 paths[pane.id] = path
48 layout = layout.splitting(focused, axis: id == "app.split-right" ? .horizontal : .vertical, new: pane.id)
49 case "app.pane-next":
50 focused = layout.next(after: focused)
51 case "app.pane-close":
52 guard isSplit else { return "Attempt to delete the only pane" }
53 close(focused, session: session, store: store)
54 case "app.pane-only":
55 for id in layout.panes where id != focused { close(id, session: session, store: store) }
56 default:
57 return nil
58 }
59 return nil
60 }
61
62 private func close(_ id: PaneID, session: DocumentSession, store: MobileEditorStore) {
63 guard let rest = layout.removing(id) else { return }
64 let next = layout.next(after: id)
65 layout = rest
66 if let path = paths[id] { store.release(id, path: path) }
67 if let pane = panes[id] { session.closePane(pane) }
68 panes[id] = nil
69 paths[id] = nil
70 if focused == id { focused = next }
71 }
72}
73
74/// The editor route's screen: its panes, with the focused one's title and toolbar.
75struct EditorSplitScreen: View {
76 let path: String
77 let offset: Int?
78 let workspace: WorkspaceModel
79 let session: DocumentSession
80 @State private var split: EditorSplit?
81 @State private var message: String?
82 @Environment(MobileModel.self) private var model
83
84 var body: some View {
85 Group {
86 if let split {
87 layoutView(split.layout, split: split)
88 .navigationTitle(split.paths[split.focused].map { session.bufferName($0) + (session.dirtyPaths.contains($0) ? " •" : "") } ?? "")
89 .navigationBarTitleDisplayMode(.inline)
90 } else {
91 ProgressView()
92 }
93 }
94 .onAppear {
95 if split == nil { split = EditorSplit(path: path, session: session, store: model.editors) }
96 }
97 }
98
99 private func layoutView(_ layout: PaneLayout, split: EditorSplit) -> AnyView {
100 switch layout {
101 case .pane(let id):
102 guard let pane = split.panes[id], let file = split.paths[id] else { return AnyView(EmptyView()) }
103 return AnyView(
104 EditorScreen(
105 path: file, offset: id == split.layout.panes.first ? offset : nil, workspace: workspace, session: session,
106 givenPane: pane, inSplit: split.isSplit, isFocused: split.focused == id,
107 onFocus: { split.focused = id },
108 onPaneCommand: { command in _ = split.run(command, session: session, store: model.editors) }
109 )
110 .id(id)
111 .overlay(alignment: .top) {
112 if split.isSplit, split.focused == id { Rectangle().fill(Color.accentColor).frame(height: 2) }
113 }
114 )
115 case .split(let axis, let first, let second, _):
116 if axis == .horizontal {
117 return AnyView(HStack(spacing: 0) {
118 layoutView(first, split: split)
119 Divider()
120 layoutView(second, split: split)
121 })
122 }
123 return AnyView(VStack(spacing: 0) {
124 layoutView(first, split: split)
125 Divider()
126 layoutView(second, split: split)
127 })
128 }
129 }
130}
131#endif
Sources/OrgstarMobile/MobileEditor+Display.swift +3 −3
@@ -138,10 +138,10 @@ extension MobileEditor {
138 var truncatesLines: Bool { 138 var truncatesLines: Bool {
139 get { (textView as? KeyedTextView)?.truncates ?? false } 139 get { (textView as? KeyedTextView)?.truncates ?? false }
140 set { 140 set {
141 guard newValue != truncatesLines, let view = textView as? KeyedTextView else { return } 141 guard newValue != truncatesLines else { return }
142 keepingTopLine { 142 keepingTopLine {
143 view.truncates = newValue 143 for case let view as KeyedTextView in textViews { view.truncates = newValue }
144 if let manager = textView.textLayoutManager { manager.invalidateLayout(for: manager.documentRange) } 144 for manager in layoutManagers { manager.invalidateLayout(for: manager.documentRange) }
145 } 145 }
146 } 146 }
147 } 147 }
Sources/OrgstarMobile/MobileEditor+Modal.swift +1 −1
@@ -312,7 +312,7 @@ extension MobileEditor {
312 /// place of the selection display's while keys are modal. 312 /// place of the selection display's while keys are modal.
313 func updateCursor() { 313 func updateCursor() {
314 let block = modal && vim.mode != .insert && vim.mode != .replace 314 let block = modal && vim.mode != .insert && vim.mode != .replace
315 for case let interaction as UITextSelectionDisplayInteraction in textView.interactions { 315 for case let interaction as UITextSelectionDisplayInteraction in textViews.flatMap(\.interactions) {
316 if let cursor = interaction.cursorView as? ModalCursorView { 316 if let cursor = interaction.cursorView as? ModalCursorView {
317 if cursor.block != block { 317 if cursor.block != block {
318 cursor.block = block 318 cursor.block = block
Sources/OrgstarMobile/MobileEditor+Styling.swift +37 −26
@@ -20,16 +20,20 @@ extension MobileEditor {
20 20
21 /// The text view's own colors, and the block band's. 21 /// The text view's own colors, and the block band's.
22 func applyThemeToView() { 22 func applyThemeToView() {
23 textView.backgroundColor = theme.color("background") ?? .systemBackground 23 for view in textViews { applyThemeToView(view) }
24 textView.tintColor = theme.color("cursor")
25 textView.typingAttributes = theme.base
26 fragmentStyle.set(blockBackground: theme.color("block-background") ?? .clear, width: textView.bounds.width) 24 fragmentStyle.set(blockBackground: theme.color("block-background") ?? .clear, width: textView.bounds.width)
27 themeSelection() 25 }
26
27 func applyThemeToView(_ view: UITextView) {
28 view.backgroundColor = theme.color("background") ?? .systemBackground
29 view.tintColor = theme.color("cursor")
30 view.typingAttributes = theme.base
31 themeSelection(view)
28 } 32 }
29 33
30 /// The selection in the theme's selection color: the text view's selection display 34 /// The selection in the theme's selection color: the text view's selection display
31 /// interaction draws it with our highlight view; the cursor and handles keep the tint. 35 /// interaction draws it with our highlight view; the cursor and handles keep the tint.
32 private func themeSelection() { 36 private func themeSelection(_ textView: UITextView) {
33 guard let interaction = textView.interactions.lazy.compactMap({ $0 as? UITextSelectionDisplayInteraction }).first else { return } 37 guard let interaction = textView.interactions.lazy.compactMap({ $0 as? UITextSelectionDisplayInteraction }).first else { return }
34 let view = interaction.highlightView as? SelectionHighlightView ?? SelectionHighlightView() 38 let view = interaction.highlightView as? SelectionHighlightView ?? SelectionHighlightView()
35 view.color = theme.color("selection") ?? UIColor.tintColor.withAlphaComponent(0.25) 39 view.color = theme.color("selection") ?? UIColor.tintColor.withAlphaComponent(0.25)
@@ -51,15 +55,17 @@ extension MobileEditor {
51 /// Lays `blocks` out again and asks their fragments, which are kept across layout passes, 55 /// Lays `blocks` out again and asks their fragments, which are kept across layout passes,
52 /// to draw again. 56 /// to draw again.
53 private func redraw(blocks: [Range<Int>]) { 57 private func redraw(blocks: [Range<Int>]) {
54 guard let manager = textView.textLayoutManager, let content = manager.textContentManager else { return } 58 for manager in layoutManagers {
55 for block in blocks { 59 guard let content = manager.textContentManager else { continue }
56 guard let start = content.location(content.documentRange.location, offsetBy: block.lowerBound), 60 for block in blocks {
57 let end = content.location(start, offsetBy: block.count), 61 guard let start = content.location(content.documentRange.location, offsetBy: block.lowerBound),
58 let textRange = NSTextRange(location: start, end: end) else { continue } 62 let end = content.location(start, offsetBy: block.count),
59 manager.invalidateRenderingAttributes(for: textRange) 63 let textRange = NSTextRange(location: start, end: end) else { continue }
60 manager.invalidateLayout(for: textRange) 64 manager.invalidateRenderingAttributes(for: textRange)
65 manager.invalidateLayout(for: textRange)
66 }
61 } 67 }
62 textView.setNeedsDisplay() 68 for view in textViews { view.setNeedsDisplay() }
63 } 69 }
64 70
65 /// The band behind blocks spans the view's width, or the widest line's when truncated; 71 /// The band behind blocks spans the view's width, or the widest line's when truncated;
@@ -67,19 +73,21 @@ extension MobileEditor {
67 /// wider line in a truncated file, which widens the band on each layout pass, redraws 73 /// wider line in a truncated file, which widens the band on each layout pass, redraws
68 /// the blocks alone: laying the whole file out again moves the text under the view. 74 /// the blocks alone: laying the whole file out again moves the text under the view.
69 func viewResized() { 75 func viewResized() {
76 // With several views, the band spans the widest and images fit the narrowest.
70 let band = fragmentStyle.blockBand 77 let band = fragmentStyle.blockBand
71 let width = max(textView.bounds.width, truncatesLines ? textView.contentSize.width : 0) 78 let width = textViews.map { max($0.bounds.width, truncatesLines ? $0.contentSize.width : 0) }.max() ?? 0
72 let resized = imageWidth != textView.bounds.width 79 let narrowest = textViews.map(\.bounds.width).filter { $0 > 0 }.min() ?? textView.bounds.width
80 let resized = imageWidth != narrowest
73 guard band.width != width || resized else { return } 81 guard band.width != width || resized else { return }
74 fragmentStyle.set(blockBackground: band.color, width: width) 82 fragmentStyle.set(blockBackground: band.color, width: width)
75 imageWidth = textView.bounds.width 83 imageWidth = narrowest
76 guard resized else { 84 guard resized else {
77 redraw(blocks: shaded.all) 85 redraw(blocks: shaded.all)
78 return 86 return
79 } 87 }
80 keepingTopLine { 88 keepingTopLine {
81 if showsImages { restyle(0..<textView.textStorage.length) } 89 if showsImages { restyle(0..<textView.textStorage.length) }
82 if let manager = textView.textLayoutManager { 90 for manager in layoutManagers {
83 manager.invalidateRenderingAttributes(for: manager.documentRange) 91 manager.invalidateRenderingAttributes(for: manager.documentRange)
84 manager.invalidateLayout(for: manager.documentRange) 92 manager.invalidateLayout(for: manager.documentRange)
85 } 93 }
@@ -92,7 +100,7 @@ extension MobileEditor {
92 defer { interval.end() } 100 defer { interval.end() }
93 keepingTopLine { 101 keepingTopLine {
94 restyle(0..<textView.textStorage.length) 102 restyle(0..<textView.textStorage.length)
95 if let manager = textView.textLayoutManager { manager.invalidateLayout(for: manager.documentRange) } 103 for manager in layoutManagers { manager.invalidateLayout(for: manager.documentRange) }
96 } 104 }
97 } 105 }
98 106
@@ -101,15 +109,18 @@ extension MobileEditor {
101 /// whole file again makes TextKit estimate the height of everything above the view afresh, 109 /// whole file again makes TextKit estimate the height of everything above the view afresh,
102 /// which moves the text under it. 110 /// which moves the text under it.
103 func invalidateLayout(lines ranges: [Range<Int>]) { 111 func invalidateLayout(lines ranges: [Range<Int>]) {
104 guard !ranges.isEmpty, let manager = textView.textLayoutManager, let content = manager.textContentManager else { return } 112 guard !ranges.isEmpty else { return }
105 let text = textView.textStorage.string as NSString 113 let text = textView.textStorage.string as NSString
106 for range in ranges { 114 for manager in layoutManagers {
107 let lower = text.lineRange(for: NSRange(location: max(0, min(range.lowerBound, text.length) - 1), length: 0)).location 115 guard let content = manager.textContentManager else { continue }
108 let upper = NSMaxRange(text.lineRange(for: NSRange(location: min(range.upperBound, text.length), length: 0))) 116 for range in ranges {
109 guard let start = content.location(content.documentRange.location, offsetBy: lower), 117 let lower = text.lineRange(for: NSRange(location: max(0, min(range.lowerBound, text.length) - 1), length: 0)).location
110 let end = content.location(start, offsetBy: upper - lower), 118 let upper = NSMaxRange(text.lineRange(for: NSRange(location: min(range.upperBound, text.length), length: 0)))
111 let textRange = NSTextRange(location: start, end: end) else { continue } 119 guard let start = content.location(content.documentRange.location, offsetBy: lower),
112 manager.invalidateLayout(for: textRange) 120 let end = content.location(start, offsetBy: upper - lower),
121 let textRange = NSTextRange(location: start, end: end) else { continue }
122 manager.invalidateLayout(for: textRange)
123 }
113 } 124 }
114 } 125 }
115 126
Sources/OrgstarMobile/MobileEditor.swift +90 −21
@@ -15,10 +15,13 @@ final class MobileEditor: NSObject, DocumentBuffer {
15 /// One highlighter for every editor and the reader: it caches compiled grammars and results. 15 /// One highlighter for every editor and the reader: it caches compiled grammars and results.
16 static let highlighter = TreeSitterHighlighter() 16 static let highlighter = TreeSitterHighlighter()
17 private(set) var document: DocumentState 17 private(set) var document: DocumentState
18 let textView: UITextView 18 /// The views showing the buffer, one per pane; the first is made with the editor.
19 private(set) var textViews: [UITextView]
20 /// The view with focus, or the last to have had it: the one commands act on.
21 private(set) var textView: UITextView
19 var options: EditingOptions = .org { 22 var options: EditingOptions = .org {
20 didSet { 23 didSet {
21 textView.spellCheckingType = options.spellCheck ? .yes : .no 24 for view in textViews { view.spellCheckingType = options.spellCheck ? .yes : .no }
22 if !showMarkup, options.hideEmphasisMarkers != oldValue.hideEmphasisMarkers || options.prettyEntities != oldValue.prettyEntities { 25 if !showMarkup, options.hideEmphasisMarkers != oldValue.hideEmphasisMarkers || options.prettyEntities != oldValue.prettyEntities {
23 restyleAll() 26 restyleAll()
24 } 27 }
@@ -137,26 +140,11 @@ final class MobileEditor: NSObject, DocumentBuffer {
137 theme = MobileTheme(spec) 140 theme = MobileTheme(spec)
138 let keyed = KeyedTextView(usingTextLayoutManager: true) 141 let keyed = KeyedTextView(usingTextLayoutManager: true)
139 textView = keyed 142 textView = keyed
143 textViews = [keyed]
140 super.init() 144 super.init()
141 keyed.keyHandler = { [weak self] key in self?.handleKey(key) ?? false } 145 configure(keyed, editable: editable)
142 keyed.onLayout = { [weak self] in self?.viewResized() }
143 textView.isEditable = editable
144 textView.autocorrectionType = .no
145 textView.autocapitalizationType = .none
146 textView.smartQuotesType = .no
147 textView.smartDashesType = .no
148 textView.smartInsertDeleteType = .no
149 textView.spellCheckingType = options.spellCheck ? .yes : .no
150 textView.keyboardDismissMode = .interactive
151 textView.alwaysBounceVertical = true
152 textView.textContainerInset = UIEdgeInsets(top: 12, left: 8, bottom: 24, right: 8)
153 textView.delegate = self
154 textView.textStorage.delegate = self 146 textView.textStorage.delegate = self
155 textView.textLayoutManager?.delegate = self
156 (textView.textLayoutManager?.textContentManager as? NSTextContentStorage)?.delegate = self 147 (textView.textLayoutManager?.textContentManager as? NSTextContentStorage)?.delegate = self
157 let foldTap = UITapGestureRecognizer(target: self, action: #selector(tappedFold))
158 foldTap.delegate = self
159 textView.addGestureRecognizer(foldTap)
160 let startup = Presentation.startupDisplay(document.tree, options: options) 148 let startup = Presentation.startupDisplay(document.tree, options: options)
161 indented = startup.indented 149 indented = startup.indented
162 hideStars = startup.hideStars 150 hideStars = startup.hideStars
@@ -171,6 +159,76 @@ final class MobileEditor: NSObject, DocumentBuffer {
171 textView.selectedRange = NSRange(location: 0, length: 0) 159 textView.selectedRange = NSRange(location: 0, length: 0)
172 } 160 }
173 161
162 /// What every view of the buffer has: the keymap, the editor as its delegates and the fold
163 /// tap. Views in one scene share its undo stack.
164 private func configure(_ view: KeyedTextView, editable: Bool) {
165 view.keyHandler = { [weak self, weak view] key in
166 guard let self else { return false }
167 if let view { focus(view) }
168 return handleKey(key)
169 }
170 view.onLayout = { [weak self] in self?.viewResized() }
171 view.isEditable = editable
172 view.autocorrectionType = .no
173 view.autocapitalizationType = .none
174 view.smartQuotesType = .no
175 view.smartDashesType = .no
176 view.smartInsertDeleteType = .no
177 view.spellCheckingType = options.spellCheck ? .yes : .no
178 view.keyboardDismissMode = .interactive
179 view.alwaysBounceVertical = true
180 view.textContainerInset = UIEdgeInsets(top: 12, left: 8, bottom: 24, right: 8)
181 view.delegate = self
182 view.textLayoutManager?.delegate = self
183 let foldTap = UITapGestureRecognizer(target: self, action: #selector(tappedFold))
184 foldTap.delegate = self
185 view.addGestureRecognizer(foldTap)
186 }
187
188 // MARK: - Views
189
190 /// Another view of the buffer, for another pane: its own layout manager on the buffer's
191 /// content storage, so text, folds and styles are shared and the caret and scroll aren't.
192 func addView() -> UITextView {
193 guard let storage = textViews[0].textLayoutManager?.textContentManager as? NSTextContentStorage else { return textViews[0] }
194 let manager = NSTextLayoutManager()
195 manager.delegate = self
196 let container = NSTextContainer(size: CGSize(width: 0, height: CGFloat.greatestFiniteMagnitude))
197 manager.textContainer = container
198 storage.addTextLayoutManager(manager)
199 let view = KeyedTextView(frame: .zero, textContainer: container)
200 configure(view, editable: textViews[0].isEditable)
201 textViews.append(view)
202 applyThemeToView(view)
203 if truncatesLines { view.truncates = true }
204 updateCursor()
205 return view
206 }
207
208 /// Drops a view `addView` made; the first stays with the editor.
209 func removeView(_ view: UITextView) {
210 guard view !== textViews[0], let index = textViews.firstIndex(where: { $0 === view }) else { return }
211 textViews.remove(at: index)
212 if let manager = view.textLayoutManager, let storage = manager.textContentManager { storage.removeTextLayoutManager(manager) }
213 view.delegate = nil
214 onFocus[ObjectIdentifier(view)] = nil
215 if textView === view { textView = textViews[0] }
216 }
217
218 /// What each view's screen does when its view takes focus: the editor's callbacks are
219 /// that screen's from then on.
220 var onFocus: [ObjectIdentifier: () -> Void] = [:]
221
222 /// Commands act on `view` from now on.
223 func focus(_ view: UITextView) {
224 guard view !== textView, textViews.contains(where: { $0 === view }) else { return }
225 textView = view
226 onFocus[ObjectIdentifier(view)]?()
227 }
228
229 /// Every view's layout manager.
230 var layoutManagers: [NSTextLayoutManager] { textViews.compactMap(\.textLayoutManager) }
231
174 // MARK: - DocumentBuffer 232 // MARK: - DocumentBuffer
175 233
176 var selection: [Range<Int>] { 234 var selection: [Range<Int>] {
@@ -481,7 +539,15 @@ final class MobileEditor: NSObject, DocumentBuffer {
481} 539}
482 540
483extension MobileEditor: UITextViewDelegate { 541extension MobileEditor: UITextViewDelegate {
542 func textViewDidBeginEditing(_ textView: UITextView) {
543 focus(textView)
544 }
545
546 /// Another view's caret moves with edits made in this one; only the focused view's
547 /// selection drives the display.
484 func textViewDidChangeSelection(_ textView: UITextView) { 548 func textViewDidChangeSelection(_ textView: UITextView) {
549 if textView.isFirstResponder { focus(textView) }
550 guard textView === self.textView else { return }
485 selectionChanged() 551 selectionChanged()
486 } 552 }
487 553
@@ -519,7 +585,8 @@ extension MobileEditor: UITextViewDelegate {
519extension MobileEditor: UIGestureRecognizerDelegate { 585extension MobileEditor: UIGestureRecognizerDelegate {
520 /// The drawer or block a tap at `point` folds or unfolds: a folded one's `…`, the space after 586 /// The drawer or block a tap at `point` folds or unfolds: a folded one's `…`, the space after
521 /// its first line, or anywhere on an open drawer's first line. 587 /// its first line, or anywhere on an open drawer's first line.
522 private func foldToggle(at point: CGPoint) -> Int? { 588 private func foldToggle(at point: CGPoint, in view: UITextView? = nil) -> Int? {
589 let textView = view ?? textView
523 guard let manager = textView.textLayoutManager, let content = manager.textContentManager else { return nil } 590 guard let manager = textView.textLayoutManager, let content = manager.textContentManager else { return nil }
524 let inContainer = CGPoint(x: point.x - textView.textContainerInset.left, y: point.y - textView.textContainerInset.top) 591 let inContainer = CGPoint(x: point.x - textView.textContainerInset.left, y: point.y - textView.textContainerInset.top)
525 guard let fragment = manager.textLayoutFragment(for: inContainer), let range = fragment.textElement?.elementRange else { return nil } 592 guard let fragment = manager.textLayoutFragment(for: inContainer), let range = fragment.textElement?.elementRange else { return nil }
@@ -534,13 +601,15 @@ extension MobileEditor: UIGestureRecognizerDelegate {
534 /// A tap on a fold's `…` opens it, and one on an open drawer's first line folds it, as TAB 601 /// A tap on a fold's `…` opens it, and one on an open drawer's first line folds it, as TAB
535 /// on the line does. 602 /// on the line does.
536 @objc fileprivate func tappedFold(_ tap: UITapGestureRecognizer) { 603 @objc fileprivate func tappedFold(_ tap: UITapGestureRecognizer) {
604 if let view = tap.view as? UITextView { focus(view) }
537 guard let start = foldToggle(at: tap.location(in: textView)), 605 guard let start = foldToggle(at: tap.location(in: textView)),
538 let next = Presentation.cycle(at: start, in: document.tree, fold) else { return } 606 let next = Presentation.cycle(at: start, in: document.tree, fold) else { return }
539 setFolds(next) 607 setFolds(next)
540 } 608 }
541 609
542 func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { 610 func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
543 foldToggle(at: gestureRecognizer.location(in: textView)) != nil 611 guard let view = gestureRecognizer.view as? UITextView else { return false }
612 return foldToggle(at: gestureRecognizer.location(in: view), in: view) != nil
544 } 613 }
545 614
546 func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith other: UIGestureRecognizer) -> Bool { 615 func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith other: UIGestureRecognizer) -> Bool {
Sources/OrgstarMobile/MobileEditorStore.swift added +50
@@ -0,0 +1,50 @@
1#if os(iOS)
2import OrgApp
3import UIKit
4
5/// The editors of the open buffers and the text views the panes show them in, across every
6/// scene: one `MobileEditor` per file, one text view per pane that shows it.
7@MainActor
8final class MobileEditorStore {
9 private var editors: [String: MobileEditor] = [:]
10 /// The pane each text view belongs to.
11 private var owners: [ObjectIdentifier: PaneID] = [:]
12
13 /// The editor of `path`, made with `make` when there's none or the session's buffer for the
14 /// file is no longer it (the file was closed and opened again).
15 func editor(for path: String, session: DocumentSession, make: () -> MobileEditor?) -> MobileEditor? {
16 if let editor = editors[path], session.isAttached(editor, for: path) { return editor }
17 if let old = editors[path] { for view in old.textViews { owners[ObjectIdentifier(view)] = nil } }
18 guard let made = make() else { return nil }
19 editors[path] = made
20 session.attach(made, for: path)
21 return made
22 }
23
24 /// The text view `pane` shows `editor` in: one no other pane owns, else a new one.
25 func view(for pane: PaneID, of editor: MobileEditor) -> UITextView {
26 if let owned = editor.textViews.first(where: { owners[ObjectIdentifier($0)] == pane }) { return owned }
27 let view = editor.textViews.first { owners[ObjectIdentifier($0)] == nil } ?? editor.addView()
28 owners[ObjectIdentifier(view)] = pane
29 return view
30 }
31
32 /// `pane` no longer shows `path`: its view goes, or is left free when it's the editor's
33 /// first, which stays with the editor.
34 func release(_ pane: PaneID, path: String) {
35 guard let editor = editors[path] else { return }
36 for view in editor.textViews where owners[ObjectIdentifier(view)] == pane {
37 owners[ObjectIdentifier(view)] = nil
38 editor.removeView(view)
39 }
40 }
41
42 /// The editors of files the session no longer has open go.
43 func prune(_ session: DocumentSession) {
44 for (path, editor) in editors where !session.isAttached(editor, for: path) {
45 for view in editor.textViews { owners[ObjectIdentifier(view)] = nil }
46 editors[path] = nil
47 }
48 }
49}
50#endif
Sources/OrgstarMobile/MobileModel.swift +2
@@ -21,6 +21,8 @@ final class MobileModel {
21 let workspace: WorkspaceModel? 21 let workspace: WorkspaceModel?
22 let failure: String? 22 let failure: String?
23 let session = DocumentSession() 23 let session = DocumentSession()
24 /// The open files' editors, shared by every scene's panes.
25 let editors = MobileEditorStore()
24 let agenda: AgendaModel? 26 let agenda: AgendaModel?
25 let scheduler = ReminderScheduler(center: SystemReminderCenter()) 27 let scheduler = ReminderScheduler(center: SystemReminderCenter())
26 let clock = ClockModel() 28 let clock = ClockModel()
Sources/OrgstarMobile/OrgstarMobileApp.swift +1 −1
@@ -71,7 +71,7 @@ extension View {
71 ReaderScreen(route: route, workspace: workspace, session: session) 71 ReaderScreen(route: route, workspace: workspace, session: session)
72 } 72 }
73 .navigationDestination(for: EditorRoute.self) { route in 73 .navigationDestination(for: EditorRoute.self) { route in
74 EditorScreen(path: route.path, offset: route.offset, workspace: workspace, session: session) 74 EditorSplitScreen(path: route.path, offset: route.offset, workspace: workspace, session: session)
75 } 75 }
76 .navigationDestination(for: SearchRoute.self) { _ in 76 .navigationDestination(for: SearchRoute.self) { _ in
77 SearchScreen(workspace: workspace, session: session) 77 SearchScreen(workspace: workspace, session: session)
Sources/OrgstarMobile/ReaderScreen.swift +51 −27
@@ -1,6 +1,7 @@
1#if os(iOS) 1#if os(iOS)
2import OrgApp 2import OrgApp
3import OrgCore 3import OrgCore
4import OrgDocument
4import OrgIndex 5import OrgIndex
5import OrgPresentation 6import OrgPresentation
6import SwiftUI 7import SwiftUI
@@ -35,13 +36,18 @@ struct ReaderScreen: View {
35 @State private var startup: StartupDisplay? 36 @State private var startup: StartupDisplay?
36 @State private var showingOutline = false 37 @State private var showingOutline = false
37 @State private var message: String? 38 @State private var message: String?
39 /// The pane the reader shows its file in, closed with the reader.
40 @State private var holder = PaneHolder()
38 @Environment(\.openURL) private var openURL 41 @Environment(\.openURL) private var openURL
39 @Environment(MobileModel.self) private var model 42 @Environment(MobileModel.self) private var model
40 43
41 private var outline: [OutlineEntry] { session.outline } 44 private var pane: EditorPane? { holder.pane }
45 private var outline: [OutlineEntry] { pane?.outline ?? [] }
46 /// The file the reader's pane shows.
47 private var shownPath: String? { pane?.path }
48 private var document: DocumentState? { shownPath.flatMap(session.document(of:)) }
42 49
43 /// The file this reader shows. Readers lower in the stack stay alive while the session 50 /// The file this reader shows.
44 /// shows another file, and draw nothing then.
45 private var path: String { 51 private var path: String {
46 switch route { 52 switch route {
47 case .file(let path), .offset(let path, _): path 53 case .file(let path), .offset(let path, _): path
@@ -49,14 +55,14 @@ struct ReaderScreen: View {
49 } 55 }
50 } 56 }
51 57
52 /// The session shows this reader's file; it opens files by their resolved paths. 58 /// The pane shows this reader's file; the session opens files by their resolved paths.
53 private var showsOwnFile: Bool { 59 private var showsOwnFile: Bool {
54 guard let current = session.path else { return false } 60 guard let current = shownPath else { return false }
55 return current == path || current == URL(fileURLWithPath: path).resolvingSymlinksInPath().path 61 return current == path || current == URL(fileURLWithPath: path).resolvingSymlinksInPath().path
56 } 62 }
57 63
58 var body: some View { 64 var body: some View {
59 let _ = session.editVersion 65 let _ = pane?.editVersion
60 // Read again when settings or the Dynamic Type size change. 66 // Read again when settings or the Dynamic Type size change.
61 let _ = model.settingsVersion 67 let _ = model.settingsVersion
62 let theme = MobileTheme(model.theme) 68 let theme = MobileTheme(model.theme)
@@ -64,7 +70,7 @@ struct ReaderScreen: View {
64 ScrollViewReader { proxy in 70 ScrollViewReader { proxy in
65 ScrollView(truncated ? [.vertical, .horizontal] : .vertical) { 71 ScrollView(truncated ? [.vertical, .horizontal] : .vertical) {
66 LazyVStack(alignment: .leading, spacing: 8) { 72 LazyVStack(alignment: .leading, spacing: 8) {
67 if let tree = session.document?.tree, showsOwnFile { 73 if let tree = document?.tree, showsOwnFile {
68 let length = (tree.text as NSString).length 74 let length = (tree.text as NSString).length
69 let preambleEnd = min(outline.first?.start ?? length, length) 75 let preambleEnd = min(outline.first?.start ?? length, length)
70 if preambleEnd > 0 { textView(tree, 0..<preambleEnd, theme) } 76 if preambleEnd > 0 { textView(tree, 0..<preambleEnd, theme) }
@@ -87,18 +93,18 @@ struct ReaderScreen: View {
87 // Narrower than the view while truncated, the text still starts at the top left. 93 // Narrower than the view while truncated, the text still starts at the top left.
88 .defaultScrollAnchor(truncated ? .topLeading : nil) 94 .defaultScrollAnchor(truncated ? .topLeading : nil)
89 .background(theme.swiftColor("background") ?? Color(uiColor: .systemBackground)) 95 .background(theme.swiftColor("background") ?? Color(uiColor: .systemBackground))
90 .onChange(of: session.revealRequest?.id) { 96 .onChange(of: pane?.revealRequest?.id) {
91 guard let offset = session.revealRequest?.offset else { return } 97 guard let offset = pane?.revealRequest?.offset else { return }
92 reveal(offset, proxy) 98 reveal(offset, proxy)
93 } 99 }
94 } 100 }
95 .navigationTitle(((session.path ?? "") as NSString).lastPathComponent) 101 .navigationTitle(((shownPath ?? "") as NSString).lastPathComponent)
96 .navigationBarTitleDisplayMode(.inline) 102 .navigationBarTitleDisplayMode(.inline)
97 .toolbar { 103 .toolbar {
98 ToolbarItemGroup(placement: .primaryAction) { 104 ToolbarItemGroup(placement: .primaryAction) {
99 Button("Outline", systemImage: "list.bullet.indent") { showingOutline = true }.disabled(outline.isEmpty) 105 Button("Outline", systemImage: "list.bullet.indent") { showingOutline = true }.disabled(outline.isEmpty)
100 if let path = session.path { 106 if let path = shownPath {
101 if let text = session.document?.text { ExportMenu(path: path, text: text) { message = $0 } } 107 if let text = document?.text { ExportMenu(path: path, text: text) { message = $0 } }
102 NavigationLink(value: EditorRoute(path: path, offset: nil)) { Label("Edit", systemImage: "square.and.pencil") } 108 NavigationLink(value: EditorRoute(path: path, offset: nil)) { Label("Edit", systemImage: "square.and.pencil") }
103 } 109 }
104 } 110 }
@@ -112,8 +118,8 @@ struct ReaderScreen: View {
112 } 118 }
113 .environment(\.openURL, OpenURLAction { url in follow(url) }) 119 .environment(\.openURL, OpenURLAction { url in follow(url) })
114 .onAppear(perform: open) 120 .onAppear(perform: open)
115 .onChange(of: session.path) { loadFolds() } 121 .onChange(of: pane?.path) { loadFolds() }
116 .onChange(of: session.editVersion) { loadFolds() } 122 .onChange(of: pane?.editVersion) { loadFolds() }
117 .onChange(of: model.settingsVersion) { loadFolds() } 123 .onChange(of: model.settingsVersion) { loadFolds() }
118 } 124 }
119 125
@@ -210,7 +216,7 @@ struct ReaderScreen: View {
210 216
211 /// Text, and with inline images on, lines that are only an image link shown as the image. 217 /// Text, and with inline images on, lines that are only an image link shown as the image.
212 private func parts(_ tree: OrgTree, _ range: Range<Int>) -> [Part] { 218 private func parts(_ tree: OrgTree, _ range: Range<Int>) -> [Part] {
213 guard startup?.inlineImages == true, let path = session.path else { return [Part(range: range)] } 219 guard startup?.inlineImages == true, let path = shownPath else { return [Part(range: range)] }
214 // Read so that the view draws again when a remote image arrives. 220 // Read so that the view draws again when a remote image arrives.
215 _ = RemoteImages.shared.version 221 _ = RemoteImages.shared.version
216 let remote = RemoteImages.Mode(rawValue: session.options.remoteInlineImages) ?? .skip 222 let remote = RemoteImages.Mode(rawValue: session.options.remoteInlineImages) ?? .skip
@@ -304,12 +310,22 @@ struct ReaderScreen: View {
304 // MARK: - Actions 310 // MARK: - Actions
305 311
306 private func open() { 312 private func open() {
307 switch route { 313 let pane = holder.pane ?? {
308 case .file(let path): if session.path != path { session.open(path) } 314 let made = session.makePane()
309 case .offset(let path, let offset): 315 holder.pane = made
310 if session.path != path { session.open(path) } 316 holder.release = { [weak session] in session?.closePane(made) }
311 session.reveal(offset) 317 return made
312 case .heading(let location): session.show(location) 318 }()
319 // What the reader opens and follows goes to its pane.
320 session.focused = pane
321 if loadedPath == nil {
322 switch route {
323 case .file(let path): session.open(path, in: pane)
324 case .offset(let path, let offset):
325 session.open(path, in: pane)
326 session.reveal(offset, in: pane)
327 case .heading(let location): session.show(location)
328 }
313 } 329 }
314 loadFolds() 330 loadFolds()
315 } 331 }
@@ -317,13 +333,13 @@ struct ReaderScreen: View {
317 /// The file's startup display, as the editor opens it; its heading folds are kept while 333 /// The file's startup display, as the editor opens it; its heading folds are kept while
318 /// the same file is open. 334 /// the same file is open.
319 private func loadFolds() { 335 private func loadFolds() {
320 guard let tree = session.document?.tree, showsOwnFile else { return } 336 guard let tree = document?.tree, showsOwnFile else { return }
321 let display = Presentation.startupDisplay(tree, options: session.options) 337 let display = Presentation.startupDisplay(tree, options: session.options)
322 startup = display 338 startup = display
323 folded = display.wrappers.map(\.hidden) 339 folded = display.wrappers.map(\.hidden)
324 foldable = folded 340 foldable = folded
325 guard loadedPath != session.path else { return } 341 guard loadedPath != shownPath else { return }
326 loadedPath = session.path 342 loadedPath = shownPath
327 fold = display.folds 343 fold = display.folds
328 } 344 }
329 345
@@ -349,11 +365,19 @@ struct ReaderScreen: View {
349 return .handled 365 return .handled
350 } 366 }
351 guard url.scheme == "orgstar-link", let offset = Int(url.absoluteString.dropFirst("orgstar-link:".count)), 367 guard url.scheme == "orgstar-link", let offset = Int(url.absoluteString.dropFirst("orgstar-link:".count)),
352 let tree = session.document?.tree, let link = Links.link(at: offset, text: tree.text, tree: tree)?.link else { 368 let tree = document?.tree, let link = Links.link(at: offset, text: tree.text, tree: tree)?.link else {
353 return .systemAction 369 return .systemAction
354 } 370 }
371 if let pane { session.focused = pane }
355 switch session.follow(link, workspace: workspace, isText: { _ in false }) { 372 switch session.follow(link, workspace: workspace, isText: { _ in false }) {
356 case .shown: message = nil 373 case .shown:
374 message = nil
375 // A link to another file shows it on its own screen; this pane keeps its file.
376 if let pane, let target = pane.path, target != path, !showsOwnFile {
377 let caret = session.caret(of: target) ?? 0
378 session.open(path, in: pane)
379 model.openRequest = .offset(target, caret)
380 }
357 case .openExternally(let target): openURL(target) 381 case .openExternally(let target): openURL(target)
358 case .message(let text): message = text 382 case .message(let text): message = text
359 } 383 }
@@ -365,7 +389,7 @@ struct ReaderScreen: View {
365 List(outline, id: \.start) { entry in 389 List(outline, id: \.start) { entry in
366 Button { 390 Button {
367 showingOutline = false 391 showingOutline = false
368 session.reveal(entry.start) 392 if let pane { session.reveal(entry.start, in: pane) }
369 } label: { 393 } label: {
370 Text(entry.title.isEmpty ? "(untitled)" : entry.title) 394 Text(entry.title.isEmpty ? "(untitled)" : entry.title)
371 .padding(.leading, indent(entry)) 395 .padding(.leading, indent(entry))
docs/manual/guide/14-ios.org +17 −1
@@ -56,6 +56,22 @@ The toolbar has:
56 56
57Messages from commands show at the top of the editor for a few seconds; tap one to dismiss it. 57Messages from commands show at the top of the editor for a few seconds; tap one to dismiss it.
58 58
59** Panes and windows on iPad
60
61On iPad, the editor can show a file in several panes, as a Mac window does (see [[file:01-files-and-folders.org][Files and folders]]):
62
63| Command | Where | Emacs keys | Does |
64|-------------------+----------------------------------------------+------------+-------------------------------------------------------------|
65| Split Pane Right | More ▸ Panes, Commands, a hardware keyboard | =C-x 3= | Halves the focused pane side by side; the new pane shows the same file |
66| Split Pane Below | More ▸ Panes, Commands, a hardware keyboard | =C-x 2= | Halves the focused pane one above the other |
67| Next Pane | More ▸ Panes, Commands, a hardware keyboard | =C-x o= | Moves focus to the next pane |
68| Close Pane | More ▸ Panes, Commands, a hardware keyboard | =C-x 0= | Closes the focused pane |
69| Close Other Panes | More ▸ Panes, Commands, a hardware keyboard | =C-x 1= | Closes every pane but the focused one |
70
71The focused pane has a line along its top and the toolbar acts on it; tap in a pane to focus it. Every pane shows the same buffer: text typed in one shows in the others at once, and folds, narrowing and styles are the buffer's. The caret and scroll position are each pane's own, and so is undo: Undo in a pane undoes what was typed or changed in that pane. A link to another file opens it on its own screen, leaving the panes as they are.
72
73Each iPad window (scene), opened from the app switcher or by dragging the app from the Dock, has its own tabs, screens and panes over the same open files, so a file edited in one window shows the edit in the others. The pane commands aren't offered on iPhone or in a narrow window.
74
59** Saving 75** Saving
60 76
61The iOS app always saves automatically: one second after you stop typing, when you leave the editor, and when the app goes to the background. The =save= setting doesn't apply on iOS. 77The iOS app always saves automatically: one second after you stop typing, when you leave the editor, and when the app goes to the background. The =save= setting doesn't apply on iOS.
@@ -393,7 +409,7 @@ Quick Look in the Files app shows org files as the HTML export renders them.
393- ODT, LaTeX, ASCII and LaTeX-made PDF export, and publishing. 409- ODT, LaTeX, ASCII and LaTeX-made PDF export, and publishing.
394- Idle detection while a clock runs. 410- Idle detection while a clock runs.
395- Import from Emacs of agenda folders. 411- Import from Emacs of agenda folders.
396- The Columns inspector, and the buffer list and tab bar. The board and column view are there (see [[file:07-agenda.org][The agenda]] and [[file:04-outlines.org][Outlines]]). 412- The Columns inspector, the buffer list and tab bar, and resizing panes by dragging their divider. The board and column view are there (see [[file:07-agenda.org][The agenda]] and [[file:04-outlines.org][Outlines]]).
397- The global capture hotkey and the Settings window. 413- The global capture hotkey and the Settings window.
398- Explicit saving. 414- Explicit saving.
399 415