Sources/OrgstarMobile/WorkingCopySync.swift
187 lines · 7999 bytes
11 symbols in this file
1#if os(iOS)
2import OrgApp
3import SwiftUI
4import UIKit
5
6/// Syncing folders through Working Copy: saves every file, opens Working Copy's commit, pull
7/// and push chain, and takes its answer from `orgstar://working-copy/…`.
8@MainActor
9@Observable
10final class WorkingCopySync {
11 /// What the last sync, or its start, came to, for the app's message line.
12 var message: String?
13 /// Folders waiting for the one being synced, by root.
14 @ObservationIgnored private var queue: [String] = []
15 @ObservationIgnored private var running: String?
16 /// When a sync last started: coming back from Working Copy makes the app active again,
17 /// which mustn't start another.
18 @ObservationIgnored private var started: Date?
19 @ObservationIgnored let folders = WorkingCopy.Folders()
20
21 /// The folder `path` is in, when it is set up.
22 func root(containing path: String, roots: [String]) -> String? {
23 let set = folders.all
24 return roots.filter { set[$0] != nil && (path == $0 || path.hasPrefix($0 + "/")) }.max { $0.count < $1.count }
25 }
26
27 /// Syncs `root`, after the folders already waiting.
28 func sync(_ root: String, session: DocumentSession) {
29 guard running != root, !queue.contains(root) else { return }
30 queue.append(root)
31 if running == nil { next(session: session) }
32 }
33
34 /// The app became active: the folders that sync on opening, unless a sync started a moment
35 /// ago and this is the return from Working Copy.
36 func appOpened(roots: [String], session: DocumentSession) {
37 if let started, Date().timeIntervalSince(started) < 120 { return }
38 let set = folders.all
39 for root in roots where set[root]?.syncOnOpen == true { sync(root, session: session) }
40 }
41
42 private func next(session: DocumentSession) {
43 guard running == nil, !queue.isEmpty else { return }
44 let root = queue.removeFirst()
45 let name = (root as NSString).lastPathComponent
46 guard let folder = folders.folder(root) else { return next(session: session) }
47 // Working Copy commits what is on disk.
48 let unsaved = session.dirtyPaths.filter { !session.save($0) }.sorted()
49 if let failed = unsaved.first {
50 message = String(localized: "\(name) wasn't synced: \((failed as NSString).lastPathComponent) couldn't be saved.", comment: "Working Copy sync")
51 queue.removeAll()
52 return
53 }
54 guard let key = WorkingCopy.Key.stored() else {
55 message = String(localized: "\(name) wasn't synced: set Working Copy's URL key in Settings ▸ Working Copy.", comment: "Working Copy sync")
56 queue.removeAll()
57 return
58 }
59 running = root
60 started = Date()
61 UIApplication.shared.open(WorkingCopy.syncURL(repo: folder.repository, key: key)) { [weak self] opened in
62 guard let self, !opened else { return }
63 self.running = nil
64 self.queue.removeAll()
65 self.message = String(localized: "\(name) wasn't synced: Working Copy isn't installed or couldn't be opened.", comment: "Working Copy sync")
66 }
67 }
68
69 /// Working Copy's answer.
70 func finished(_ callback: WorkingCopy.Callback, workspace: WorkspaceModel, session: DocumentSession) {
71 running = nil
72 switch callback {
73 case .success(let repo):
74 let name = folders.root(of: repo).map { ($0 as NSString).lastPathComponent } ?? repo
75 message = String(localized: "Synced \(name) with Working Copy", comment: "Working Copy sync")
76 Task { await workspace.refresh() }
77 next(session: session)
78 case .failure(let repo, let reason):
79 let name = folders.root(of: repo).map { ($0 as NSString).lastPathComponent } ?? repo
80 message = reason.map { String(localized: "\(name) wasn't synced: \($0)", comment: "Working Copy sync; Working Copy's error follows") }
81 ?? String(localized: "\(name) wasn't synced: Working Copy reported an error.", comment: "Working Copy sync")
82 queue.removeAll()
83 }
84 }
85}
86
87/// Settings ▸ Working Copy: the URL key, and for each folder whether it syncs.
88struct WorkingCopyScreen: View {
89 let workspace: WorkspaceModel
90 @State private var key = WorkingCopy.Key.stored() ?? ""
91 @State private var keyStored = WorkingCopy.Key.stored() != nil
92
93 var body: some View {
94 Form {
95 Section {
96 SecureField("URL key", text: $key)
97 .textInputAutocapitalization(.never)
98 .autocorrectionDisabled()
99 .onSubmit(storeKey)
100 Button(keyStored ? "Replace Key" : "Save Key", action: storeKey).disabled(key.isEmpty)
101 if keyStored {
102 Button("Remove Key", role: .destructive) {
103 WorkingCopy.Key.store(nil)
104 key = ""
105 keyStored = false
106 }
107 }
108 } footer: {
109 Text("Working Copy runs orgstar's sync only with the URL key from Working Copy's settings. orgstar keeps it in the Keychain on this device.")
110 }
111 ForEach(workspace.rootPaths, id: \.self) { root in
112 WorkingCopyFolderSection(root: root)
113 }
114 }
115 .navigationTitle("Working Copy")
116 }
117
118 private func storeKey() {
119 guard !key.isEmpty else { return }
120 keyStored = WorkingCopy.Key.store(key)
121 }
122}
123
124/// Whether a folder syncs with Working Copy, the repository's name there, and whether it syncs
125/// when orgstar opens.
126struct WorkingCopyFolderSection: View {
127 let root: String
128 @State private var folder: WorkingCopy.Folder?
129
130 init(root: String) {
131 self.root = root
132 _folder = State(initialValue: WorkingCopy.Folders().folder(root))
133 }
134
135 var body: some View {
136 let name = (root as NSString).lastPathComponent
137 Section {
138 Toggle("Sync with Working Copy", isOn: Binding {
139 folder != nil
140 } set: { on in
141 save(on ? WorkingCopy.Folder(repository: name) : nil)
142 })
143 if let folder {
144 LabeledContent("Repository") {
145 TextField(name, text: Binding { folder.repository } set: { value in
146 save(WorkingCopy.Folder(repository: value.isEmpty ? name : value, syncOnOpen: folder.syncOnOpen))
147 })
148 .multilineTextAlignment(.trailing)
149 .textInputAutocapitalization(.never)
150 .autocorrectionDisabled()
151 }
152 Toggle("Sync when orgstar opens", isOn: Binding { folder.syncOnOpen } set: { on in
153 save(WorkingCopy.Folder(repository: folder.repository, syncOnOpen: on))
154 })
155 }
156 } header: {
157 Text(verbatim: name)
158 } footer: {
159 if folder != nil {
160 Text("Sync saves every file, then Working Copy commits every changed file in the repository, pulls and pushes. The repository is its name in Working Copy's list.")
161 } else if WorkingCopy.isRepository(root) {
162 Text("This folder is a git repository.")
163 }
164 }
165 }
166
167 private func save(_ new: WorkingCopy.Folder?) {
168 folder = new
169 WorkingCopy.Folders().set(new, for: root)
170 }
171}
172
173/// A folder's Working Copy settings on their own, from its menu in Folders.
174struct WorkingCopyFolderScreen: View {
175 let root: String
176 @Environment(\.dismiss) private var dismiss
177
178 var body: some View {
179 NavigationStack {
180 Form { WorkingCopyFolderSection(root: root) }
181 .navigationTitle("Working Copy")
182 .navigationBarTitleDisplayMode(.inline)
183 .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() } } }
184 }
185 }
186}
187#endif