tera
12
Wow, that's awesome project!
Here's a very crude version of an alternative "low-tech" approach (running "/usr/bin/swift" from within the app)
import SwiftUI
// MARK: sandbox is disabled
// tried com.apple.security.temporary-exception.files.absolute-path.read-only /usr/bin/swift
// but that didn't work for some reason
// TODO: proper error checking and remove force unwrapping
struct ContentView: View {
@State var source = #"print("Hello, World!")"#
@State var output = ""
@State var outcome = ""
@State var executing = false
var body: some View {
VStack(alignment: .leading) {
HStack {
Spacer()
Button("run", action: run)
.disabled(executing)
.keyboardShortcut(.defaultAction)
}
TextEditor(text: $source)
.monospaced()
.font(.title2)
TextEditor(text: $output)
.disabled(true)
.font(.title2)
.foregroundColor(.secondary)
Text(outcome)
.font(.title2)
.foregroundColor(.red)
}
.padding()
}
func run() {
let fileUrl = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("foo.swift")
let outputUrl = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("output.txt")
try! source.data(using: .utf8)!.write(to: fileUrl)
try! "".data(using: .utf8)!.write(to: outputUrl)
let task = try! NSUserUnixTask(url: URL(fileURLWithPath: "/usr/bin/swift"))
let file = try! FileHandle(forWritingTo: outputUrl)
task.standardOutput = file
task.standardError = file
output = ""
outcome = ""
executing = true
task.execute(withArguments: [fileUrl.path]) { error in
let data = try! Data(contentsOf: outputUrl)
output = String(data: data, encoding: .utf8)!
outcome = error?.localizedDescription ?? ""
executing = false
try? file.close()
}
}
}
// smart quotes workaround
extension NSTextView {
open override var frame: CGRect {
didSet {
isAutomaticQuoteSubstitutionEnabled = false
}
}
}
@main struct macUApp: App {
var body: some Scene {
WindowGroup { ContentView() }
}
}
Obviously this depends on "/usr/bin/swift" being available on the computer. Note that this was very quickly cooked and the code is littered with unsafe optional unwrapping and lacks proper error handling.
I had to disable sandbox as I wasn't able to talk macOS into using a provided temporary exception absolute file path readonly access. With sandbox enabled the app will refuse with: "The file "swift" couldn't be opened because you don't have permission to view it."
Example output

1 Like