Commit f27a6bd93c

f27a6bd93cdfe2371b72cd290a487149eec8acd4

parent: 777d40b51d

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-21 08:45 UTC

Share the publishing exporter, keep publishing folders as bookmarks, idle time from background time

Layout: unified · split

Sources/OrgApp/AppStoreCommands.swift +7 −1
@@ -1,7 +1,8 @@
1import Foundation 1import Foundation
2 2
3/// The commands the Mac App Store build leaves out of the palette and menus: exports that run 3/// The commands the Mac App Store build leaves out of the palette and menus: exports that run
4/// Emacs, and attaching by link, which the sandbox doesn't allow. 4/// Emacs, and attaching by link, which the sandbox doesn't allow. The iOS app refuses those
5/// with nothing in their place too.
5public enum AppStoreCommands { 6public enum AppStoreCommands {
6 public static let hidden: Set<String> = [ 7 public static let hidden: Set<String> = [
7 "app.export.pdf", 8 "app.export.pdf",
@@ -12,4 +13,9 @@ public enum AppStoreCommands {
12 public static func replacement(for id: String) -> String? { 13 public static func replacement(for id: String) -> String? {
13 id == "app.export.pdf" ? "app.export.print-pdf" : nil 14 id == "app.export.pdf" ? "app.export.print-pdf" : nil
14 } 15 }
16
17 /// A hidden command with nothing in its place.
18 public static func unavailable(_ id: String) -> Bool {
19 hidden.contains(id) && replacement(for: id) == nil
20 }
15} 21}
Sources/OrgApp/ClockModel.swift +9
@@ -567,6 +567,15 @@ public final class ClockModel {
567 ) 567 )
568 } 568 }
569 569
570 /// Where iOS has no idle time: since when the user was away, for `resolveIdle`, when the
571 /// app was in the background from `backgrounded` to `now` with `running` going for more
572 /// than `idleMinutes` of that time (`org-clock-idle-time`, 0 for never).
573 public nonisolated static func idleSince(backgrounded: Date, now: Date, running: Running?, idleMinutes: Int) -> Date? {
574 guard idleMinutes > 0, let running else { return nil }
575 let since = max(backgrounded, running.startedAt)
576 return now.timeIntervalSince(since) > Double(idleMinutes * 60) ? since : nil
577 }
578
570 /// `org-clock-resolve`: asks what to do with `clock`'s time since `lastValid` and does it. 579 /// `org-clock-resolve`: asks what to do with `clock`'s time since `lastValid` and does it.
571 func resolve( 580 func resolve(
572 _ clock: OpenClock, description: String, lastValid: Date, clockingIn: Bool, _ session: DocumentSession, ask: Ask, now: () -> Date 581 _ clock: OpenClock, description: String, lastValid: Date, clockingIn: Bool, _ session: DocumentSession, ask: Ask, now: () -> Date
Sources/OrgApp/Publish.swift +29
@@ -284,6 +284,35 @@ public enum Publish {
284 return report 284 return report
285 } 285 }
286 286
287 /// What `function` makes of `text`, the file at `path`: HTML, Markdown, LaTeX or plain text,
288 /// with `settings` and the file's setup files. The `export` of `publish` on every platform.
289 public static func export(
290 _ function: String, text: String, path: String, bodyOnly: Bool, settings: OrgSettings, codeStyle: HTMLCodeStyle?,
291 author: String = NSFullUserName(), language: String = OrgPreferences.exportLanguage()
292 ) throws -> String {
293 let settings = settings.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile)
294 let name = (path as NSString).lastPathComponent
295 switch function {
296 case "org-md-publish-to-md":
297 return MarkdownExport.document(text, settings: settings, path: path, bodyOnly: bodyOnly)
298 case "org-latex-publish-to-latex":
299 do {
300 return try LaTeXExport.document(text, settings: settings, path: path, bodyOnly: bodyOnly, author: author, language: language, file: true)
301 } catch let error as LaTeXExport.Unsupported {
302 throw LaTeXExport.Unsupported(reason: "Can't export \(name) to LaTeX: \(error.reason)")
303 }
304 case "org-ascii-publish-to-ascii":
305 do {
306 return try ASCIIExport.document(text, settings: settings, path: path, bodyOnly: bodyOnly, author: author, language: language, file: true)
307 } catch let error as ASCIIExport.Unsupported {
308 throw ASCIIExport.Unsupported(reason: "Can't export \(name) to plain text: \(error.reason)")
309 }
310 default:
311 let base = (name as NSString).deletingPathExtension
312 return HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path, bodyOnly: bodyOnly, codeStyle: codeStyle, language: language)
313 }
314 }
315
287 /// Where `function` publishes `file` in `outputDirectory`; nil for an attachment already there. 316 /// Where `function` publishes `file` in `outputDirectory`; nil for an attachment already there.
288 private static func outputPath(_ file: String, function: String, in outputDirectory: String, read: (String) -> String?) throws -> String? { 317 private static func outputPath(_ file: String, function: String, in outputDirectory: String, read: (String) -> String?) throws -> String? {
289 guard function != "org-publish-attachment" else { 318 guard function != "org-publish-attachment" else {
Sources/OrgApp/PublishFolders.swift added +63
@@ -0,0 +1,63 @@
1import Foundation
2import OrgCore
3
4/// Publishing directories chosen in a folder picker, by project name. On iOS the app can write
5/// only to folders it was given, so a project whose `publishing-directory` is outside the
6/// app's folders publishes to the folder chosen for it instead. Kept as bookmarks.
7@MainActor
8public final class PublishFolders {
9 public static let shared = PublishFolders()
10 static let key = "publishFolders"
11
12 private let defaults: UserDefaults
13 private let sandboxed: Bool
14 /// The chosen folders by project name, with access started.
15 private var folders: [String: URL] = [:]
16
17 init(defaults: UserDefaults = .standard, sandboxed: Bool = Sandbox.isActive) {
18 self.defaults = defaults
19 self.sandboxed = sandboxed
20 let saved = defaults.dictionary(forKey: Self.key) as? [String: Data] ?? [:]
21 var kept = saved
22 for (name, data) in saved {
23 guard let (url, renewed) = SecurityBookmark.resolve(data, sandboxed: sandboxed) else { continue }
24 folders[name] = url
25 if let renewed { kept[name] = renewed }
26 }
27 if kept != saved { defaults.set(kept, forKey: Self.key) }
28 }
29
30 /// The folder chosen for `project`, if any.
31 public func folder(for project: String) -> URL? { folders[project] }
32
33 /// Keeps `url`, a folder from a folder picker, as where `project` publishes. False when its
34 /// bookmark can't be made, so it lasts only until the app quits.
35 @discardableResult
36 public func set(_ url: URL, for project: String) -> Bool {
37 _ = url.startAccessingSecurityScopedResource()
38 folders[project] = url
39 guard let data = SecurityBookmark.make(url, sandboxed: sandboxed) else { return false }
40 var saved = defaults.dictionary(forKey: Self.key) as? [String: Data] ?? [:]
41 saved[project] = data
42 defaults.set(saved, forKey: Self.key)
43 return true
44 }
45
46 /// `projects`, each publishing to the folder chosen for it where there is one.
47 public func applied(to projects: [PublishProject]) -> [PublishProject] {
48 projects.map { project in
49 var project = project
50 if let folder = folders[project.name] { project.publishingDirectory = folder.path }
51 return project
52 }
53 }
54
55 /// The projects among `projects` (expanded from projects of projects) that publish outside
56 /// `roots` with no folder chosen for them.
57 public func needed(_ projects: [PublishProject], all: [PublishProject], roots: [String]) throws -> [PublishProject] {
58 try Publish.expand(projects, all: all).filter { project in
59 folders[project.name] == nil
60 && !roots.contains { FolderGrants.covers(URL(fileURLWithPath: $0), URL(fileURLWithPath: project.publishingDirectory)) }
61 }
62 }
63}
Sources/Orgstar/ContentView.swift +1 −18
@@ -1004,24 +1004,7 @@ struct ContentView: View {
1004 guard reach(involved().flatMap { [$0.baseDirectory, $0.publishingDirectory] }, directories: true) else { return } 1004 guard reach(involved().flatMap { [$0.baseDirectory, $0.publishingDirectory] }, directories: true) else { return }
1005 do { 1005 do {
1006 let report = try Publish.publish(chosen, all: loaded.projects, only: only, read: read) { function, text, path, bodyOnly in 1006 let report = try Publish.publish(chosen, all: loaded.projects, only: only, read: read) { function, text, path, bodyOnly in
1007 let settings = Preferences.orgSettings.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile) 1007 try Publish.export(function, text: text, path: path, bodyOnly: bodyOnly, settings: Preferences.orgSettings, codeStyle: codeStyle)
1008 if function == "org-md-publish-to-md" { return MarkdownExport.document(text, settings: settings, path: path, bodyOnly: bodyOnly) }
1009 if function == "org-latex-publish-to-latex" {
1010 do {
1011 return try LaTeXExport.document(text, settings: settings, path: path, bodyOnly: bodyOnly, author: NSFullUserName(), language: OrgPreferences.exportLanguage(), file: true)
1012 } catch let error as LaTeXExport.Unsupported {
1013 throw LaTeXExport.Unsupported(reason: "Can't export \((path as NSString).lastPathComponent) to LaTeX: \(error.reason)")
1014 }
1015 }
1016 if function == "org-ascii-publish-to-ascii" {
1017 do {
1018 return try ASCIIExport.document(text, settings: settings, path: path, bodyOnly: bodyOnly, author: NSFullUserName(), language: OrgPreferences.exportLanguage(), file: true)
1019 } catch let error as ASCIIExport.Unsupported {
1020 throw ASCIIExport.Unsupported(reason: "Can't export \((path as NSString).lastPathComponent) to plain text: \(error.reason)")
1021 }
1022 }
1023 let base = ((path as NSString).lastPathComponent as NSString).deletingPathExtension
1024 return HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path, bodyOnly: bodyOnly, codeStyle: codeStyle, language: OrgPreferences.exportLanguage())
1025 } 1008 }
1026 commands.show("Published \(report.published.count) files" + (report.skipped.isEmpty ? "" : ", \(report.skipped.count) up to date")) 1009 commands.show("Published \(report.published.count) files" + (report.skipped.isEmpty ? "" : ", \(report.skipped.count) up to date"))
1027 } catch { 1010 } catch {
Tests/OrgAppTests/ClockHistoryModelTests.swift +13
@@ -192,4 +192,17 @@ struct ClockHistoryModelTests {
192 #expect(next.asked == ["You stopped another clock 50 mins ago; start this one from then? (y or n) "]) 192 #expect(next.asked == ["You stopped another clock 50 mins ago; start this one from then? (y or n) "])
193 #expect(clock.running?.heading == "C" && clock.running?.startedAt == idle && clock.leftover == nil) 193 #expect(clock.running?.heading == "C" && clock.running?.startedAt == idle && clock.leftover == nil)
194 } 194 }
195
196 /// iOS: time in the background past `org-clock-idle-time` is idle from when the app left,
197 /// or from clocking in, when that came later.
198 @Test func backgroundTimeIsIdleTime() {
199 let running = ClockModel.Running(path: work.path, start: "2026-09-09 Wed 10:00", heading: "A", startedAt: start)
200 let left = start.addingTimeInterval(10 * 60)
201 #expect(ClockModel.idleSince(backgrounded: left, now: left.addingTimeInterval(16 * 60), running: running, idleMinutes: 15) == left)
202 #expect(ClockModel.idleSince(backgrounded: left, now: left.addingTimeInterval(15 * 60), running: running, idleMinutes: 15) == nil)
203 #expect(ClockModel.idleSince(backgrounded: left, now: left.addingTimeInterval(60 * 60), running: running, idleMinutes: 0) == nil)
204 #expect(ClockModel.idleSince(backgrounded: left, now: left.addingTimeInterval(60 * 60), running: nil, idleMinutes: 15) == nil)
205 let earlier = start.addingTimeInterval(-30 * 60)
206 #expect(ClockModel.idleSince(backgrounded: earlier, now: start.addingTimeInterval(20 * 60), running: running, idleMinutes: 15) == start)
207 }
195} 208}
Tests/OrgAppTests/PublishTests.swift +65
@@ -278,4 +278,69 @@ struct PublishTests {
278 #expect(Publish.projects(fromConfig: "[[publish]]\nname = \"x\"\n", root: nil).problems.count == 1) 278 #expect(Publish.projects(fromConfig: "[[publish]]\nname = \"x\"\n", root: nil).problems.count == 1)
279 #expect(throws: Publish.Failure.self) { try Publish.expand([PublishProject(name: "m")].map { var p = $0; p.components = ["nope"]; return p }, all: []) } 279 #expect(throws: Publish.Failure.self) { try Publish.expand([PublishProject(name: "m")].map { var p = $0; p.components = ["nope"]; return p }, all: []) }
280 } 280 }
281
282 /// The exporter both apps publish with: each function's format, and the file named in a
283 /// refusal.
284 @Test func exportsByFunction() throws {
285 let path = "/notes/a.org"
286 let text = "#+TITLE: A\n* One\nText.\n"
287 func export(_ function: String) throws -> String {
288 try Publish.export(function, text: text, path: path, bodyOnly: false, settings: .default, codeStyle: nil, author: "A. Writer", language: "en")
289 }
290 #expect(try export("org-html-publish-to-html").contains("<title>A</title>"))
291 #expect(try export("org-md-publish-to-md").contains("# One"))
292 #expect(try export("org-latex-publish-to-latex").contains("\\title{A}"))
293 #expect(try export("org-ascii-publish-to-ascii").contains("1 One"))
294 #expect(throws: LaTeXExport.Unsupported(reason: "Can't export a.org to LaTeX: Radio targets")) {
295 try Publish.export("org-latex-publish-to-latex", text: "<<<radio>>> radio\n", path: path, bodyOnly: false, settings: .default, codeStyle: nil, author: "", language: "en")
296 }
297 }
298}
299
300/// Publishing on iOS: a project that publishes outside the app's folders writes to the folder
301/// chosen for it, kept as a bookmark.
302@MainActor
303struct PublishFoldersTests {
304 @Test func publishesToTheBookmarkedFolder() throws {
305 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-publish-ios-\(UUID().uuidString)").resolvingSymlinksInPath()
306 defer { try? FileManager.default.removeItem(at: folder) }
307 try PublishTests.tree(folder)
308 let chosen = folder.appendingPathComponent("chosen")
309 try FileManager.default.createDirectory(at: chosen, withIntermediateDirectories: true)
310 let config = """
311 [[publish]]
312 name = "site"
313 base-directory = "src"
314 publishing-directory = "~/public_html"
315
316 [[publish]]
317 name = "inside"
318 base-directory = "src"
319 publishing-directory = "src/out"
320
321 [[publish]]
322 name = "both"
323 components = "site inside"
324 """
325 let root = folder.path
326 let loaded = Publish.projects(fromConfig: config, root: root)
327 let defaults = UserDefaults(suiteName: "orgstar-publish-\(UUID().uuidString)")!
328 let folders = PublishFolders(defaults: defaults, sandboxed: false)
329 let both = loaded.projects.first { $0.name == "both" }!
330 #expect(try folders.needed([both], all: loaded.projects, roots: [root]).map(\.name) == ["site"])
331 #expect(folders.set(chosen, for: "site"))
332
333 // After a relaunch, the bookmark gives the folder back.
334 let again = PublishFolders(defaults: defaults, sandboxed: false)
335 #expect(again.folder(for: "site")?.standardizedFileURL == chosen.standardizedFileURL)
336 #expect(try again.needed([both], all: loaded.projects, roots: [root]).isEmpty)
337 let projects = again.applied(to: loaded.projects)
338 let site = projects.first { $0.name == "site" }!
339 #expect(URL(fileURLWithPath: site.publishingDirectory).standardizedFileURL == chosen.standardizedFileURL)
340 #expect(projects.first { $0.name == "inside" }?.publishingDirectory == root + "/src/out")
341 let read = { (path: String) in try? String(contentsOfFile: path, encoding: .utf8) }
342 let report = try Publish.publish([site], all: projects, read: read) { _, text, _, _ in text }
343 #expect(!report.published.isEmpty)
344 #expect(FileManager.default.fileExists(atPath: chosen.appendingPathComponent("a.html").path))
345 }
281} 346}
Tests/OrgEditorAppKitTests/AppStoreCommandsTests.swift +8
@@ -29,4 +29,12 @@ struct AppStoreCommandsTests {
29 #expect(AppStoreCommands.replacement(for: id) == nil) 29 #expect(AppStoreCommands.replacement(for: id) == nil)
30 } 30 }
31 } 31 }
32
33 /// Linking a file from another container fails in the sandbox, so iOS refuses these too.
34 @Test func attachingByLinkIsUnavailable() {
35 #expect(AppStoreCommands.unavailable("app.attach.link"))
36 #expect(AppStoreCommands.unavailable("app.attach.symlink"))
37 #expect(!AppStoreCommands.unavailable("app.attach.attach"))
38 #expect(!AppStoreCommands.unavailable("app.export.pdf"))
39 }
32} 40}