Keep queued shared captures and unreadable configuration files !454
13 files changed, +365 −61
Layout: unified · split
Sources/OrgApp/AgendaViews.swift +3 −3
| @@ -251,11 +251,11 @@ public enum AgendaViewLoader { | ||
| 251 | 251 | guard let table = table(name: name, mode: mode) else { |
| 252 | 252 | throw SaveFailure(description: String(localized: "This view can't be saved from here; write it in views.toml.")) |
| 253 | 253 | } |
| 254 | var text = (try? String(contentsOf: userFile, encoding: .utf8)) ?? "" | |
| 255 | if !text.isEmpty { text += text.hasSuffix("\n") ? "\n" : "\n\n" } | |
| 256 | 254 | do { |
| 257 | 255 | try FileManager.default.createDirectory(at: userFile.deletingLastPathComponent(), withIntermediateDirectories: true) |
| 258 | try (text + table).write(to: userFile, atomically: true, encoding: .utf8) | |
| 256 | try UserFile.update(userFile) { text in | |
| 257 | text + (text.isEmpty ? "" : text.hasSuffix("\n") ? "\n" : "\n\n") + table | |
| 258 | } | |
| 259 | 259 | } catch { |
| 260 | 260 | throw SaveFailure(description: error.localizedDescription) |
| 261 | 261 | } |
Sources/OrgApp/CaptureInbox.swift +14 −4
| @@ -36,16 +36,26 @@ public struct CaptureInbox: Sendable { | ||
| 36 | 36 | try Data(link.utf8).write(to: folder.appendingPathComponent(name), options: .atomic) |
| 37 | 37 | } |
| 38 | 38 | |
| 39 | /// The waiting links, oldest first, each removed as it's taken. | |
| 40 | public func take() -> [String] { | |
| 39 | /// A waiting link and the file that holds it. | |
| 40 | public struct Link: Sendable, Hashable { | |
| 41 | public let file: URL | |
| 42 | public let text: String | |
| 43 | } | |
| 44 | ||
| 45 | /// The waiting links, oldest first. Each stays until `remove`; a file that can't be read | |
| 46 | /// is left out and kept. | |
| 47 | public func links() -> [Link] { | |
| 41 | 48 | let names = ((try? FileManager.default.contentsOfDirectory(atPath: folder.path)) ?? []).filter { $0.hasSuffix(".link") }.sorted() |
| 42 | 49 | return names.compactMap { name in |
| 43 | 50 | let file = folder.appendingPathComponent(name) |
| 44 | defer { try? FileManager.default.removeItem(at: file) } | |
| 45 | return (try? Data(contentsOf: file)).flatMap { String(data: $0, encoding: .utf8) } | |
| 51 | return (try? Data(contentsOf: file)).flatMap { String(data: $0, encoding: .utf8) }.map { Link(file: file, text: $0) } | |
| 46 | 52 | } |
| 47 | 53 | } |
| 48 | 54 | |
| 55 | public func remove(_ link: Link) { | |
| 56 | try? FileManager.default.removeItem(at: link.file) | |
| 57 | } | |
| 58 | ||
| 49 | 59 | public func setTemplates(_ templates: [Template]) throws { |
| 50 | 60 | try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) |
| 51 | 61 | try JSONEncoder().encode(templates).write(to: templatesFile, options: .atomic) |
Sources/OrgApp/ConfigSync.swift +41 −10
| @@ -24,6 +24,9 @@ public final class ConfigSync { | ||
| 24 | 24 | private let defaults: UserDefaults |
| 25 | 25 | @ObservationIgnored private var text: String? |
| 26 | 26 | @ObservationIgnored private var configProblems: [String] = [] |
| 27 | @ObservationIgnored private var themeProblems: [String] = [] | |
| 28 | /// Why the file couldn't be read or written, the last time a setting was to go into it. | |
| 29 | @ObservationIgnored private var fileProblem: String? | |
| 27 | 30 | @ObservationIgnored private var applying = false |
| 28 | 31 | @ObservationIgnored private var watcher: FSEventsWatcher? |
| 29 | 32 | @ObservationIgnored private var observer: NSObjectProtocol? |
| @@ -53,15 +56,11 @@ public final class ConfigSync { | ||
| 53 | 56 | if let text { |
| 54 | 57 | let migrated = UserConfig.usesLegacyNames(text) ? UserConfig.migratingLegacyNames(text) : text |
| 55 | 58 | let completed = UserConfig.addingMissingSections(migrated, from: defaults) |
| 56 | if completed != text { | |
| 57 | try? completed.write(to: target, atomically: true, encoding: .utf8) | |
| 58 | self.text = completed | |
| 59 | } | |
| 59 | if completed != text, write(completed) { self.text = completed } | |
| 60 | 60 | } |
| 61 | 61 | } else { |
| 62 | 62 | let template = UserConfig.template(from: defaults) |
| 63 | try? template.write(to: target, atomically: true, encoding: .utf8) | |
| 64 | text = template | |
| 63 | if write(template) { text = template } | |
| 65 | 64 | } |
| 66 | 65 | observer = NotificationCenter.default.addObserver(forName: UserDefaults.didChangeNotification, object: defaults, queue: .main) { [weak self] _ in |
| 67 | 66 | MainActor.assumeIsolated { self?.writeBack() } |
| @@ -105,6 +104,8 @@ public final class ConfigSync { | ||
| 105 | 104 | observer = nil |
| 106 | 105 | text = nil |
| 107 | 106 | configProblems = [] |
| 107 | themeProblems = [] | |
| 108 | fileProblem = nil | |
| 108 | 109 | self.url = url |
| 109 | 110 | start(watch: watches) |
| 110 | 111 | readTheme() |
| @@ -142,13 +143,40 @@ public final class ConfigSync { | ||
| 142 | 143 | in: url.deletingLastPathComponent() |
| 143 | 144 | ) else { return } |
| 144 | 145 | if read.theme != theme { theme = read.theme } |
| 145 | problems = configProblems + read.problems | |
| 146 | themeProblems = read.problems | |
| 147 | updateProblems() | |
| 148 | } | |
| 149 | ||
| 150 | private func updateProblems() { | |
| 151 | let all = (fileProblem.map { [$0] } ?? []) + configProblems + themeProblems | |
| 152 | if all != problems { problems = all } | |
| 153 | } | |
| 154 | ||
| 155 | /// Writes the file; false, with the reason among `problems`, when that fails. | |
| 156 | private func write(_ new: String) -> Bool { | |
| 157 | do { | |
| 158 | try new.write(to: target, atomically: true, encoding: .utf8) | |
| 159 | fileProblem = nil | |
| 160 | } catch { | |
| 161 | fileProblem = "\(url.lastPathComponent) wasn't written: \(error.localizedDescription)" | |
| 162 | } | |
| 163 | updateProblems() | |
| 164 | return fileProblem == nil | |
| 146 | 165 | } |
| 147 | 166 | |
| 148 | 167 | /// Writes settings that differ from the file into it. |
| 149 | 168 | func writeBack() { |
| 150 | 169 | // The file as it is now, so that tables written into it since, as by Emacs import, stay. |
| 151 | guard !applying, var current = (try? String(contentsOf: url, encoding: .utf8)) ?? text else { return } | |
| 170 | guard !applying else { return } | |
| 171 | let onDisk: String? | |
| 172 | do { | |
| 173 | onDisk = try UserFile.text(at: url) | |
| 174 | } catch { | |
| 175 | fileProblem = "\(url.lastPathComponent) wasn't changed: \(error.localizedDescription)" | |
| 176 | updateProblems() | |
| 177 | return | |
| 178 | } | |
| 179 | guard var current = onDisk ?? text else { return } | |
| 152 | 180 | let values = UserConfig.values(in: current) |
| 153 | 181 | let original = current |
| 154 | 182 | for setting in UserConfig.settings where defaults.object(forKey: setting.defaultsKey) != nil { |
| @@ -164,9 +192,12 @@ public final class ConfigSync { | ||
| 164 | 192 | for template in UserConfig.denoteTemplates(defaults) where values[UserConfig.path(UserConfig.denoteTemplateTable, template.key)] != .string(template.text) { |
| 165 | 193 | current = UserConfig.setting(current, section: UserConfig.denoteTemplateTable, key: template.key, to: .string(template.text)) |
| 166 | 194 | } |
| 167 | guard current != original else { return } | |
| 195 | guard current != original else { | |
| 196 | fileProblem = nil | |
| 197 | return updateProblems() | |
| 198 | } | |
| 199 | guard write(current) else { return } | |
| 168 | 200 | text = current |
| 169 | try? current.write(to: target, atomically: true, encoding: .utf8) | |
| 170 | 201 | // A theme picked in Settings; the watcher's reload sees the text unchanged and skips it. |
| 171 | 202 | readTheme() |
| 172 | 203 | } |
Sources/OrgApp/EmacsImport.swift +33 −11
| @@ -1134,7 +1134,8 @@ extension EmacsImport { | ||
| 1134 | 1134 | /// Applies `items`: settings to `defaults` (and so config.toml), folders to the workspace, |
| 1135 | 1135 | /// capture templates and key bindings appended to capture.toml and keymap.toml in |
| 1136 | 1136 | /// `directory`, leaving out templates whose key is there already and bindings that are |
| 1137 | /// there already. Returns a summary. | |
| 1137 | /// there already. A file that is there but can't be read is left as it is. Returns a summary, | |
| 1138 | /// which counts only what was written. | |
| 1138 | 1139 | @MainActor |
| 1139 | 1140 | /// With `writeConfig`, settings and structure templates are written into `config.toml` too, |
| 1140 | 1141 | /// for where nothing syncs user defaults into it (iOS). With `chosenFolders`, folders chosen in |
| @@ -1193,8 +1194,28 @@ extension EmacsImport { | ||
| 1193 | 1194 | } |
| 1194 | 1195 | } |
| 1195 | 1196 | try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) |
| 1197 | // Files that are there but can't be read; nothing is written to them. | |
| 1198 | var unreadable: Set<URL> = [] | |
| 1199 | func read(_ file: URL) -> String { | |
| 1200 | do { | |
| 1201 | return try UserFile.text(at: file) ?? "" | |
| 1202 | } catch { | |
| 1203 | if unreadable.insert(file).inserted { problems.append("\(file.lastPathComponent) wasn't changed: \(error.localizedDescription)") } | |
| 1204 | return "" | |
| 1205 | } | |
| 1206 | } | |
| 1207 | func write(_ text: String, to file: URL) -> Bool { | |
| 1208 | guard !unreadable.contains(file) else { return false } | |
| 1209 | do { | |
| 1210 | try text.write(to: file, atomically: true, encoding: .utf8) | |
| 1211 | return true | |
| 1212 | } catch { | |
| 1213 | problems.append("\(file.lastPathComponent) wasn't written: \(error.localizedDescription)") | |
| 1214 | return false | |
| 1215 | } | |
| 1216 | } | |
| 1196 | 1217 | let captureFile = directory.appendingPathComponent("capture.toml") |
| 1197 | var capture = (try? String(contentsOf: captureFile, encoding: .utf8)) ?? "" | |
| 1218 | var capture = read(captureFile) | |
| 1198 | 1219 | let existingKeys = Set((try? TOML.parse(capture))?.compactMap { $0.values["key"]?.string } ?? []) |
| 1199 | 1220 | var addedCapture = "" |
| 1200 | 1221 | for item in items { |
| @@ -1204,10 +1225,10 @@ extension EmacsImport { | ||
| 1204 | 1225 | } |
| 1205 | 1226 | if !addedCapture.isEmpty { |
| 1206 | 1227 | capture += (capture.isEmpty ? "# Capture templates. Imported from Emacs.\n" : "\n# Imported from Emacs.\n") + addedCapture |
| 1207 | try? capture.write(to: captureFile, atomically: true, encoding: .utf8) | |
| 1228 | if !write(capture, to: captureFile) { templates = 0 } | |
| 1208 | 1229 | } |
| 1209 | 1230 | let viewsFile = directory.appendingPathComponent("views.toml") |
| 1210 | var viewsText = (try? String(contentsOf: viewsFile, encoding: .utf8)) ?? "" | |
| 1231 | var viewsText = read(viewsFile) | |
| 1211 | 1232 | var viewNames = Set((try? TOML.parse(viewsText))?.filter { $0.name == "view" }.compactMap { $0.values["name"]?.string } ?? []) |
| 1212 | 1233 | var addedViews = "" |
| 1213 | 1234 | for item in items { |
| @@ -1217,10 +1238,10 @@ extension EmacsImport { | ||
| 1217 | 1238 | } |
| 1218 | 1239 | if !addedViews.isEmpty { |
| 1219 | 1240 | viewsText += (viewsText.isEmpty ? "# Agenda views. Imported from Emacs.\n" : "\n# Imported from Emacs.\n") + addedViews |
| 1220 | try? viewsText.write(to: viewsFile, atomically: true, encoding: .utf8) | |
| 1241 | if !write(viewsText, to: viewsFile) { views = 0 } | |
| 1221 | 1242 | } |
| 1222 | 1243 | let configFile = directory.appendingPathComponent("config.toml") |
| 1223 | var config = (try? String(contentsOf: configFile, encoding: .utf8)) ?? "" | |
| 1244 | var config = read(configFile) | |
| 1224 | 1245 | var projectNames = Set((try? TOML.parse(config))?.filter { $0.name == "publish" }.compactMap { $0.values["name"]?.string } ?? []) |
| 1225 | 1246 | var addedProjects = "" |
| 1226 | 1247 | for item in items { |
| @@ -1230,10 +1251,10 @@ extension EmacsImport { | ||
| 1230 | 1251 | } |
| 1231 | 1252 | if !addedProjects.isEmpty { |
| 1232 | 1253 | config += (config.isEmpty || config.hasSuffix("\n") ? "" : "\n") + "\n# Publishing projects. Imported from Emacs.\n" + addedProjects |
| 1233 | try? config.write(to: configFile, atomically: true, encoding: .utf8) | |
| 1254 | if !write(config, to: configFile) { projects = 0 } | |
| 1234 | 1255 | } |
| 1235 | 1256 | let keymapFile = directory.appendingPathComponent("keymap.toml") |
| 1236 | var keymap = (try? String(contentsOf: keymapFile, encoding: .utf8)) ?? "" | |
| 1257 | var keymap = read(keymapFile) | |
| 1237 | 1258 | func binding(_ keys: String?, _ command: String?, _ mode: String?) -> String { [keys ?? "", command ?? "", mode ?? ""].joined(separator: "\u{0}") } |
| 1238 | 1259 | var existingBindings = Set((try? TOML.parse(keymap))?.filter { $0.name == "bind" && $0.values["when"] == nil } |
| 1239 | 1260 | .map { binding($0.values["keys"]?.string, $0.values["command"]?.string, $0.values["mode"]?.string) } ?? []) |
| @@ -1247,7 +1268,7 @@ extension EmacsImport { | ||
| 1247 | 1268 | } |
| 1248 | 1269 | if !addedKeys.isEmpty { |
| 1249 | 1270 | keymap += (keymap.isEmpty ? "" : "\n") + "# Imported from Emacs.\n" + addedKeys |
| 1250 | try? keymap.write(to: keymapFile, atomically: true, encoding: .utf8) | |
| 1271 | if !write(keymap, to: keymapFile) { bindings = 0 } | |
| 1251 | 1272 | } |
| 1252 | 1273 | // Into user defaults, from where ConfigSync writes them into config.toml. |
| 1253 | 1274 | var rows = UserConfig.structureTemplates(defaults) |
| @@ -1267,7 +1288,7 @@ extension EmacsImport { | ||
| 1267 | 1288 | } |
| 1268 | 1289 | if noteTemplates > 0 { UserConfig.setDenoteTemplates(notes, in: defaults) } |
| 1269 | 1290 | if writeConfig, settings + blocks + noteTemplates > 0 { |
| 1270 | var text = (try? String(contentsOf: configFile, encoding: .utf8)) ?? "" | |
| 1291 | var text = read(configFile) | |
| 1271 | 1292 | for setting in stored { |
| 1272 | 1293 | text = UserConfig.setting(text, section: setting.section, key: setting.key, to: UserConfig.value(setting, in: defaults)) |
| 1273 | 1294 | } |
| @@ -1279,7 +1300,8 @@ extension EmacsImport { | ||
| 1279 | 1300 | guard case .denoteTemplate(let key, let template) = item.change else { continue } |
| 1280 | 1301 | text = UserConfig.setting(text, section: UserConfig.denoteTemplateTable, key: key, to: .string(template)) |
| 1281 | 1302 | } |
| 1282 | try? text.write(to: configFile, atomically: true, encoding: .utf8) | |
| 1303 | // Here config.toml holds the settings, so one that isn't in it wasn't imported. | |
| 1304 | if !write(text, to: configFile) { (settings, blocks, noteTemplates) = (0, 0, 0) } | |
| 1283 | 1305 | } |
| 1284 | 1306 | func count(_ n: Int, _ word: String) -> String? { n == 0 ? nil : "\(n) \(word)\(n == 1 ? "" : "s")" } |
| 1285 | 1307 | let done = [count(settings, "setting"), count(folders, "folder"), count(templates, "capture template"), count(bindings, "key binding"), |
Sources/OrgApp/UserFile.swift added +30
| @@ -0,0 +1,30 @@ | ||
| 1 | import Foundation | |
| 2 | ||
| 3 | /// Reading a configuration file in order to change it: only a file that isn't there counts as | |
| 4 | /// empty, so that one that can't be read is never written over. | |
| 5 | public enum UserFile { | |
| 6 | /// The file's text, or nil when there is no such file. Any other failure is thrown. | |
| 7 | public static func text(at url: URL) throws -> String? { | |
| 8 | do { | |
| 9 | return try String(contentsOf: url, encoding: .utf8) | |
| 10 | } catch CocoaError.fileReadNoSuchFile, CocoaError.fileNoSuchFile { | |
| 11 | return nil | |
| 12 | } | |
| 13 | } | |
| 14 | ||
| 15 | /// Writes what `change` makes of the file's text, "" when there is no such file. Throws, | |
| 16 | /// leaving the file alone, when it can't be read. With `coordinated`, in coordination with | |
| 17 | /// the app that syncs the file. | |
| 18 | public static func update(_ url: URL, coordinated: Bool = false, _ change: (String) -> String) throws { | |
| 19 | func write(_ url: URL) throws { | |
| 20 | try change(text(at: url) ?? "").write(to: url, atomically: true, encoding: .utf8) | |
| 21 | } | |
| 22 | guard coordinated else { return try write(url) } | |
| 23 | var coordination: NSError? | |
| 24 | var failure: Error? | |
| 25 | NSFileCoordinator(filePresenter: nil).coordinate(writingItemAt: url, options: [], error: &coordination) { url in | |
| 26 | do { try write(url) } catch { failure = error } | |
| 27 | } | |
| 28 | if let error = coordination ?? failure { throw error } | |
| 29 | } | |
| 30 | } | |
Sources/Orgstar/ClockViews.swift +5 −1
| @@ -259,6 +259,10 @@ struct ClockReportView: View { | ||
| 259 | 259 | let panel = NSSavePanel() |
| 260 | 260 | panel.nameFieldStringValue = "time-report.org" |
| 261 | 261 | guard panel.runModal() == .OK, let url = panel.url else { return } |
| 262 | try? report.write(to: url, atomically: true, encoding: .utf8) | |
| 262 | do { | |
| 263 | try report.write(to: url, atomically: true, encoding: .utf8) | |
| 264 | } catch { | |
| 265 | NSAlert(error: error).runModal() | |
| 266 | } | |
| 263 | 267 | } |
| 264 | 268 | } |
Sources/OrgstarMobile/MobileModel.swift +33 −18
| @@ -108,16 +108,17 @@ final class MobileModel { | ||
| 108 | 108 | |
| 109 | 109 | /// Chooses the configuration folder, or with nil stops using one; its settings apply now. |
| 110 | 110 | func setConfigFolder(_ url: URL?) { |
| 111 | var problem: String? | |
| 111 | 112 | if let url { |
| 112 | 113 | ConfigFolder.set(url) |
| 113 | Self.createConfig(in: url) | |
| 114 | problem = Self.createConfig(in: url) | |
| 114 | 115 | } else { |
| 115 | 116 | ConfigFolder.clear() |
| 116 | 117 | // What the folder set no longer applies. |
| 117 | 118 | for setting in UserConfig.settings { UserDefaults.standard.removeObject(forKey: setting.defaultsKey) } |
| 118 | 119 | } |
| 119 | 120 | configFolder = url |
| 120 | reloadConfig() | |
| 121 | _ = reloadConfig(after: problem) | |
| 121 | 122 | watchConfig() |
| 122 | 123 | } |
| 123 | 124 | |
| @@ -168,27 +169,38 @@ final class MobileModel { | ||
| 168 | 169 | configFolder.flatMap { Self.read($0.appendingPathComponent("config.toml")) } |
| 169 | 170 | } |
| 170 | 171 | |
| 171 | /// Writes the folder's `config.toml` and applies it. | |
| 172 | func saveConfig(_ text: String) { | |
| 173 | guard let configFolder else { return } | |
| 174 | var error: NSError? | |
| 175 | NSFileCoordinator(filePresenter: nil).coordinate(writingItemAt: configFolder.appendingPathComponent("config.toml"), options: [], error: &error) { url in | |
| 176 | try? text.write(to: url, atomically: true, encoding: .utf8) | |
| 172 | /// Writes the folder's `config.toml` and applies it. False, with the reason first in | |
| 173 | /// `configProblems`, when the file can't be written or what it holds can't be read. | |
| 174 | @discardableResult | |
| 175 | func saveConfig(_ text: String) -> Bool { | |
| 176 | guard let configFolder else { return false } | |
| 177 | return reloadConfig(after: Self.updateConfig(in: configFolder) { _ in text }) | |
| 178 | } | |
| 179 | ||
| 180 | /// Changes the folder's `config.toml`; returns the problem when it can't be read or written. | |
| 181 | private static func updateConfig(in folder: URL, _ change: (String) -> String) -> String? { | |
| 182 | do { | |
| 183 | try UserFile.update(folder.appendingPathComponent("config.toml"), coordinated: true, change) | |
| 184 | return nil | |
| 185 | } catch { | |
| 186 | return "config.toml wasn't changed: \(error.localizedDescription)" | |
| 177 | 187 | } |
| 188 | } | |
| 189 | ||
| 190 | /// Applies the folder's settings, with the `problem` of the write before it first. | |
| 191 | private func reloadConfig(after problem: String?) -> Bool { | |
| 178 | 192 | reloadConfig() |
| 193 | if let problem { configProblems.insert(problem, at: 0) } | |
| 194 | return problem == nil | |
| 179 | 195 | } |
| 180 | 196 | |
| 181 | 197 | /// Changes a setting from the app: in the folder's config.toml when there is a folder, as |
| 182 | 198 | /// the Mac's Settings write it, else in this device's settings. |
| 183 | 199 | func set(_ defaultsKey: String, to value: TOML.Value) { |
| 184 | 200 | guard let setting = UserConfig.settings.first(where: { $0.defaultsKey == defaultsKey }) else { return } |
| 201 | var problem: String? | |
| 185 | 202 | if let configFolder { |
| 186 | let file = configFolder.appendingPathComponent("config.toml") | |
| 187 | var error: NSError? | |
| 188 | NSFileCoordinator(filePresenter: nil).coordinate(writingItemAt: file, options: [], error: &error) { url in | |
| 189 | let text = (try? String(contentsOf: url, encoding: .utf8)) ?? "" | |
| 190 | try? UserConfig.setting(text, section: setting.section, key: setting.key, to: value).write(to: url, atomically: true, encoding: .utf8) | |
| 191 | } | |
| 203 | problem = Self.updateConfig(in: configFolder) { UserConfig.setting($0, section: setting.section, key: setting.key, to: value) } | |
| 192 | 204 | } else { |
| 193 | 205 | switch value { |
| 194 | 206 | case .bool(let b): UserDefaults.standard.set(b, forKey: defaultsKey) |
| @@ -196,7 +208,7 @@ final class MobileModel { | ||
| 196 | 208 | case .integer(let i): UserDefaults.standard.set(i, forKey: defaultsKey) |
| 197 | 209 | } |
| 198 | 210 | } |
| 199 | reloadConfig() | |
| 211 | _ = reloadConfig(after: problem) | |
| 200 | 212 | } |
| 201 | 213 | |
| 202 | 214 | /// The capture templates, for the share extension to offer. |
| @@ -218,14 +230,17 @@ final class MobileModel { | ||
| 218 | 230 | |
| 219 | 231 | /// Applies the folder's `config.toml` to the settings; returns its problems and the theme's |
| 220 | 232 | /// colors. |
| 221 | /// Writes `config.toml` with every setting at its default when the folder has none. | |
| 222 | private static func createConfig(in folder: URL) { | |
| 233 | /// Writes `config.toml` with every setting at its default when the folder has none; returns | |
| 234 | /// the problem when it can't be written. | |
| 235 | private static func createConfig(in folder: URL) -> String? { | |
| 223 | 236 | let file = folder.appendingPathComponent("config.toml") |
| 224 | 237 | var error: NSError? |
| 238 | var failure: Error? | |
| 225 | 239 | NSFileCoordinator(filePresenter: nil).coordinate(writingItemAt: file, options: [], error: &error) { url in |
| 226 | 240 | guard !FileManager.default.fileExists(atPath: url.path) else { return } |
| 227 | try? UserConfig.defaultTemplate.write(to: url, atomically: true, encoding: .utf8) | |
| 241 | do { try UserConfig.defaultTemplate.write(to: url, atomically: true, encoding: .utf8) } catch { failure = error } | |
| 228 | 242 | } |
| 243 | return (error ?? failure).map { "config.toml wasn't created: \($0.localizedDescription)" } | |
| 229 | 244 | } |
| 230 | 245 | |
| 231 | 246 | private static func readConfig(_ folder: URL?) -> ([String], ThemeSpec) { |
Sources/OrgstarMobile/OrgstarMobileApp.swift +27 −6
| @@ -120,8 +120,9 @@ struct RootView: View { | ||
| 120 | 120 | let workspace: WorkspaceModel |
| 121 | 121 | let agenda: AgendaModel |
| 122 | 122 | @State private var capture: CaptureRequest? |
| 123 | /// Captures from the share extension after the one showing. | |
| 124 | @State private var waiting: [CaptureRequest] = [] | |
| 123 | /// The share extension's link whose capture sheet is showing, with its request's id. The link | |
| 124 | /// stays in the inbox until the sheet is dismissed. | |
| 125 | @State private var shared: (link: CaptureInbox.Link, request: UUID)? | |
| 125 | 126 | /// Files from the share extension, waiting for the entry to attach them to. |
| 126 | 127 | @State private var sharedFiles: SharedFiles? |
| 127 | 128 | @State private var tab = AppTab.agenda |
| @@ -290,7 +291,11 @@ struct RootView: View { | ||
| 290 | 291 | capture = request |
| 291 | 292 | } |
| 292 | 293 | |
| 293 | .sheet(item: $capture, onDismiss: showWaiting) { request in | |
| 294 | // Another capture took the sheet from a shared one, which stays in the inbox for later. | |
| 295 | .onChange(of: capture?.id) { _, id in | |
| 296 | if let id, id != shared?.request { shared = nil } | |
| 297 | } | |
| 298 | .sheet(item: $capture, onDismiss: captureDismissed) { request in | |
| 294 | 299 | CaptureScreen(workspace: workspace, session: session, request: request) |
| 295 | 300 | } |
| 296 | 301 | .sheet(item: $sharedFiles) { shared in |
| @@ -371,13 +376,29 @@ struct RootView: View { | ||
| 371 | 376 | |
| 372 | 377 | /// What the share extension left, one capture sheet at a time. |
| 373 | 378 | private func takeShared() { |
| 374 | waiting += (model.inbox?.take() ?? []).compactMap(CaptureRequest.init(link:)) | |
| 375 | if capture == nil { showWaiting() } | |
| 379 | showWaiting() | |
| 376 | 380 | if sharedFiles == nil, let batch = AttachmentInbox()?.batches().first { sharedFiles = SharedFiles(batch: batch) } |
| 377 | 381 | } |
| 378 | 382 | |
| 383 | /// The inbox's oldest capture, unless a capture sheet is showing or being dismissed. | |
| 379 | 384 | private func showWaiting() { |
| 380 | if !waiting.isEmpty { capture = waiting.removeFirst() } | |
| 385 | guard capture == nil, shared == nil, let inbox = model.inbox else { return } | |
| 386 | for link in inbox.links() { | |
| 387 | guard let request = CaptureRequest(link: link.text) else { | |
| 388 | inbox.remove(link) | |
| 389 | continue | |
| 390 | } | |
| 391 | shared = (link, request.id) | |
| 392 | capture = request | |
| 393 | return | |
| 394 | } | |
| 395 | } | |
| 396 | ||
| 397 | /// The shared capture was saved or discarded, so its link goes; then the next one shows. | |
| 398 | private func captureDismissed() { | |
| 399 | if let shared { model.inbox?.remove(shared.link) } | |
| 400 | shared = nil | |
| 401 | showWaiting() | |
| 381 | 402 | } |
| 382 | 403 | |
| 383 | 404 | /// A widget's or the Live Activity's link. |
Sources/OrgstarMobile/SettingsScreen.swift +1 −2
| @@ -362,8 +362,7 @@ struct ConfigFileEditor: View { | ||
| 362 | 362 | |
| 363 | 363 | private func save() { |
| 364 | 364 | guard text != saved else { return } |
| 365 | model.saveConfig(text) | |
| 366 | saved = text | |
| 365 | if model.saveConfig(text) { saved = text } | |
| 367 | 366 | } |
| 368 | 367 | } |
| 369 | 368 | |
Tests/OrgAppTests/CaptureInboxTests.swift +23 −4
| @@ -5,14 +5,33 @@ import Testing | ||
| 5 | 5 | @testable import OrgApp |
| 6 | 6 | |
| 7 | 7 | struct CaptureInboxTests { |
| 8 | @Test func takesLinksOldestFirstOnce() throws { | |
| 8 | @Test func keepsLinksOldestFirstUntilRemoved() throws { | |
| 9 | 9 | let folder = try Folder() |
| 10 | 10 | let inbox = CaptureInbox(folder: folder.url.appendingPathComponent("Captures")) |
| 11 | #expect(inbox.take() == []) | |
| 11 | #expect(inbox.links() == []) | |
| 12 | 12 | try inbox.add("org-protocol://capture?body=one") |
| 13 | 13 | try inbox.add("org-protocol://capture?body=two") |
| 14 | #expect(inbox.take() == ["org-protocol://capture?body=one", "org-protocol://capture?body=two"]) | |
| 15 | #expect(inbox.take() == []) | |
| 14 | let links = inbox.links() | |
| 15 | #expect(links.map(\.text) == ["org-protocol://capture?body=one", "org-protocol://capture?body=two"]) | |
| 16 | // Another instance, as after the app was ended with both queued. | |
| 17 | #expect(CaptureInbox(folder: inbox.folder).links() == links) | |
| 18 | inbox.remove(links[0]) | |
| 19 | #expect(inbox.links().map(\.text) == ["org-protocol://capture?body=two"]) | |
| 20 | inbox.remove(links[1]) | |
| 21 | #expect(inbox.links() == []) | |
| 22 | } | |
| 23 | ||
| 24 | @Test func keepsALinkItCannotRead() throws { | |
| 25 | let folder = try Folder() | |
| 26 | let inbox = CaptureInbox(folder: folder.url.appendingPathComponent("Captures")) | |
| 27 | try inbox.add("org-protocol://capture?body=one") | |
| 28 | let notText = inbox.folder.appendingPathComponent("0-not-text.link") | |
| 29 | try Data([0xFF, 0xFE, 0xFD]).write(to: notText) | |
| 30 | let directory = inbox.folder.appendingPathComponent("1-directory.link") | |
| 31 | try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) | |
| 32 | #expect(inbox.links().map(\.text) == ["org-protocol://capture?body=one"]) | |
| 33 | #expect(FileManager.default.fileExists(atPath: notText.path)) | |
| 34 | #expect(FileManager.default.fileExists(atPath: directory.path)) | |
| 16 | 35 | } |
| 17 | 36 | |
| 18 | 37 | @Test func keepsTheTemplateList() throws { |
Tests/OrgAppTests/UserFileTests.swift added +153
| @@ -0,0 +1,153 @@ | ||
| 1 | import Foundation | |
| 2 | import OrgCore | |
| 3 | import Testing | |
| 4 | @testable import OrgApp | |
| 5 | ||
| 6 | /// Bytes that aren't UTF-8: a file that is there and can't be read as text. | |
| 7 | private let notText = Data([0xFF, 0xFE, 0xFD]) | |
| 8 | ||
| 9 | private func item(_ change: EmacsImport.Change) -> EmacsImport.Item { | |
| 10 | EmacsImport.Item(id: 0, name: "", summary: "", source: "config.el:1", change: change) | |
| 11 | } | |
| 12 | ||
| 13 | private func defaults() -> UserDefaults { | |
| 14 | let name = "orgstar-userfile-\(UUID().uuidString)" | |
| 15 | let defaults = UserDefaults(suiteName: name)! | |
| 16 | defaults.removePersistentDomain(forName: name) | |
| 17 | return defaults | |
| 18 | } | |
| 19 | ||
| 20 | /// Takes or gives back the folder's write permission, so that writes into it fail. | |
| 21 | private func setWritable(_ writable: Bool, _ folder: URL) { | |
| 22 | try? FileManager.default.setAttributes([.posixPermissions: writable ? 0o755 : 0o555], ofItemAtPath: folder.path) | |
| 23 | } | |
| 24 | ||
| 25 | struct UserFileTests { | |
| 26 | @Test func onlyAMissingFileIsEmpty() throws { | |
| 27 | let folder = try Folder() | |
| 28 | let file = folder.url.appendingPathComponent("config.toml") | |
| 29 | #expect(try UserFile.text(at: file) == nil) | |
| 30 | try "a = 1\n".write(to: file, atomically: true, encoding: .utf8) | |
| 31 | #expect(try UserFile.text(at: file) == "a = 1\n") | |
| 32 | try notText.write(to: file) | |
| 33 | #expect(throws: (any Error).self) { try UserFile.text(at: file) } | |
| 34 | try FileManager.default.removeItem(at: file) | |
| 35 | try FileManager.default.createDirectory(at: file, withIntermediateDirectories: true) | |
| 36 | #expect(throws: (any Error).self) { try UserFile.text(at: file) } | |
| 37 | } | |
| 38 | ||
| 39 | @Test(arguments: [false, true]) func updateLeavesAFileItCannotRead(coordinated: Bool) throws { | |
| 40 | let folder = try Folder() | |
| 41 | let file = folder.url.appendingPathComponent("config.toml") | |
| 42 | try UserFile.update(file, coordinated: coordinated) { $0 + "a = 1\n" } | |
| 43 | try UserFile.update(file, coordinated: coordinated) { $0 + "b = 2\n" } | |
| 44 | #expect(try String(contentsOf: file, encoding: .utf8) == "a = 1\nb = 2\n") | |
| 45 | try notText.write(to: file) | |
| 46 | #expect(throws: (any Error).self) { try UserFile.update(file, coordinated: coordinated) { $0 + "c = 3\n" } } | |
| 47 | #expect(try Data(contentsOf: file) == notText) | |
| 48 | } | |
| 49 | ||
| 50 | @Test(arguments: [false, true]) func updateReportsAFailedWrite(coordinated: Bool) throws { | |
| 51 | let folder = try Folder() | |
| 52 | let file = folder.url.appendingPathComponent("config.toml") | |
| 53 | setWritable(false, folder.url) | |
| 54 | defer { setWritable(true, folder.url) } | |
| 55 | #expect(throws: (any Error).self) { try UserFile.update(file, coordinated: coordinated) { $0 + "a = 1\n" } } | |
| 56 | #expect(!FileManager.default.fileExists(atPath: file.path)) | |
| 57 | } | |
| 58 | ||
| 59 | @MainActor | |
| 60 | @Test func savingAViewLeavesAFileItCannotRead() throws { | |
| 61 | let folder = try Folder() | |
| 62 | let file = folder.url.appendingPathComponent("views.toml") | |
| 63 | try notText.write(to: file) | |
| 64 | #expect(throws: AgendaViewLoader.SaveFailure.self) { try AgendaViewLoader.save(name: "Work", mode: .match("+work", todoOnly: false), userFile: file) } | |
| 65 | #expect(try Data(contentsOf: file) == notText) | |
| 66 | } | |
| 67 | } | |
| 68 | ||
| 69 | @MainActor | |
| 70 | struct EmacsImportFileTests { | |
| 71 | private let items = [ | |
| 72 | item(.capture(key: "x", toml: "[[template]]\nkey = \"x\"\nfile = \"x.org\"\ntemplate = \"* %?\"\n")), | |
| 73 | item(.view(name: "Work", toml: "[[view]]\nname = \"Work\"\ntype = \"match\"\nmatch = \"+work\"\n")), | |
| 74 | item(.binding(keys: "C-c z", command: "app.agenda", mode: nil)), | |
| 75 | item(.setting(key: "fill-column", value: .integer(64))), | |
| 76 | ] | |
| 77 | ||
| 78 | @Test func leavesFilesItCannotReadAndDoesNotCountThem() async throws { | |
| 79 | let folder = try Folder() | |
| 80 | let names = ["capture.toml", "views.toml", "keymap.toml", "config.toml"] | |
| 81 | for name in names { try notText.write(to: folder.url.appendingPathComponent(name)) } | |
| 82 | let summary = await EmacsImport.apply(items, defaults: defaults(), workspace: nil, directory: folder.url, writeConfig: true) | |
| 83 | for name in names { | |
| 84 | #expect(try Data(contentsOf: folder.url.appendingPathComponent(name)) == notText) | |
| 85 | #expect(summary.components(separatedBy: "\(name) wasn't changed: ").count == 2, "\(summary)") | |
| 86 | } | |
| 87 | #expect(summary.hasPrefix("Nothing new to import. "), "\(summary)") | |
| 88 | } | |
| 89 | ||
| 90 | @Test func oneUnreadableFileDoesNotStopTheOthers() async throws { | |
| 91 | let folder = try Folder() | |
| 92 | try notText.write(to: folder.url.appendingPathComponent("capture.toml")) | |
| 93 | let summary = await EmacsImport.apply(items, defaults: defaults(), workspace: nil, directory: folder.url) | |
| 94 | #expect(summary.hasPrefix("Imported 1 setting, 1 key binding, 1 agenda view. capture.toml wasn't changed: "), "\(summary)") | |
| 95 | #expect(try Data(contentsOf: folder.url.appendingPathComponent("capture.toml")) == notText) | |
| 96 | #expect(try String(contentsOf: folder.url.appendingPathComponent("views.toml"), encoding: .utf8).contains("name = \"Work\"")) | |
| 97 | } | |
| 98 | ||
| 99 | @Test func reportsFailedWritesAndDoesNotCountThem() async throws { | |
| 100 | let folder = try Folder() | |
| 101 | setWritable(false, folder.url) | |
| 102 | defer { setWritable(true, folder.url) } | |
| 103 | let summary = await EmacsImport.apply(items, defaults: defaults(), workspace: nil, directory: folder.url, writeConfig: true) | |
| 104 | #expect(summary.hasPrefix("Nothing new to import. "), "\(summary)") | |
| 105 | for name in ["capture.toml", "views.toml", "keymap.toml", "config.toml"] { | |
| 106 | #expect(summary.contains("\(name) wasn't written: "), "\(summary)") | |
| 107 | } | |
| 108 | } | |
| 109 | } | |
| 110 | ||
| 111 | @MainActor | |
| 112 | struct ConfigSyncFileTests { | |
| 113 | @Test func leavesAFileItCannotReadAndReportsIt() throws { | |
| 114 | let folder = try Folder() | |
| 115 | let url = folder.url.appendingPathComponent("config.toml") | |
| 116 | try notText.write(to: url) | |
| 117 | let store = defaults() | |
| 118 | let sync = ConfigSync(url: url, defaults: store) | |
| 119 | sync.start(watch: false) | |
| 120 | store.set(64, forKey: "fillColumn") | |
| 121 | sync.writeBack() | |
| 122 | #expect(try Data(contentsOf: url) == notText) | |
| 123 | #expect(sync.problems.first?.hasPrefix("config.toml wasn't changed: ") == true, "\(sync.problems)") | |
| 124 | } | |
| 125 | ||
| 126 | @Test func reportsAFailedWriteUntilOneWorks() throws { | |
| 127 | let folder = try Folder() | |
| 128 | let url = folder.url.appendingPathComponent("config.toml") | |
| 129 | let store = defaults() | |
| 130 | let sync = ConfigSync(url: url, defaults: store) | |
| 131 | sync.start(watch: false) | |
| 132 | let written = try String(contentsOf: url, encoding: .utf8) | |
| 133 | setWritable(false, folder.url) | |
| 134 | defer { setWritable(true, folder.url) } | |
| 135 | store.set(64, forKey: "fillColumn") | |
| 136 | sync.writeBack() | |
| 137 | #expect(try String(contentsOf: url, encoding: .utf8) == written) | |
| 138 | #expect(sync.problems.first?.hasPrefix("config.toml wasn't written: ") == true, "\(sync.problems)") | |
| 139 | setWritable(true, folder.url) | |
| 140 | sync.writeBack() | |
| 141 | #expect(try String(contentsOf: url, encoding: .utf8).contains("fill-column = 64")) | |
| 142 | #expect(!sync.problems.contains { $0.contains("wasn't written") }) | |
| 143 | } | |
| 144 | ||
| 145 | @Test func reportsAFileItCannotCreate() throws { | |
| 146 | let folder = try Folder() | |
| 147 | let sync = ConfigSync(url: folder.url.appendingPathComponent("config.toml"), defaults: defaults()) | |
| 148 | setWritable(false, folder.url) | |
| 149 | defer { setWritable(true, folder.url) } | |
| 150 | sync.start(watch: false) | |
| 151 | #expect(sync.problems.first?.hasPrefix("config.toml wasn't written: ") == true, "\(sync.problems)") | |
| 152 | } | |
| 153 | } | |
docs/manual/guide/08-capture.org +1 −1
| @@ -353,7 +353,7 @@ In another app, share a web page or text and choose orgstar. The share form has: | ||
| 353 | 353 | - for a link, its title (editable) and address; |
| 354 | 354 | - a Text field, filled with shared text. |
| 355 | 355 | |
| 356 | Capture saves the item in the app group's capture inbox. The next time you open orgstar, it opens the capture sheet with the item as an org-protocol capture: the link becomes =%a= and =%:link=, the title =%:description=, and the text =%i=. Several waiting items open one after another, oldest first. If the extension says orgstar's shared folder isn't available, the app group is missing from the build and nothing can be saved. | |
| 356 | Capture saves the item in the app group's capture inbox. The next time you open orgstar, it opens the capture sheet with the item as an org-protocol capture: the link becomes =%a= and =%:link=, the title =%:description=, and the text =%i=. Several waiting items open one after another, oldest first. An item stays in the inbox until its sheet is saved or cancelled, so items still waiting when orgstar is ended open the next time. If the extension says orgstar's shared folder isn't available, the app group is missing from the build and nothing can be saved. | |
| 357 | 357 | |
| 358 | 358 | The share form lists no templates until orgstar has run once with your configuration folder; the capture sheet then starts on the first template. |
| 359 | 359 | |
docs/manual/guide/13-configuration.org +1 −1
| @@ -23,7 +23,7 @@ The folder holds these files: | ||
| 23 | 23 | | =views.toml= | Saved agenda views | No | |
| 24 | 24 | | =default-theme.toml= | The default theme's colors, for reference | Yes, at every launch | |
| 25 | 25 | |
| 26 | =config.toml= is the source of truth. The Settings window writes each change into it, keeping your comments and the order of lines, and edits you make to the file apply while orgstar runs. If the file doesn't exist at launch, orgstar creates it with every setting at its current value and a comment after each one. | |
| 26 | =config.toml= is the source of truth. The Settings window writes each change into it, keeping your comments and the order of lines, and edits you make to the file apply while orgstar runs. If the file doesn't exist at launch, orgstar creates it with every setting at its current value and a comment after each one. A file that is there but can't be read, such as one that isn't UTF-8, is left as it is: the change isn't written and a message says why, as it does when a write fails. Import from Emacs and saving an agenda view treat =capture.toml=, =views.toml= and =keymap.toml= the same way. | |
| 27 | 27 | |
| 28 | 28 | When you add the folder to a dotfiles repository, keep =default-theme.toml= out of it or ignore its changes: orgstar rewrites it whenever its contents differ from the built-in theme. |
| 29 | 29 | |