Commit 23c126fd8a

23c126fd8a5ee1409aa3e324cfaabd3c02ec2e91

parent: 83d994d220

Verified · cmc

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

Gate the Mac app for the App Store build

- APPSTORE compiles out Sparkle and Check for Updates, the license key forms, DevelopmentHooks, the Emacs export and table branches, and the Emacs rows of the export sheet
- App Store init starts ProStore and writes widget data to the app group; the widget bundle reads it there and locks without orgstar+
- hiddenCommandIDs (AppStoreCommands.hidden) leaves Emacs exports and link attaching out of the palette, the Export menu and keys; app.export.pdf keys run print-pdf
- Exports whose default target is outside every folder ask with a save panel; attaching by moving needs the file inside a folder
- Import from Emacs starts with the picker; StoreForm and StorePaywallSheet stand in for the Mac StoreKit UI
- Shared messages no longer say a feature needs Emacs
- WorkspaceModel.contains for the folder checks

Layout: unified · split

Sources/OrgApp/AppStoreCommands.swift added +15
@@ -0,0 +1,15 @@
1import Foundation
2
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.
5public enum AppStoreCommands {
6 public static let hidden: Set<String> = [
7 "app.export.pdf", "app.export.odt", "app.export.latex", "app.export.text",
8 "app.attach.link", "app.attach.symlink",
9 ]
10
11 /// What a key bound to a hidden command runs instead; nil when nothing takes its place.
12 public static func replacement(for id: String) -> String? {
13 id == "app.export.pdf" ? "app.export.print-pdf" : nil
14 }
15}
Sources/OrgApp/WorkspaceModel.swift +18
@@ -136,6 +136,24 @@ public final class WorkspaceModel {
136 /// Resolved root paths, sorted. 136 /// Resolved root paths, sorted.
137 public var rootPaths: [String] { resolvedRoots.keys.sorted() } 137 public var rootPaths: [String] { resolvedRoots.keys.sorted() }
138 138
139 /// Whether `url` is a root or inside one.
140 public func contains(_ url: URL) -> Bool {
141 Self.isInside(url, roots: Array(resolvedRoots.values))
142 }
143
144 /// Whether `url` is one of `roots` or inside one, by whole path components, as written or
145 /// with symbolic links resolved.
146 nonisolated static func isInside(_ url: URL, roots: [URL]) -> Bool {
147 func forms(_ url: URL) -> [[String]] {
148 let standard = url.standardizedFileURL
149 return [standard.pathComponents, standard.resolvingSymlinksInPath().pathComponents]
150 }
151 let paths = forms(url)
152 return roots.flatMap(forms).contains { root in
153 paths.contains { $0.count >= root.count && Array($0.prefix(root.count)) == root }
154 }
155 }
156
139 // MARK: - Indexing 157 // MARK: - Indexing
140 158
141 /// Which files the folders show; a change rescans them. 159 /// Which files the folders show; a change rescans them.
Sources/OrgCore/Compute/BabelCache.swift +1 −1
@@ -45,7 +45,7 @@ extension Babel {
45 /// sorted by key and printed with `%S`, then the expanded body. 45 /// sorted by key and printed with `%S`, then the expanded body.
46 static func cacheInput(language: String, params: Params, tables: Tables, expanded: String, call: Bool) throws -> String { 46 static func cacheInput(language: String, params: Params, tables: Tables, expanded: String, call: Bool) throws -> String {
47 if let key = params.lisp.first(where: { params.evaluated[$0] == nil }) { 47 if let key = params.lisp.first(where: { params.evaluated[$0] == nil }) {
48 throw Failure.message(":cache with \(key) \(params.single[key] ?? "") needs Emacs to evaluate the Lisp; nothing was run.") 48 throw Failure.message(":cache with \(key) \(params.single[key] ?? "") is Lisp that can't be evaluated here; nothing was run.")
49 } 49 }
50 let ignored: Set<String> = ["replace", "silent", "none", "discard", "append", "prepend"] 50 let ignored: Set<String> = ["replace", "silent", "none", "discard", "append", "prepend"]
51 let drawsFile = language == "dot" || language == "plantuml" 51 let drawsFile = language == "dot" || language == "plantuml"
Sources/OrgCore/Compute/BabelExpand.swift +1 −1
@@ -518,7 +518,7 @@ extension Babel {
518 run = "echo | clojure -M \(file)\n" 518 run = "echo | clojure -M \(file)\n"
519 programs = ["clojure"] 519 programs = ["clojure"]
520 case let backend?: 520 case let backend?:
521 throw Failure.message("The \(backend) backend for clojure needs Emacs; orgstar runs babashka or clojure-cli.") 521 throw Failure.message("The \(backend) backend for clojure isn't supported; orgstar runs babashka or clojure-cli.")
522 } 522 }
523 return CompiledRun(source: expanded, script: start + "cat > \(file)\n" + run + end, programs: [programs]) 523 return CompiledRun(source: expanded, script: start + "cat > \(file)\n" + run + end, programs: [programs])
524 default: 524 default:
Sources/OrgCore/Compute/TableFormulaCommands.swift +2 −2
@@ -9,7 +9,7 @@ public struct TableRecalculate: OrgCommand {
9 public var id: String { all ? "org.table.recalc-all" : "org.table.recalc" } 9 public var id: String { all ? "org.table.recalc-all" : "org.table.recalc" }
10 public var title: String { all ? "Recalculate Table" : "Recalculate Table Row" } 10 public var title: String { all ? "Recalculate Table" : "Recalculate Table Row" }
11 11
12 public static let emacsMessage = "needs Emacs: " 12 public static let emacsMessage = "can't be calculated here: "
13 13
14 public func applies(in context: EditContext) -> Bool { 14 public func applies(in context: EditContext) -> Bool {
15 KeyContext.holds("table", in: context) || Self.tblfmLine(in: context) != nil 15 KeyContext.holds("table", in: context) || Self.tblfmLine(in: context) != nil
@@ -199,7 +199,7 @@ extension EmacsBuffer {
199 do { 199 do {
200 try tableEvalFormula(formula, analysis: analysis, substituted: false) 200 try tableEvalFormula(formula, analysis: analysis, substituted: false)
201 } catch let error as Calc.Unsupported { 201 } catch let error as Calc.Unsupported {
202 message = "The formula was stored; recalculating it needs Emacs: " + error.reason 202 message = "The formula was stored; it can't be calculated here: " + error.reason
203 } 203 }
204 tableAlign() 204 tableAlign()
205 } 205 }
Sources/OrgEditorAppKit/OrgEditor.swift +1 −1
@@ -652,7 +652,7 @@ public final class OrgEditor: NSObject {
652 case .failed(let message): 652 case .failed(let message):
653 onMessage?(message) 653 onMessage?(message)
654 case .external(let request): 654 case .external(let request):
655 if let onExternal { onExternal(request) } else { onMessage?("This needs Emacs, which isn't available here.") } 655 if let onExternal { onExternal(request) } else { onMessage?("This isn't available here.") }
656 case .prompt(let prompt): 656 case .prompt(let prompt):
657 onPrompt?(prompt) { [weak self] answer in 657 onPrompt?(prompt) { [weak self] answer in
658 guard let self else { return } 658 guard let self else { return }
Sources/Orgstar/ContentView.swift +56 −4
@@ -346,7 +346,13 @@ struct ContentView: View {
346 .onChange(of: preset, initial: true) { loadKeymap() } 346 .onChange(of: preset, initial: true) { loadKeymap() }
347 .sheet(isPresented: $showingImport) { EmacsImportView(workspace: workspace) } 347 .sheet(isPresented: $showingImport) { EmacsImportView(workspace: workspace) }
348 .sheet(item: $panel) { panel in panelView(panel) } 348 .sheet(item: $panel) { panel in panelView(panel) }
349 .sheet(item: Bindable(ProAccess.shared).paywall) { feature in ProPaywallSheet(feature: feature) } 349 .sheet(item: Bindable(ProAccess.shared).paywall) { feature in
350 #if APPSTORE
351 StorePaywallSheet(feature: feature)
352 #else
353 ProPaywallSheet(feature: feature)
354 #endif
355 }
350 .sheet(item: $blockEdit) { request in 356 .sheet(item: $blockEdit) { request in
351 BlockEditorView(edit: request.edit) { content in 357 BlockEditorView(edit: request.edit) { content in
352 blockEdit = nil 358 blockEdit = nil
@@ -490,12 +496,18 @@ struct ContentView: View {
490 } 496 }
491 } 497 }
492 .task { 498 .task {
499 #if !APPSTORE
493 DevelopmentHooks.scheduleSnapshot() 500 DevelopmentHooks.scheduleSnapshot()
501 #endif
494 pendingCarets = BufferRestore.restore(session) 502 pendingCarets = BufferRestore.restore(session)
495 if let path = session.path, let caret = pendingCarets.removeValue(forKey: path) { session.reveal(caret) } 503 if let path = session.path, let caret = pendingCarets.removeValue(forKey: path) { session.reveal(caret) }
496 // Files handed over at launch open after the restored buffers, and show. 504 // Files handed over at launch open after the restored buffers, and show.
497 for path in AppDelegate.pendingOpens { session.open(path) } 505 for path in AppDelegate.pendingOpens { session.open(path) }
498 AppDelegate.pendingOpens = [] 506 AppDelegate.pendingOpens = []
507 #if APPSTORE
508 for link in AppDelegate.pendingLinks { commands.handle(protocolURL: link) }
509 AppDelegate.pendingLinks = []
510 #else
499 for link in AppDelegate.pendingLinks + [DevelopmentHooks.urlToOpen].compactMap({ $0 }) { commands.handle(protocolURL: link) } 511 for link in AppDelegate.pendingLinks + [DevelopmentHooks.urlToOpen].compactMap({ $0 }) { commands.handle(protocolURL: link) }
500 AppDelegate.pendingLinks = [] 512 AppDelegate.pendingLinks = []
501 if let path = DevelopmentHooks.fileToOpen { selectedFile = path } 513 if let path = DevelopmentHooks.fileToOpen { selectedFile = path }
@@ -512,6 +524,7 @@ struct ContentView: View {
512 if let id = DevelopmentHooks.windowToOpen { 524 if let id = DevelopmentHooks.windowToOpen {
513 if id == "settings" { openSettings() } else { openWindow(id: id) } 525 if id == "settings" { openSettings() } else { openWindow(id: id) }
514 } 526 }
527 #endif
515 await workspace.refresh() 528 await workspace.refresh()
516 workspace.startWatching() 529 workspace.startWatching()
517 } 530 }
@@ -574,6 +587,8 @@ struct ContentView: View {
574 } 587 }
575 switch format { 588 switch format {
576 case "icalendar": 589 case "icalendar":
590 let name = ExportScope.fileName(whole, subtreeAt: subtree ? caret : nil, settings: defaults)
591 guard let destination = destination ?? writable(ExportScope.output(for: url, name: name, extension: "ics")) else { return }
577 do { 592 do {
578 let target = try ICalendarFiles.export(whole, path: path, settings: defaults, options: OrgPreferences.icalendarOptions(), 593 let target = try ICalendarFiles.export(whole, path: path, settings: defaults, options: OrgPreferences.icalendarOptions(),
579 subtree: subtree ? caret : nil, destination: destination) 594 subtree: subtree ? caret : nil, destination: destination)
@@ -584,7 +599,7 @@ struct ContentView: View {
584 } 599 }
585 case "html", "html-open", "markdown": 600 case "html", "html-open", "markdown":
586 let name = ExportScope.fileName(whole, subtreeAt: subtree ? caret : nil, settings: defaults) 601 let name = ExportScope.fileName(whole, subtreeAt: subtree ? caret : nil, settings: defaults)
587 let target = destination ?? ExportScope.output(for: url, name: name, extension: format == "markdown" ? "md" : "html") 602 guard let target = destination ?? writable(ExportScope.output(for: url, name: name, extension: format == "markdown" ? "md" : "html")) else { return }
588 let content = format == "markdown" 603 let content = format == "markdown"
589 ? MarkdownExport.document(text, settings: defaults, path: path, bodyOnly: bodyOnly) 604 ? MarkdownExport.document(text, settings: defaults, path: path, bodyOnly: bodyOnly)
590 : HTMLExport.page( 605 : HTMLExport.page(
@@ -602,7 +617,7 @@ struct ContentView: View {
602 case "print-pdf", "docx", "rtf", "plain-text": 617 case "print-pdf", "docx", "rtf", "plain-text":
603 let ext = ["print-pdf": "pdf", "plain-text": "txt"][format] ?? format 618 let ext = ["print-pdf": "pdf", "plain-text": "txt"][format] ?? format
604 let name = ExportScope.fileName(whole, subtreeAt: subtree ? caret : nil, settings: defaults) 619 let name = ExportScope.fileName(whole, subtreeAt: subtree ? caret : nil, settings: defaults)
605 let target = destination ?? ExportScope.output(for: url, name: name, extension: ext) 620 guard let target = destination ?? writable(ExportScope.output(for: url, name: name, extension: ext)) else { return }
606 let html = HTMLExport.page( 621 let html = HTMLExport.page(
607 text, fallbackTitle: base.lastPathComponent, settings: defaults, path: path, 622 text, fallbackTitle: base.lastPathComponent, settings: defaults, path: path,
608 codeStyle: HTMLCodeStyle(highlighter: PaneView.highlighter, theme: theme), language: OrgPreferences.exportLanguage() 623 codeStyle: HTMLCodeStyle(highlighter: PaneView.highlighter, theme: theme), language: OrgPreferences.exportLanguage()
@@ -652,11 +667,32 @@ struct ContentView: View {
652 } 667 }
653 } 668 }
654 #else 669 #else
655 break 670 let title = EditorCommands.all.first { $0.id == "app.export." + format }?.title
671 commands.show(Self.unavailable(title ?? format))
656 #endif 672 #endif
657 } 673 }
658 } 674 }
659 675
676 /// `url`; in the App Store build, when it is outside every folder, where a save panel puts it
677 /// instead, as the sandbox lets orgstar write only there. Nil when the panel is canceled.
678 private func writable(_ url: URL) -> URL? {
679 #if APPSTORE
680 guard !workspace.contains(url) else { return url }
681 let panel = NSSavePanel()
682 panel.directoryURL = url.deletingLastPathComponent()
683 panel.nameFieldStringValue = url.lastPathComponent
684 panel.message = String(localized: "This file isn't in one of your folders. Choose where the export goes.", comment: "Save panel for an export outside the sidebar's folders")
685 return panel.runModal() == .OK ? panel.url : nil
686 #else
687 return url
688 #endif
689 }
690
691 /// Says a command doesn't run in this build.
692 static func unavailable(_ title: String) -> String {
693 String(localized: "\(CommandTitle.localized(title)) isn't available.", comment: "A command the Mac App Store build leaves out")
694 }
695
660 /// `org-icalendar-export-agenda-files`, or with `combined`, `org-icalendar-combine-agenda-files`. 696 /// `org-icalendar-export-agenda-files`, or with `combined`, `org-icalendar-combine-agenda-files`.
661 private func exportAgendaCalendars(combined: Bool) { 697 private func exportAgendaCalendars(combined: Bool) {
662 let paths = workspace.agendaFilePaths() 698 let paths = workspace.agendaFilePaths()
@@ -740,6 +776,13 @@ struct ContentView: View {
740 panel.allowsMultipleSelection = true 776 panel.allowsMultipleSelection = true
741 panel.message = "File to keep as an attachment" 777 panel.message = "File to keep as an attachment"
742 guard panel.runModal() == .OK else { return } 778 guard panel.runModal() == .OK else { return }
779 #if APPSTORE
780 // The sandbox can remove only files in the sidebar's folders, and links nothing.
781 if method == .mv, let outside = panel.urls.first(where: { !workspace.contains($0) }) {
782 return commands.show(String(localized: "\(outside.lastPathComponent) isn't in one of your folders, so it can't be moved. Attach a copy instead.", comment: "Attach by moving a file from outside the sidebar's folders"))
783 }
784 guard method == .cp || method == .mv else { return }
785 #endif
743 attachActions.attach(panel.urls, method: method) 786 attachActions.attach(panel.urls, method: method)
744 }) 787 })
745 } 788 }
@@ -884,6 +927,10 @@ struct ContentView: View {
884 blockEdit = BlockEditRequest(edit: edit) 927 blockEdit = BlockEditRequest(edit: edit)
885 case .columnView(let view): 928 case .columnView(let view):
886 panel = .columns(UUID(), view) 929 panel = .columns(UUID(), view)
930 #if APPSTORE
931 case .emacsTable(_, _, _, let reason, _):
932 commands.show(String(localized: "This table's formulas can't be calculated here: \(TableReason.localized(reason)).", comment: "Table formulas orgstar can't calculate"))
933 #else
887 case .emacsTable(let table, let point, let form, let reason, let lisp): 934 case .emacsTable(let table, let point, let form, let reason, let lisp):
888 let run = { 935 let run = {
889 commands.show(String(localized: "Recalculating in Emacs (\(TableReason.localized(reason)))…", comment: "Table formulas sent to Emacs, and why")) 936 commands.show(String(localized: "Recalculating in Emacs (\(TableReason.localized(reason)))…", comment: "Table formulas sent to Emacs, and why"))
@@ -901,6 +948,7 @@ struct ContentView: View {
901 default: commands.show("Not recalculated") 948 default: commands.show("Not recalculated")
902 } 949 }
903 } 950 }
951 #endif
904 case .babel(let job): 952 case .babel(let job):
905 guard ProAccess.shared.allows(.babel) else { return } 953 guard ProAccess.shared.allows(.babel) else { return }
906 let run = { 954 let run = {
@@ -1007,6 +1055,10 @@ struct ContentView: View {
1007 1055
1008 /// Runs a command from a key, the palette or the Org menu. 1056 /// Runs a command from a key, the palette or the Org menu.
1009 private func perform(_ id: String) { 1057 private func perform(_ id: String) {
1058 if hiddenCommandIDs.contains(id) {
1059 if let replacement = AppStoreCommands.replacement(for: id) { return perform(replacement) }
1060 return commands.show(Self.unavailable(EditorCommands.all.first { $0.id == id }?.title ?? id))
1061 }
1010 if let feature = ProFeature.required(byCommand: id), !ProAccess.shared.allows(feature) { return } 1062 if let feature = ProFeature.required(byCommand: id), !ProAccess.shared.allows(feature) { return }
1011 let orgOnly = ["app.refile", "app.refile.copy", "app.archive", "app.clock.in", "app.clock.default", "app.copy-rich-text"].contains(id) || (id.hasPrefix("app.export.") && !id.hasPrefix("app.export.icalendar-")) || id.hasPrefix("org.") 1063 let orgOnly = ["app.refile", "app.refile.copy", "app.archive", "app.clock.in", "app.clock.default", "app.copy-rich-text"].contains(id) || (id.hasPrefix("app.export.") && !id.hasPrefix("app.export.icalendar-")) || id.hasPrefix("org.")
1012 if orgOnly, !session.isOrg { 1064 if orgOnly, !session.isOrg {
Sources/Orgstar/DevelopmentHooks.swift +2
@@ -1,3 +1,4 @@
1#if !APPSTORE
1import AppKit 2import AppKit
2import OrgEditorAppKit 3import OrgEditorAppKit
3 4
@@ -47,3 +48,4 @@ enum DevelopmentHooks {
47 } 48 }
48 } 49 }
49} 50}
51#endif
Sources/Orgstar/EmacsImportView.swift +5
@@ -44,7 +44,12 @@ struct EmacsImportView: View {
44 } 44 }
45 .frame(width: 640, height: 560) 45 .frame(width: 640, height: 560)
46 .onAppear { 46 .onAppear {
47 // The sandbox can't look in the home folder, so the App Store build starts with the picker.
48 #if APPSTORE
49 if location == nil { choosing = true }
50 #else
47 if location == nil, let first = EmacsImport.defaultLocations().first { read(first) } 51 if location == nil, let first = EmacsImport.defaultLocations().first { read(first) }
52 #endif
48 } 53 }
49 .fileImporter(isPresented: $choosing, allowedContentTypes: [.folder, .item]) { chosen in 54 .fileImporter(isPresented: $choosing, allowedContentTypes: [.folder, .item]) { chosen in
50 if case .success(let url) = chosen { read(url) } 55 if case .success(let url) = chosen { read(url) }
Sources/Orgstar/ExportSheet.swift +14 −1
@@ -8,7 +8,9 @@ struct ExportSheet: View {
8 let inSubtree: Bool 8 let inSubtree: Bool
9 /// The default destination for an extension, with or without the subtree. 9 /// The default destination for an extension, with or without the subtree.
10 let target: (_ ext: String, _ subtree: Bool) -> URL 10 let target: (_ ext: String, _ subtree: Bool) -> URL
11 let export: (_ format: String, _ destination: URL, _ open: Bool, _ subtree: Bool, _ bodyOnly: Bool) -> Void 11 /// Without a chosen destination, the App Store build passes nil, and the export asks where
12 /// to write when the default is outside the sandbox's reach.
13 let export: (_ format: String, _ destination: URL?, _ open: Bool, _ subtree: Bool, _ bodyOnly: Bool) -> Void
12 @AppStorage("exportFormat") private var format = "html" 14 @AppStorage("exportFormat") private var format = "html"
13 @AppStorage("exportOpenAfter") private var openAfter = false 15 @AppStorage("exportOpenAfter") private var openAfter = false
14 @AppStorage("exportBodyOnly") private var bodyOnly = false 16 @AppStorage("exportBodyOnly") private var bodyOnly = false
@@ -19,12 +21,19 @@ struct ExportSheet: View {
19 @State private var destination: URL? 21 @State private var destination: URL?
20 @Environment(\.dismiss) private var dismiss 22 @Environment(\.dismiss) private var dismiss
21 23
24 #if APPSTORE
25 static let formats: [(id: String, title: String, ext: String)] = [
26 ("html", "HTML", "html"), ("markdown", "Markdown", "md"), ("print-pdf", "PDF", "pdf"), ("docx", "Word", "docx"),
27 ("rtf", "Rich Text (RTF)", "rtf"), ("plain-text", "Plain text", "txt"), ("icalendar", "iCalendar", "ics"),
28 ]
29 #else
22 static let formats: [(id: String, title: String, ext: String)] = [ 30 static let formats: [(id: String, title: String, ext: String)] = [
23 ("html", "HTML", "html"), ("markdown", "Markdown", "md"), ("print-pdf", "PDF", "pdf"), ("docx", "Word", "docx"), 31 ("html", "HTML", "html"), ("markdown", "Markdown", "md"), ("print-pdf", "PDF", "pdf"), ("docx", "Word", "docx"),
24 ("rtf", "Rich Text (RTF)", "rtf"), ("plain-text", "Plain text", "txt"), ("pdf", "PDF via LaTeX (Emacs)", "pdf"), 32 ("rtf", "Rich Text (RTF)", "rtf"), ("plain-text", "Plain text", "txt"), ("pdf", "PDF via LaTeX (Emacs)", "pdf"),
25 ("odt", "ODT (Emacs)", "odt"), ("latex", "LaTeX (Emacs)", "tex"), ("text", "Plain text, ASCII (Emacs)", "txt"), 33 ("odt", "ODT (Emacs)", "odt"), ("latex", "LaTeX (Emacs)", "tex"), ("text", "Plain text, ASCII (Emacs)", "txt"),
26 ("icalendar", "iCalendar", "ics"), 34 ("icalendar", "iCalendar", "ics"),
27 ] 35 ]
36 #endif
28 37
29 private var ext: String { Self.formats.first { $0.id == format }?.ext ?? "html" } 38 private var ext: String { Self.formats.first { $0.id == format }?.ext ?? "html" }
30 private var chosen: URL { destination ?? target(ext, subtree) } 39 private var chosen: URL { destination ?? target(ext, subtree) }
@@ -68,7 +77,11 @@ struct ExportSheet: View {
68 Spacer() 77 Spacer()
69 Button("Cancel") { dismiss() }.keyboardShortcut(.cancelAction) 78 Button("Cancel") { dismiss() }.keyboardShortcut(.cancelAction)
70 Button("Export") { 79 Button("Export") {
80 #if APPSTORE
81 export(format, destination, openAfter, subtree && inSubtree, bodyOnly && allowsBodyOnly)
82 #else
71 export(format, chosen, openAfter, subtree && inSubtree, bodyOnly && allowsBodyOnly) 83 export(format, chosen, openAfter, subtree && inSubtree, bodyOnly && allowsBodyOnly)
84 #endif
72 dismiss() 85 dismiss()
73 } 86 }
74 .keyboardShortcut(.defaultAction) 87 .keyboardShortcut(.defaultAction)
Sources/Orgstar/Keys.swift +8 −1
@@ -179,6 +179,13 @@ extension EchoArea {
179 } 179 }
180} 180}
181 181
182/// Commands this build leaves out of the palette and menus; their keys say so when pressed.
183#if APPSTORE
184let hiddenCommandIDs = AppStoreCommands.hidden
185#else
186let hiddenCommandIDs: Set<String> = []
187#endif
188
182/// M-x and ⇧⌘P: every command by title, with its keys. 189/// M-x and ⇧⌘P: every command by title, with its keys.
183struct PaletteView: View { 190struct PaletteView: View {
184 let commands: AppCommands 191 let commands: AppCommands
@@ -187,7 +194,7 @@ struct PaletteView: View {
187 @Environment(\.dismiss) private var dismiss 194 @Environment(\.dismiss) private var dismiss
188 195
189 private var matches: [EditorCommand] { 196 private var matches: [EditorCommand] {
190 let scored: [(command: EditorCommand, score: Int)] = EditorCommands.all.filter(\.inPalette).compactMap { command in 197 let scored: [(command: EditorCommand, score: Int)] = EditorCommands.all.filter { $0.inPalette && !hiddenCommandIDs.contains($0.id) }.compactMap { command in
191 guard let score = FuzzyMatch.score(query, command.localizedTitle) ?? FuzzyMatch.score(query, command.title) else { return nil } 198 guard let score = FuzzyMatch.score(query, command.localizedTitle) ?? FuzzyMatch.score(query, command.title) else { return nil }
192 return (command, score) 199 return (command, score)
193 } 200 }
Sources/Orgstar/OrgstarApp.swift +24 −3
@@ -182,12 +182,16 @@ struct PromptRequest: Identifiable {
182final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCenterDelegate { 182final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCenterDelegate {
183 var session: DocumentSession? 183 var session: DocumentSession?
184 var commands: AppCommands? 184 var commands: AppCommands?
185 #if !APPSTORE
185 let updates = Updates() 186 let updates = Updates()
187 #endif
186 188
187 func applicationDidFinishLaunching(_ notification: Notification) { 189 func applicationDidFinishLaunching(_ notification: Notification) {
188 DockIcon.start() 190 DockIcon.start()
189 if SystemReminderCenter.isAvailable { UNUserNotificationCenter.current().delegate = self } 191 if SystemReminderCenter.isAvailable { UNUserNotificationCenter.current().delegate = self }
192 #if !APPSTORE
190 updates.start() 193 updates.start()
194 #endif
191 } 195 }
192 196
193 /// `:session` interpreters end with the app. 197 /// `:session` interpreters end with the app.
@@ -329,11 +333,14 @@ struct OrgstarApp: App {
329 }() 333 }()
330 334
331 init() { 335 init() {
332 #if !APPSTORE 336 #if APPSTORE
337 AgendaSnapshot.useGroupContainer = true
338 ProStore.shared.start()
339 #else
333 DocumentSession.programs = Programs() 340 DocumentSession.programs = Programs()
334 #endif
335 MacPro.resolve() 341 MacPro.resolve()
336 MacPro.renewInBackground() 342 MacPro.renewInBackground()
343 #endif
337 // Debug builds, and runs with ORGSTAR_PERF set: main-thread stalls in the console. 344 // Debug builds, and runs with ORGSTAR_PERF set: main-thread stalls in the console.
338 #if DEBUG 345 #if DEBUG
339 Perf.watchMainThread() 346 Perf.watchMainThread()
@@ -408,7 +415,7 @@ struct OrgstarApp: App {
408 } 415 }
409 CommandGroup(after: .saveItem) { 416 CommandGroup(after: .saveItem) {
410 Menu("Export") { 417 Menu("Export") {
411 ForEach(EditorCommands.all.filter { $0.id.hasPrefix("app.export.") }, id: \.id) { command in 418 ForEach(EditorCommands.all.filter { $0.id.hasPrefix("app.export.") && !hiddenCommandIDs.contains($0.id) }, id: \.id) { command in
412 Button(command.localizedTitle) { commands.run(command.id) } 419 Button(command.localizedTitle) { commands.run(command.id) }
413 } 420 }
414 } 421 }
@@ -511,12 +518,18 @@ struct OrgstarApp: App {
511 Button("Edit Config File") { commands.jump(path: UserConfig.configFile.path, offset: 0) } 518 Button("Edit Config File") { commands.jump(path: UserConfig.configFile.path, offset: 0) }
512 .keyboardShortcut(",", modifiers: [.command, .option]) 519 .keyboardShortcut(",", modifiers: [.command, .option])
513 } 520 }
521 #if !APPSTORE
514 CommandGroup(after: .appInfo) { 522 CommandGroup(after: .appInfo) {
515 CheckForUpdatesItem(updates: delegate.updates) 523 CheckForUpdatesItem(updates: delegate.updates)
516 } 524 }
525 #endif
517 } 526 }
518 Settings { 527 Settings {
528 #if APPSTORE
529 SettingsView(commands: commands, workspace: try? workspace.get())
530 #else
519 SettingsView(commands: commands, workspace: try? workspace.get(), updates: delegate.updates) 531 SettingsView(commands: commands, workspace: try? workspace.get(), updates: delegate.updates)
532 #endif
520 } 533 }
521 } 534 }
522} 535}
@@ -595,7 +608,9 @@ struct AgendaMenuItem: View {
595struct SettingsView: View { 608struct SettingsView: View {
596 let commands: AppCommands 609 let commands: AppCommands
597 let workspace: WorkspaceModel? 610 let workspace: WorkspaceModel?
611 #if !APPSTORE
598 let updates: Updates 612 let updates: Updates
613 #endif
599 @State private var importing = false 614 @State private var importing = false
600 @Environment(\.openWindow) private var openWindow 615 @Environment(\.openWindow) private var openWindow
601 @AppStorage("saveMode") private var saveMode = SaveMode.automatic 616 @AppStorage("saveMode") private var saveMode = SaveMode.automatic
@@ -659,7 +674,11 @@ struct SettingsView: View {
659 Tab("Appearance", systemImage: "paintpalette", value: "appearance") { appearance } 674 Tab("Appearance", systemImage: "paintpalette", value: "appearance") { appearance }
660 Tab("Agenda", systemImage: "calendar", value: "agenda") { agenda } 675 Tab("Agenda", systemImage: "calendar", value: "agenda") { agenda }
661 Tab("Capture", systemImage: "tray.and.arrow.down", value: "capture") { capture } 676 Tab("Capture", systemImage: "tray.and.arrow.down", value: "capture") { capture }
677 #if APPSTORE
678 Tab("orgstar+", systemImage: "star", value: "pro") { StoreForm() }
679 #else
662 Tab("orgstar+", systemImage: "star", value: "pro") { LicenseForm() } 680 Tab("orgstar+", systemImage: "star", value: "pro") { LicenseForm() }
681 #endif
663 } 682 }
664 .frame(width: 600) 683 .frame(width: 600)
665 } 684 }
@@ -687,6 +706,7 @@ struct SettingsView: View {
687 Text("Every setting here is also in \(UserConfig.configFile.path), which you can edit, share or keep with your dotfiles. Changes in either place show up in the other.") 706 Text("Every setting here is also in \(UserConfig.configFile.path), which you can edit, share or keep with your dotfiles. Changes in either place show up in the other.")
688 .settingsFooter() 707 .settingsFooter()
689 } 708 }
709 #if !APPSTORE
690 if updates.canCheck { 710 if updates.canCheck {
691 Section { 711 Section {
692 Toggle("Check for updates automatically", isOn: Binding(get: { updates.automatically }, set: { updates.automatically = $0 })) 712 Toggle("Check for updates automatically", isOn: Binding(get: { updates.automatically }, set: { updates.automatically = $0 }))
@@ -695,6 +715,7 @@ struct SettingsView: View {
695 .settingsFooter() 715 .settingsFooter()
696 } 716 }
697 } 717 }
718 #endif
698 Section { 719 Section {
699 Picker("Save files", selection: $saveMode) { 720 Picker("Save files", selection: $saveMode) {
700 Text("Automatically, when typing stops").tag(SaveMode.automatic) 721 Text("Automatically, when typing stops").tag(SaveMode.automatic)
Sources/Orgstar/ProLicense.swift +3
@@ -1,6 +1,7 @@
1import OrgApp 1import OrgApp
2import SwiftUI 2import SwiftUI
3 3
4#if !APPSTORE
4/// Pro on the Mac: a license key for sponsoring on GitHub, or an install that predates Pro. 5/// Pro on the Mac: a license key for sponsoring on GitHub, or an install that predates Pro.
5enum MacPro { 6enum MacPro {
6 static let buyURL = URL(string: "https://krz.sh/apps/orgstar/buy")! 7 static let buyURL = URL(string: "https://krz.sh/apps/orgstar/buy")!
@@ -129,6 +130,8 @@ struct ProPaywallSheet: View {
129 } 130 }
130} 131}
131 132
133#endif
134
132extension ProFeature { 135extension ProFeature {
133 /// The Pro features the Mac app has. 136 /// The Pro features the Mac app has.
134 static let macFeatures: [ProFeature] = [.babel, .export, .encryption, .roam, .widgets, .calendar, .shortcuts] 137 static let macFeatures: [ProFeature] = [.babel, .export, .encryption, .roam, .widgets, .calendar, .shortcuts]
Sources/Orgstar/StoreViews.swift added +64
@@ -0,0 +1,64 @@
1#if APPSTORE
2import OrgApp
3import StoreKit
4import SwiftUI
5
6// TODO(M1.6): the full Mac StoreKit UI (plans with per-period prices and renewal terms,
7// Manage Subscription, Terms and Privacy, Tips) replaces these two views, keeping their names.
8
9/// orgstar+ from the App Store: status, plans, and restoring.
10struct StoreForm: View {
11 private var store: ProStore { .shared }
12 private var access: ProAccess { .shared }
13
14 var body: some View {
15 Form {
16 Section {
17 LabeledContent("orgstar+", value: access.isUnlocked ? String(localized: "Unlocked") : String(localized: "Not purchased"))
18 }
19 if !access.isUnlocked {
20 Section {
21 ForEach(store.products, id: \.id) { product in
22 LabeledContent(product.displayName) {
23 Button(product.displayPrice) { Task { await store.buy(product) } }
24 .disabled(store.busy)
25 }
26 }
27 Button("Restore Purchases") { Task { await store.restore() } }
28 .disabled(store.busy)
29 if let message = store.message { Text(message).foregroundStyle(.secondary) }
30 }
31 }
32 Section("Included in orgstar+") {
33 ForEach(ProFeature.macFeatures) { feature in
34 Label(feature.title, systemImage: feature.systemImage)
35 }
36 }
37 }
38 .formStyle(.grouped)
39 .task { await store.loadProducts() }
40 }
41}
42
43/// Shown when a Pro feature is used without Pro.
44struct StorePaywallSheet: View {
45 let feature: ProFeature
46 @Environment(\.dismiss) private var dismiss
47
48 var body: some View {
49 VStack(alignment: .leading, spacing: 0) {
50 Label("\(feature.title) needs orgstar+", systemImage: feature.systemImage)
51 .font(.headline)
52 .padding([.horizontal, .top], 20)
53 StoreForm()
54 HStack {
55 Spacer()
56 Button("Done") { dismiss() }.keyboardShortcut(.defaultAction)
57 }
58 .padding([.horizontal, .bottom], 20)
59 }
60 .frame(width: 480, height: 520)
61 .onChange(of: ProAccess.shared.isUnlocked) { _, unlocked in if unlocked { dismiss() } }
62 }
63}
64#endif
Sources/Orgstar/Updates.swift +2
@@ -1,3 +1,4 @@
1#if !APPSTORE
1import Combine 2import Combine
2import Sparkle 3import Sparkle
3import SwiftUI 4import SwiftUI
@@ -40,3 +41,4 @@ struct CheckForUpdatesItem: View {
40 .disabled(!updates.canCheck) 41 .disabled(!updates.canCheck)
41 } 42 }
42} 43}
44#endif
Sources/OrgstarWidgets/AgendaTimeline.swift +3 −3
@@ -2,10 +2,10 @@ import OrgApp
2import SwiftUI 2import SwiftUI
3import WidgetKit 3import WidgetKit
4 4
5/// Whether the app lacks Pro, which the widgets need. Only iOS shares the flag with the widgets; 5/// Whether the app lacks Pro, which the widgets need. iOS and the App Store Mac app share the flag
6/// the Mac app stops writing their data instead. 6/// with the widgets; the Developer ID Mac app stops writing their data instead.
7var widgetsLocked: Bool { 7var widgetsLocked: Bool {
8 #if os(iOS) 8 #if os(iOS) || APPSTORE
9 !ProAccess.isUnlockedNow 9 !ProAccess.isUnlockedNow
10 #else 10 #else
11 false 11 false
Sources/OrgstarWidgets/OrgstarWidgets.swift +7
@@ -8,6 +8,13 @@ import WidgetKit
8/// the desktop and in Notification Center. 8/// the desktop and in Notification Center.
9@main 9@main
10struct OrgstarWidgets: WidgetBundle { 10struct OrgstarWidgets: WidgetBundle {
11 #if APPSTORE
12 /// The App Store app writes the widgets' data to the app group's container.
13 init() {
14 AgendaSnapshot.useGroupContainer = true
15 }
16 #endif
17
11 var body: some Widget { 18 var body: some Widget {
12 TodayWidget() 19 TodayWidget()
13 HabitsWidget() 20 HabitsWidget()
Tests/OrgAppTests/WorkspaceContainsTests.swift added +27
@@ -0,0 +1,27 @@
1import Foundation
2import Testing
3@testable import OrgApp
4
5struct WorkspaceContainsTests {
6 @Test func insideByWholeComponents() {
7 let root = URL(fileURLWithPath: "/tmp/notes")
8 #expect(WorkspaceModel.isInside(URL(fileURLWithPath: "/tmp/notes"), roots: [root]))
9 #expect(WorkspaceModel.isInside(URL(fileURLWithPath: "/tmp/notes/a/b.html"), roots: [root]))
10 #expect(WorkspaceModel.isInside(URL(fileURLWithPath: "/tmp/notes/../notes/b.html"), roots: [root]))
11 #expect(!WorkspaceModel.isInside(URL(fileURLWithPath: "/tmp/notes2/b.html"), roots: [root]))
12 #expect(!WorkspaceModel.isInside(URL(fileURLWithPath: "/tmp/b.html"), roots: [root]))
13 #expect(!WorkspaceModel.isInside(URL(fileURLWithPath: "/tmp/notes/b.html"), roots: []))
14 }
15
16 @Test func insideThroughSymbolicLinks() throws {
17 let base = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
18 defer { try? FileManager.default.removeItem(at: base) }
19 let real = base.appendingPathComponent("real")
20 try FileManager.default.createDirectory(at: real, withIntermediateDirectories: true)
21 let link = base.appendingPathComponent("link")
22 try FileManager.default.createSymbolicLink(at: link, withDestinationURL: real)
23 try Data().write(to: real.appendingPathComponent("a.org"))
24 #expect(WorkspaceModel.isInside(link.appendingPathComponent("a.org"), roots: [real]))
25 #expect(WorkspaceModel.isInside(real.appendingPathComponent("a.org"), roots: [link]))
26 }
27}
Tests/OrgCoreTests/BabelCompiledTests.swift +1 −1
@@ -220,6 +220,6 @@ struct BabelCompiledTests {
220 Issue.record("planned cider") 220 Issue.record("planned cider")
221 return 221 return
222 } 222 }
223 #expect(message == "The cider backend for clojure needs Emacs; orgstar runs babashka or clojure-cli.") 223 #expect(message == "The cider backend for clojure isn't supported; orgstar runs babashka or clojure-cli.")
224 } 224 }
225} 225}
Tests/OrgCoreTests/TableFormulaEntryTests.swift +1 −1
@@ -98,7 +98,7 @@ extension TableFormulaEntryTests {
98 let tab = try #require(committed(TableCommand(.nextField), symbolic, after: "*2")) 98 let tab = try #require(committed(TableCommand(.nextField), symbolic, after: "*2"))
99 #expect(tab.text == "| a | b |\n| x | =$1*2 |\n| y | |\n#+TBLFM: $2=$1*2\n", "\(tab.text.debugDescription)") 99 #expect(tab.text == "| a | b |\n| x | =$1*2 |\n| y | |\n#+TBLFM: $2=$1*2\n", "\(tab.text.debugDescription)")
100 #expect(tab.caret == (tab.text as NSString).range(of: "| y").location + 2) 100 #expect(tab.caret == (tab.text as NSString).range(of: "| y").location + 2)
101 #expect(tab.message?.hasPrefix("The formula was stored; recalculating it needs Emacs") == true) 101 #expect(tab.message?.hasPrefix("The formula was stored; it can't be calculated here") == true)
102 let prompted = try #require(committed(TableEvalFormula(named: false), symbolic, after: "| x", answers: ["formula": "$1+1"])) 102 let prompted = try #require(committed(TableEvalFormula(named: false), symbolic, after: "| x", answers: ["formula": "$1+1"]))
103 #expect(prompted.text.hasSuffix("#+TBLFM: $1=$1+1\n") && prompted.message != nil, "\(prompted)") 103 #expect(prompted.text.hasSuffix("#+TBLFM: $1=$1+1\n") && prompted.message != nil, "\(prompted)")
104 } 104 }
Tests/OrgEditorAppKitTests/AppStoreCommandsTests.swift added +20
@@ -0,0 +1,20 @@
1import Foundation
2import OrgEditorAppKit
3import Testing
4import OrgApp
5
6struct AppStoreCommandsTests {
7 @Test func hiddenCommandsExist() {
8 let ids = Set(EditorCommands.all.map(\.id))
9 #expect(AppStoreCommands.hidden.isSubset(of: ids))
10 }
11
12 @Test func pdfKeysExportThroughWebKit() throws {
13 let replacement = try #require(AppStoreCommands.replacement(for: "app.export.pdf"))
14 #expect(replacement == "app.export.print-pdf")
15 #expect(!AppStoreCommands.hidden.contains(replacement))
16 for id in AppStoreCommands.hidden where id != "app.export.pdf" {
17 #expect(AppStoreCommands.replacement(for: id) == nil)
18 }
19 }
20}