Commit c14bb70928

c14bb709281f24e063705eed4979a235abdb4967

parent: 7f9206ed92

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-20 05:59 UTC

Choose the configuration folder in the Mac App Store build

- Move the configuration folder bookmark from MobileModel into OrgApp as ConfigFolder, security-scoped in the Mac sandbox; iOS keeps its key and behaviour
- ConfigSync.move(to:) switches to another folder's config.toml and reloads keymap.toml; the legacy folder is not watched with a chosen folder
- App Store build: restore the chosen folder before ConfigSync starts, and add Choose Configuration Folder… and Use Default Folder in Settings > General, starting at the real ~/.config/orgstar
- Translate the new strings

Layout: unified · split

Sources/OrgApp/ConfigFolder.swift added +40
@@ -0,0 +1,40 @@
1import Foundation
2import OrgCore
3
4/// A configuration folder chosen in the app, kept as a bookmark: on iOS a synced copy of the
5/// Mac's `~/.config/orgstar`, in the Mac sandbox a folder outside the container. The bookmark
6/// is security-scoped in the Mac sandbox and plain elsewhere.
7public enum ConfigFolder {
8 public static let bookmarkKey = "configFolderBookmark"
9
10 /// The chosen folder with access to it started, or nil when none is chosen or its bookmark
11 /// no longer resolves. A stale bookmark is renewed.
12 public static func resolve(defaults: UserDefaults = .standard, sandboxed: Bool = Sandbox.isActive) -> URL? {
13 guard let data = defaults.data(forKey: bookmarkKey) else { return nil }
14 var stale = false
15 guard let url = try? URL(resolvingBookmarkData: data, options: Sandbox.bookmarkResolutionOptions(sandboxed: sandboxed), bookmarkDataIsStale: &stale) else { return nil }
16 _ = url.startAccessingSecurityScopedResource()
17 if stale, let fresh = try? url.bookmarkData(options: Sandbox.bookmarkCreationOptions(sandboxed: sandboxed)) {
18 defaults.set(fresh, forKey: bookmarkKey)
19 }
20 return url
21 }
22
23 /// Keeps `url`, as from a folder picker, as the chosen folder and starts access to it.
24 public static func set(_ url: URL, defaults: UserDefaults = .standard, sandboxed: Bool = Sandbox.isActive) {
25 _ = url.startAccessingSecurityScopedResource()
26 if let bookmark = try? url.bookmarkData(options: Sandbox.bookmarkCreationOptions(sandboxed: sandboxed)) {
27 defaults.set(bookmark, forKey: bookmarkKey)
28 }
29 }
30
31 /// Stops using a chosen folder.
32 public static func clear(defaults: UserDefaults = .standard) {
33 defaults.removeObject(forKey: bookmarkKey)
34 }
35
36 /// `~/.config/orgstar` in the real home folder, where a folder picker starts.
37 public static var suggested: URL {
38 URL(fileURLWithPath: OrgPaths.home).appendingPathComponent(".config/orgstar")
39 }
40}
Sources/OrgApp/ConfigSync.swift +22 −2
@@ -20,7 +20,7 @@ public final class ConfigSync {
2020 /// The last file of the configuration folder that changed, with a serial number.
2121 public private(set) var changedFile: (name: String, serial: Int)?
2222
23 private let url: URL
23 @ObservationIgnored private var url: URL
2424 private let defaults: UserDefaults
2525 @ObservationIgnored private var text: String?
2626 @ObservationIgnored private var configProblems: [String] = []
@@ -28,6 +28,7 @@ public final class ConfigSync {
2828 @ObservationIgnored private var watcher: FSEventsWatcher?
2929 @ObservationIgnored private var observer: NSObjectProtocol?
3030 @ObservationIgnored private var serial = 0
31 @ObservationIgnored private var watches = true
3132
3233 /// Where `url` leads: a symlinked config.toml is written through, not replaced by a file.
3334 private var target: URL { url.resolvingSymlinksInPath() }
@@ -39,6 +40,7 @@ public final class ConfigSync {
3940
4041 public func start(watch: Bool = true) {
4142 guard observer == nil else { return }
43 watches = watch
4244 try? FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
4345 let reference = url.deletingLastPathComponent().appendingPathComponent("default-theme.toml")
4446 if (try? String(contentsOf: reference, encoding: .utf8)) != ThemeSpec.defaultThemeFile() {
@@ -71,7 +73,7 @@ public final class ConfigSync {
7173 let watchesLinked = linked.path != directory.path
7274 // Files still read from where earlier versions kept them reload when edited there too.
7375 let legacy = UserConfig.legacyDirectory.resolvingSymlinksInPath()
74 let watchesLegacy = legacy.path != directory.path && FileManager.default.fileExists(atPath: legacy.path)
76 let watchesLegacy = UserConfig.directoryOverride == nil && legacy.path != directory.path && FileManager.default.fileExists(atPath: legacy.path)
7577 watcher = FSEventsWatcher(roots: [directory] + (watchesLinked ? [linked] : []) + (watchesLegacy ? [legacy] : [])) { [weak self] events in
7678 let changed = Set(events.compactMap { event -> URL? in
7779 if case .changed(let url) = event { return url }
@@ -93,6 +95,24 @@ public final class ConfigSync {
9395 watcher?.start()
9496 }
9597
98 /// Uses `url`, as in another configuration folder, from now on: its settings apply, and a
99 /// missing file is created with the current ones. Does nothing before `start`.
100 public func move(to url: URL) {
101 guard observer != nil, url != self.url else { return }
102 watcher?.stop()
103 watcher = nil
104 if let observer { NotificationCenter.default.removeObserver(observer) }
105 observer = nil
106 text = nil
107 configProblems = []
108 self.url = url
109 start(watch: watches)
110 readTheme()
111 // Windows read keymap.toml once, so they reload it from the new folder.
112 serial += 1
113 changedFile = ("keymap.toml", serial)
114 }
115
96116 /// Reads the file and applies it when it changed since the last read or write.
97117 public func reload() {
98118 guard let new = try? String(contentsOf: url, encoding: .utf8), new != text else { return }
Sources/Orgstar/OrgstarApp.swift +34
@@ -612,6 +612,9 @@ struct SettingsView: View {
612612 let updates: Updates
613613 #endif
614614 @State private var importing = false
615 #if APPSTORE
616 @State private var configFolder = UserConfig.directoryOverride
617 #endif
615618 @Environment(\.openWindow) private var openWindow
616619 @AppStorage("saveMode") private var saveMode = SaveMode.automatic
617620 @AppStorage("keymap") private var preset = KeymapPreset.emacs
@@ -689,6 +692,29 @@ struct SettingsView: View {
689692 commands.jump(path: UserConfig.configFile.path, offset: 0)
690693 }
691694
695 #if APPSTORE
696 /// A folder outside the app's container, such as `~/.config/orgstar` kept with dotfiles.
697 private func chooseConfigFolder() {
698 let panel = NSOpenPanel()
699 panel.canChooseFiles = false
700 panel.canChooseDirectories = true
701 panel.canCreateDirectories = true
702 panel.directoryURL = configFolder ?? ConfigFolder.suggested
703 panel.message = String(localized: "Choose the folder for config.toml and orgstar's other configuration files.", comment: "Choose Configuration Folder panel")
704 guard panel.runModal() == .OK, let url = panel.url else { return }
705 ConfigFolder.set(url)
706 useConfigFolder(url)
707 }
708
709 /// Reads and writes the configuration in `url`, or with nil in the default folder.
710 private func useConfigFolder(_ url: URL?) {
711 if url == nil { ConfigFolder.clear() }
712 UserConfig.directoryOverride = url
713 configFolder = url
714 ConfigSync.shared.move(to: UserConfig.configFile)
715 }
716 #endif
717
692718 private var general: some View {
693719 Form {
694720 Section {
@@ -699,6 +725,14 @@ struct SettingsView: View {
699725 Button("Show in Finder") { NSWorkspace.shared.activateFileViewerSelecting([UserConfig.configFile]) }
700726 }
701727 }
728 #if APPSTORE
729 LabeledContent("Folder") {
730 HStack {
731 Button("Choose Configuration Folder…") { chooseConfigFolder() }
732 if configFolder != nil { Button("Use Default Folder") { useConfigFolder(nil) } }
733 }
734 }
735 #endif
702736 LabeledContent("Emacs") {
703737 Button("Import from Emacs…") { importing = true }
704738 }
Sources/Orgstar/Preferences.swift +9
@@ -6,9 +6,18 @@ import OrgCore
66enum Preferences {
77 static let defaultTodoKeywords = OrgPreferences.defaultTodoKeywords
88
9 #if APPSTORE
10 /// The folder chosen with Choose Configuration Folder…, used before anything reads the
11 /// configuration.
12 private static let chosenConfigFolder: Void = { UserConfig.directoryOverride = ConfigFolder.resolve() }()
13 #endif
14
915 /// TODO keywords for files without `#+TODO`, read at launch.
1016 @MainActor
1117 static var orgSettings: OrgSettings {
18 #if APPSTORE
19 _ = chosenConfigFolder
20 #endif
1221 // config.toml applies before anything reads settings.
1322 ConfigSync.shared.start()
1423 return OrgPreferences.orgSettings()
Sources/OrgstarMobile/MobileModel.swift +3 −15
@@ -66,11 +66,9 @@ final class MobileModel {
6666 @ObservationIgnored private var presenter: FolderPresenter?
6767 @ObservationIgnored private var sizeObserver: NSObjectProtocol?
6868
69 private static let bookmarkKey = "configFolderBookmark"
70
7169 private init() {
7270 // Development: `ORGSTAR_CONFIG_DIR` stands in for a chosen folder.
73 let folder = Self.resolveBookmark() ?? ProcessInfo.processInfo.environment["ORGSTAR_CONFIG_DIR"].map { URL(fileURLWithPath: $0) }
71 let folder = ConfigFolder.resolve() ?? ProcessInfo.processInfo.environment["ORGSTAR_CONFIG_DIR"].map { URL(fileURLWithPath: $0) }
7472 UserConfig.directoryOverride = folder
7573 let (problems, colors) = Self.readConfig(folder)
7674 let settings = OrgPreferences.orgSettings()
@@ -109,11 +107,10 @@ final class MobileModel {
109107 /// Chooses the configuration folder, or with nil stops using one; its settings apply now.
110108 func setConfigFolder(_ url: URL?) {
111109 if let url {
112 _ = url.startAccessingSecurityScopedResource()
113 if let bookmark = try? url.bookmarkData() { UserDefaults.standard.set(bookmark, forKey: Self.bookmarkKey) }
110 ConfigFolder.set(url)
114111 Self.createConfig(in: url)
115112 } else {
116 UserDefaults.standard.removeObject(forKey: Self.bookmarkKey)
113 ConfigFolder.clear()
117114 // What the folder set no longer applies.
118115 for setting in UserConfig.settings { UserDefaults.standard.removeObject(forKey: setting.defaultsKey) }
119116 }
@@ -217,15 +214,6 @@ final class MobileModel {
217214 self.presenter = presenter
218215 }
219216
220 private static func resolveBookmark() -> URL? {
221 guard let data = UserDefaults.standard.data(forKey: bookmarkKey) else { return nil }
222 var stale = false
223 guard let url = try? URL(resolvingBookmarkData: data, bookmarkDataIsStale: &stale) else { return nil }
224 _ = url.startAccessingSecurityScopedResource()
225 if stale, let fresh = try? url.bookmarkData() { UserDefaults.standard.set(fresh, forKey: bookmarkKey) }
226 return url
227 }
228
229217 /// Applies the folder's `config.toml` to the settings; returns its problems and the theme's
230218 /// colors.
231219 /// Writes `config.toml` with every setting at its default when the folder has none.
Tests/OrgAppTests/ConfigFolderTests.swift added +93
@@ -0,0 +1,93 @@
1import Foundation
2import OrgCore
3import Testing
4@testable import OrgApp
5
6@MainActor
7struct ConfigFolderTests {
8 func defaults() -> UserDefaults {
9 let name = "orgstar-config-folder-\(UUID().uuidString)"
10 let defaults = UserDefaults(suiteName: name)!
11 defaults.removePersistentDomain(forName: name)
12 return defaults
13 }
14
15 func folder() throws -> URL {
16 let url = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-config-folder-\(UUID().uuidString)")
17 try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
18 return url
19 }
20
21 @Test func chosenFolderResolves() throws {
22 let store = defaults()
23 let url = try folder()
24 defer { try? FileManager.default.removeItem(at: url) }
25 #expect(ConfigFolder.resolve(defaults: store) == nil)
26 ConfigFolder.set(url, defaults: store)
27 #expect(store.data(forKey: ConfigFolder.bookmarkKey) != nil)
28 let resolved = try #require(ConfigFolder.resolve(defaults: store))
29 #expect(resolved.resolvingSymlinksInPath().path == url.resolvingSymlinksInPath().path)
30 ConfigFolder.clear(defaults: store)
31 #expect(ConfigFolder.resolve(defaults: store) == nil)
32 }
33
34 /// iOS keeps its folder under the key it always used.
35 @Test func bookmarkKeyIsUnchanged() {
36 #expect(ConfigFolder.bookmarkKey == "configFolderBookmark")
37 }
38
39 @Test func suggestedIsInTheRealHome() {
40 #expect(ConfigFolder.suggested.path == OrgPaths.home + "/.config/orgstar")
41 }
42
43 @Test func movingAppliesTheNewFolder() throws {
44 let first = try folder()
45 let second = try folder()
46 defer {
47 try? FileManager.default.removeItem(at: first)
48 try? FileManager.default.removeItem(at: second)
49 }
50 try "fill-column = 64\n".write(to: first.appendingPathComponent("config.toml"), atomically: true, encoding: .utf8)
51 try "fill-column = 72\n".write(to: second.appendingPathComponent("config.toml"), atomically: true, encoding: .utf8)
52 let store = defaults()
53 let sync = ConfigSync(url: first.appendingPathComponent("config.toml"), defaults: store)
54 sync.start(watch: false)
55 #expect(store.integer(forKey: "fillColumn") == 64)
56 sync.move(to: second.appendingPathComponent("config.toml"))
57 #expect(store.integer(forKey: "fillColumn") == 72)
58 #expect(sync.changedFile?.name == "keymap.toml")
59 // Changes made in the app go into the new file only.
60 store.set(80, forKey: "fillColumn")
61 sync.writeBack()
62 #expect(try String(contentsOf: second.appendingPathComponent("config.toml"), encoding: .utf8).contains("fill-column = 80"))
63 let old = try String(contentsOf: first.appendingPathComponent("config.toml"), encoding: .utf8)
64 #expect(old.contains("fill-column = 64") && !old.contains("fill-column = 80"))
65 }
66
67 @Test func movingToAnEmptyFolderWritesTheCurrentSettings() throws {
68 let first = try folder()
69 let second = try folder()
70 defer {
71 try? FileManager.default.removeItem(at: first)
72 try? FileManager.default.removeItem(at: second)
73 }
74 try "fill-column = 64\n".write(to: first.appendingPathComponent("config.toml"), atomically: true, encoding: .utf8)
75 let store = defaults()
76 let sync = ConfigSync(url: first.appendingPathComponent("config.toml"), defaults: store)
77 sync.start(watch: false)
78 sync.move(to: second.appendingPathComponent("config.toml"))
79 #expect(try String(contentsOf: second.appendingPathComponent("config.toml"), encoding: .utf8).contains("fill-column = 64"))
80 }
81
82 @Test func movingBeforeStartDoesNothing() throws {
83 let first = try folder()
84 let second = try folder()
85 defer {
86 try? FileManager.default.removeItem(at: first)
87 try? FileManager.default.removeItem(at: second)
88 }
89 let sync = ConfigSync(url: first.appendingPathComponent("config.toml"), defaults: defaults())
90 sync.move(to: second.appendingPathComponent("config.toml"))
91 #expect(!FileManager.default.fileExists(atPath: second.appendingPathComponent("config.toml").path))
92 }
93}
l10n/Localizable.xcstrings +103
@@ -5565,6 +5565,40 @@
55655565 }
55665566 }
55675567 },
5568 "Choose Configuration Folder…": {
5569 "localizations": {
5570 "de": {
5571 "stringUnit": {
5572 "state": "translated",
5573 "value": "Konfigurationsordner wählen …"
5574 }
5575 },
5576 "es": {
5577 "stringUnit": {
5578 "state": "translated",
5579 "value": "Elegir carpeta de configuración…"
5580 }
5581 },
5582 "fr": {
5583 "stringUnit": {
5584 "state": "translated",
5585 "value": "Choisir le dossier de configuration…"
5586 }
5587 },
5588 "ja": {
5589 "stringUnit": {
5590 "state": "translated",
5591 "value": "構成フォルダを選択…"
5592 }
5593 },
5594 "pt-BR": {
5595 "stringUnit": {
5596 "state": "translated",
5597 "value": "Escolher Pasta de Configuração…"
5598 }
5599 }
5600 }
5601 },
55685602 "Choose Folder": {
55695603 "localizations": {
55705604 "de": {
@@ -5735,6 +5769,41 @@
57355769 }
57365770 }
57375771 },
5772 "Choose the folder for config.toml and orgstar's other configuration files.": {
5773 "comment": "Choose Configuration Folder panel",
5774 "localizations": {
5775 "de": {
5776 "stringUnit": {
5777 "state": "translated",
5778 "value": "Wähle den Ordner für config.toml und die anderen Konfigurationsdateien von orgstar."
5779 }
5780 },
5781 "es": {
5782 "stringUnit": {
5783 "state": "translated",
5784 "value": "Elige la carpeta para config.toml y los demás archivos de configuración de orgstar."
5785 }
5786 },
5787 "fr": {
5788 "stringUnit": {
5789 "state": "translated",
5790 "value": "Choisissez le dossier de config.toml et des autres fichiers de configuration d'orgstar."
5791 }
5792 },
5793 "ja": {
5794 "stringUnit": {
5795 "state": "translated",
5796 "value": "config.toml と orgstar のほかの構成ファイルを置くフォルダを選択してください。"
5797 }
5798 },
5799 "pt-BR": {
5800 "stringUnit": {
5801 "state": "translated",
5802 "value": "Escolha a pasta para o config.toml e os outros arquivos de configuração do orgstar."
5803 }
5804 }
5805 }
5806 },
57385807 "Choose your init.el, or the folder holding it (~/.emacs.d, ~/.config/doom).": {
57395808 "localizations": {
57405809 "de": {
@@ -32024,6 +32093,40 @@
3202432093 }
3202532094 }
3202632095 },
32096 "Use Default Folder": {
32097 "localizations": {
32098 "de": {
32099 "stringUnit": {
32100 "state": "translated",
32101 "value": "Standardordner verwenden"
32102 }
32103 },
32104 "es": {
32105 "stringUnit": {
32106 "state": "translated",
32107 "value": "Usar carpeta predeterminada"
32108 }
32109 },
32110 "fr": {
32111 "stringUnit": {
32112 "state": "translated",
32113 "value": "Utiliser le dossier par défaut"
32114 }
32115 },
32116 "ja": {
32117 "stringUnit": {
32118 "state": "translated",
32119 "value": "デフォルトのフォルダを使用"
32120 }
32121 },
32122 "pt-BR": {
32123 "stringUnit": {
32124 "state": "translated",
32125 "value": "Usar Pasta Padrão"
32126 }
32127 }
32128 }
32129 },
3202732130 "Use Disk Version": {
3202832131 "localizations": {
3202932132 "de": {