Sources/Orgstar/EmacsImportView.swift

58f3b73e8ff337e5a15111fbb32c0d57cf2346da
orgstar/Sources/Orgstar/EmacsImportView.swift history · blame · raw

172 lines · 7341 bytes

8 symbols in this file
  1import OrgApp
  2import OrgCore
  3import SwiftUI
  4
  5/// Import from Emacs: what was read from a configuration, to pick from before anything changes.
  6struct EmacsImportView: View {
  7    let workspace: WorkspaceModel?
  8    @Environment(\.dismiss) private var dismiss
  9    @State private var location: URL?
 10    @State private var result: EmacsImport?
 11    @State private var selected: Set<Int> = []
 12    @State private var choosing = false
 13    @State private var summary: String?
 14    @State private var importing = false
 15    /// Doom's own folder, chosen in the App Store build, where the sandbox can't find it.
 16    @State private var doomInstall: URL?
 17
 18    var body: some View {
 19        VStack(alignment: .leading, spacing: 0) {
 20            header
 21            Divider()
 22            if let summary {
 23                Text(summary).padding(20).frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
 24            } else if let result {
 25                list(result)
 26            } else {
 27                ContentUnavailableView("No Emacs configuration found", systemImage: "doc.questionmark",
 28                                       description: Text("Choose your init.el, or the folder holding it (~/.emacs.d, ~/.config/doom)."))
 29            }
 30            Divider()
 31            HStack {
 32                if let result, summary == nil {
 33                    Text(footnote(result)).font(.caption).foregroundStyle(.secondary)
 34                }
 35                Spacer()
 36                if summary == nil {
 37                    Button("Cancel") { dismiss() }.keyboardShortcut(.cancelAction)
 38                    Button("Import") { runImport() }
 39                        .keyboardShortcut(.defaultAction)
 40                        .disabled(selected.isEmpty || importing)
 41                } else {
 42                    Button("Done") { dismiss() }.keyboardShortcut(.defaultAction)
 43                }
 44            }
 45            .padding(12)
 46        }
 47        .frame(width: 640, height: 560)
 48        .onAppear {
 49            // The sandbox can't look in the home folder, so the App Store build starts with the picker.
 50            #if APPSTORE
 51            if location == nil { DispatchQueue.main.async { choose() } }
 52            #else
 53            if location == nil, let first = EmacsImport.defaultLocations().first { read(first) }
 54            #endif
 55        }
 56        .fileImporter(isPresented: $choosing, allowedContentTypes: [.folder, .item]) { chosen in
 57            if case .success(let url) = chosen { read(url) }
 58        }
 59    }
 60
 61    private var header: some View {
 62        HStack {
 63            VStack(alignment: .leading, spacing: 2) {
 64                Text("Import from Emacs").font(.headline)
 65                Text(location.map { "Reading \($0.path)" + (withDoomDefaults ? ", with Doom's own org defaults" : "") } ?? "")
 66                    .font(.caption).foregroundStyle(.secondary).lineLimit(2)
 67            }
 68            Spacer()
 69            #if APPSTORE
 70            if let result, result.isDoom, !result.doomDefaultsRead {
 71                Button("Choose Doom Folder…") { chooseDoom() }
 72                    .help("Doom's own org defaults are read from the folder Doom is installed in")
 73            }
 74            #endif
 75            Button("Choose…") { choose() }
 76        }
 77        .padding(12)
 78    }
 79
 80    private var withDoomDefaults: Bool {
 81        #if APPSTORE
 82        result?.doomDefaultsRead ?? false
 83        #else
 84        result?.isDoom ?? false
 85        #endif
 86    }
 87
 88    private func choose() {
 89        #if APPSTORE
 90        let message = String(localized: "Choose your init.el, or the folder holding it (~/.emacs.d, ~/.config/doom).",
 91                             comment: "Open panel for importing an Emacs configuration")
 92        if let url = GrantAccess.choose(at: EmacsImport.pickerLocation(), message: message, prompt: String(localized: "Choose"), files: true, hidden: true) {
 93            read(url)
 94        }
 95        #else
 96        choosing = true
 97        #endif
 98    }
 99
100    #if APPSTORE
101    /// Doom's install folder, for its org defaults; the sandbox keeps orgstar from finding it.
102    private func chooseDoom() {
103        let message = String(localized: "Choose the folder Doom is installed in (~/.config/emacs or ~/.emacs.d) to read Doom's own org defaults.",
104                             comment: "Open panel for Doom's install folder when importing from Emacs")
105        guard let install = EmacsImport.doomInstallLocations().first,
106              let url = GrantAccess.choose(at: install, message: message, prompt: String(localized: "Choose"), hidden: true),
107              let location else { return }
108        doomInstall = url
109        read(location)
110    }
111
112    /// Asks for each folder the import adds, with an open panel at it, and adds the folders
113    /// chosen there: the sandbox lets orgstar into those alone.
114    private func chooseFolders(_ items: [EmacsImport.Item]) -> [String: URL] {
115        var chosen: [String: URL] = [:]
116        for path in EmacsImport.foldersToAdd(items, workspace: workspace) where chosen[path] == nil {
117            let name = OrgPaths.abbreviatingWithTilde(OrgPaths.expandingTilde(path))
118            let message = String(localized: "Choose \(name) to add it to the sidebar.", comment: "Open panel for a folder imported from Emacs")
119            if let url = GrantAccess.choose(at: URL(fileURLWithPath: OrgPaths.expandingTilde(path)), message: message,
120                                            prompt: String(localized: "Add Folder")) {
121                chosen[path] = url
122            }
123        }
124        return chosen
125    }
126    #endif
127
128    private func list(_ result: EmacsImport) -> some View {
129        List {
130            EmacsImportSections(result: result, groups: result.groups(folders: true), selected: $selected,
131                                font: .system(.body, design: .monospaced))
132        }
133    }
134
135    private func footnote(_ result: EmacsImport) -> String {
136        var parts = ["\(result.skipped) variables not about org left alone"]
137        if result.doomDefaultsLeftOut > 0 { parts.append("\(result.doomDefaultsLeftOut) Doom defaults orgstar has no use for") }
138        #if APPSTORE
139        if result.isDoom, !result.doomDefaultsRead { parts.append("Doom's own org defaults skipped") }
140        #endif
141        return parts.joined(separator: "; ")
142    }
143
144    private func read(_ url: URL) {
145        let accessing = url.startAccessingSecurityScopedResource()
146        defer { if accessing { url.stopAccessingSecurityScopedResource() } }
147        location = url
148        #if APPSTORE
149        let scanned = EmacsImport.scan(EmacsImport.files(in: url), doomDefaults: doomInstall.map(EmacsImport.doomDefaultFiles(in:)))
150        #else
151        let scanned = EmacsImport.scan(EmacsImport.files(in: url))
152        #endif
153        result = scanned
154        selected = Set(scanned.items.map(\.id))
155        summary = nil
156    }
157
158    private func runImport() {
159        guard let result else { return }
160        importing = true
161        let chosen = result.items.filter { selected.contains($0.id) }
162        #if APPSTORE
163        let folders: [String: URL]? = chooseFolders(chosen)
164        #else
165        let folders: [String: URL]? = nil
166        #endif
167        Task {
168            summary = await EmacsImport.apply(chosen, workspace: workspace, chosenFolders: folders)
169            importing = false
170        }
171    }
172}