Sources/Orgstar/EmacsImportView.swift

62e3c7dafd265558ed379cccd7ca5877f42fafec
orgstar/Sources/Orgstar/EmacsImportView.swift

173 lines · 7458 bytes

  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 result.snippetsSkipped > 0 { parts.append("\(result.snippetsSkipped) snippets with Emacs Lisp skipped") }
139        #if APPSTORE
140        if result.isDoom, !result.doomDefaultsRead { parts.append("Doom's own org defaults skipped") }
141        #endif
142        return parts.joined(separator: "; ")
143    }
144
145    private func read(_ url: URL) {
146        let accessing = url.startAccessingSecurityScopedResource()
147        defer { if accessing { url.stopAccessingSecurityScopedResource() } }
148        location = url
149        #if APPSTORE
150        let scanned = EmacsImport.scan(EmacsImport.files(in: url), doomDefaults: doomInstall.map(EmacsImport.doomDefaultFiles(in:)))
151        #else
152        let scanned = EmacsImport.scan(EmacsImport.files(in: url))
153        #endif
154        result = scanned
155        selected = Set(scanned.items.map(\.id))
156        summary = nil
157    }
158
159    private func runImport() {
160        guard let result else { return }
161        importing = true
162        let chosen = result.items.filter { selected.contains($0.id) }
163        #if APPSTORE
164        let folders: [String: URL]? = chooseFolders(chosen)
165        #else
166        let folders: [String: URL]? = nil
167        #endif
168        Task {
169            summary = await EmacsImport.apply(chosen, workspace: workspace, chosenFolders: folders)
170            importing = false
171        }
172    }
173}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form