diff --git a/OrionToolbar/OrionMenuView.swift b/OrionToolbar/OrionMenuView.swift index 1dd9579..30b33c9 100644 --- a/OrionToolbar/OrionMenuView.swift +++ b/OrionToolbar/OrionMenuView.swift @@ -59,11 +59,11 @@ struct OrionMenuView: View { } .padding(14) } - .frame(height: 570) + .frame(height: 610) Divider().overlay(.white.opacity(0.10)) footer } - .frame(width: 790) + .frame(width: 960) .background( LinearGradient(colors: [Color(red: 0.10, green: 0.15, blue: 0.23), Color(red: 0.075, green: 0.09, blue: 0.13)], startPoint: .topTrailing, endPoint: .bottomLeading) ) @@ -179,7 +179,7 @@ struct OrionMenuView: View { Circle().fill(color).frame(width: 8, height: 8) Text(status.capitalized).font(.system(size: 12, weight: .medium)) .foregroundStyle(color) - }.frame(width: 103, alignment: .leading) + }.frame(width: 90, alignment: .leading) } private func integrated(_ machine: ParallelsVM) -> ServerDefinition? { @@ -189,11 +189,11 @@ struct OrionMenuView: View { private func runningRow(_ machine: ParallelsVM) -> some View { HStack(spacing: 10) { icon(machine) - Text(machine.name).font(.system(size: 12, weight: .semibold)).lineLimit(1).frame(width: 150, alignment: .leading) + Text(machine.name).font(.system(size: 12, weight: .semibold)).lineLimit(1).frame(width: 210, alignment: .leading) state(machine.status) Text(machine.ipAddress.isEmpty ? "—" : machine.ipAddress) .font(.system(size: 11, design: .monospaced)) - .foregroundStyle(OrionStyle.muted).lineLimit(1).frame(width: 100, alignment: .leading) + .foregroundStyle(OrionStyle.muted).lineLimit(1).frame(width: 125, alignment: .leading) Spacer(minLength: 0) if let server = integrated(machine) { action("SSH", "terminal", tint: OrionStyle.blue) { vm.openSSH(server) } @@ -201,8 +201,14 @@ struct OrionMenuView: View { action("Mailpit", "globe", tint: OrionStyle.blue) { vm.openMailpit(server) } .disabled(server.host.isEmpty || server.mailpitPort == nil) } - action("Restart", "arrow.clockwise", tint: OrionStyle.card) { vm.operate(machine, action: "restart") } - action("Stop", "stop.fill", tint: OrionStyle.red) { vm.operate(machine, action: "stop") } + if vm.busyVMIDs.contains(machine.id) { + ProgressView().controlSize(.small) + .frame(width: 70) + .help("Waiting for Parallels to complete the operation") + } else { + action("Restart", "arrow.clockwise", tint: OrionStyle.card) { vm.operate(machine, action: "restart") } + action("Stop", "stop.fill", tint: OrionStyle.red) { vm.operate(machine, action: "stop") } + } Menu { Button("Force Stop", role: .destructive) { pendingForceStop = machine } } label: { @@ -218,7 +224,7 @@ struct OrionMenuView: View { private func machineRow(_ machine: ParallelsVM) -> some View { HStack(spacing: 10) { icon(machine) - Text(machine.name).font(.system(size: 12, weight: .semibold)).lineLimit(1).frame(width: 180, alignment: .leading) + Text(machine.name).font(.system(size: 12, weight: .semibold)).lineLimit(1).frame(width: 230, alignment: .leading) state(machine.status) Text(machine.ipAddress.isEmpty ? "—" : machine.ipAddress) .font(.system(size: 11, design: .monospaced)) @@ -260,11 +266,11 @@ struct OrionMenuView: View { return HStack(spacing: 10) { if let machine { icon(machine) } else { Image(systemName: "server.rack").frame(width: 36, height: 36).foregroundStyle(.cyan) } - Text(server.name).font(.system(size: 12, weight: .semibold)).lineLimit(1).frame(width: 125, alignment: .leading) + Text(server.name).font(.system(size: 12, weight: .semibold)).lineLimit(1).frame(width: 185, alignment: .leading) state(status) Text(server.host.isEmpty ? "—" : server.host) .font(.system(size: 11, design: .monospaced)).foregroundStyle(OrionStyle.muted) - .lineLimit(1).frame(width: 98, alignment: .leading) + .lineLimit(1).frame(width: 125, alignment: .leading) Spacer(minLength: 0) if let machine { if status.lowercased() == "running" { @@ -279,6 +285,7 @@ struct OrionMenuView: View { .disabled(status.lowercased() != "running" || server.host.isEmpty || server.mailpitPort == nil) action("Remove", "trash", tint: OrionStyle.card) { pendingRemoval = server } } + .disabled(machine.map { vm.busyVMIDs.contains($0.id) } ?? false) .padding(.horizontal, 10).padding(.vertical, 7) .background(OrionStyle.card.opacity(0.75), in: RoundedRectangle(cornerRadius: 10)) } @@ -288,7 +295,7 @@ struct OrionMenuView: View { Label(title, systemImage: symbol) .font(.system(size: 11, weight: .semibold)) .lineLimit(1) - .frame(minWidth: 56) + .frame(minWidth: 48) }.buttonStyle(OrionActionStyle(tint: tint)) } @@ -312,7 +319,7 @@ private struct OrionActionStyle: ButtonStyle { func makeBody(configuration: Configuration) -> some View { configuration.label .foregroundStyle(.white) - .padding(.horizontal, 10).padding(.vertical, 8) + .padding(.horizontal, 8).padding(.vertical, 7) .background(tint.opacity(configuration.isPressed ? 0.65 : 1), in: RoundedRectangle(cornerRadius: 8)) .opacity(configuration.isPressed ? 0.8 : 1) } diff --git a/OrionToolbar/OrionMenuView.swift.bak-20261023-094430 b/OrionToolbar/OrionMenuView.swift.bak-20261023-094430 new file mode 100644 index 0000000..1dd9579 --- /dev/null +++ b/OrionToolbar/OrionMenuView.swift.bak-20261023-094430 @@ -0,0 +1,319 @@ +import AppKit +import SwiftUI + +private enum OrionStyle { + static let panel = Color(red: 0.105, green: 0.14, blue: 0.20) + static let card = Color(red: 0.15, green: 0.19, blue: 0.25) + static let blue = Color(red: 0.08, green: 0.39, blue: 0.91) + static let green = Color(red: 0.05, green: 0.88, blue: 0.49) + static let red = Color(red: 0.91, green: 0.19, blue: 0.23) + static let muted = Color(red: 0.62, green: 0.73, blue: 0.86) +} + +struct OrionMenuView: View { + @EnvironmentObject private var vm: OrionVMController + @Environment(\.openSettings) private var openSettings + @State private var showRunning = true + @State private var showAll = true + @State private var showIntegrated = true + @State private var pendingRemoval: ServerDefinition? + @State private var pendingForceStop: ParallelsVM? + + private var running: [ParallelsVM] { + vm.discoveredVMs.filter { $0.status.lowercased() == "running" } + } + + var body: some View { + VStack(spacing: 0) { + header + Divider().overlay(.white.opacity(0.10)) + ScrollView { + VStack(alignment: .leading, spacing: 15) { + section(icon: "play.fill", title: "Running Virtual Machines", count: "\(running.count) running", accent: OrionStyle.green, expanded: $showRunning) { + if running.isEmpty { + emptyState("No running virtual machines", icon: "moon.zzz") + } else { + ForEach(running) { machine in + runningRow(machine) + } + } + } + section(icon: "desktopcomputer", title: "All Virtual Machines", count: "\(vm.discoveredVMs.count) VMs", accent: .cyan, expanded: $showAll) { + if vm.discoveredVMs.isEmpty { + emptyState(vm.discovering ? "Discovering Parallels VMs…" : "No virtual machines found", icon: "desktopcomputer.trianglebadge.exclamationmark") + } else { + ForEach(vm.discoveredVMs) { machine in + machineRow(machine) + } + } + } + section(icon: "server.rack", title: "Integrated Servers", count: "\(vm.servers.count) servers", accent: OrionStyle.blue, expanded: $showIntegrated) { + if vm.servers.isEmpty { + emptyState("No integrations. Add a VM using + above.", icon: "plus.circle") + } else { + ForEach(vm.servers) { server in + integratedRow(server) + } + } + } + } + .padding(14) + } + .frame(height: 570) + Divider().overlay(.white.opacity(0.10)) + footer + } + .frame(width: 790) + .background( + LinearGradient(colors: [Color(red: 0.10, green: 0.15, blue: 0.23), Color(red: 0.075, green: 0.09, blue: 0.13)], startPoint: .topTrailing, endPoint: .bottomLeading) + ) + .preferredColorScheme(.dark) + .task { await vm.discoverVMs(); await vm.refreshAll() } + .alert("OrionToolbar", isPresented: Binding(get: { vm.lastError != nil }, set: { if !$0 { vm.lastError = nil } })) { + Button("OK") { vm.lastError = nil } + } message: { Text(vm.lastError ?? "") } + .confirmationDialog("Remove server integration?", isPresented: Binding(get: { pendingRemoval != nil }, set: { if !$0 { pendingRemoval = nil } }), titleVisibility: .visible) { + Button("Remove Integration", role: .destructive) { + if let server = pendingRemoval { vm.removeDefinition(server) } + pendingRemoval = nil + } + Button("Cancel", role: .cancel) { pendingRemoval = nil } + } message: { + Text("The Parallels virtual machine will not be deleted.") + } + .confirmationDialog("Force stop virtual machine?", isPresented: Binding(get: { pendingForceStop != nil }, set: { if !$0 { pendingForceStop = nil } }), titleVisibility: .visible) { + Button("Force Stop", role: .destructive) { + if let machine = pendingForceStop { vm.operate(machine, action: "force-stop") } + pendingForceStop = nil + } + Button("Cancel", role: .cancel) { pendingForceStop = nil } + } message: { Text("Force Stop immediately powers off the VM and can cause data loss.") } + } + + private var header: some View { + HStack(spacing: 12) { + Image(systemName: "server.rack") + .font(.system(size: 22, weight: .bold)) + .foregroundStyle(.cyan) + .frame(width: 37, height: 37) + .background(OrionStyle.blue.opacity(0.24), in: RoundedRectangle(cornerRadius: 10)) + Text("OrionToolbar").font(.system(size: 21, weight: .bold)) + Circle().fill(vm.discoveredVMs.isEmpty ? Color.orange : OrionStyle.green).frame(width: 8, height: 8) + Text(vm.discoveredVMs.isEmpty ? "Waiting for Parallels" : "Parallels Connected") + .foregroundStyle(OrionStyle.muted).font(.subheadline) + Spacer() + if vm.discovering { ProgressView().controlSize(.small) } + Button { Task { await vm.discoverVMs(); await vm.refreshAll() } } label: { + Image(systemName: "arrow.clockwise").font(.system(size: 16, weight: .semibold)) + }.buttonStyle(OrionActionStyle(tint: OrionStyle.card)).help("Refresh virtual machines") + Button { showSettings() } label: { + Image(systemName: "gearshape.fill").font(.system(size: 16)) + }.buttonStyle(OrionActionStyle(tint: OrionStyle.card)).help("Settings") + }.padding(.horizontal, 17).padding(.vertical, 13) + } + + private func section(icon: String, title: String, count: String, accent: Color, expanded: Binding, @ViewBuilder content: () -> Content) -> some View { + VStack(spacing: 4) { + Button { expanded.wrappedValue.toggle() } label: { + HStack(spacing: 10) { + Image(systemName: icon).font(.system(size: 17, weight: .bold)) + .foregroundStyle(accent).frame(width: 27) + Text(title).font(.system(size: 16, weight: .semibold)) + Spacer() + Text(count).font(.caption.weight(.medium)) + .foregroundStyle(accent) + .padding(.horizontal, 10).padding(.vertical, 5) + .background(accent.opacity(0.13), in: RoundedRectangle(cornerRadius: 8)) + Image(systemName: expanded.wrappedValue ? "chevron.up" : "chevron.down") + .font(.caption.weight(.bold)).foregroundStyle(OrionStyle.muted) + } + .contentShape(Rectangle()) + .padding(.horizontal, 11).padding(.vertical, 10) + }.buttonStyle(.plain) + if expanded.wrappedValue { + VStack(spacing: 3) { content() } + .padding(.horizontal, 5).padding(.bottom, 7) + } + } + .background(OrionStyle.panel.opacity(0.92), in: RoundedRectangle(cornerRadius: 16)) + .overlay(RoundedRectangle(cornerRadius: 16).strokeBorder(.white.opacity(0.09))) + } + + private func emptyState(_ title: String, icon: String) -> some View { + Label(title, systemImage: icon) + .font(.subheadline).foregroundStyle(OrionStyle.muted) + .frame(maxWidth: .infinity, alignment: .leading) + .padding(15) + } + + private func icon(_ machine: ParallelsVM) -> some View { + Group { + if let image = vm.icon(for: machine) { + Image(nsImage: image).resizable().scaledToFit() + } else { + Image(systemName: machine.operatingSystem == "Windows" ? "desktopcomputer" : "server.rack") + .font(.system(size: 21, weight: .medium)) + .foregroundStyle(.white) + .frame(maxWidth: .infinity, maxHeight: .infinity) + .background(osColor(machine.operatingSystem), in: Circle()) + } + }.frame(width: 36, height: 36) + } + + private func osColor(_ os: String) -> Color { + switch os { + case "Ubuntu": return .orange + case "Debian": return .pink + case "Fedora": return .blue + case "CentOS": return .purple + case "Alpine": return .teal + case "Windows": return .cyan + default: return OrionStyle.blue + } + } + + private func state(_ status: String) -> some View { + let s = status.lowercased() + let color: Color = s == "running" ? OrionStyle.green : (s == "stopped" ? OrionStyle.muted : .orange) + return HStack(spacing: 6) { + Circle().fill(color).frame(width: 8, height: 8) + Text(status.capitalized).font(.system(size: 12, weight: .medium)) + .foregroundStyle(color) + }.frame(width: 103, alignment: .leading) + } + + private func integrated(_ machine: ParallelsVM) -> ServerDefinition? { + vm.servers.first { $0.vmUUID == machine.id || $0.vmName == machine.name } + } + + private func runningRow(_ machine: ParallelsVM) -> some View { + HStack(spacing: 10) { + icon(machine) + Text(machine.name).font(.system(size: 12, weight: .semibold)).lineLimit(1).frame(width: 150, alignment: .leading) + state(machine.status) + Text(machine.ipAddress.isEmpty ? "—" : machine.ipAddress) + .font(.system(size: 11, design: .monospaced)) + .foregroundStyle(OrionStyle.muted).lineLimit(1).frame(width: 100, alignment: .leading) + Spacer(minLength: 0) + if let server = integrated(machine) { + action("SSH", "terminal", tint: OrionStyle.blue) { vm.openSSH(server) } + .disabled(server.host.isEmpty || server.sshUser.isEmpty) + action("Mailpit", "globe", tint: OrionStyle.blue) { vm.openMailpit(server) } + .disabled(server.host.isEmpty || server.mailpitPort == nil) + } + action("Restart", "arrow.clockwise", tint: OrionStyle.card) { vm.operate(machine, action: "restart") } + action("Stop", "stop.fill", tint: OrionStyle.red) { vm.operate(machine, action: "stop") } + Menu { + Button("Force Stop", role: .destructive) { pendingForceStop = machine } + } label: { + Image(systemName: "ellipsis").frame(width: 16) + }.menuStyle(.borderlessButton).frame(width: 22) + .help("More VM actions") + } + .disabled(vm.busyVMIDs.contains(machine.id)) + .padding(.horizontal, 10).padding(.vertical, 7) + .background(OrionStyle.card.opacity(0.75), in: RoundedRectangle(cornerRadius: 10)) + } + + private func machineRow(_ machine: ParallelsVM) -> some View { + HStack(spacing: 10) { + icon(machine) + Text(machine.name).font(.system(size: 12, weight: .semibold)).lineLimit(1).frame(width: 180, alignment: .leading) + state(machine.status) + Text(machine.ipAddress.isEmpty ? "—" : machine.ipAddress) + .font(.system(size: 11, design: .monospaced)) + .foregroundStyle(OrionStyle.muted).lineLimit(1) + Spacer(minLength: 2) + if vm.busyVMIDs.contains(machine.id) { ProgressView().controlSize(.small) } + else if machine.status.lowercased() == "running" { + action("Stop", "stop.fill", tint: OrionStyle.red) { vm.operate(machine, action: "stop") } + } else if ["suspended", "paused"].contains(machine.status.lowercased()) { + action("Resume", "play.fill", tint: OrionStyle.blue) { vm.operate(machine, action: "resume") } + } else { + action("Start", "play.fill", tint: OrionStyle.blue) { vm.operate(machine, action: "start") } + } + if vm.isIntegrated(machine) { + Image(systemName: "checkmark.circle.fill").foregroundStyle(OrionStyle.green) + .frame(width: 28).help("Integrated") + } else { + Button { vm.integrate(machine) } label: { + Image(systemName: "plus.circle").font(.system(size: 20)) + }.buttonStyle(.plain).foregroundStyle(OrionStyle.muted) + .frame(width: 28).help("Integrate VM") + } + Menu { + Button("Open in Parallels") { vm.openParallels() } + if machine.status.lowercased() == "running" { + Button("Restart") { vm.operate(machine, action: "restart") } + Button("Force Stop", role: .destructive) { pendingForceStop = machine } + } + } label: { Image(systemName: "chevron.right").foregroundStyle(OrionStyle.muted) } + .menuStyle(.borderlessButton).frame(width: 22) + } + .padding(.horizontal, 10).padding(.vertical, 7) + .background(OrionStyle.card.opacity(0.75), in: RoundedRectangle(cornerRadius: 10)) + } + + private func integratedRow(_ server: ServerDefinition) -> some View { + let machine = vm.discoveredVMs.first { $0.id == server.vmUUID || $0.name == server.vmName } + let status = machine?.status ?? "unavailable" + return HStack(spacing: 10) { + if let machine { icon(machine) } + else { Image(systemName: "server.rack").frame(width: 36, height: 36).foregroundStyle(.cyan) } + Text(server.name).font(.system(size: 12, weight: .semibold)).lineLimit(1).frame(width: 125, alignment: .leading) + state(status) + Text(server.host.isEmpty ? "—" : server.host) + .font(.system(size: 11, design: .monospaced)).foregroundStyle(OrionStyle.muted) + .lineLimit(1).frame(width: 98, alignment: .leading) + Spacer(minLength: 0) + if let machine { + if status.lowercased() == "running" { + action("Stop", "stop.fill", tint: OrionStyle.red) { vm.operate(machine, action: "stop") } + } else { + action("Start", "play.fill", tint: OrionStyle.blue) { vm.operate(machine, action: "start") } + } + } + action("SSH", "terminal", tint: OrionStyle.card) { vm.openSSH(server) } + .disabled(status.lowercased() != "running" || server.host.isEmpty || server.sshUser.isEmpty) + action("Mailpit", "globe", tint: OrionStyle.card) { vm.openMailpit(server) } + .disabled(status.lowercased() != "running" || server.host.isEmpty || server.mailpitPort == nil) + action("Remove", "trash", tint: OrionStyle.card) { pendingRemoval = server } + } + .padding(.horizontal, 10).padding(.vertical, 7) + .background(OrionStyle.card.opacity(0.75), in: RoundedRectangle(cornerRadius: 10)) + } + + private func action(_ title: String, _ symbol: String, tint: Color, perform: @escaping () -> Void) -> some View { + Button(action: perform) { + Label(title, systemImage: symbol) + .font(.system(size: 11, weight: .semibold)) + .lineLimit(1) + .frame(minWidth: 56) + }.buttonStyle(OrionActionStyle(tint: tint)) + } + + private var footer: some View { + HStack { + action("Open Parallels", "macwindow", tint: OrionStyle.card) { vm.openParallels() } + Spacer() + action("Settings…", "gearshape", tint: OrionStyle.card) { showSettings() } + action("Quit", "power", tint: OrionStyle.card) { NSApplication.shared.terminate(nil) } + }.padding(.horizontal, 17).padding(.vertical, 12) + } + + private func showSettings() { + openSettings() + NSApplication.shared.activate(ignoringOtherApps: true) + } +} + +private struct OrionActionStyle: ButtonStyle { + let tint: Color + func makeBody(configuration: Configuration) -> some View { + configuration.label + .foregroundStyle(.white) + .padding(.horizontal, 10).padding(.vertical, 8) + .background(tint.opacity(configuration.isPressed ? 0.65 : 1), in: RoundedRectangle(cornerRadius: 8)) + .opacity(configuration.isPressed ? 0.8 : 1) + } +} diff --git a/OrionToolbar/OrionVMController.swift b/OrionToolbar/OrionVMController.swift index 9ac15a0..191c1ab 100644 --- a/OrionToolbar/OrionVMController.swift +++ b/OrionToolbar/OrionVMController.swift @@ -83,7 +83,7 @@ final class OrionVMController: ObservableObject { await discoverVMs() await refreshAll() } - timer = Timer.scheduledTimer(withTimeInterval: 5, repeats: true) { [weak self] _ in Task { @MainActor in guard let self else { return }; await self.discoverVMs(); await self.refreshAll() } } + timer = Timer.scheduledTimer(withTimeInterval: 15, repeats: true) { [weak self] _ in Task { @MainActor in guard let self else { return }; await self.discoverVMs(); await self.refreshAll() } } } deinit { timer?.invalidate() } @@ -106,6 +106,12 @@ final class OrionVMController: ObservableObject { ) } + let knownBundlePaths = Dictionary(uniqueKeysWithValues: + discoveredVMs.compactMap { machine -> (String, String)? in + guard let path = machine.bundlePath else { return nil } + return (machine.id, path) + } + ) discoveredVMs = records.compactMap { record in guard let uuid = record["uuid"] as? String, let name = record["name"] as? String else { @@ -121,7 +127,7 @@ final class OrionVMController: ObservableObject { status: status, ipAddress: ip == "-" ? "" : ip, operatingSystem: ParallelsVM.detectOS(name), - bundlePath: nil + bundlePath: knownBundlePaths[uuid] ) } .sorted { @@ -130,7 +136,7 @@ final class OrionVMController: ObservableObject { } // Resolve Parallels VM bundles without requiring the guest to run. - for i in discoveredVMs.indices { + for i in discoveredVMs.indices where discoveredVMs[i].bundlePath == nil { if let detail = try? await runPrlctl(["list", "-i", discoveredVMs[i].id]) { let pattern = #"(?m)^\s*Home:\s*(.+?\.pvm)\s*$"# if let range = detail.range(of: pattern, options: .regularExpression) { diff --git a/OrionToolbar/OrionVMController.swift.bak-20261023-094430 b/OrionToolbar/OrionVMController.swift.bak-20261023-094430 new file mode 100644 index 0000000..9ac15a0 --- /dev/null +++ b/OrionToolbar/OrionVMController.swift.bak-20261023-094430 @@ -0,0 +1,358 @@ +import AppKit +import Foundation + +struct ServerDefinition: Identifiable, Codable, Hashable { + var id = UUID() + var name: String + var vmName: String + var vmUUID: String? = nil + 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) +} + + +struct ParallelsVM: Identifiable, Hashable { + let id: String + let name: String + let status: String + let ipAddress: String + let operatingSystem: String + var bundlePath: String? + + var symbol: String { + switch operatingSystem { + case "Windows": return "desktopcomputer" + case "Ubuntu": return "server.rack" + case "Debian": return "server.rack" + case "Fedora": return "server.rack" + case "CentOS": return "server.rack" + case "Alpine": return "server.rack" + case "Oracle Linux": return "server.rack" + default: return "desktopcomputer" + } + } + + static func detectOS(_ name: String) -> String { + let value = name.lowercased() + + if value.contains("windows") { return "Windows" } + if value.contains("ubuntu") { return "Ubuntu" } + if value.contains("debian") { return "Debian" } + if value.contains("fedora") { return "Fedora" } + if value.contains("centos") { return "CentOS" } + if value.contains("alpine") { return "Alpine" } + if value.contains("oracle") { return "Oracle Linux" } + if value.contains("rocky") { return "Rocky Linux" } + if value.contains("alma") { return "AlmaLinux" } + if value.contains("arch") { return "Arch Linux" } + if value.contains("gentoo") { return "Gentoo" } + if value.contains("freebsd") { return "FreeBSD" } + + return "Other" + } +} + +@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 = [] + @Published var lastError: String? + @Published var discoveredVMs: [ParallelsVM] = [] + @Published var selectedVMIDs: Set = [] + @Published var discovering = false + @Published var busyVMIDs: Set = [] + 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) { servers = saved } + else { servers = [.orion] } + Task { + await discoverVMs() + await refreshAll() + } + timer = Timer.scheduledTimer(withTimeInterval: 5, repeats: true) { [weak self] _ in Task { @MainActor in guard let self else { return }; await self.discoverVMs(); await self.refreshAll() } } + } + deinit { timer?.invalidate() } + + + func discoverVMs() async { + guard !discovering else { return } + + discovering = true + defer { discovering = false } + + do { + let output = try await runPrlctl(["list", "-a", "-j"]) + + guard let data = output.data(using: .utf8), + let records = try JSONSerialization.jsonObject( + with: data + ) as? [[String: Any]] else { + throw OrionError.commandFailed( + "Invalid Parallels VM discovery response." + ) + } + + discoveredVMs = records.compactMap { record in + guard let uuid = record["uuid"] as? String, + let name = record["name"] as? String else { + return nil + } + + let status = record["status"] as? String ?? "unknown" + let ip = record["ip_configured"] as? String ?? "" + + return ParallelsVM( + id: uuid, + name: name, + status: status, + ipAddress: ip == "-" ? "" : ip, + operatingSystem: ParallelsVM.detectOS(name), + bundlePath: nil + ) + } + .sorted { + $0.name.localizedStandardCompare($1.name) + == .orderedAscending + } + + // Resolve Parallels VM bundles without requiring the guest to run. + for i in discoveredVMs.indices { + if let detail = try? await runPrlctl(["list", "-i", discoveredVMs[i].id]) { + let pattern = #"(?m)^\s*Home:\s*(.+?\.pvm)\s*$"# + if let range = detail.range(of: pattern, options: .regularExpression) { + let line = String(detail[range.lowerBound.. Bool { + servers.contains { + $0.vmUUID == machine.id || + ($0.vmUUID == nil && $0.vmName == machine.name) + } + } + + func toggleSelection(_ machine: ParallelsVM) { + if selectedVMIDs.contains(machine.id) { + selectedVMIDs.remove(machine.id) + } else { + selectedVMIDs.insert(machine.id) + } + } + + func selectAllVMs() { + selectedVMIDs = Set(discoveredVMs.map(\.id)) + } + + func clearVMSelection() { + selectedVMIDs.removeAll() + } + + func integrateSelectedVMs() { + let selected = discoveredVMs.filter { + selectedVMIDs.contains($0.id) + } + + for machine in selected { + guard !isIntegrated(machine) else { continue } + + let server = ServerDefinition( + name: machine.name, + vmName: machine.name, + vmUUID: machine.id, + host: machine.ipAddress, + sshUser: "sysadmin", + sshPort: 22, + sshIdentityFile: "", + mailpitPort: nil + ) + + add(server) + } + + selectedVMIDs.removeAll() + } + + func icon(for machine: ParallelsVM) -> NSImage? { + guard let path = machine.bundlePath, + FileManager.default.fileExists(atPath: path) else { + return nil + } + + return NSWorkspace.shared.icon(forFile: path) + } + + 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 } + guard let machine = discoveredVMs.first(where: { + $0.id == server.vmUUID || $0.name == server.vmName + }) else { + statuses[server.id] = .unavailable("VM not found in Parallels") + return + } + switch machine.status.lowercased() { + case "running": statuses[server.id] = .running + case "stopped": statuses[server.id] = .stopped + case "suspended", "paused": statuses[server.id] = .suspended + default: statuses[server.id] = .unavailable(machine.status) + } + } + + func removeDefinition(_ server: ServerDefinition) { + servers.removeAll { $0.id == server.id } + statuses.removeValue(forKey: server.id) + busyServers.remove(server.id) + } + + var runningVMs: [ParallelsVM] { + discoveredVMs.filter { $0.status.lowercased() == "running" } + } + + func start(_ s: ServerDefinition) { perform(["start", s.vmUUID ?? s.vmName], server: s) } + func stop(_ s: ServerDefinition) { perform(["stop", s.vmUUID ?? s.vmName], server: s) } + func restart(_ s: ServerDefinition) { perform(["restart", s.vmUUID ?? s.vmName], server: s) } + func forceStop(_ s: ServerDefinition) { perform(["stop", s.vmUUID ?? 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 operate(_ machine: ParallelsVM, action: String) { + guard !busyVMIDs.contains(machine.id) else { return } + busyVMIDs.insert(machine.id) + lastError = nil + Task { + let arguments = action == "force-stop" + ? ["stop", machine.id, "--kill"] + : [action, machine.id] + do { _ = try await runPrlctl(arguments) } + catch { lastError = error.localizedDescription } + busyVMIDs.remove(machine.id) + await discoverVMs() + await refreshAll() + } + } + + func integrate(_ machine: ParallelsVM) { + guard !isIntegrated(machine) else { return } + add(ServerDefinition(name: machine.name, vmName: machine.name, + vmUUID: machine.id, host: machine.ipAddress, sshUser: "", + sshPort: 22, sshIdentityFile: "", mailpitPort: nil)) + } + + func icon(for server: ServerDefinition) -> NSImage? { + guard let machine = discoveredVMs.first(where: { + $0.id == server.vmUUID || $0.name == server.vmName + }) else { return nil } + return icon(for: machine) + } + + 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(); let data = pipe.fileHandleForReading.readDataToEndOfFile(); p.waitUntilExit(); let out = String(decoding: data, 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) } } }