Initial Commit

This commit is contained in:
Mark Gregory
2026-10-23 07:10:24 +01:00
commit d3db58bc8d
61 changed files with 3033 additions and 0 deletions
@@ -0,0 +1,134 @@
import SwiftUI
struct OrionMenuView: View {
@EnvironmentObject var vm: OrionVMController
@Environment(\.openSettings) private var openSettings
private var server: ServerDefinition { vm.servers.first ?? .orion }
private var status: OrionVMController.VMStatus { vm.status(for: server) }
var body: some View {
VStack(alignment: .leading, spacing: 0) {
statusRow
separator
menuRow("terminal", "Open SSH in Terminal") { vm.openSSH(server) }
.disabled(status != .running)
menuRow("envelope.fill", "Open Mailpit", tint: .blue) { vm.openMailpit(server) }
.disabled(status != .running || server.mailpitPort == nil)
separator
if status == .stopped {
menuRow("play.fill", "Start", tint: .green) { vm.start(server) }
} else {
menuRow("stop.fill", "Stop", tint: .red) { vm.stop(server) }
.disabled(vm.isBusy(server))
menuRow("arrow.clockwise", "Restart", tint: .orange) { vm.restart(server) }
.disabled(vm.isBusy(server) || status != .running)
menuRow("exclamationmark.triangle.fill", "Force Stop", tint: .orange) { vm.forceStop(server) }
.disabled(vm.isBusy(server))
}
separator
menuRow("macwindow", "Open in Parallels Desktop", tint: .red) { vm.openParallels() }
separator
menuRow("gearshape.fill", "Settings…", tint: .secondary) {
openSettings()
NSApplication.shared.activate(ignoringOtherApps: true)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.15) {
NSApplication.shared.activate(ignoringOtherApps: true)
NSApplication.shared.windows
.filter { $0.isVisible }
.forEach { $0.makeKeyAndOrderFront(nil) }
}
}
separator
menuRow("xmark", "Quit OrionToolbar") { NSApplication.shared.terminate(nil) }
}
.padding(.horizontal, 16)
.padding(.vertical, 10)
.frame(width: 365)
.task { await vm.refreshStatus(server) }
}
private var statusRow: some View {
Button {
Task { await vm.refreshStatus(server) }
} label: {
HStack(spacing: 12) {
Circle()
.fill(statusDotColor)
.frame(width: 12, height: 12)
VStack(alignment: .leading, spacing: 3) {
Text(server.name)
.font(.system(size: 17, weight: .medium))
.foregroundStyle(.primary)
HStack(spacing: 5) {
Text(status.title)
.foregroundStyle(.secondary)
Text("·")
.foregroundStyle(.secondary)
Text(reachabilityText)
.foregroundStyle(reachabilityColor)
}
.font(.system(size: 14))
}
Spacer()
if vm.isBusy(server) {
ProgressView().controlSize(.small)
} else {
Image(systemName: "chevron.right")
.font(.system(size: 15, weight: .semibold))
.foregroundStyle(.secondary)
}
}
.contentShape(Rectangle())
.frame(height: 62)
}
.buttonStyle(.plain)
}
private var separator: some View {
Divider().padding(.vertical, 4)
}
private func menuRow(_ icon: String, _ title: String, tint: Color = .primary, action: @escaping () -> Void) -> some View {
Button(action: action) {
HStack(spacing: 14) {
Image(systemName: icon)
.font(.system(size: 17, weight: .medium))
.foregroundStyle(tint)
.frame(width: 24, alignment: .center)
Text(title)
.font(.system(size: 16))
.foregroundStyle(.primary)
Spacer()
}
.contentShape(Rectangle())
.frame(height: 43)
}
.buttonStyle(.plain)
}
private var statusDotColor: Color {
switch status {
case .running: .green
case .stopped, .unavailable: .red
case .suspended, .transitioning: .orange
case .checking: .gray
}
}
private var reachabilityText: String {
switch status {
case .running: "Reachable"
case .checking: "Checking…"
case .transitioning: "Working…"
default: "Unavailable"
}
}
private var reachabilityColor: Color {
status == .running ? .green : .secondary
}
}
@@ -0,0 +1,126 @@
import AppKit
import Foundation
struct ServerDefinition: Identifiable, Codable, Hashable {
var id = UUID()
var name: String
var vmName: String
var host: String
var sshUser: String
var sshPort: Int = 22
var sshIdentityFile: String = ""
var mailpitPort: Int?
static let orion = ServerDefinition(name: "Orion", vmName: "Ubuntu Linux Server", host: "10.211.55.100", sshUser: "sysadmin", sshPort: 22, sshIdentityFile: "", mailpitPort: 8025)
}
@MainActor
final class OrionVMController: ObservableObject {
enum VMStatus: Equatable {
case checking, running, stopped, suspended, transitioning, unavailable(String)
var title: String { switch self { case .checking: "Checking…"; case .running: "Running"; case .stopped: "Stopped"; case .suspended: "Suspended"; case .transitioning: "Working…"; case .unavailable: "Unavailable" } }
var symbolName: String { switch self { case .running: "server.rack"; case .stopped: "power"; case .suspended: "pause.circle"; case .transitioning, .checking: "arrow.triangle.2.circlepath"; case .unavailable: "exclamationmark.triangle" } }
}
@Published var servers: [ServerDefinition] { didSet { saveServers() } }
@Published var statuses: [UUID: VMStatus] = [:]
@Published var busyServers: Set<UUID> = []
@Published var lastError: String?
private var timer: Timer?
private let defaultsKey = "serverDefinitions.v2"
init() {
if let data = UserDefaults.standard.data(forKey: defaultsKey), let saved = try? JSONDecoder().decode([ServerDefinition].self, from: data), !saved.isEmpty { servers = saved }
else { servers = [.orion] }
Task { await refreshAll() }
timer = Timer.scheduledTimer(withTimeInterval: 5, repeats: true) { [weak self] _ in Task { @MainActor in await self?.refreshAll() } }
}
deinit { timer?.invalidate() }
func status(for server: ServerDefinition) -> VMStatus { statuses[server.id] ?? .checking }
func isBusy(_ server: ServerDefinition) -> Bool { busyServers.contains(server.id) }
func add(_ server: ServerDefinition) { servers.append(server); Task { await refreshStatus(server) } }
func update(_ server: ServerDefinition) { if let i = servers.firstIndex(where: { $0.id == server.id }) { servers[i] = server; Task { await refreshStatus(server) } } }
func delete(at offsets: IndexSet) { for i in offsets { statuses[servers[i].id] = nil }; servers.remove(atOffsets: offsets) }
func refreshAll() async { for server in servers { await refreshStatus(server) } }
func refreshStatus(_ server: ServerDefinition) async {
guard !isBusy(server) else { return }
do {
let output = try await runPrlctl(["status", server.vmName]); let value = output.lowercased()
if value.contains("running") { statuses[server.id] = .running }
else if value.contains("stopped") { statuses[server.id] = .stopped }
else if value.contains("suspended") || value.contains("paused") { statuses[server.id] = .suspended }
else { statuses[server.id] = .unavailable(output.trimmingCharacters(in: .whitespacesAndNewlines)) }
} catch { statuses[server.id] = .unavailable(error.localizedDescription) }
}
func start(_ s: ServerDefinition) { perform(["start", s.vmName], server: s) }
func stop(_ s: ServerDefinition) { perform(["stop", s.vmName], server: s) }
func restart(_ s: ServerDefinition) { perform(["restart", s.vmName], server: s) }
func forceStop(_ s: ServerDefinition) { perform(["stop", s.vmName, "--kill"], server: s) }
private func perform(_ arguments: [String], server: ServerDefinition) {
guard !isBusy(server) else { return }; busyServers.insert(server.id); statuses[server.id] = .transitioning; lastError = nil
Task { do { _ = try await runPrlctl(arguments) } catch { lastError = error.localizedDescription }; busyServers.remove(server.id); try? await Task.sleep(for: .seconds(1)); await refreshStatus(server) }
}
func openSSH(_ s: ServerDefinition) {
let userHost = "\(s.sshUser)@\(s.host)"
var command = "/usr/bin/ssh -p \(s.sshPort)"
let identity = s.sshIdentityFile.trimmingCharacters(in: .whitespacesAndNewlines)
if !identity.isEmpty {
command += " -i \(shellQuote((identity as NSString).expandingTildeInPath))"
}
command += " \(shellQuote(userHost))"
do {
// Terminal reliably opens executable .command files without requiring
// Apple Events/Automation permission from this menu-bar application.
let directory = FileManager.default.temporaryDirectory
.appendingPathComponent("OrionToolbar", isDirectory: true)
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
let safeName = s.name.replacingOccurrences(of: "/", with: "-")
let scriptURL = directory.appendingPathComponent("SSH-\(safeName).command")
let script = """
#!/bin/zsh
clear
echo "Connecting to \(s.name) (\(userHost))..."
exec \(command)
"""
try script.write(to: scriptURL, atomically: true, encoding: .utf8)
try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: scriptURL.path)
guard let terminalURL = NSWorkspace.shared.urlForApplication(withBundleIdentifier: "com.apple.Terminal") else {
lastError = "Terminal.app could not be found."
return
}
let configuration = NSWorkspace.OpenConfiguration()
configuration.activates = true
NSWorkspace.shared.open([scriptURL], withApplicationAt: terminalURL, configuration: configuration) { _, error in
Task { @MainActor in
if let error { self.lastError = "Could not open Terminal: \(error.localizedDescription)" }
}
}
} catch {
lastError = "Could not create SSH launcher: \(error.localizedDescription)"
}
}
private func shellQuote(_ value: String) -> String {
"'" + value.replacingOccurrences(of: "'", with: "'\"'\"'") + "'"
}
func openMailpit(_ s: ServerDefinition) { if let p = s.mailpitPort, let url = URL(string: "http://\(s.host):\(p)") { NSWorkspace.shared.open(url) } }
func openParallels() { NSWorkspace.shared.openApplication(at: URL(fileURLWithPath: "/Applications/Parallels Desktop.app"), configuration: .init()) }
private func saveServers() { if let data = try? JSONEncoder().encode(servers) { UserDefaults.standard.set(data, forKey: defaultsKey) } }
private func prlctlURL() -> URL? { ["/usr/local/bin/prlctl", "/Applications/Parallels Desktop.app/Contents/MacOS/prlctl"].map(URL.init(fileURLWithPath:)).first { FileManager.default.isExecutableFile(atPath: $0.path) } }
private func runPrlctl(_ arguments: [String]) async throws -> String {
guard let executable = prlctlURL() else { throw OrionError.prlctlNotFound }
return try await Task.detached(priority: .userInitiated) { let p = Process(); let pipe = Pipe(); p.executableURL = executable; p.arguments = arguments; p.standardOutput = pipe; p.standardError = pipe; try p.run(); p.waitUntilExit(); let out = String(decoding: pipe.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self); guard p.terminationStatus == 0 else { throw OrionError.commandFailed(out) }; return out }.value
}
}
enum OrionError: LocalizedError { case prlctlNotFound, commandFailed(String); var errorDescription: String? { switch self { case .prlctlNotFound: "Parallels prlctl was not found."; case .commandFailed(let o): o.trimmingCharacters(in: .whitespacesAndNewlines) } } }