updates to launcer
This commit is contained in:
@@ -11,6 +11,7 @@ private enum OrionStyle {
|
||||
}
|
||||
|
||||
struct OrionMenuView: View {
|
||||
@Environment(\.openWindow) private var openWindow
|
||||
@EnvironmentObject private var vm: OrionVMController
|
||||
@State private var showRunning = true
|
||||
@State private var showAll = true
|
||||
@@ -258,7 +259,7 @@ struct OrionMenuView: View {
|
||||
if !server.host.isEmpty && !server.sshUser.isEmpty && vm.reachableSSH.contains(server.id) {
|
||||
action("SSH", "terminal", tint: OrionStyle.blue) { vm.openSSH(server) }
|
||||
}
|
||||
if !server.host.isEmpty && server.mailpitPort != nil && vm.reachableMailpit.contains(server.id) {
|
||||
if !server.host.isEmpty && (server.mailpitPort.map { (1...65535).contains($0) } ?? false) {
|
||||
action("Mailpit", "globe", tint: OrionStyle.blue) { vm.openMailpit(server) }
|
||||
}
|
||||
}
|
||||
@@ -381,7 +382,7 @@ struct OrionMenuView: View {
|
||||
if !server.host.isEmpty && !server.sshUser.isEmpty && vm.reachableSSH.contains(server.id) {
|
||||
action("SSH", "terminal", tint: OrionStyle.card) { vm.openSSH(server) }
|
||||
}
|
||||
if !server.host.isEmpty && server.mailpitPort != nil && vm.reachableMailpit.contains(server.id) {
|
||||
if !server.host.isEmpty && (server.mailpitPort.map { (1...65535).contains($0) } ?? false) {
|
||||
action("Mailpit", "globe", tint: OrionStyle.card) { vm.openMailpit(server) }
|
||||
}
|
||||
action("Remove", "trash", tint: OrionStyle.card) { pendingRemoval = server }
|
||||
@@ -417,6 +418,10 @@ struct OrionMenuView: View {
|
||||
HStack {
|
||||
action("Open Parallels", "macwindow", tint: OrionStyle.card) { vm.openParallels() }
|
||||
Spacer()
|
||||
action("Help", "questionmark.circle", tint: OrionStyle.card) {
|
||||
NSApp.activate(ignoringOtherApps: true)
|
||||
openWindow(id: "orion-help")
|
||||
}
|
||||
action("Settings…", "gearshape", tint: OrionStyle.card) { showSettings() }
|
||||
action("Quit", "power", tint: OrionStyle.card) { NSApplication.shared.terminate(nil) }
|
||||
}.padding(.horizontal, 17).padding(.vertical, 12)
|
||||
@@ -445,7 +450,6 @@ private final class OrionSettingsWindowPresenter: NSObject, NSWindowDelegate {
|
||||
private static var current: OrionSettingsWindowPresenter?
|
||||
|
||||
private var window: NSWindow?
|
||||
private weak var parentWindow: NSWindow?
|
||||
|
||||
static func present(vm: OrionVMController) {
|
||||
if let current, let window = current.window {
|
||||
@@ -460,10 +464,6 @@ private final class OrionSettingsWindowPresenter: NSObject, NSWindowDelegate {
|
||||
}
|
||||
|
||||
private func open(vm: OrionVMController) {
|
||||
// Capture the currently active menu-bar panel.
|
||||
let parent = NSApp.keyWindow
|
||||
?? NSApp.windows.first(where: { $0.isVisible })
|
||||
|
||||
let content = SettingsView()
|
||||
.environmentObject(vm)
|
||||
.preferredColorScheme(.dark)
|
||||
@@ -482,23 +482,382 @@ private final class OrionSettingsWindowPresenter: NSObject, NSWindowDelegate {
|
||||
window.center()
|
||||
|
||||
self.window = window
|
||||
self.parentWindow = parent
|
||||
|
||||
if let parent {
|
||||
parent.addChildWindow(window, ordered: .above)
|
||||
}
|
||||
|
||||
NSApp.activate(ignoringOtherApps: true)
|
||||
window.makeKeyAndOrderFront(nil)
|
||||
window.orderFrontRegardless()
|
||||
}
|
||||
|
||||
func windowWillClose(_ notification: Notification) {
|
||||
if let window {
|
||||
parentWindow?.removeChildWindow(window)
|
||||
}
|
||||
|
||||
window = nil
|
||||
Self.current = nil
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Operating System Installation Help
|
||||
|
||||
private struct OrionHelpGuide: Identifiable {
|
||||
let id: String
|
||||
let title: String
|
||||
let category: String
|
||||
let description: String
|
||||
let commands: String
|
||||
let verification: String
|
||||
let notes: String
|
||||
}
|
||||
|
||||
private enum OrionHelpLibrary {
|
||||
static let systems = [
|
||||
"Ubuntu",
|
||||
"Debian",
|
||||
"Fedora",
|
||||
"CentOS Stream",
|
||||
"Alpine"
|
||||
]
|
||||
|
||||
static func guides(for system: String) -> [OrionHelpGuide] {
|
||||
let apt = system == "Ubuntu" || system == "Debian"
|
||||
let dnf = system == "Fedora" || system == "CentOS Stream"
|
||||
let alpine = system == "Alpine"
|
||||
|
||||
let update = apt
|
||||
? "sudo apt update"
|
||||
: dnf
|
||||
? "sudo dnf makecache"
|
||||
: "sudo apk update"
|
||||
|
||||
func packages(_ names: String) -> String {
|
||||
if apt { return "sudo apt install -y \(names)" }
|
||||
if dnf { return "sudo dnf install -y \(names)" }
|
||||
return "sudo apk add \(names)"
|
||||
}
|
||||
|
||||
func guide(
|
||||
_ id: String,
|
||||
_ title: String,
|
||||
_ category: String,
|
||||
_ description: String,
|
||||
_ commands: String,
|
||||
_ verification: String,
|
||||
_ notes: String = ""
|
||||
) -> OrionHelpGuide {
|
||||
OrionHelpGuide(
|
||||
id: id,
|
||||
title: title,
|
||||
category: category,
|
||||
description: description,
|
||||
commands: commands,
|
||||
verification: verification,
|
||||
notes: notes
|
||||
)
|
||||
}
|
||||
|
||||
let nginx = guide(
|
||||
"nginx", "Nginx", "Web Servers",
|
||||
"Install and enable the Nginx web server.",
|
||||
"""
|
||||
\(update)
|
||||
\(packages("nginx"))
|
||||
sudo systemctl enable --now nginx
|
||||
""",
|
||||
"systemctl status nginx --no-pager\ncurl -I http://127.0.0.1",
|
||||
"On Alpine with OpenRC, use: sudo rc-update add nginx default; sudo rc-service nginx start."
|
||||
)
|
||||
|
||||
let phpPackages = apt
|
||||
? "php-cli php-fpm php-mysql php-pgsql php-xml php-mbstring php-curl php-zip php-gd php-intl php-bcmath"
|
||||
: dnf
|
||||
? "php-cli php-fpm php-mysqlnd php-pgsql php-xml php-mbstring php-curl php-zip php-gd php-intl php-bcmath"
|
||||
: "php php-fpm php-mysqli php-pgsql php-xml php-mbstring php-curl php-zip php-gd php-intl"
|
||||
|
||||
let php = guide(
|
||||
"php", "PHP and PHP-FPM", "PHP",
|
||||
"Install the distribution's default PHP version and commonly used extensions.",
|
||||
"""
|
||||
\(update)
|
||||
\(packages(phpPackages))
|
||||
php -v
|
||||
php -m
|
||||
""",
|
||||
"php -v\nphp -m\nsystemctl list-unit-files '*php*fpm*'",
|
||||
"PHP versions and PHP-FPM service names vary by distribution. CentOS Stream may require a third-party repository for PHP 8.5. Alpine uses OpenRC rather than systemd."
|
||||
)
|
||||
|
||||
let composer = guide(
|
||||
"composer", "Composer", "PHP",
|
||||
"Install the Composer dependency manager.",
|
||||
"""
|
||||
\(update)
|
||||
\(packages("composer"))
|
||||
""",
|
||||
"composer --version",
|
||||
"Distribution packages may provide an older Composer version."
|
||||
)
|
||||
|
||||
let database = guide(
|
||||
"mariadb", "MariaDB", "Databases",
|
||||
"Install a MariaDB database server.",
|
||||
"""
|
||||
\(update)
|
||||
\(packages(alpine ? "mariadb mariadb-client" : "mariadb-server"))
|
||||
\(alpine ? "# Initialise the data directory according to your Alpine release." : "sudo systemctl enable --now mariadb")
|
||||
""",
|
||||
"mariadb --version",
|
||||
"For Alpine, initialise the database and enable the mariadb OpenRC service before use. Secure database accounts and avoid exposing port 3306 publicly."
|
||||
)
|
||||
|
||||
let postgres = guide(
|
||||
"postgresql", "PostgreSQL", "Databases",
|
||||
"Install PostgreSQL using the distribution repository.",
|
||||
"""
|
||||
\(update)
|
||||
\(packages(alpine ? "postgresql postgresql-client" : "postgresql postgresql-server"))
|
||||
""",
|
||||
"psql --version",
|
||||
"PostgreSQL cluster initialization and service names differ across distributions. Fedora/CentOS commonly require postgresql-setup --initdb before starting the service."
|
||||
)
|
||||
|
||||
let cachePackage = system == "Fedora" || system == "CentOS Stream"
|
||||
? "valkey"
|
||||
: "redis"
|
||||
|
||||
let cache = guide(
|
||||
"cache", "Redis / Valkey", "Caching",
|
||||
"Install the distribution's Redis-compatible cache server.",
|
||||
"""
|
||||
\(update)
|
||||
\(packages(cachePackage))
|
||||
\(alpine ? "# Enable and start the appropriate OpenRC service." : "sudo systemctl enable --now \(cachePackage)")
|
||||
""",
|
||||
"\(cachePackage == "valkey" ? "valkey-cli" : "redis-cli") ping",
|
||||
"Keep the cache bound to localhost or a private interface. Do not expose it publicly without appropriate security controls."
|
||||
)
|
||||
|
||||
let mailpit = guide(
|
||||
"mailpit", "Mailpit", "Email Testing",
|
||||
"Mailpit provides a local SMTP test server and a browser-based inbox.",
|
||||
"""
|
||||
# Install Mailpit from its official release or package instructions.
|
||||
# Verify the binary after installation:
|
||||
mailpit --version
|
||||
|
||||
# Example foreground test:
|
||||
mailpit --listen 127.0.0.1:8025 --smtp 127.0.0.1:1025
|
||||
""",
|
||||
"curl -I http://127.0.0.1:8025\nss -lntp | grep -E '8025|1025'",
|
||||
"Web interface: 8025. SMTP: 1025. For OrionToolbar access from macOS, bind the web listener to the VM's private interface and restrict access using the firewall. Do not expose an unauthenticated Mailpit inbox publicly."
|
||||
)
|
||||
|
||||
let cockpit = guide(
|
||||
"cockpit", "Cockpit", "Administration",
|
||||
"Install the browser-based Linux administration console.",
|
||||
"""
|
||||
\(update)
|
||||
\(packages("cockpit"))
|
||||
\(alpine ? "# Configure the Cockpit service if supported by this Alpine release." : "sudo systemctl enable --now cockpit.socket")
|
||||
""",
|
||||
"ss -lntp | grep 9090",
|
||||
"Cockpit typically uses HTTPS port 9090. Package and service availability vary on Alpine."
|
||||
)
|
||||
|
||||
let ssh = guide(
|
||||
"ssh", "OpenSSH Server", "Administration",
|
||||
"Install an SSH server for remote administration.",
|
||||
"""
|
||||
\(update)
|
||||
\(packages(alpine ? "openssh" : "openssh-server"))
|
||||
\(alpine ? "sudo rc-update add sshd default\nsudo rc-service sshd start" : "sudo systemctl enable --now sshd 2>/dev/null || sudo systemctl enable --now ssh")
|
||||
""",
|
||||
"ss -lntp | grep ':22'",
|
||||
"Use SSH keys where possible and restrict access through the firewall."
|
||||
)
|
||||
|
||||
let git = guide(
|
||||
"git", "Git", "Development",
|
||||
"Install Git for source control.",
|
||||
"""
|
||||
\(update)
|
||||
\(packages("git"))
|
||||
""",
|
||||
"git --version"
|
||||
)
|
||||
|
||||
let node = guide(
|
||||
"node", "Node.js and npm", "Development",
|
||||
"Install the distribution's Node.js runtime and npm.",
|
||||
"""
|
||||
\(update)
|
||||
\(packages("nodejs npm"))
|
||||
""",
|
||||
"node --version\nnpm --version",
|
||||
"For specific Node.js versions, use a supported version manager or official distribution packages."
|
||||
)
|
||||
|
||||
let tools = guide(
|
||||
"tools", "Build Tools", "Development",
|
||||
"Install compilers and common build utilities.",
|
||||
"""
|
||||
\(update)
|
||||
\(packages(apt ? "build-essential curl wget unzip" : dnf ? "gcc gcc-c++ make curl wget unzip" : "build-base curl wget unzip"))
|
||||
""",
|
||||
"gcc --version\nmake --version"
|
||||
)
|
||||
|
||||
let apache = guide(
|
||||
"apache", "Apache HTTP Server", "Web Servers",
|
||||
"Install Apache as an alternative to Nginx.",
|
||||
"""
|
||||
\(update)
|
||||
\(packages(apt ? "apache2" : dnf ? "httpd" : "apache2"))
|
||||
\(alpine ? "sudo rc-update add apache2 default\nsudo rc-service apache2 start" : "sudo systemctl enable --now \(apt ? "apache2" : "httpd")")
|
||||
""",
|
||||
"curl -I http://127.0.0.1"
|
||||
)
|
||||
|
||||
return [
|
||||
nginx, apache, php, composer,
|
||||
database, postgres, cache, mailpit,
|
||||
cockpit, ssh, git, node, tools
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
struct OrionHelpView: View {
|
||||
@State private var system = "Fedora"
|
||||
@State private var selectedGuide = "mailpit"
|
||||
@State private var search = ""
|
||||
|
||||
private var guides: [OrionHelpGuide] {
|
||||
OrionHelpLibrary.guides(for: system)
|
||||
}
|
||||
|
||||
private var filtered: [OrionHelpGuide] {
|
||||
guard !search.isEmpty else { return guides }
|
||||
return guides.filter {
|
||||
$0.title.localizedCaseInsensitiveContains(search) ||
|
||||
$0.category.localizedCaseInsensitiveContains(search) ||
|
||||
$0.description.localizedCaseInsensitiveContains(search)
|
||||
}
|
||||
}
|
||||
|
||||
private var selected: OrionHelpGuide? {
|
||||
guides.first { $0.id == selectedGuide }
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
NavigationSplitView {
|
||||
VStack(spacing: 10) {
|
||||
Picker("Operating System", selection: $system) {
|
||||
ForEach(OrionHelpLibrary.systems, id: \.self) { name in
|
||||
Text(name).tag(name)
|
||||
}
|
||||
}
|
||||
.padding(.horizontal, 12)
|
||||
.padding(.top, 12)
|
||||
|
||||
List(selection: $selectedGuide) {
|
||||
ForEach(filtered) { guide in
|
||||
Label(guide.title, systemImage: icon(for: guide.category))
|
||||
.tag(guide.id)
|
||||
}
|
||||
}
|
||||
.listStyle(.sidebar)
|
||||
.searchable(text: $search, prompt: "Find components")
|
||||
}
|
||||
.navigationSplitViewColumnWidth(min: 220, ideal: 250)
|
||||
} detail: {
|
||||
if let guide = selected {
|
||||
ScrollView {
|
||||
VStack(alignment: .leading, spacing: 20) {
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
Text(guide.category.uppercased())
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
|
||||
Text(guide.title)
|
||||
.font(.largeTitle.bold())
|
||||
|
||||
Text(guide.description)
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
|
||||
commandSection(
|
||||
"Installation",
|
||||
text: guide.commands
|
||||
)
|
||||
|
||||
commandSection(
|
||||
"Verification",
|
||||
text: guide.verification
|
||||
)
|
||||
|
||||
if !guide.notes.isEmpty {
|
||||
VStack(alignment: .leading, spacing: 8) {
|
||||
Label("Important Notes", systemImage: "info.circle")
|
||||
.font(.headline)
|
||||
|
||||
Text(guide.notes)
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
}
|
||||
.padding()
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.background(.quaternary.opacity(0.4),
|
||||
in: RoundedRectangle(cornerRadius: 10))
|
||||
}
|
||||
|
||||
Text("Review commands before running them. Package names and service configuration may differ between releases.")
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
.padding(24)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
.navigationTitle(guide.title)
|
||||
} else {
|
||||
ContentUnavailableView(
|
||||
"Select a Component",
|
||||
systemImage: "questionmark.circle"
|
||||
)
|
||||
}
|
||||
}
|
||||
.frame(minWidth: 850, minHeight: 580)
|
||||
}
|
||||
|
||||
private func commandSection(_ title: String, text: String) -> some View {
|
||||
VStack(alignment: .leading, spacing: 10) {
|
||||
HStack {
|
||||
Text(title)
|
||||
.font(.headline)
|
||||
|
||||
Spacer()
|
||||
|
||||
Button {
|
||||
NSPasteboard.general.clearContents()
|
||||
NSPasteboard.general.setString(text, forType: .string)
|
||||
} label: {
|
||||
Label("Copy Commands", systemImage: "doc.on.doc")
|
||||
}
|
||||
}
|
||||
|
||||
Text(text)
|
||||
.font(.system(size: 12, design: .monospaced))
|
||||
.textSelection(.enabled)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.padding(14)
|
||||
.background(Color(nsColor: .textBackgroundColor),
|
||||
in: RoundedRectangle(cornerRadius: 9))
|
||||
}
|
||||
}
|
||||
|
||||
private func icon(for category: String) -> String {
|
||||
switch category {
|
||||
case "Web Servers": return "globe"
|
||||
case "PHP": return "chevron.left.forwardslash.chevron.right"
|
||||
case "Databases": return "externaldrive"
|
||||
case "Caching": return "memorychip"
|
||||
case "Email Testing": return "envelope"
|
||||
case "Administration": return "gearshape"
|
||||
default: return "hammer"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,504 @@
|
||||
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
|
||||
@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.visibleVMs.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.visibleVMs.count) VMs", accent: .cyan, expanded: $showAll) {
|
||||
if vm.visibleVMs.isEmpty {
|
||||
emptyState(vm.discovering ? "Discovering Parallels VMs…" : "No virtual machines found", icon: "desktopcomputer.trianglebadge.exclamationmark")
|
||||
} else {
|
||||
ForEach(vm.visibleVMs) { 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.filter { server in
|
||||
!vm.hiddenVMIDs.contains(server.vmUUID ??
|
||||
vm.discoveredVMs.first(where: { $0.name == server.vmName })?.id ?? "")
|
||||
}) { server in
|
||||
integratedRow(server)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
.padding(14)
|
||||
}
|
||||
.frame(height: 610)
|
||||
Divider().overlay(.white.opacity(0.10))
|
||||
footer
|
||||
}
|
||||
.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)
|
||||
)
|
||||
|
||||
.preferredColorScheme(.dark)
|
||||
.task {
|
||||
await vm.discoverVMs()
|
||||
await vm.refreshAll()
|
||||
while !Task.isCancelled {
|
||||
await vm.refreshServiceAvailability()
|
||||
try? await Task.sleep(for: .seconds(10))
|
||||
}
|
||||
}
|
||||
.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()
|
||||
Menu {
|
||||
if vm.hiddenVMs.isEmpty {
|
||||
Text("No removed virtual machines")
|
||||
} else {
|
||||
ForEach(vm.hiddenVMs) { machine in
|
||||
Button("Re-add " + machine.name) { vm.restoreVM(machine) }
|
||||
}
|
||||
}
|
||||
} label: {
|
||||
Label("Re-add VM", systemImage: "plus.rectangle.on.folder")
|
||||
}
|
||||
.help("Restore virtual machines removed from OrionToolbar")
|
||||
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<Content: View>(icon: String, title: String, count: String, accent: Color, expanded: Binding<Bool>, @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: 90, alignment: .leading)
|
||||
}
|
||||
|
||||
private func integrated(_ machine: ParallelsVM) -> ServerDefinition? {
|
||||
vm.servers.first { $0.vmUUID == machine.id || $0.vmName == machine.name }
|
||||
}
|
||||
|
||||
// Native text selection supports Command-C; the copy button works in menu-bar panels.
|
||||
private func vmIdentity(name: String, ip: String, os: String, fallbackIP: String = "") -> some View {
|
||||
let address = ip.isEmpty ? fallbackIP : ip
|
||||
return VStack(alignment: .leading, spacing: 5) {
|
||||
Text(name)
|
||||
.font(.system(size: 12, weight: .semibold))
|
||||
.foregroundStyle(.white)
|
||||
.lineLimit(1)
|
||||
HStack(spacing: 6) {
|
||||
Image(systemName: "network")
|
||||
.font(.system(size: 10))
|
||||
.foregroundStyle(OrionStyle.muted)
|
||||
Text(address.isEmpty ? "No IP assigned" : address)
|
||||
.font(.system(size: 11, design: .monospaced))
|
||||
.foregroundStyle(OrionStyle.muted)
|
||||
.textSelection(.enabled)
|
||||
.lineLimit(1)
|
||||
if !address.isEmpty {
|
||||
Button {
|
||||
NSPasteboard.general.clearContents()
|
||||
NSPasteboard.general.setString(address, forType: .string)
|
||||
} label: {
|
||||
Image(systemName: "doc.on.doc")
|
||||
.font(.system(size: 10))
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.foregroundStyle(OrionStyle.muted)
|
||||
.help("Copy IP address: " + address)
|
||||
}
|
||||
if !os.isEmpty {
|
||||
Text("· " + os)
|
||||
.font(.system(size: 10))
|
||||
.foregroundStyle(OrionStyle.muted.opacity(0.75))
|
||||
.lineLimit(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func runningRow(_ machine: ParallelsVM) -> some View {
|
||||
HStack(spacing: 10) {
|
||||
icon(machine)
|
||||
vmIdentity(name: machine.name, ip: machine.ipAddress, os: machine.operatingSystem)
|
||||
.frame(width: 265, alignment: .leading)
|
||||
state(machine.status)
|
||||
Spacer(minLength: 0)
|
||||
if let server = integrated(machine) {
|
||||
if !server.host.isEmpty && !server.sshUser.isEmpty && vm.reachableSSH.contains(server.id) {
|
||||
action("SSH", "terminal", tint: OrionStyle.blue) { vm.openSSH(server) }
|
||||
}
|
||||
if !server.host.isEmpty && server.mailpitPort != nil && vm.reachableMailpit.contains(server.id) {
|
||||
action("Mailpit", "globe", tint: OrionStyle.blue) { vm.openMailpit(server) }
|
||||
}
|
||||
}
|
||||
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") }
|
||||
.padding(.leading, 6)
|
||||
}
|
||||
Menu {
|
||||
Button("Force Stop", role: .destructive) { pendingForceStop = machine }
|
||||
} label: {
|
||||
Image(systemName: "ellipsis").frame(width: 22)
|
||||
}.menuStyle(.borderlessButton).frame(width: 30)
|
||||
.padding(.leading, 12)
|
||||
.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)
|
||||
HStack(spacing: 6) {
|
||||
Image(systemName: "line.3.horizontal")
|
||||
.foregroundStyle(OrionStyle.muted)
|
||||
vmIdentity(name: machine.name, ip: machine.ipAddress, os: machine.operatingSystem)
|
||||
}
|
||||
.frame(width: 280, alignment: .leading)
|
||||
.contentShape(Rectangle())
|
||||
.onDrag { NSItemProvider(object: ("vm:" + machine.id) as NSString) }
|
||||
state(machine.status)
|
||||
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") }
|
||||
}
|
||||
Button {
|
||||
vm.hideVM(machine)
|
||||
} label: {
|
||||
Image(systemName: "minus.circle")
|
||||
.foregroundStyle(OrionStyle.muted)
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.help("Remove from OrionToolbar (keeps the Parallels VM)")
|
||||
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")
|
||||
}
|
||||
|
||||
}
|
||||
.padding(.horizontal, 10).padding(.vertical, 7)
|
||||
.background(OrionStyle.card.opacity(0.75), in: RoundedRectangle(cornerRadius: 10))
|
||||
.contextMenu {
|
||||
Button("Remove from OrionToolbar", systemImage: "minus.circle") {
|
||||
vm.hideVM(machine)
|
||||
}
|
||||
}
|
||||
.onDrop(of: [.plainText], isTargeted: nil) { providers in
|
||||
guard let provider = providers.first else { return false }
|
||||
_ = provider.loadObject(ofClass: NSString.self) { item, _ in
|
||||
guard let string = item as? NSString else { return }
|
||||
let value = string as String
|
||||
guard value.hasPrefix("vm:") else { return }
|
||||
Task { @MainActor in
|
||||
vm.reorderVM(draggedID: String(value.dropFirst(3)), onto: machine.id)
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
private func integratedRow(_ server: ServerDefinition) -> some View {
|
||||
let machine = vm.machine(for: server)
|
||||
let status = machine?.status ?? "unavailable"
|
||||
return HStack(spacing: 10) {
|
||||
Group {
|
||||
if let image = vm.icon(for: server) {
|
||||
Image(nsImage: image).resizable().scaledToFit()
|
||||
} else if let machine {
|
||||
icon(machine)
|
||||
} else {
|
||||
Image(systemName: "server.rack").foregroundStyle(.cyan)
|
||||
}
|
||||
}.frame(width: 36, height: 36)
|
||||
HStack(spacing: 5) {
|
||||
Image(systemName: "line.3.horizontal").foregroundStyle(OrionStyle.muted)
|
||||
vmIdentity(name: server.name,
|
||||
ip: machine?.ipAddress ?? "",
|
||||
os: machine?.operatingSystem ?? "",
|
||||
fallbackIP: server.host)
|
||||
}
|
||||
.frame(width: 280, alignment: .leading)
|
||||
.onDrag {
|
||||
NSItemProvider(object: ("server:" + server.id.uuidString) as NSString)
|
||||
}
|
||||
state(status)
|
||||
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") }
|
||||
}
|
||||
}
|
||||
if !server.host.isEmpty && !server.sshUser.isEmpty && vm.reachableSSH.contains(server.id) {
|
||||
action("SSH", "terminal", tint: OrionStyle.card) { vm.openSSH(server) }
|
||||
}
|
||||
if !server.host.isEmpty && server.mailpitPort != nil && vm.reachableMailpit.contains(server.id) {
|
||||
action("Mailpit", "globe", tint: OrionStyle.card) { vm.openMailpit(server) }
|
||||
}
|
||||
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))
|
||||
.onDrop(of: [.plainText], isTargeted: nil) { providers in
|
||||
guard let provider = providers.first else { return false }
|
||||
_ = provider.loadObject(ofClass: NSString.self) { item, _ in
|
||||
guard let string = item as? NSString else { return }
|
||||
let value = string as String
|
||||
guard value.hasPrefix("server:"),
|
||||
let dragged = UUID(uuidString: String(value.dropFirst(7))) else { return }
|
||||
Task { @MainActor in
|
||||
vm.reorderServer(draggedID: dragged, onto: server.id)
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
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: 48)
|
||||
}.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() {
|
||||
OrionSettingsWindowPresenter.present(vm: vm)
|
||||
}
|
||||
}
|
||||
|
||||
private struct OrionActionStyle: ButtonStyle {
|
||||
let tint: Color
|
||||
func makeBody(configuration: Configuration) -> some View {
|
||||
configuration.label
|
||||
.foregroundStyle(.white)
|
||||
.padding(.horizontal, 8).padding(.vertical, 7)
|
||||
.background(tint.opacity(configuration.isPressed ? 0.65 : 1), in: RoundedRectangle(cornerRadius: 8))
|
||||
.opacity(configuration.isPressed ? 0.8 : 1)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Keep Settings above its originating MenuBarExtra panel.
|
||||
@MainActor
|
||||
private final class OrionSettingsWindowPresenter: NSObject, NSWindowDelegate {
|
||||
private static var current: OrionSettingsWindowPresenter?
|
||||
|
||||
private var window: NSWindow?
|
||||
private weak var parentWindow: NSWindow?
|
||||
|
||||
static func present(vm: OrionVMController) {
|
||||
if let current, let window = current.window {
|
||||
NSApp.activate(ignoringOtherApps: true)
|
||||
window.makeKeyAndOrderFront(nil)
|
||||
return
|
||||
}
|
||||
|
||||
let presenter = OrionSettingsWindowPresenter()
|
||||
current = presenter
|
||||
presenter.open(vm: vm)
|
||||
}
|
||||
|
||||
private func open(vm: OrionVMController) {
|
||||
// Capture the currently active menu-bar panel.
|
||||
let parent = NSApp.keyWindow
|
||||
?? NSApp.windows.first(where: { $0.isVisible })
|
||||
|
||||
let content = SettingsView()
|
||||
.environmentObject(vm)
|
||||
.preferredColorScheme(.dark)
|
||||
|
||||
let window = NSWindow(
|
||||
contentRect: NSRect(x: 0, y: 0, width: 650, height: 380),
|
||||
styleMask: [.titled, .closable],
|
||||
backing: .buffered,
|
||||
defer: false
|
||||
)
|
||||
|
||||
window.title = "OrionToolbar Settings"
|
||||
window.contentViewController = NSHostingController(rootView: content)
|
||||
window.delegate = self
|
||||
window.isReleasedWhenClosed = false
|
||||
window.center()
|
||||
|
||||
self.window = window
|
||||
self.parentWindow = parent
|
||||
|
||||
if let parent {
|
||||
parent.addChildWindow(window, ordered: .above)
|
||||
}
|
||||
|
||||
NSApp.activate(ignoringOtherApps: true)
|
||||
window.makeKeyAndOrderFront(nil)
|
||||
window.orderFrontRegardless()
|
||||
}
|
||||
|
||||
func windowWillClose(_ notification: Notification) {
|
||||
if let window {
|
||||
parentWindow?.removeChildWindow(window)
|
||||
}
|
||||
|
||||
window = nil
|
||||
Self.current = nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,489 @@
|
||||
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
|
||||
@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.visibleVMs.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.visibleVMs.count) VMs", accent: .cyan, expanded: $showAll) {
|
||||
if vm.visibleVMs.isEmpty {
|
||||
emptyState(vm.discovering ? "Discovering Parallels VMs…" : "No virtual machines found", icon: "desktopcomputer.trianglebadge.exclamationmark")
|
||||
} else {
|
||||
ForEach(vm.visibleVMs) { 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.filter { server in
|
||||
!vm.hiddenVMIDs.contains(server.vmUUID ??
|
||||
vm.discoveredVMs.first(where: { $0.name == server.vmName })?.id ?? "")
|
||||
}) { server in
|
||||
integratedRow(server)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
.padding(14)
|
||||
}
|
||||
.frame(height: 610)
|
||||
Divider().overlay(.white.opacity(0.10))
|
||||
footer
|
||||
}
|
||||
.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)
|
||||
)
|
||||
|
||||
.preferredColorScheme(.dark)
|
||||
.task {
|
||||
await vm.discoverVMs()
|
||||
await vm.refreshAll()
|
||||
while !Task.isCancelled {
|
||||
await vm.refreshServiceAvailability()
|
||||
try? await Task.sleep(for: .seconds(10))
|
||||
}
|
||||
}
|
||||
.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()
|
||||
Menu {
|
||||
if vm.hiddenVMs.isEmpty {
|
||||
Text("No removed virtual machines")
|
||||
} else {
|
||||
ForEach(vm.hiddenVMs) { machine in
|
||||
Button("Re-add " + machine.name) { vm.restoreVM(machine) }
|
||||
}
|
||||
}
|
||||
} label: {
|
||||
Label("Re-add VM", systemImage: "plus.rectangle.on.folder")
|
||||
}
|
||||
.help("Restore virtual machines removed from OrionToolbar")
|
||||
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<Content: View>(icon: String, title: String, count: String, accent: Color, expanded: Binding<Bool>, @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: 90, alignment: .leading)
|
||||
}
|
||||
|
||||
private func integrated(_ machine: ParallelsVM) -> ServerDefinition? {
|
||||
vm.servers.first { $0.vmUUID == machine.id || $0.vmName == machine.name }
|
||||
}
|
||||
|
||||
// Native text selection supports Command-C; the copy button works in menu-bar panels.
|
||||
private func vmIdentity(name: String, ip: String, os: String, fallbackIP: String = "") -> some View {
|
||||
let address = ip.isEmpty ? fallbackIP : ip
|
||||
return VStack(alignment: .leading, spacing: 5) {
|
||||
Text(name)
|
||||
.font(.system(size: 12, weight: .semibold))
|
||||
.foregroundStyle(.white)
|
||||
.lineLimit(1)
|
||||
HStack(spacing: 6) {
|
||||
Image(systemName: "network")
|
||||
.font(.system(size: 10))
|
||||
.foregroundStyle(OrionStyle.muted)
|
||||
Text(address.isEmpty ? "No IP assigned" : address)
|
||||
.font(.system(size: 11, design: .monospaced))
|
||||
.foregroundStyle(OrionStyle.muted)
|
||||
.textSelection(.enabled)
|
||||
.lineLimit(1)
|
||||
if !address.isEmpty {
|
||||
Button {
|
||||
NSPasteboard.general.clearContents()
|
||||
NSPasteboard.general.setString(address, forType: .string)
|
||||
} label: {
|
||||
Image(systemName: "doc.on.doc")
|
||||
.font(.system(size: 10))
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.foregroundStyle(OrionStyle.muted)
|
||||
.help("Copy IP address: " + address)
|
||||
}
|
||||
if !os.isEmpty {
|
||||
Text("· " + os)
|
||||
.font(.system(size: 10))
|
||||
.foregroundStyle(OrionStyle.muted.opacity(0.75))
|
||||
.lineLimit(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func runningRow(_ machine: ParallelsVM) -> some View {
|
||||
HStack(spacing: 10) {
|
||||
icon(machine)
|
||||
vmIdentity(name: machine.name, ip: machine.ipAddress, os: machine.operatingSystem)
|
||||
.frame(width: 265, alignment: .leading)
|
||||
state(machine.status)
|
||||
Spacer(minLength: 0)
|
||||
if let server = integrated(machine) {
|
||||
if !server.host.isEmpty && !server.sshUser.isEmpty && vm.reachableSSH.contains(server.id) {
|
||||
action("SSH", "terminal", tint: OrionStyle.blue) { vm.openSSH(server) }
|
||||
}
|
||||
if !server.host.isEmpty && server.mailpitPort != nil && vm.reachableMailpit.contains(server.id) {
|
||||
action("Mailpit", "globe", tint: OrionStyle.blue) { vm.openMailpit(server) }
|
||||
}
|
||||
}
|
||||
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") }
|
||||
.padding(.leading, 6)
|
||||
}
|
||||
Menu {
|
||||
Button("Force Stop", role: .destructive) { pendingForceStop = machine }
|
||||
} label: {
|
||||
Image(systemName: "ellipsis").frame(width: 22)
|
||||
}.menuStyle(.borderlessButton).frame(width: 30)
|
||||
.padding(.leading, 12)
|
||||
.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)
|
||||
HStack(spacing: 6) {
|
||||
Image(systemName: "line.3.horizontal")
|
||||
.foregroundStyle(OrionStyle.muted)
|
||||
vmIdentity(name: machine.name, ip: machine.ipAddress, os: machine.operatingSystem)
|
||||
}
|
||||
.frame(width: 280, alignment: .leading)
|
||||
.contentShape(Rectangle())
|
||||
.onDrag { NSItemProvider(object: ("vm:" + machine.id) as NSString) }
|
||||
state(machine.status)
|
||||
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") }
|
||||
}
|
||||
Button {
|
||||
vm.hideVM(machine)
|
||||
} label: {
|
||||
Image(systemName: "minus.circle")
|
||||
.foregroundStyle(OrionStyle.muted)
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.help("Remove from OrionToolbar (keeps the Parallels VM)")
|
||||
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")
|
||||
}
|
||||
|
||||
}
|
||||
.padding(.horizontal, 10).padding(.vertical, 7)
|
||||
.background(OrionStyle.card.opacity(0.75), in: RoundedRectangle(cornerRadius: 10))
|
||||
.contextMenu {
|
||||
Button("Remove from OrionToolbar", systemImage: "minus.circle") {
|
||||
vm.hideVM(machine)
|
||||
}
|
||||
}
|
||||
.onDrop(of: [.plainText], isTargeted: nil) { providers in
|
||||
guard let provider = providers.first else { return false }
|
||||
_ = provider.loadObject(ofClass: NSString.self) { item, _ in
|
||||
guard let string = item as? NSString else { return }
|
||||
let value = string as String
|
||||
guard value.hasPrefix("vm:") else { return }
|
||||
Task { @MainActor in
|
||||
vm.reorderVM(draggedID: String(value.dropFirst(3)), onto: machine.id)
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
private func integratedRow(_ server: ServerDefinition) -> some View {
|
||||
let machine = vm.machine(for: server)
|
||||
let status = machine?.status ?? "unavailable"
|
||||
return HStack(spacing: 10) {
|
||||
Group {
|
||||
if let image = vm.icon(for: server) {
|
||||
Image(nsImage: image).resizable().scaledToFit()
|
||||
} else if let machine {
|
||||
icon(machine)
|
||||
} else {
|
||||
Image(systemName: "server.rack").foregroundStyle(.cyan)
|
||||
}
|
||||
}.frame(width: 36, height: 36)
|
||||
HStack(spacing: 5) {
|
||||
Image(systemName: "line.3.horizontal").foregroundStyle(OrionStyle.muted)
|
||||
vmIdentity(name: server.name,
|
||||
ip: machine?.ipAddress ?? "",
|
||||
os: machine?.operatingSystem ?? "",
|
||||
fallbackIP: server.host)
|
||||
}
|
||||
.frame(width: 280, alignment: .leading)
|
||||
.onDrag {
|
||||
NSItemProvider(object: ("server:" + server.id.uuidString) as NSString)
|
||||
}
|
||||
state(status)
|
||||
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") }
|
||||
}
|
||||
}
|
||||
if !server.host.isEmpty && !server.sshUser.isEmpty && vm.reachableSSH.contains(server.id) {
|
||||
action("SSH", "terminal", tint: OrionStyle.card) { vm.openSSH(server) }
|
||||
}
|
||||
if !server.host.isEmpty && server.mailpitPort != nil && vm.reachableMailpit.contains(server.id) {
|
||||
action("Mailpit", "globe", tint: OrionStyle.card) { vm.openMailpit(server) }
|
||||
}
|
||||
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))
|
||||
.onDrop(of: [.plainText], isTargeted: nil) { providers in
|
||||
guard let provider = providers.first else { return false }
|
||||
_ = provider.loadObject(ofClass: NSString.self) { item, _ in
|
||||
guard let string = item as? NSString else { return }
|
||||
let value = string as String
|
||||
guard value.hasPrefix("server:"),
|
||||
let dragged = UUID(uuidString: String(value.dropFirst(7))) else { return }
|
||||
Task { @MainActor in
|
||||
vm.reorderServer(draggedID: dragged, onto: server.id)
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
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: 48)
|
||||
}.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() {
|
||||
OrionSettingsWindowPresenter.present(vm: vm)
|
||||
}
|
||||
}
|
||||
|
||||
private struct OrionActionStyle: ButtonStyle {
|
||||
let tint: Color
|
||||
func makeBody(configuration: Configuration) -> some View {
|
||||
configuration.label
|
||||
.foregroundStyle(.white)
|
||||
.padding(.horizontal, 8).padding(.vertical, 7)
|
||||
.background(tint.opacity(configuration.isPressed ? 0.65 : 1), in: RoundedRectangle(cornerRadius: 8))
|
||||
.opacity(configuration.isPressed ? 0.8 : 1)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Keep Settings above its originating MenuBarExtra panel.
|
||||
@MainActor
|
||||
private final class OrionSettingsWindowPresenter: NSObject, NSWindowDelegate {
|
||||
private static var current: OrionSettingsWindowPresenter?
|
||||
|
||||
private var window: NSWindow?
|
||||
|
||||
static func present(vm: OrionVMController) {
|
||||
if let current, let window = current.window {
|
||||
NSApp.activate(ignoringOtherApps: true)
|
||||
window.makeKeyAndOrderFront(nil)
|
||||
return
|
||||
}
|
||||
|
||||
let presenter = OrionSettingsWindowPresenter()
|
||||
current = presenter
|
||||
presenter.open(vm: vm)
|
||||
}
|
||||
|
||||
private func open(vm: OrionVMController) {
|
||||
let content = SettingsView()
|
||||
.environmentObject(vm)
|
||||
.preferredColorScheme(.dark)
|
||||
|
||||
let window = NSWindow(
|
||||
contentRect: NSRect(x: 0, y: 0, width: 650, height: 380),
|
||||
styleMask: [.titled, .closable],
|
||||
backing: .buffered,
|
||||
defer: false
|
||||
)
|
||||
|
||||
window.title = "OrionToolbar Settings"
|
||||
window.contentViewController = NSHostingController(rootView: content)
|
||||
window.delegate = self
|
||||
window.isReleasedWhenClosed = false
|
||||
window.center()
|
||||
|
||||
self.window = window
|
||||
NSApp.activate(ignoringOtherApps: true)
|
||||
window.makeKeyAndOrderFront(nil)
|
||||
window.orderFrontRegardless()
|
||||
}
|
||||
|
||||
func windowWillClose(_ notification: Notification) {
|
||||
window = nil
|
||||
Self.current = nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,489 @@
|
||||
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
|
||||
@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.visibleVMs.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.visibleVMs.count) VMs", accent: .cyan, expanded: $showAll) {
|
||||
if vm.visibleVMs.isEmpty {
|
||||
emptyState(vm.discovering ? "Discovering Parallels VMs…" : "No virtual machines found", icon: "desktopcomputer.trianglebadge.exclamationmark")
|
||||
} else {
|
||||
ForEach(vm.visibleVMs) { 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.filter { server in
|
||||
!vm.hiddenVMIDs.contains(server.vmUUID ??
|
||||
vm.discoveredVMs.first(where: { $0.name == server.vmName })?.id ?? "")
|
||||
}) { server in
|
||||
integratedRow(server)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
.padding(14)
|
||||
}
|
||||
.frame(height: 610)
|
||||
Divider().overlay(.white.opacity(0.10))
|
||||
footer
|
||||
}
|
||||
.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)
|
||||
)
|
||||
|
||||
.preferredColorScheme(.dark)
|
||||
.task {
|
||||
await vm.discoverVMs()
|
||||
await vm.refreshAll()
|
||||
while !Task.isCancelled {
|
||||
await vm.refreshServiceAvailability()
|
||||
try? await Task.sleep(for: .seconds(10))
|
||||
}
|
||||
}
|
||||
.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()
|
||||
Menu {
|
||||
if vm.hiddenVMs.isEmpty {
|
||||
Text("No removed virtual machines")
|
||||
} else {
|
||||
ForEach(vm.hiddenVMs) { machine in
|
||||
Button("Re-add " + machine.name) { vm.restoreVM(machine) }
|
||||
}
|
||||
}
|
||||
} label: {
|
||||
Label("Re-add VM", systemImage: "plus.rectangle.on.folder")
|
||||
}
|
||||
.help("Restore virtual machines removed from OrionToolbar")
|
||||
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<Content: View>(icon: String, title: String, count: String, accent: Color, expanded: Binding<Bool>, @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: 90, alignment: .leading)
|
||||
}
|
||||
|
||||
private func integrated(_ machine: ParallelsVM) -> ServerDefinition? {
|
||||
vm.servers.first { $0.vmUUID == machine.id || $0.vmName == machine.name }
|
||||
}
|
||||
|
||||
// Native text selection supports Command-C; the copy button works in menu-bar panels.
|
||||
private func vmIdentity(name: String, ip: String, os: String, fallbackIP: String = "") -> some View {
|
||||
let address = ip.isEmpty ? fallbackIP : ip
|
||||
return VStack(alignment: .leading, spacing: 5) {
|
||||
Text(name)
|
||||
.font(.system(size: 12, weight: .semibold))
|
||||
.foregroundStyle(.white)
|
||||
.lineLimit(1)
|
||||
HStack(spacing: 6) {
|
||||
Image(systemName: "network")
|
||||
.font(.system(size: 10))
|
||||
.foregroundStyle(OrionStyle.muted)
|
||||
Text(address.isEmpty ? "No IP assigned" : address)
|
||||
.font(.system(size: 11, design: .monospaced))
|
||||
.foregroundStyle(OrionStyle.muted)
|
||||
.textSelection(.enabled)
|
||||
.lineLimit(1)
|
||||
if !address.isEmpty {
|
||||
Button {
|
||||
NSPasteboard.general.clearContents()
|
||||
NSPasteboard.general.setString(address, forType: .string)
|
||||
} label: {
|
||||
Image(systemName: "doc.on.doc")
|
||||
.font(.system(size: 10))
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.foregroundStyle(OrionStyle.muted)
|
||||
.help("Copy IP address: " + address)
|
||||
}
|
||||
if !os.isEmpty {
|
||||
Text("· " + os)
|
||||
.font(.system(size: 10))
|
||||
.foregroundStyle(OrionStyle.muted.opacity(0.75))
|
||||
.lineLimit(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func runningRow(_ machine: ParallelsVM) -> some View {
|
||||
HStack(spacing: 10) {
|
||||
icon(machine)
|
||||
vmIdentity(name: machine.name, ip: machine.ipAddress, os: machine.operatingSystem)
|
||||
.frame(width: 265, alignment: .leading)
|
||||
state(machine.status)
|
||||
Spacer(minLength: 0)
|
||||
if let server = integrated(machine) {
|
||||
if !server.host.isEmpty && !server.sshUser.isEmpty && vm.reachableSSH.contains(server.id) {
|
||||
action("SSH", "terminal", tint: OrionStyle.blue) { vm.openSSH(server) }
|
||||
}
|
||||
if !server.host.isEmpty && (server.mailpitPort.map { (1...65535).contains($0) } ?? false) {
|
||||
action("Mailpit", "globe", tint: OrionStyle.blue) { vm.openMailpit(server) }
|
||||
}
|
||||
}
|
||||
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") }
|
||||
.padding(.leading, 6)
|
||||
}
|
||||
Menu {
|
||||
Button("Force Stop", role: .destructive) { pendingForceStop = machine }
|
||||
} label: {
|
||||
Image(systemName: "ellipsis").frame(width: 22)
|
||||
}.menuStyle(.borderlessButton).frame(width: 30)
|
||||
.padding(.leading, 12)
|
||||
.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)
|
||||
HStack(spacing: 6) {
|
||||
Image(systemName: "line.3.horizontal")
|
||||
.foregroundStyle(OrionStyle.muted)
|
||||
vmIdentity(name: machine.name, ip: machine.ipAddress, os: machine.operatingSystem)
|
||||
}
|
||||
.frame(width: 280, alignment: .leading)
|
||||
.contentShape(Rectangle())
|
||||
.onDrag { NSItemProvider(object: ("vm:" + machine.id) as NSString) }
|
||||
state(machine.status)
|
||||
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") }
|
||||
}
|
||||
Button {
|
||||
vm.hideVM(machine)
|
||||
} label: {
|
||||
Image(systemName: "minus.circle")
|
||||
.foregroundStyle(OrionStyle.muted)
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.help("Remove from OrionToolbar (keeps the Parallels VM)")
|
||||
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")
|
||||
}
|
||||
|
||||
}
|
||||
.padding(.horizontal, 10).padding(.vertical, 7)
|
||||
.background(OrionStyle.card.opacity(0.75), in: RoundedRectangle(cornerRadius: 10))
|
||||
.contextMenu {
|
||||
Button("Remove from OrionToolbar", systemImage: "minus.circle") {
|
||||
vm.hideVM(machine)
|
||||
}
|
||||
}
|
||||
.onDrop(of: [.plainText], isTargeted: nil) { providers in
|
||||
guard let provider = providers.first else { return false }
|
||||
_ = provider.loadObject(ofClass: NSString.self) { item, _ in
|
||||
guard let string = item as? NSString else { return }
|
||||
let value = string as String
|
||||
guard value.hasPrefix("vm:") else { return }
|
||||
Task { @MainActor in
|
||||
vm.reorderVM(draggedID: String(value.dropFirst(3)), onto: machine.id)
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
private func integratedRow(_ server: ServerDefinition) -> some View {
|
||||
let machine = vm.machine(for: server)
|
||||
let status = machine?.status ?? "unavailable"
|
||||
return HStack(spacing: 10) {
|
||||
Group {
|
||||
if let image = vm.icon(for: server) {
|
||||
Image(nsImage: image).resizable().scaledToFit()
|
||||
} else if let machine {
|
||||
icon(machine)
|
||||
} else {
|
||||
Image(systemName: "server.rack").foregroundStyle(.cyan)
|
||||
}
|
||||
}.frame(width: 36, height: 36)
|
||||
HStack(spacing: 5) {
|
||||
Image(systemName: "line.3.horizontal").foregroundStyle(OrionStyle.muted)
|
||||
vmIdentity(name: server.name,
|
||||
ip: machine?.ipAddress ?? "",
|
||||
os: machine?.operatingSystem ?? "",
|
||||
fallbackIP: server.host)
|
||||
}
|
||||
.frame(width: 280, alignment: .leading)
|
||||
.onDrag {
|
||||
NSItemProvider(object: ("server:" + server.id.uuidString) as NSString)
|
||||
}
|
||||
state(status)
|
||||
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") }
|
||||
}
|
||||
}
|
||||
if !server.host.isEmpty && !server.sshUser.isEmpty && vm.reachableSSH.contains(server.id) {
|
||||
action("SSH", "terminal", tint: OrionStyle.card) { vm.openSSH(server) }
|
||||
}
|
||||
if !server.host.isEmpty && (server.mailpitPort.map { (1...65535).contains($0) } ?? false) {
|
||||
action("Mailpit", "globe", tint: OrionStyle.card) { vm.openMailpit(server) }
|
||||
}
|
||||
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))
|
||||
.onDrop(of: [.plainText], isTargeted: nil) { providers in
|
||||
guard let provider = providers.first else { return false }
|
||||
_ = provider.loadObject(ofClass: NSString.self) { item, _ in
|
||||
guard let string = item as? NSString else { return }
|
||||
let value = string as String
|
||||
guard value.hasPrefix("server:"),
|
||||
let dragged = UUID(uuidString: String(value.dropFirst(7))) else { return }
|
||||
Task { @MainActor in
|
||||
vm.reorderServer(draggedID: dragged, onto: server.id)
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
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: 48)
|
||||
}.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() {
|
||||
OrionSettingsWindowPresenter.present(vm: vm)
|
||||
}
|
||||
}
|
||||
|
||||
private struct OrionActionStyle: ButtonStyle {
|
||||
let tint: Color
|
||||
func makeBody(configuration: Configuration) -> some View {
|
||||
configuration.label
|
||||
.foregroundStyle(.white)
|
||||
.padding(.horizontal, 8).padding(.vertical, 7)
|
||||
.background(tint.opacity(configuration.isPressed ? 0.65 : 1), in: RoundedRectangle(cornerRadius: 8))
|
||||
.opacity(configuration.isPressed ? 0.8 : 1)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Keep Settings above its originating MenuBarExtra panel.
|
||||
@MainActor
|
||||
private final class OrionSettingsWindowPresenter: NSObject, NSWindowDelegate {
|
||||
private static var current: OrionSettingsWindowPresenter?
|
||||
|
||||
private var window: NSWindow?
|
||||
|
||||
static func present(vm: OrionVMController) {
|
||||
if let current, let window = current.window {
|
||||
NSApp.activate(ignoringOtherApps: true)
|
||||
window.makeKeyAndOrderFront(nil)
|
||||
return
|
||||
}
|
||||
|
||||
let presenter = OrionSettingsWindowPresenter()
|
||||
current = presenter
|
||||
presenter.open(vm: vm)
|
||||
}
|
||||
|
||||
private func open(vm: OrionVMController) {
|
||||
let content = SettingsView()
|
||||
.environmentObject(vm)
|
||||
.preferredColorScheme(.dark)
|
||||
|
||||
let window = NSWindow(
|
||||
contentRect: NSRect(x: 0, y: 0, width: 650, height: 380),
|
||||
styleMask: [.titled, .closable],
|
||||
backing: .buffered,
|
||||
defer: false
|
||||
)
|
||||
|
||||
window.title = "OrionToolbar Settings"
|
||||
window.contentViewController = NSHostingController(rootView: content)
|
||||
window.delegate = self
|
||||
window.isReleasedWhenClosed = false
|
||||
window.center()
|
||||
|
||||
self.window = window
|
||||
NSApp.activate(ignoringOtherApps: true)
|
||||
window.makeKeyAndOrderFront(nil)
|
||||
window.orderFrontRegardless()
|
||||
}
|
||||
|
||||
func windowWillClose(_ notification: Notification) {
|
||||
window = nil
|
||||
Self.current = nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,909 @@
|
||||
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
|
||||
@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.visibleVMs.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.visibleVMs.count) VMs", accent: .cyan, expanded: $showAll) {
|
||||
if vm.visibleVMs.isEmpty {
|
||||
emptyState(vm.discovering ? "Discovering Parallels VMs…" : "No virtual machines found", icon: "desktopcomputer.trianglebadge.exclamationmark")
|
||||
} else {
|
||||
ForEach(vm.visibleVMs) { 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.filter { server in
|
||||
!vm.hiddenVMIDs.contains(server.vmUUID ??
|
||||
vm.discoveredVMs.first(where: { $0.name == server.vmName })?.id ?? "")
|
||||
}) { server in
|
||||
integratedRow(server)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
.padding(14)
|
||||
}
|
||||
.frame(height: 610)
|
||||
Divider().overlay(.white.opacity(0.10))
|
||||
footer
|
||||
}
|
||||
.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)
|
||||
)
|
||||
|
||||
.preferredColorScheme(.dark)
|
||||
.task {
|
||||
await vm.discoverVMs()
|
||||
await vm.refreshAll()
|
||||
while !Task.isCancelled {
|
||||
await vm.refreshServiceAvailability()
|
||||
try? await Task.sleep(for: .seconds(10))
|
||||
}
|
||||
}
|
||||
.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()
|
||||
Menu {
|
||||
if vm.hiddenVMs.isEmpty {
|
||||
Text("No removed virtual machines")
|
||||
} else {
|
||||
ForEach(vm.hiddenVMs) { machine in
|
||||
Button("Re-add " + machine.name) { vm.restoreVM(machine) }
|
||||
}
|
||||
}
|
||||
} label: {
|
||||
Label("Re-add VM", systemImage: "plus.rectangle.on.folder")
|
||||
}
|
||||
.help("Restore virtual machines removed from OrionToolbar")
|
||||
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<Content: View>(icon: String, title: String, count: String, accent: Color, expanded: Binding<Bool>, @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: 90, alignment: .leading)
|
||||
}
|
||||
|
||||
private func integrated(_ machine: ParallelsVM) -> ServerDefinition? {
|
||||
vm.servers.first { $0.vmUUID == machine.id || $0.vmName == machine.name }
|
||||
}
|
||||
|
||||
// Native text selection supports Command-C; the copy button works in menu-bar panels.
|
||||
private func vmIdentity(name: String, ip: String, os: String, fallbackIP: String = "") -> some View {
|
||||
let address = ip.isEmpty ? fallbackIP : ip
|
||||
return VStack(alignment: .leading, spacing: 5) {
|
||||
Text(name)
|
||||
.font(.system(size: 12, weight: .semibold))
|
||||
.foregroundStyle(.white)
|
||||
.lineLimit(1)
|
||||
HStack(spacing: 6) {
|
||||
Image(systemName: "network")
|
||||
.font(.system(size: 10))
|
||||
.foregroundStyle(OrionStyle.muted)
|
||||
Text(address.isEmpty ? "No IP assigned" : address)
|
||||
.font(.system(size: 11, design: .monospaced))
|
||||
.foregroundStyle(OrionStyle.muted)
|
||||
.textSelection(.enabled)
|
||||
.lineLimit(1)
|
||||
if !address.isEmpty {
|
||||
Button {
|
||||
NSPasteboard.general.clearContents()
|
||||
NSPasteboard.general.setString(address, forType: .string)
|
||||
} label: {
|
||||
Image(systemName: "doc.on.doc")
|
||||
.font(.system(size: 10))
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.foregroundStyle(OrionStyle.muted)
|
||||
.help("Copy IP address: " + address)
|
||||
}
|
||||
if !os.isEmpty {
|
||||
Text("· " + os)
|
||||
.font(.system(size: 10))
|
||||
.foregroundStyle(OrionStyle.muted.opacity(0.75))
|
||||
.lineLimit(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func runningRow(_ machine: ParallelsVM) -> some View {
|
||||
HStack(spacing: 10) {
|
||||
icon(machine)
|
||||
vmIdentity(name: machine.name, ip: machine.ipAddress, os: machine.operatingSystem)
|
||||
.frame(width: 265, alignment: .leading)
|
||||
state(machine.status)
|
||||
Spacer(minLength: 0)
|
||||
if let server = integrated(machine) {
|
||||
if !server.host.isEmpty && !server.sshUser.isEmpty && vm.reachableSSH.contains(server.id) {
|
||||
action("SSH", "terminal", tint: OrionStyle.blue) { vm.openSSH(server) }
|
||||
}
|
||||
if !server.host.isEmpty && (server.mailpitPort.map { (1...65535).contains($0) } ?? false) {
|
||||
action("Mailpit", "globe", tint: OrionStyle.blue) { vm.openMailpit(server) }
|
||||
}
|
||||
}
|
||||
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") }
|
||||
.padding(.leading, 6)
|
||||
}
|
||||
Menu {
|
||||
Button("Force Stop", role: .destructive) { pendingForceStop = machine }
|
||||
} label: {
|
||||
Image(systemName: "ellipsis").frame(width: 22)
|
||||
}.menuStyle(.borderlessButton).frame(width: 30)
|
||||
.padding(.leading, 12)
|
||||
.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)
|
||||
HStack(spacing: 6) {
|
||||
Image(systemName: "line.3.horizontal")
|
||||
.foregroundStyle(OrionStyle.muted)
|
||||
vmIdentity(name: machine.name, ip: machine.ipAddress, os: machine.operatingSystem)
|
||||
}
|
||||
.frame(width: 280, alignment: .leading)
|
||||
.contentShape(Rectangle())
|
||||
.onDrag { NSItemProvider(object: ("vm:" + machine.id) as NSString) }
|
||||
state(machine.status)
|
||||
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") }
|
||||
}
|
||||
Button {
|
||||
vm.hideVM(machine)
|
||||
} label: {
|
||||
Image(systemName: "minus.circle")
|
||||
.foregroundStyle(OrionStyle.muted)
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.help("Remove from OrionToolbar (keeps the Parallels VM)")
|
||||
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")
|
||||
}
|
||||
|
||||
}
|
||||
.padding(.horizontal, 10).padding(.vertical, 7)
|
||||
.background(OrionStyle.card.opacity(0.75), in: RoundedRectangle(cornerRadius: 10))
|
||||
.contextMenu {
|
||||
Button("Remove from OrionToolbar", systemImage: "minus.circle") {
|
||||
vm.hideVM(machine)
|
||||
}
|
||||
}
|
||||
.onDrop(of: [.plainText], isTargeted: nil) { providers in
|
||||
guard let provider = providers.first else { return false }
|
||||
_ = provider.loadObject(ofClass: NSString.self) { item, _ in
|
||||
guard let string = item as? NSString else { return }
|
||||
let value = string as String
|
||||
guard value.hasPrefix("vm:") else { return }
|
||||
Task { @MainActor in
|
||||
vm.reorderVM(draggedID: String(value.dropFirst(3)), onto: machine.id)
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
private func integratedRow(_ server: ServerDefinition) -> some View {
|
||||
let machine = vm.machine(for: server)
|
||||
let status = machine?.status ?? "unavailable"
|
||||
return HStack(spacing: 10) {
|
||||
Group {
|
||||
if let image = vm.icon(for: server) {
|
||||
Image(nsImage: image).resizable().scaledToFit()
|
||||
} else if let machine {
|
||||
icon(machine)
|
||||
} else {
|
||||
Image(systemName: "server.rack").foregroundStyle(.cyan)
|
||||
}
|
||||
}.frame(width: 36, height: 36)
|
||||
HStack(spacing: 5) {
|
||||
Image(systemName: "line.3.horizontal").foregroundStyle(OrionStyle.muted)
|
||||
vmIdentity(name: server.name,
|
||||
ip: machine?.ipAddress ?? "",
|
||||
os: machine?.operatingSystem ?? "",
|
||||
fallbackIP: server.host)
|
||||
}
|
||||
.frame(width: 280, alignment: .leading)
|
||||
.onDrag {
|
||||
NSItemProvider(object: ("server:" + server.id.uuidString) as NSString)
|
||||
}
|
||||
state(status)
|
||||
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") }
|
||||
}
|
||||
}
|
||||
if !server.host.isEmpty && !server.sshUser.isEmpty && vm.reachableSSH.contains(server.id) {
|
||||
action("SSH", "terminal", tint: OrionStyle.card) { vm.openSSH(server) }
|
||||
}
|
||||
if !server.host.isEmpty && (server.mailpitPort.map { (1...65535).contains($0) } ?? false) {
|
||||
action("Mailpit", "globe", tint: OrionStyle.card) { vm.openMailpit(server) }
|
||||
}
|
||||
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))
|
||||
.onDrop(of: [.plainText], isTargeted: nil) { providers in
|
||||
guard let provider = providers.first else { return false }
|
||||
_ = provider.loadObject(ofClass: NSString.self) { item, _ in
|
||||
guard let string = item as? NSString else { return }
|
||||
let value = string as String
|
||||
guard value.hasPrefix("server:"),
|
||||
let dragged = UUID(uuidString: String(value.dropFirst(7))) else { return }
|
||||
Task { @MainActor in
|
||||
vm.reorderServer(draggedID: dragged, onto: server.id)
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
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: 48)
|
||||
}.buttonStyle(OrionActionStyle(tint: tint))
|
||||
}
|
||||
|
||||
private var footer: some View {
|
||||
HStack {
|
||||
action("Open Parallels", "macwindow", tint: OrionStyle.card) { vm.openParallels() }
|
||||
Spacer()
|
||||
action("Help", "questionmark.circle", tint: OrionStyle.card) {
|
||||
OrionHelpWindowPresenter.present()
|
||||
}
|
||||
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() {
|
||||
OrionSettingsWindowPresenter.present(vm: vm)
|
||||
}
|
||||
}
|
||||
|
||||
private struct OrionActionStyle: ButtonStyle {
|
||||
let tint: Color
|
||||
func makeBody(configuration: Configuration) -> some View {
|
||||
configuration.label
|
||||
.foregroundStyle(.white)
|
||||
.padding(.horizontal, 8).padding(.vertical, 7)
|
||||
.background(tint.opacity(configuration.isPressed ? 0.65 : 1), in: RoundedRectangle(cornerRadius: 8))
|
||||
.opacity(configuration.isPressed ? 0.8 : 1)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Keep Settings above its originating MenuBarExtra panel.
|
||||
@MainActor
|
||||
private final class OrionSettingsWindowPresenter: NSObject, NSWindowDelegate {
|
||||
private static var current: OrionSettingsWindowPresenter?
|
||||
|
||||
private var window: NSWindow?
|
||||
|
||||
static func present(vm: OrionVMController) {
|
||||
if let current, let window = current.window {
|
||||
NSApp.activate(ignoringOtherApps: true)
|
||||
window.makeKeyAndOrderFront(nil)
|
||||
return
|
||||
}
|
||||
|
||||
let presenter = OrionSettingsWindowPresenter()
|
||||
current = presenter
|
||||
presenter.open(vm: vm)
|
||||
}
|
||||
|
||||
private func open(vm: OrionVMController) {
|
||||
let content = SettingsView()
|
||||
.environmentObject(vm)
|
||||
.preferredColorScheme(.dark)
|
||||
|
||||
let window = NSWindow(
|
||||
contentRect: NSRect(x: 0, y: 0, width: 650, height: 380),
|
||||
styleMask: [.titled, .closable],
|
||||
backing: .buffered,
|
||||
defer: false
|
||||
)
|
||||
|
||||
window.title = "OrionToolbar Settings"
|
||||
window.contentViewController = NSHostingController(rootView: content)
|
||||
window.delegate = self
|
||||
window.isReleasedWhenClosed = false
|
||||
window.center()
|
||||
|
||||
self.window = window
|
||||
NSApp.activate(ignoringOtherApps: true)
|
||||
window.makeKeyAndOrderFront(nil)
|
||||
window.orderFrontRegardless()
|
||||
}
|
||||
|
||||
func windowWillClose(_ notification: Notification) {
|
||||
window = nil
|
||||
Self.current = nil
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Operating System Installation Help
|
||||
|
||||
private struct OrionHelpGuide: Identifiable {
|
||||
let id: String
|
||||
let title: String
|
||||
let category: String
|
||||
let description: String
|
||||
let commands: String
|
||||
let verification: String
|
||||
let notes: String
|
||||
}
|
||||
|
||||
private enum OrionHelpLibrary {
|
||||
static let systems = [
|
||||
"Ubuntu",
|
||||
"Debian",
|
||||
"Fedora",
|
||||
"CentOS Stream",
|
||||
"Alpine"
|
||||
]
|
||||
|
||||
static func guides(for system: String) -> [OrionHelpGuide] {
|
||||
let apt = system == "Ubuntu" || system == "Debian"
|
||||
let dnf = system == "Fedora" || system == "CentOS Stream"
|
||||
let alpine = system == "Alpine"
|
||||
|
||||
let update = apt
|
||||
? "sudo apt update"
|
||||
: dnf
|
||||
? "sudo dnf makecache"
|
||||
: "sudo apk update"
|
||||
|
||||
func packages(_ names: String) -> String {
|
||||
if apt { return "sudo apt install -y \(names)" }
|
||||
if dnf { return "sudo dnf install -y \(names)" }
|
||||
return "sudo apk add \(names)"
|
||||
}
|
||||
|
||||
func guide(
|
||||
_ id: String,
|
||||
_ title: String,
|
||||
_ category: String,
|
||||
_ description: String,
|
||||
_ commands: String,
|
||||
_ verification: String,
|
||||
_ notes: String = ""
|
||||
) -> OrionHelpGuide {
|
||||
OrionHelpGuide(
|
||||
id: id,
|
||||
title: title,
|
||||
category: category,
|
||||
description: description,
|
||||
commands: commands,
|
||||
verification: verification,
|
||||
notes: notes
|
||||
)
|
||||
}
|
||||
|
||||
let nginx = guide(
|
||||
"nginx", "Nginx", "Web Servers",
|
||||
"Install and enable the Nginx web server.",
|
||||
"""
|
||||
\(update)
|
||||
\(packages("nginx"))
|
||||
sudo systemctl enable --now nginx
|
||||
""",
|
||||
"systemctl status nginx --no-pager\ncurl -I http://127.0.0.1",
|
||||
"On Alpine with OpenRC, use: sudo rc-update add nginx default; sudo rc-service nginx start."
|
||||
)
|
||||
|
||||
let phpPackages = apt
|
||||
? "php-cli php-fpm php-mysql php-pgsql php-xml php-mbstring php-curl php-zip php-gd php-intl php-bcmath"
|
||||
: dnf
|
||||
? "php-cli php-fpm php-mysqlnd php-pgsql php-xml php-mbstring php-curl php-zip php-gd php-intl php-bcmath"
|
||||
: "php php-fpm php-mysqli php-pgsql php-xml php-mbstring php-curl php-zip php-gd php-intl"
|
||||
|
||||
let php = guide(
|
||||
"php", "PHP and PHP-FPM", "PHP",
|
||||
"Install the distribution's default PHP version and commonly used extensions.",
|
||||
"""
|
||||
\(update)
|
||||
\(packages(phpPackages))
|
||||
php -v
|
||||
php -m
|
||||
""",
|
||||
"php -v\nphp -m\nsystemctl list-unit-files '*php*fpm*'",
|
||||
"PHP versions and PHP-FPM service names vary by distribution. CentOS Stream may require a third-party repository for PHP 8.5. Alpine uses OpenRC rather than systemd."
|
||||
)
|
||||
|
||||
let composer = guide(
|
||||
"composer", "Composer", "PHP",
|
||||
"Install the Composer dependency manager.",
|
||||
"""
|
||||
\(update)
|
||||
\(packages("composer"))
|
||||
""",
|
||||
"composer --version",
|
||||
"Distribution packages may provide an older Composer version."
|
||||
)
|
||||
|
||||
let database = guide(
|
||||
"mariadb", "MariaDB", "Databases",
|
||||
"Install a MariaDB database server.",
|
||||
"""
|
||||
\(update)
|
||||
\(packages(alpine ? "mariadb mariadb-client" : "mariadb-server"))
|
||||
\(alpine ? "# Initialise the data directory according to your Alpine release." : "sudo systemctl enable --now mariadb")
|
||||
""",
|
||||
"mariadb --version",
|
||||
"For Alpine, initialise the database and enable the mariadb OpenRC service before use. Secure database accounts and avoid exposing port 3306 publicly."
|
||||
)
|
||||
|
||||
let postgres = guide(
|
||||
"postgresql", "PostgreSQL", "Databases",
|
||||
"Install PostgreSQL using the distribution repository.",
|
||||
"""
|
||||
\(update)
|
||||
\(packages(alpine ? "postgresql postgresql-client" : "postgresql postgresql-server"))
|
||||
""",
|
||||
"psql --version",
|
||||
"PostgreSQL cluster initialization and service names differ across distributions. Fedora/CentOS commonly require postgresql-setup --initdb before starting the service."
|
||||
)
|
||||
|
||||
let cachePackage = system == "Fedora" || system == "CentOS Stream"
|
||||
? "valkey"
|
||||
: "redis"
|
||||
|
||||
let cache = guide(
|
||||
"cache", "Redis / Valkey", "Caching",
|
||||
"Install the distribution's Redis-compatible cache server.",
|
||||
"""
|
||||
\(update)
|
||||
\(packages(cachePackage))
|
||||
\(alpine ? "# Enable and start the appropriate OpenRC service." : "sudo systemctl enable --now \(cachePackage)")
|
||||
""",
|
||||
"\(cachePackage == "valkey" ? "valkey-cli" : "redis-cli") ping",
|
||||
"Keep the cache bound to localhost or a private interface. Do not expose it publicly without appropriate security controls."
|
||||
)
|
||||
|
||||
let mailpit = guide(
|
||||
"mailpit", "Mailpit", "Email Testing",
|
||||
"Mailpit provides a local SMTP test server and a browser-based inbox.",
|
||||
"""
|
||||
# Install Mailpit from its official release or package instructions.
|
||||
# Verify the binary after installation:
|
||||
mailpit --version
|
||||
|
||||
# Example foreground test:
|
||||
mailpit --listen 127.0.0.1:8025 --smtp 127.0.0.1:1025
|
||||
""",
|
||||
"curl -I http://127.0.0.1:8025\nss -lntp | grep -E '8025|1025'",
|
||||
"Web interface: 8025. SMTP: 1025. For OrionToolbar access from macOS, bind the web listener to the VM's private interface and restrict access using the firewall. Do not expose an unauthenticated Mailpit inbox publicly."
|
||||
)
|
||||
|
||||
let cockpit = guide(
|
||||
"cockpit", "Cockpit", "Administration",
|
||||
"Install the browser-based Linux administration console.",
|
||||
"""
|
||||
\(update)
|
||||
\(packages("cockpit"))
|
||||
\(alpine ? "# Configure the Cockpit service if supported by this Alpine release." : "sudo systemctl enable --now cockpit.socket")
|
||||
""",
|
||||
"ss -lntp | grep 9090",
|
||||
"Cockpit typically uses HTTPS port 9090. Package and service availability vary on Alpine."
|
||||
)
|
||||
|
||||
let ssh = guide(
|
||||
"ssh", "OpenSSH Server", "Administration",
|
||||
"Install an SSH server for remote administration.",
|
||||
"""
|
||||
\(update)
|
||||
\(packages(alpine ? "openssh" : "openssh-server"))
|
||||
\(alpine ? "sudo rc-update add sshd default\nsudo rc-service sshd start" : "sudo systemctl enable --now sshd 2>/dev/null || sudo systemctl enable --now ssh")
|
||||
""",
|
||||
"ss -lntp | grep ':22'",
|
||||
"Use SSH keys where possible and restrict access through the firewall."
|
||||
)
|
||||
|
||||
let git = guide(
|
||||
"git", "Git", "Development",
|
||||
"Install Git for source control.",
|
||||
"""
|
||||
\(update)
|
||||
\(packages("git"))
|
||||
""",
|
||||
"git --version"
|
||||
)
|
||||
|
||||
let node = guide(
|
||||
"node", "Node.js and npm", "Development",
|
||||
"Install the distribution's Node.js runtime and npm.",
|
||||
"""
|
||||
\(update)
|
||||
\(packages("nodejs npm"))
|
||||
""",
|
||||
"node --version\nnpm --version",
|
||||
"For specific Node.js versions, use a supported version manager or official distribution packages."
|
||||
)
|
||||
|
||||
let tools = guide(
|
||||
"tools", "Build Tools", "Development",
|
||||
"Install compilers and common build utilities.",
|
||||
"""
|
||||
\(update)
|
||||
\(packages(apt ? "build-essential curl wget unzip" : dnf ? "gcc gcc-c++ make curl wget unzip" : "build-base curl wget unzip"))
|
||||
""",
|
||||
"gcc --version\nmake --version"
|
||||
)
|
||||
|
||||
let apache = guide(
|
||||
"apache", "Apache HTTP Server", "Web Servers",
|
||||
"Install Apache as an alternative to Nginx.",
|
||||
"""
|
||||
\(update)
|
||||
\(packages(apt ? "apache2" : dnf ? "httpd" : "apache2"))
|
||||
\(alpine ? "sudo rc-update add apache2 default\nsudo rc-service apache2 start" : "sudo systemctl enable --now \(apt ? "apache2" : "httpd")")
|
||||
""",
|
||||
"curl -I http://127.0.0.1"
|
||||
)
|
||||
|
||||
return [
|
||||
nginx, apache, php, composer,
|
||||
database, postgres, cache, mailpit,
|
||||
cockpit, ssh, git, node, tools
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
private struct OrionHelpView: View {
|
||||
@State private var system = "Fedora"
|
||||
@State private var selectedGuide = "mailpit"
|
||||
@State private var search = ""
|
||||
|
||||
private var guides: [OrionHelpGuide] {
|
||||
OrionHelpLibrary.guides(for: system)
|
||||
}
|
||||
|
||||
private var filtered: [OrionHelpGuide] {
|
||||
guard !search.isEmpty else { return guides }
|
||||
return guides.filter {
|
||||
$0.title.localizedCaseInsensitiveContains(search) ||
|
||||
$0.category.localizedCaseInsensitiveContains(search) ||
|
||||
$0.description.localizedCaseInsensitiveContains(search)
|
||||
}
|
||||
}
|
||||
|
||||
private var selected: OrionHelpGuide? {
|
||||
guides.first { $0.id == selectedGuide }
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
NavigationSplitView {
|
||||
VStack(spacing: 10) {
|
||||
Picker("Operating System", selection: $system) {
|
||||
ForEach(OrionHelpLibrary.systems, id: \.self) { name in
|
||||
Text(name).tag(name)
|
||||
}
|
||||
}
|
||||
.padding(.horizontal, 12)
|
||||
.padding(.top, 12)
|
||||
|
||||
List(selection: $selectedGuide) {
|
||||
ForEach(filtered) { guide in
|
||||
Label(guide.title, systemImage: icon(for: guide.category))
|
||||
.tag(guide.id)
|
||||
}
|
||||
}
|
||||
.listStyle(.sidebar)
|
||||
.searchable(text: $search, prompt: "Find components")
|
||||
}
|
||||
.navigationSplitViewColumnWidth(min: 220, ideal: 250)
|
||||
} detail: {
|
||||
if let guide = selected {
|
||||
ScrollView {
|
||||
VStack(alignment: .leading, spacing: 20) {
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
Text(guide.category.uppercased())
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
|
||||
Text(guide.title)
|
||||
.font(.largeTitle.bold())
|
||||
|
||||
Text(guide.description)
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
|
||||
commandSection(
|
||||
"Installation",
|
||||
text: guide.commands
|
||||
)
|
||||
|
||||
commandSection(
|
||||
"Verification",
|
||||
text: guide.verification
|
||||
)
|
||||
|
||||
if !guide.notes.isEmpty {
|
||||
VStack(alignment: .leading, spacing: 8) {
|
||||
Label("Important Notes", systemImage: "info.circle")
|
||||
.font(.headline)
|
||||
|
||||
Text(guide.notes)
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
}
|
||||
.padding()
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.background(.quaternary.opacity(0.4),
|
||||
in: RoundedRectangle(cornerRadius: 10))
|
||||
}
|
||||
|
||||
Text("Review commands before running them. Package names and service configuration may differ between releases.")
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
.padding(24)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
.navigationTitle(guide.title)
|
||||
} else {
|
||||
ContentUnavailableView(
|
||||
"Select a Component",
|
||||
systemImage: "questionmark.circle"
|
||||
)
|
||||
}
|
||||
}
|
||||
.frame(minWidth: 850, minHeight: 580)
|
||||
}
|
||||
|
||||
private func commandSection(_ title: String, text: String) -> some View {
|
||||
VStack(alignment: .leading, spacing: 10) {
|
||||
HStack {
|
||||
Text(title)
|
||||
.font(.headline)
|
||||
|
||||
Spacer()
|
||||
|
||||
Button {
|
||||
NSPasteboard.general.clearContents()
|
||||
NSPasteboard.general.setString(text, forType: .string)
|
||||
} label: {
|
||||
Label("Copy Commands", systemImage: "doc.on.doc")
|
||||
}
|
||||
}
|
||||
|
||||
Text(text)
|
||||
.font(.system(size: 12, design: .monospaced))
|
||||
.textSelection(.enabled)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.padding(14)
|
||||
.background(Color(nsColor: .textBackgroundColor),
|
||||
in: RoundedRectangle(cornerRadius: 9))
|
||||
}
|
||||
}
|
||||
|
||||
private func icon(for category: String) -> String {
|
||||
switch category {
|
||||
case "Web Servers": return "globe"
|
||||
case "PHP": return "chevron.left.forwardslash.chevron.right"
|
||||
case "Databases": return "externaldrive"
|
||||
case "Caching": return "memorychip"
|
||||
case "Email Testing": return "envelope"
|
||||
case "Administration": return "gearshape"
|
||||
default: return "hammer"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
private final class OrionHelpWindowPresenter: NSObject, NSWindowDelegate {
|
||||
private static var current: OrionHelpWindowPresenter?
|
||||
private var window: NSWindow?
|
||||
|
||||
static func present() {
|
||||
if let current, let window = current.window {
|
||||
NSApp.activate(ignoringOtherApps: true)
|
||||
window.makeKeyAndOrderFront(nil)
|
||||
return
|
||||
}
|
||||
|
||||
let presenter = OrionHelpWindowPresenter()
|
||||
current = presenter
|
||||
presenter.open()
|
||||
}
|
||||
|
||||
private func open() {
|
||||
let window = NSWindow(
|
||||
contentRect: NSRect(x: 0, y: 0, width: 950, height: 650),
|
||||
styleMask: [.titled, .closable, .miniaturizable, .resizable],
|
||||
backing: .buffered,
|
||||
defer: false
|
||||
)
|
||||
|
||||
window.title = "OrionToolbar Help"
|
||||
window.contentViewController = NSHostingController(
|
||||
rootView: OrionHelpView()
|
||||
)
|
||||
window.isReleasedWhenClosed = false
|
||||
window.delegate = self
|
||||
window.center()
|
||||
|
||||
self.window = window
|
||||
|
||||
// Keep Help independent of the temporary menu-bar window.
|
||||
// A floating level avoids the menu-bar panel covering Help.
|
||||
window.level = .floating
|
||||
NSApp.activate(ignoringOtherApps: true)
|
||||
window.makeKeyAndOrderFront(nil)
|
||||
}
|
||||
|
||||
func windowWillClose(_ notification: Notification) {
|
||||
window = nil
|
||||
Self.current = nil
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,12 @@ struct OrionToolbarApp: App {
|
||||
}
|
||||
.menuBarExtraStyle(.window)
|
||||
|
||||
Window("OrionToolbar Help", id: "orion-help") {
|
||||
OrionHelpView()
|
||||
.preferredColorScheme(.dark)
|
||||
}
|
||||
.defaultSize(width: 950, height: 650)
|
||||
|
||||
Settings { SettingsView().environmentObject(vm) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import SwiftUI
|
||||
|
||||
@main
|
||||
struct OrionToolbarApp: App {
|
||||
@StateObject private var vm = OrionVMController()
|
||||
|
||||
private var aggregateColor: Color {
|
||||
let states = vm.servers.map { vm.status(for: $0) }
|
||||
if states.isEmpty { return .gray }
|
||||
if states.allSatisfy({ $0 == .running }) { return .green }
|
||||
if states.contains(where: { $0 == .transitioning || $0 == .checking || $0 == .suspended }) { return .orange }
|
||||
if states.contains(where: { $0 == .running }) { return .orange }
|
||||
if states.allSatisfy({ $0 == .stopped }) { return .red }
|
||||
return .red
|
||||
}
|
||||
|
||||
var body: some Scene {
|
||||
MenuBarExtra {
|
||||
OrionMenuView().environmentObject(vm)
|
||||
} label: {
|
||||
HStack(spacing: 4) {
|
||||
Image(systemName: "server.rack")
|
||||
Circle().fill(aggregateColor).frame(width: 7, height: 7)
|
||||
}
|
||||
.accessibilityLabel("Server status")
|
||||
}
|
||||
.menuBarExtraStyle(.window)
|
||||
|
||||
Settings { SettingsView().environmentObject(vm) }
|
||||
}
|
||||
}
|
||||
@@ -124,6 +124,16 @@ final class OrionVMController: ObservableObject {
|
||||
init() {
|
||||
if let data = UserDefaults.standard.data(forKey: defaultsKey), let saved = try? JSONDecoder().decode([ServerDefinition].self, from: data) { servers = saved }
|
||||
else { servers = [.orion] }
|
||||
// Migrate existing Fedora and CentOS definitions that were
|
||||
// integrated before Mailpit was enabled by default.
|
||||
for index in servers.indices {
|
||||
let name = (servers[index].name + " " + servers[index].vmName).lowercased()
|
||||
if (name.contains("fedora") || name.contains("centos")),
|
||||
servers[index].mailpitPort == nil {
|
||||
servers[index].mailpitPort = 8025
|
||||
}
|
||||
}
|
||||
|
||||
Task {
|
||||
await discoverVMs()
|
||||
await refreshAll()
|
||||
@@ -430,7 +440,7 @@ final class OrionVMController: ObservableObject {
|
||||
sshUser: "sysadmin",
|
||||
sshPort: 22,
|
||||
sshIdentityFile: "",
|
||||
mailpitPort: nil
|
||||
mailpitPort: 8025
|
||||
)
|
||||
|
||||
add(server)
|
||||
@@ -471,7 +481,14 @@ final class OrionVMController: ObservableObject {
|
||||
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 update(_ server: ServerDefinition) {
|
||||
guard let index = servers.firstIndex(where: { $0.id == server.id }) else { return }
|
||||
servers[index] = server
|
||||
Task {
|
||||
await refreshStatus(server)
|
||||
await refreshServiceAvailability()
|
||||
}
|
||||
}
|
||||
func delete(at offsets: IndexSet) { for i in offsets { statuses[servers[i].id] = nil }; servers.remove(atOffsets: offsets) }
|
||||
|
||||
func refreshAll() async {
|
||||
@@ -535,7 +552,7 @@ final class OrionVMController: ObservableObject {
|
||||
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))
|
||||
sshPort: 22, sshIdentityFile: "", mailpitPort: 8025))
|
||||
}
|
||||
|
||||
func moveServer(from source: IndexSet, to destination: Int) {
|
||||
|
||||
@@ -0,0 +1,706 @@
|
||||
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?
|
||||
var customIconPath: String? = nil
|
||||
|
||||
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
|
||||
var 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<UUID> = []
|
||||
@Published private(set) var reachableSSH: Set<UUID> = []
|
||||
@Published private(set) var reachableMailpit: Set<UUID> = []
|
||||
@Published var lastError: String?
|
||||
@Published var discoveredVMs: [ParallelsVM] = []
|
||||
@Published private(set) var hiddenVMIDs: Set<String> = Set(
|
||||
UserDefaults.standard.stringArray(forKey: "orionHiddenVMIDs.v1") ?? []
|
||||
)
|
||||
|
||||
func hideVM(_ machine: ParallelsVM) {
|
||||
hiddenVMIDs.insert(machine.id)
|
||||
UserDefaults.standard.set(hiddenVMIDs.sorted(), forKey: "orionHiddenVMIDs.v1")
|
||||
}
|
||||
|
||||
func restoreVM(_ machine: ParallelsVM) {
|
||||
hiddenVMIDs.remove(machine.id)
|
||||
UserDefaults.standard.set(hiddenVMIDs.sorted(), forKey: "orionHiddenVMIDs.v1")
|
||||
}
|
||||
|
||||
var visibleVMs: [ParallelsVM] {
|
||||
discoveredVMs.filter { !hiddenVMIDs.contains($0.id) }
|
||||
}
|
||||
|
||||
var hiddenVMs: [ParallelsVM] {
|
||||
discoveredVMs.filter { hiddenVMIDs.contains($0.id) }
|
||||
}
|
||||
|
||||
@Published var selectedVMIDs: Set<String> = []
|
||||
@Published var discovering = false
|
||||
@Published var busyVMIDs: Set<String> = []
|
||||
private var timer: Timer?
|
||||
private let defaultsKey = "serverDefinitions.v2"
|
||||
private let vmOrderKey = "orionVMOrder.v1"
|
||||
private var vmOrder: [String] {
|
||||
get { UserDefaults.standard.stringArray(forKey: vmOrderKey) ?? [] }
|
||||
set { UserDefaults.standard.set(newValue, forKey: vmOrderKey) }
|
||||
}
|
||||
|
||||
func reorderVM(draggedID: String, onto targetID: String) {
|
||||
guard draggedID != targetID,
|
||||
discoveredVMs.contains(where: { $0.id == draggedID }),
|
||||
discoveredVMs.contains(where: { $0.id == targetID }) else { return }
|
||||
var order = discoveredVMs.map(\.id)
|
||||
guard let from = order.firstIndex(of: draggedID),
|
||||
let to = order.firstIndex(of: targetID) else { return }
|
||||
order.remove(at: from)
|
||||
order.insert(draggedID, at: to)
|
||||
vmOrder = order
|
||||
let ranks = Dictionary(uniqueKeysWithValues: order.enumerated().map { ($0.element, $0.offset) })
|
||||
discoveredVMs.sort { (ranks[$0.id] ?? Int.max) < (ranks[$1.id] ?? Int.max) }
|
||||
}
|
||||
|
||||
|
||||
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()
|
||||
await refreshServiceAvailability()
|
||||
}
|
||||
|
||||
}
|
||||
deinit { timer?.invalidate() }
|
||||
|
||||
|
||||
// Retry missing guest IPs every 500 ms until available.
|
||||
// Uses the lightweight Parallels listing rather than full discovery.
|
||||
private var ipRetryTask: Task<Void, Never>?
|
||||
|
||||
private func startIPRetry() {
|
||||
guard ipRetryTask == nil else { return }
|
||||
|
||||
ipRetryTask = Task { @MainActor [weak self] in
|
||||
guard let self else { return }
|
||||
|
||||
defer { self.ipRetryTask = nil }
|
||||
|
||||
while !Task.isCancelled {
|
||||
let missing = self.discoveredVMs.contains {
|
||||
$0.status.lowercased() == "running" &&
|
||||
$0.ipAddress.isEmpty
|
||||
}
|
||||
|
||||
if !missing { break }
|
||||
|
||||
guard !Task.isCancelled else { break }
|
||||
|
||||
if let output = try? await self.runPrlctl(["list", "-f"]) {
|
||||
var addresses: [String: String] = [:]
|
||||
|
||||
for line in output.split(separator: "\n").dropFirst() {
|
||||
let fields = line.split(
|
||||
maxSplits: 3,
|
||||
omittingEmptySubsequences: true,
|
||||
whereSeparator: { $0.isWhitespace }
|
||||
)
|
||||
|
||||
guard fields.count == 4 else { continue }
|
||||
|
||||
let uuid = String(fields[0])
|
||||
.trimmingCharacters(
|
||||
in: CharacterSet(charactersIn: "{}")
|
||||
)
|
||||
.lowercased()
|
||||
|
||||
let ip = String(fields[2])
|
||||
|
||||
if ip != "-" && ip != "0.0.0.0" {
|
||||
addresses[uuid] = ip
|
||||
}
|
||||
}
|
||||
|
||||
for index in self.discoveredVMs.indices {
|
||||
let uuid = self.discoveredVMs[index].id
|
||||
.trimmingCharacters(
|
||||
in: CharacterSet(charactersIn: "{}")
|
||||
)
|
||||
.lowercased()
|
||||
|
||||
if self.discoveredVMs[index].status.lowercased() == "running",
|
||||
self.discoveredVMs[index].ipAddress.isEmpty,
|
||||
let ip = addresses[uuid] {
|
||||
self.discoveredVMs[index].ipAddress = ip
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let stillMissing = self.discoveredVMs.contains {
|
||||
$0.status.lowercased() == "running" &&
|
||||
$0.ipAddress.isEmpty
|
||||
}
|
||||
|
||||
if !stillMissing { break }
|
||||
|
||||
try? await Task.sleep(for: .milliseconds(500))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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."
|
||||
)
|
||||
}
|
||||
|
||||
// Preserve acquired IPs while VMs remain running.
|
||||
let knownIPs = Dictionary(
|
||||
uniqueKeysWithValues: discoveredVMs.compactMap {
|
||||
machine -> (String, String)? in
|
||||
|
||||
guard machine.status.lowercased() == "running",
|
||||
!machine.ipAddress.isEmpty else {
|
||||
return nil
|
||||
}
|
||||
|
||||
return (machine.id, machine.ipAddress)
|
||||
}
|
||||
)
|
||||
|
||||
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 {
|
||||
return nil
|
||||
}
|
||||
|
||||
let status = record["status"] as? String ?? "unknown"
|
||||
let configuredIP = record["ip_configured"] as? String ?? ""
|
||||
|
||||
let ip: String
|
||||
if status.lowercased() == "running" {
|
||||
let reportedIP = configuredIP == "-" ? "" : configuredIP
|
||||
ip = knownIPs[uuid] ?? reportedIP
|
||||
} else {
|
||||
ip = ""
|
||||
}
|
||||
|
||||
return ParallelsVM(
|
||||
id: uuid,
|
||||
name: name,
|
||||
status: status,
|
||||
ipAddress: ip == "-" ? "" : ip,
|
||||
operatingSystem: ParallelsVM.detectOS(name),
|
||||
bundlePath: knownBundlePaths[uuid]
|
||||
)
|
||||
}
|
||||
.sorted {
|
||||
$0.name.localizedStandardCompare($1.name)
|
||||
== .orderedAscending
|
||||
}
|
||||
|
||||
// Keep the user's VM order through every 15-second discovery refresh.
|
||||
// New VMs are appended in discovery order.
|
||||
let savedOrder = vmOrder
|
||||
let ranks = Dictionary(uniqueKeysWithValues: savedOrder.enumerated().map { ($0.element, $0.offset) })
|
||||
discoveredVMs.sort { left, right in
|
||||
let a = ranks[left.id] ?? Int.max
|
||||
let b = ranks[right.id] ?? Int.max
|
||||
if a != b { return a < b }
|
||||
return left.name.localizedStandardCompare(right.name) == .orderedAscending
|
||||
}
|
||||
|
||||
// Resolve Parallels VM bundles without requiring the guest to run.
|
||||
for i in discoveredVMs.indices where discoveredVMs[i].bundlePath == nil {
|
||||
if let detail = try? await runPrlctl(["list", "-i", discoveredVMs[i].id]) {
|
||||
// `Home:` ends with .pvm/ on this Parallels installation.
|
||||
if let homeLine = detail.split(separator: "\n").first(where: {
|
||||
$0.trimmingCharacters(in: .whitespaces).hasPrefix("Home:")
|
||||
}) {
|
||||
let trimmed = homeLine.trimmingCharacters(in: .whitespaces)
|
||||
let raw = String(trimmed.dropFirst("Home:".count))
|
||||
.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
.trimmingCharacters(in: CharacterSet(charactersIn: "\"'"))
|
||||
let expanded = (raw as NSString).expandingTildeInPath
|
||||
let normalized = (expanded as NSString).standardizingPath
|
||||
if FileManager.default.fileExists(atPath: normalized) {
|
||||
discoveredVMs[i].bundlePath = normalized
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let needsIP = discoveredVMs.contains {
|
||||
$0.status.lowercased() == "running" &&
|
||||
$0.ipAddress.isEmpty
|
||||
}
|
||||
|
||||
if needsIP {
|
||||
startIPRetry()
|
||||
} else {
|
||||
ipRetryTask?.cancel()
|
||||
ipRetryTask = nil
|
||||
}
|
||||
|
||||
// Keep selections only for VMs still present.
|
||||
let available = Set(discoveredVMs.map(\.id))
|
||||
selectedVMIDs.formIntersection(available)
|
||||
|
||||
// Repair missing or outdated VM associations.
|
||||
for index in servers.indices {
|
||||
guard let machine = machine(for: servers[index]) else {
|
||||
continue
|
||||
}
|
||||
|
||||
if servers[index].vmUUID != machine.id {
|
||||
servers[index].vmUUID = machine.id
|
||||
}
|
||||
|
||||
if servers[index].vmName != machine.name {
|
||||
servers[index].vmName = machine.name
|
||||
}
|
||||
}
|
||||
|
||||
// Associate existing configurations with discovered VMs.
|
||||
// This preserves the original Orion configuration.
|
||||
for machine in discoveredVMs {
|
||||
guard let index = servers.firstIndex(where: {
|
||||
$0.vmUUID == machine.id ||
|
||||
($0.vmUUID == nil && $0.vmName == machine.name)
|
||||
}) else {
|
||||
continue
|
||||
}
|
||||
|
||||
if servers[index].vmUUID == nil {
|
||||
servers[index].vmUUID = machine.id
|
||||
}
|
||||
}
|
||||
|
||||
} catch {
|
||||
lastError = error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
func machine(for server: ServerDefinition) -> ParallelsVM? {
|
||||
if let uuid = server.vmUUID,
|
||||
let machine = discoveredVMs.first(where: { $0.id == uuid }) {
|
||||
return machine
|
||||
}
|
||||
|
||||
let candidates = [server.vmName, server.name]
|
||||
.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
|
||||
.filter { !$0.isEmpty }
|
||||
|
||||
for name in candidates {
|
||||
let matches = discoveredVMs.filter {
|
||||
$0.name.caseInsensitiveCompare(name) == .orderedSame
|
||||
}
|
||||
|
||||
if matches.count == 1 {
|
||||
return matches[0]
|
||||
}
|
||||
}
|
||||
|
||||
for name in candidates {
|
||||
let matches = discoveredVMs.filter {
|
||||
$0.name.localizedCaseInsensitiveContains(name)
|
||||
}
|
||||
|
||||
if matches.count == 1 {
|
||||
return matches[0]
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func isIntegrated(_ machine: ParallelsVM) -> 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 }
|
||||
let bundle = URL(fileURLWithPath: path, isDirectory: true)
|
||||
|
||||
// Parallels stores the per-VM application under <VM>.pvm/VM.app.
|
||||
// The .pvm Finder icon itself is generic and must not be used.
|
||||
let app = bundle.appendingPathComponent("VM.app", isDirectory: true)
|
||||
let plist = app.appendingPathComponent("Contents/Info.plist")
|
||||
if let info = NSDictionary(contentsOf: plist) as? [String: Any] {
|
||||
let resourceDir = app.appendingPathComponent("Contents/Resources", isDirectory: true)
|
||||
for key in ["CFBundleIconFile", "CFBundleIconName"] {
|
||||
if let name = info[key] as? String, !name.isEmpty {
|
||||
let names = name.lowercased().hasSuffix(".icns") ? [name] : [name + ".icns", name]
|
||||
for candidate in names {
|
||||
if let image = NSImage(contentsOf: resourceDir.appendingPathComponent(candidate)) {
|
||||
return image
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for name in ["icon.png", "Icon.png", "icon.icns", "Icon.icns", ".VolumeIcon.icns"] {
|
||||
if let image = NSImage(contentsOf: bundle.appendingPathComponent(name)) { return image }
|
||||
}
|
||||
// Never return NSWorkspace.icon(forFile: path): it is the generic .pvm icon.
|
||||
return nil
|
||||
}
|
||||
|
||||
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()
|
||||
await refreshServiceAvailability()
|
||||
}
|
||||
}
|
||||
|
||||
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 moveServer(from source: IndexSet, to destination: Int) {
|
||||
servers.move(fromOffsets: source, toOffset: destination)
|
||||
}
|
||||
|
||||
func moveServer(_ id: UUID, by delta: Int) {
|
||||
guard let index = servers.firstIndex(where: { $0.id == id }) else { return }
|
||||
let target = index + delta
|
||||
guard servers.indices.contains(target) else { return }
|
||||
servers.swapAt(index, target)
|
||||
}
|
||||
|
||||
func reorderServer(draggedID: UUID, onto targetID: UUID) {
|
||||
guard draggedID != targetID,
|
||||
let from = servers.firstIndex(where: { $0.id == draggedID }),
|
||||
let to = servers.firstIndex(where: { $0.id == targetID }) else { return }
|
||||
let moved = servers.remove(at: from)
|
||||
servers.insert(moved, at: to) // @Published didSet persists the order.
|
||||
}
|
||||
|
||||
func icon(for server: ServerDefinition) -> NSImage? {
|
||||
if let path = server.customIconPath, let image = NSImage(contentsOfFile: path) {
|
||||
return image
|
||||
}
|
||||
|
||||
guard let machine = discoveredVMs.first(where: {
|
||||
$0.id == server.vmUUID || $0.name == server.vmName
|
||||
}) else { return nil }
|
||||
return icon(for: machine)
|
||||
}
|
||||
|
||||
// Availability is probed off the main actor. An open SSH port means
|
||||
// the SSH action can be offered; credentials are checked by ssh itself.
|
||||
func refreshServiceAvailability() async {
|
||||
let candidates = servers.filter { server in
|
||||
guard !server.host.isEmpty else { return false }
|
||||
return discoveredVMs.contains {
|
||||
($0.id == server.vmUUID || $0.name == server.vmName) &&
|
||||
$0.status.lowercased() == "running"
|
||||
}
|
||||
}
|
||||
let results = await withTaskGroup(of: (UUID, Bool, Bool).self,
|
||||
returning: [(UUID, Bool, Bool)].self) { group in
|
||||
for server in candidates {
|
||||
group.addTask {
|
||||
async let ssh = Self.tcpPortOpen(host: server.host, port: server.sshPort)
|
||||
async let mailpit = Self.mailpitResponding(host: server.host, port: server.mailpitPort)
|
||||
return (server.id, await ssh, await mailpit)
|
||||
}
|
||||
}
|
||||
var values: [(UUID, Bool, Bool)] = []
|
||||
for await result in group { values.append(result) }
|
||||
return values
|
||||
}
|
||||
reachableSSH = Set(results.filter { $0.1 }.map { $0.0 })
|
||||
reachableMailpit = Set(results.filter { $0.2 }.map { $0.0 })
|
||||
}
|
||||
|
||||
private nonisolated static func tcpPortOpen(host: String, port: Int) async -> Bool {
|
||||
guard (1...65535).contains(port), !host.isEmpty else { return false }
|
||||
return await Task.detached(priority: .utility) {
|
||||
let process = Process()
|
||||
process.executableURL = URL(fileURLWithPath: "/usr/bin/nc")
|
||||
process.arguments = ["-G", "2", "-z", host, String(port)]
|
||||
process.standardOutput = FileHandle.nullDevice
|
||||
process.standardError = FileHandle.nullDevice
|
||||
do {
|
||||
try process.run()
|
||||
process.waitUntilExit()
|
||||
return process.terminationStatus == 0
|
||||
} catch { return false }
|
||||
}.value
|
||||
}
|
||||
|
||||
private nonisolated static func mailpitResponding(host: String, port: Int?) async -> Bool {
|
||||
guard let port, (1...65535).contains(port), !host.isEmpty,
|
||||
let url = URL(string: "http://\(host):\(port)/") else { return false }
|
||||
var request = URLRequest(url: url)
|
||||
request.timeoutInterval = 3
|
||||
request.httpMethod = "GET"
|
||||
do {
|
||||
let (_, response) = try await URLSession.shared.data(for: request)
|
||||
guard let http = response as? HTTPURLResponse else { return false }
|
||||
return (200..<500).contains(http.statusCode)
|
||||
} catch { return false }
|
||||
}
|
||||
|
||||
func openSSH(_ s: ServerDefinition) {
|
||||
NSApp.hide(nil)
|
||||
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) { application, error in
|
||||
Task { @MainActor in
|
||||
if let error {
|
||||
self.lastError = "Could not open Terminal: \(error.localizedDescription)"
|
||||
} else {
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + 0.35) {
|
||||
application?.activate(options: [.activateAllWindows])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
lastError = "Could not create SSH launcher: \(error.localizedDescription)"
|
||||
}
|
||||
}
|
||||
|
||||
private func shellQuote(_ value: String) -> String {
|
||||
"'" + value.replacingOccurrences(of: "'", with: "'\"'\"'") + "'"
|
||||
}
|
||||
func openMailpit(_ s: ServerDefinition) {
|
||||
guard let p = s.mailpitPort,
|
||||
let url = URL(string: "http://\(s.host):\(p)") else { return }
|
||||
NSApp.hide(nil)
|
||||
let browserURL = NSWorkspace.shared.urlForApplication(toOpen: url)
|
||||
NSWorkspace.shared.open(url)
|
||||
if let browserURL {
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) {
|
||||
let browser = NSWorkspace.shared.runningApplications.first {
|
||||
$0.bundleURL == browserURL
|
||||
}
|
||||
browser?.activate(options: [.activateAllWindows])
|
||||
}
|
||||
}
|
||||
}
|
||||
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) } } }
|
||||
@@ -0,0 +1,706 @@
|
||||
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?
|
||||
var customIconPath: String? = nil
|
||||
|
||||
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
|
||||
var 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<UUID> = []
|
||||
@Published private(set) var reachableSSH: Set<UUID> = []
|
||||
@Published private(set) var reachableMailpit: Set<UUID> = []
|
||||
@Published var lastError: String?
|
||||
@Published var discoveredVMs: [ParallelsVM] = []
|
||||
@Published private(set) var hiddenVMIDs: Set<String> = Set(
|
||||
UserDefaults.standard.stringArray(forKey: "orionHiddenVMIDs.v1") ?? []
|
||||
)
|
||||
|
||||
func hideVM(_ machine: ParallelsVM) {
|
||||
hiddenVMIDs.insert(machine.id)
|
||||
UserDefaults.standard.set(hiddenVMIDs.sorted(), forKey: "orionHiddenVMIDs.v1")
|
||||
}
|
||||
|
||||
func restoreVM(_ machine: ParallelsVM) {
|
||||
hiddenVMIDs.remove(machine.id)
|
||||
UserDefaults.standard.set(hiddenVMIDs.sorted(), forKey: "orionHiddenVMIDs.v1")
|
||||
}
|
||||
|
||||
var visibleVMs: [ParallelsVM] {
|
||||
discoveredVMs.filter { !hiddenVMIDs.contains($0.id) }
|
||||
}
|
||||
|
||||
var hiddenVMs: [ParallelsVM] {
|
||||
discoveredVMs.filter { hiddenVMIDs.contains($0.id) }
|
||||
}
|
||||
|
||||
@Published var selectedVMIDs: Set<String> = []
|
||||
@Published var discovering = false
|
||||
@Published var busyVMIDs: Set<String> = []
|
||||
private var timer: Timer?
|
||||
private let defaultsKey = "serverDefinitions.v2"
|
||||
private let vmOrderKey = "orionVMOrder.v1"
|
||||
private var vmOrder: [String] {
|
||||
get { UserDefaults.standard.stringArray(forKey: vmOrderKey) ?? [] }
|
||||
set { UserDefaults.standard.set(newValue, forKey: vmOrderKey) }
|
||||
}
|
||||
|
||||
func reorderVM(draggedID: String, onto targetID: String) {
|
||||
guard draggedID != targetID,
|
||||
discoveredVMs.contains(where: { $0.id == draggedID }),
|
||||
discoveredVMs.contains(where: { $0.id == targetID }) else { return }
|
||||
var order = discoveredVMs.map(\.id)
|
||||
guard let from = order.firstIndex(of: draggedID),
|
||||
let to = order.firstIndex(of: targetID) else { return }
|
||||
order.remove(at: from)
|
||||
order.insert(draggedID, at: to)
|
||||
vmOrder = order
|
||||
let ranks = Dictionary(uniqueKeysWithValues: order.enumerated().map { ($0.element, $0.offset) })
|
||||
discoveredVMs.sort { (ranks[$0.id] ?? Int.max) < (ranks[$1.id] ?? Int.max) }
|
||||
}
|
||||
|
||||
|
||||
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()
|
||||
await refreshServiceAvailability()
|
||||
}
|
||||
|
||||
}
|
||||
deinit { timer?.invalidate() }
|
||||
|
||||
|
||||
// Retry missing guest IPs every 500 ms until available.
|
||||
// Uses the lightweight Parallels listing rather than full discovery.
|
||||
private var ipRetryTask: Task<Void, Never>?
|
||||
|
||||
private func startIPRetry() {
|
||||
guard ipRetryTask == nil else { return }
|
||||
|
||||
ipRetryTask = Task { @MainActor [weak self] in
|
||||
guard let self else { return }
|
||||
|
||||
defer { self.ipRetryTask = nil }
|
||||
|
||||
while !Task.isCancelled {
|
||||
let missing = self.discoveredVMs.contains {
|
||||
$0.status.lowercased() == "running" &&
|
||||
$0.ipAddress.isEmpty
|
||||
}
|
||||
|
||||
if !missing { break }
|
||||
|
||||
guard !Task.isCancelled else { break }
|
||||
|
||||
if let output = try? await self.runPrlctl(["list", "-f"]) {
|
||||
var addresses: [String: String] = [:]
|
||||
|
||||
for line in output.split(separator: "\n").dropFirst() {
|
||||
let fields = line.split(
|
||||
maxSplits: 3,
|
||||
omittingEmptySubsequences: true,
|
||||
whereSeparator: { $0.isWhitespace }
|
||||
)
|
||||
|
||||
guard fields.count == 4 else { continue }
|
||||
|
||||
let uuid = String(fields[0])
|
||||
.trimmingCharacters(
|
||||
in: CharacterSet(charactersIn: "{}")
|
||||
)
|
||||
.lowercased()
|
||||
|
||||
let ip = String(fields[2])
|
||||
|
||||
if ip != "-" && ip != "0.0.0.0" {
|
||||
addresses[uuid] = ip
|
||||
}
|
||||
}
|
||||
|
||||
for index in self.discoveredVMs.indices {
|
||||
let uuid = self.discoveredVMs[index].id
|
||||
.trimmingCharacters(
|
||||
in: CharacterSet(charactersIn: "{}")
|
||||
)
|
||||
.lowercased()
|
||||
|
||||
if self.discoveredVMs[index].status.lowercased() == "running",
|
||||
self.discoveredVMs[index].ipAddress.isEmpty,
|
||||
let ip = addresses[uuid] {
|
||||
self.discoveredVMs[index].ipAddress = ip
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let stillMissing = self.discoveredVMs.contains {
|
||||
$0.status.lowercased() == "running" &&
|
||||
$0.ipAddress.isEmpty
|
||||
}
|
||||
|
||||
if !stillMissing { break }
|
||||
|
||||
try? await Task.sleep(for: .milliseconds(500))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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."
|
||||
)
|
||||
}
|
||||
|
||||
// Preserve acquired IPs while VMs remain running.
|
||||
let knownIPs = Dictionary(
|
||||
uniqueKeysWithValues: discoveredVMs.compactMap {
|
||||
machine -> (String, String)? in
|
||||
|
||||
guard machine.status.lowercased() == "running",
|
||||
!machine.ipAddress.isEmpty else {
|
||||
return nil
|
||||
}
|
||||
|
||||
return (machine.id, machine.ipAddress)
|
||||
}
|
||||
)
|
||||
|
||||
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 {
|
||||
return nil
|
||||
}
|
||||
|
||||
let status = record["status"] as? String ?? "unknown"
|
||||
let configuredIP = record["ip_configured"] as? String ?? ""
|
||||
|
||||
let ip: String
|
||||
if status.lowercased() == "running" {
|
||||
let reportedIP = configuredIP == "-" ? "" : configuredIP
|
||||
ip = knownIPs[uuid] ?? reportedIP
|
||||
} else {
|
||||
ip = ""
|
||||
}
|
||||
|
||||
return ParallelsVM(
|
||||
id: uuid,
|
||||
name: name,
|
||||
status: status,
|
||||
ipAddress: ip == "-" ? "" : ip,
|
||||
operatingSystem: ParallelsVM.detectOS(name),
|
||||
bundlePath: knownBundlePaths[uuid]
|
||||
)
|
||||
}
|
||||
.sorted {
|
||||
$0.name.localizedStandardCompare($1.name)
|
||||
== .orderedAscending
|
||||
}
|
||||
|
||||
// Keep the user's VM order through every 15-second discovery refresh.
|
||||
// New VMs are appended in discovery order.
|
||||
let savedOrder = vmOrder
|
||||
let ranks = Dictionary(uniqueKeysWithValues: savedOrder.enumerated().map { ($0.element, $0.offset) })
|
||||
discoveredVMs.sort { left, right in
|
||||
let a = ranks[left.id] ?? Int.max
|
||||
let b = ranks[right.id] ?? Int.max
|
||||
if a != b { return a < b }
|
||||
return left.name.localizedStandardCompare(right.name) == .orderedAscending
|
||||
}
|
||||
|
||||
// Resolve Parallels VM bundles without requiring the guest to run.
|
||||
for i in discoveredVMs.indices where discoveredVMs[i].bundlePath == nil {
|
||||
if let detail = try? await runPrlctl(["list", "-i", discoveredVMs[i].id]) {
|
||||
// `Home:` ends with .pvm/ on this Parallels installation.
|
||||
if let homeLine = detail.split(separator: "\n").first(where: {
|
||||
$0.trimmingCharacters(in: .whitespaces).hasPrefix("Home:")
|
||||
}) {
|
||||
let trimmed = homeLine.trimmingCharacters(in: .whitespaces)
|
||||
let raw = String(trimmed.dropFirst("Home:".count))
|
||||
.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
.trimmingCharacters(in: CharacterSet(charactersIn: "\"'"))
|
||||
let expanded = (raw as NSString).expandingTildeInPath
|
||||
let normalized = (expanded as NSString).standardizingPath
|
||||
if FileManager.default.fileExists(atPath: normalized) {
|
||||
discoveredVMs[i].bundlePath = normalized
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let needsIP = discoveredVMs.contains {
|
||||
$0.status.lowercased() == "running" &&
|
||||
$0.ipAddress.isEmpty
|
||||
}
|
||||
|
||||
if needsIP {
|
||||
startIPRetry()
|
||||
} else {
|
||||
ipRetryTask?.cancel()
|
||||
ipRetryTask = nil
|
||||
}
|
||||
|
||||
// Keep selections only for VMs still present.
|
||||
let available = Set(discoveredVMs.map(\.id))
|
||||
selectedVMIDs.formIntersection(available)
|
||||
|
||||
// Repair missing or outdated VM associations.
|
||||
for index in servers.indices {
|
||||
guard let machine = machine(for: servers[index]) else {
|
||||
continue
|
||||
}
|
||||
|
||||
if servers[index].vmUUID != machine.id {
|
||||
servers[index].vmUUID = machine.id
|
||||
}
|
||||
|
||||
if servers[index].vmName != machine.name {
|
||||
servers[index].vmName = machine.name
|
||||
}
|
||||
}
|
||||
|
||||
// Associate existing configurations with discovered VMs.
|
||||
// This preserves the original Orion configuration.
|
||||
for machine in discoveredVMs {
|
||||
guard let index = servers.firstIndex(where: {
|
||||
$0.vmUUID == machine.id ||
|
||||
($0.vmUUID == nil && $0.vmName == machine.name)
|
||||
}) else {
|
||||
continue
|
||||
}
|
||||
|
||||
if servers[index].vmUUID == nil {
|
||||
servers[index].vmUUID = machine.id
|
||||
}
|
||||
}
|
||||
|
||||
} catch {
|
||||
lastError = error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
func machine(for server: ServerDefinition) -> ParallelsVM? {
|
||||
if let uuid = server.vmUUID,
|
||||
let machine = discoveredVMs.first(where: { $0.id == uuid }) {
|
||||
return machine
|
||||
}
|
||||
|
||||
let candidates = [server.vmName, server.name]
|
||||
.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
|
||||
.filter { !$0.isEmpty }
|
||||
|
||||
for name in candidates {
|
||||
let matches = discoveredVMs.filter {
|
||||
$0.name.caseInsensitiveCompare(name) == .orderedSame
|
||||
}
|
||||
|
||||
if matches.count == 1 {
|
||||
return matches[0]
|
||||
}
|
||||
}
|
||||
|
||||
for name in candidates {
|
||||
let matches = discoveredVMs.filter {
|
||||
$0.name.localizedCaseInsensitiveContains(name)
|
||||
}
|
||||
|
||||
if matches.count == 1 {
|
||||
return matches[0]
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func isIntegrated(_ machine: ParallelsVM) -> 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: 8025
|
||||
)
|
||||
|
||||
add(server)
|
||||
}
|
||||
|
||||
selectedVMIDs.removeAll()
|
||||
}
|
||||
|
||||
func icon(for machine: ParallelsVM) -> NSImage? {
|
||||
guard let path = machine.bundlePath,
|
||||
FileManager.default.fileExists(atPath: path) else { return nil }
|
||||
let bundle = URL(fileURLWithPath: path, isDirectory: true)
|
||||
|
||||
// Parallels stores the per-VM application under <VM>.pvm/VM.app.
|
||||
// The .pvm Finder icon itself is generic and must not be used.
|
||||
let app = bundle.appendingPathComponent("VM.app", isDirectory: true)
|
||||
let plist = app.appendingPathComponent("Contents/Info.plist")
|
||||
if let info = NSDictionary(contentsOf: plist) as? [String: Any] {
|
||||
let resourceDir = app.appendingPathComponent("Contents/Resources", isDirectory: true)
|
||||
for key in ["CFBundleIconFile", "CFBundleIconName"] {
|
||||
if let name = info[key] as? String, !name.isEmpty {
|
||||
let names = name.lowercased().hasSuffix(".icns") ? [name] : [name + ".icns", name]
|
||||
for candidate in names {
|
||||
if let image = NSImage(contentsOf: resourceDir.appendingPathComponent(candidate)) {
|
||||
return image
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for name in ["icon.png", "Icon.png", "icon.icns", "Icon.icns", ".VolumeIcon.icns"] {
|
||||
if let image = NSImage(contentsOf: bundle.appendingPathComponent(name)) { return image }
|
||||
}
|
||||
// Never return NSWorkspace.icon(forFile: path): it is the generic .pvm icon.
|
||||
return nil
|
||||
}
|
||||
|
||||
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()
|
||||
await refreshServiceAvailability()
|
||||
}
|
||||
}
|
||||
|
||||
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: 8025))
|
||||
}
|
||||
|
||||
func moveServer(from source: IndexSet, to destination: Int) {
|
||||
servers.move(fromOffsets: source, toOffset: destination)
|
||||
}
|
||||
|
||||
func moveServer(_ id: UUID, by delta: Int) {
|
||||
guard let index = servers.firstIndex(where: { $0.id == id }) else { return }
|
||||
let target = index + delta
|
||||
guard servers.indices.contains(target) else { return }
|
||||
servers.swapAt(index, target)
|
||||
}
|
||||
|
||||
func reorderServer(draggedID: UUID, onto targetID: UUID) {
|
||||
guard draggedID != targetID,
|
||||
let from = servers.firstIndex(where: { $0.id == draggedID }),
|
||||
let to = servers.firstIndex(where: { $0.id == targetID }) else { return }
|
||||
let moved = servers.remove(at: from)
|
||||
servers.insert(moved, at: to) // @Published didSet persists the order.
|
||||
}
|
||||
|
||||
func icon(for server: ServerDefinition) -> NSImage? {
|
||||
if let path = server.customIconPath, let image = NSImage(contentsOfFile: path) {
|
||||
return image
|
||||
}
|
||||
|
||||
guard let machine = discoveredVMs.first(where: {
|
||||
$0.id == server.vmUUID || $0.name == server.vmName
|
||||
}) else { return nil }
|
||||
return icon(for: machine)
|
||||
}
|
||||
|
||||
// Availability is probed off the main actor. An open SSH port means
|
||||
// the SSH action can be offered; credentials are checked by ssh itself.
|
||||
func refreshServiceAvailability() async {
|
||||
let candidates = servers.filter { server in
|
||||
guard !server.host.isEmpty else { return false }
|
||||
return discoveredVMs.contains {
|
||||
($0.id == server.vmUUID || $0.name == server.vmName) &&
|
||||
$0.status.lowercased() == "running"
|
||||
}
|
||||
}
|
||||
let results = await withTaskGroup(of: (UUID, Bool, Bool).self,
|
||||
returning: [(UUID, Bool, Bool)].self) { group in
|
||||
for server in candidates {
|
||||
group.addTask {
|
||||
async let ssh = Self.tcpPortOpen(host: server.host, port: server.sshPort)
|
||||
async let mailpit = Self.mailpitResponding(host: server.host, port: server.mailpitPort)
|
||||
return (server.id, await ssh, await mailpit)
|
||||
}
|
||||
}
|
||||
var values: [(UUID, Bool, Bool)] = []
|
||||
for await result in group { values.append(result) }
|
||||
return values
|
||||
}
|
||||
reachableSSH = Set(results.filter { $0.1 }.map { $0.0 })
|
||||
reachableMailpit = Set(results.filter { $0.2 }.map { $0.0 })
|
||||
}
|
||||
|
||||
private nonisolated static func tcpPortOpen(host: String, port: Int) async -> Bool {
|
||||
guard (1...65535).contains(port), !host.isEmpty else { return false }
|
||||
return await Task.detached(priority: .utility) {
|
||||
let process = Process()
|
||||
process.executableURL = URL(fileURLWithPath: "/usr/bin/nc")
|
||||
process.arguments = ["-G", "2", "-z", host, String(port)]
|
||||
process.standardOutput = FileHandle.nullDevice
|
||||
process.standardError = FileHandle.nullDevice
|
||||
do {
|
||||
try process.run()
|
||||
process.waitUntilExit()
|
||||
return process.terminationStatus == 0
|
||||
} catch { return false }
|
||||
}.value
|
||||
}
|
||||
|
||||
private nonisolated static func mailpitResponding(host: String, port: Int?) async -> Bool {
|
||||
guard let port, (1...65535).contains(port), !host.isEmpty,
|
||||
let url = URL(string: "http://\(host):\(port)/") else { return false }
|
||||
var request = URLRequest(url: url)
|
||||
request.timeoutInterval = 3
|
||||
request.httpMethod = "GET"
|
||||
do {
|
||||
let (_, response) = try await URLSession.shared.data(for: request)
|
||||
guard let http = response as? HTTPURLResponse else { return false }
|
||||
return (200..<500).contains(http.statusCode)
|
||||
} catch { return false }
|
||||
}
|
||||
|
||||
func openSSH(_ s: ServerDefinition) {
|
||||
NSApp.hide(nil)
|
||||
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) { application, error in
|
||||
Task { @MainActor in
|
||||
if let error {
|
||||
self.lastError = "Could not open Terminal: \(error.localizedDescription)"
|
||||
} else {
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + 0.35) {
|
||||
application?.activate(options: [.activateAllWindows])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
lastError = "Could not create SSH launcher: \(error.localizedDescription)"
|
||||
}
|
||||
}
|
||||
|
||||
private func shellQuote(_ value: String) -> String {
|
||||
"'" + value.replacingOccurrences(of: "'", with: "'\"'\"'") + "'"
|
||||
}
|
||||
func openMailpit(_ s: ServerDefinition) {
|
||||
guard let p = s.mailpitPort,
|
||||
let url = URL(string: "http://\(s.host):\(p)") else { return }
|
||||
NSApp.hide(nil)
|
||||
let browserURL = NSWorkspace.shared.urlForApplication(toOpen: url)
|
||||
NSWorkspace.shared.open(url)
|
||||
if let browserURL {
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) {
|
||||
let browser = NSWorkspace.shared.runningApplications.first {
|
||||
$0.bundleURL == browserURL
|
||||
}
|
||||
browser?.activate(options: [.activateAllWindows])
|
||||
}
|
||||
}
|
||||
}
|
||||
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) } } }
|
||||
@@ -129,7 +129,28 @@ struct SettingsView: View {
|
||||
}.padding(20).frame(width: 530, height: 420)
|
||||
.task { await vm.discoverVMs() }
|
||||
}
|
||||
.sheet(item: $editing) { server in ServerEditor(server: server, isNew: !vm.servers.contains(where: {$0.id == server.id})) { value, isNew in if isNew { vm.add(value) } else { vm.update(value) }; selection = value.id } }
|
||||
.sheet(
|
||||
isPresented: Binding(
|
||||
get: { editing != nil },
|
||||
set: { if !$0 { editing = nil } }
|
||||
)
|
||||
) {
|
||||
if let server = editing {
|
||||
ServerEditor(
|
||||
server: server,
|
||||
isNew: !vm.servers.contains(where: { $0.id == server.id })
|
||||
) { value, isNew in
|
||||
if isNew {
|
||||
vm.add(value)
|
||||
} else {
|
||||
vm.update(value)
|
||||
}
|
||||
selection = value.id
|
||||
editing = nil
|
||||
}
|
||||
.interactiveDismissDisabled()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
import SwiftUI
|
||||
import UniformTypeIdentifiers
|
||||
|
||||
struct SettingsView: View {
|
||||
@EnvironmentObject var vm: OrionVMController
|
||||
@State private var selection: UUID?
|
||||
@State private var editing: ServerDefinition?
|
||||
@State private var addingVMs = false
|
||||
@State private var pendingRemoval: ServerDefinition?
|
||||
var body: some View {
|
||||
HStack(spacing: 0) {
|
||||
// ORION_REORDER_ICONS_V3: explicit drop targets; no List/onMove interception.
|
||||
ScrollView {
|
||||
LazyVStack(spacing: 3) {
|
||||
ForEach(vm.servers) { server in
|
||||
HStack(spacing: 8) {
|
||||
Image(systemName: "line.3.horizontal")
|
||||
.foregroundStyle(.secondary)
|
||||
.help("Drag this server to reorder")
|
||||
Group {
|
||||
if let image = vm.icon(for: server) {
|
||||
Image(nsImage: image).resizable().scaledToFit()
|
||||
} else {
|
||||
Image(systemName: "server.rack")
|
||||
}
|
||||
}.frame(width: 23, height: 23)
|
||||
Text(server.name).lineLimit(1)
|
||||
Spacer(minLength: 0)
|
||||
}
|
||||
.padding(.horizontal, 9)
|
||||
.padding(.vertical, 9)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.background(selection == server.id ? Color.accentColor.opacity(0.3) : Color.clear,
|
||||
in: RoundedRectangle(cornerRadius: 7))
|
||||
.contentShape(Rectangle())
|
||||
.onTapGesture { selection = server.id }
|
||||
// Native macOS drag source. Works in the menu-bar Settings window.
|
||||
.onDrag {
|
||||
NSItemProvider(object: server.id.uuidString as NSString)
|
||||
}
|
||||
.onDrop(of: [UTType.utf8PlainText.identifier, UTType.plainText.identifier], isTargeted: nil) { providers in
|
||||
guard let provider = providers.first(where: {
|
||||
$0.canLoadObject(ofClass: NSString.self)
|
||||
}) else { return false }
|
||||
let targetID = server.id
|
||||
_ = provider.loadObject(ofClass: NSString.self) { object, _ in
|
||||
guard let raw = object as? String,
|
||||
let draggedID = UUID(uuidString: raw) else { return }
|
||||
Task { @MainActor in
|
||||
vm.reorderServer(draggedID: draggedID, onto: targetID)
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
.padding(6)
|
||||
}
|
||||
.frame(width: 220)
|
||||
Divider()
|
||||
VStack(alignment: .leading, spacing: 14) {
|
||||
if let id = selection, let server = vm.servers.first(where: { $0.id == id }) {
|
||||
Text(server.name).font(.title2).fontWeight(.semibold)
|
||||
LabeledContent("Parallels VM", value: server.vmName); LabeledContent("Host", value: server.host); LabeledContent("SSH user", value: server.sshUser); LabeledContent("SSH port", value: String(server.sshPort)); LabeledContent("SSH key", value: server.sshIdentityFile.isEmpty ? "Default SSH configuration" : server.sshIdentityFile); LabeledContent("Mailpit", value: server.mailpitPort.map(String.init) ?? "Disabled")
|
||||
HStack {
|
||||
Button("Edit…") { editing = server }
|
||||
Button("Move Up", systemImage: "arrow.up") { vm.moveServer(server.id, by: -1) }
|
||||
.disabled(vm.servers.first?.id == server.id)
|
||||
Button("Move Down", systemImage: "arrow.down") { vm.moveServer(server.id, by: 1) }
|
||||
.disabled(vm.servers.last?.id == server.id)
|
||||
Button("Force Stop", role: .destructive) { vm.forceStop(server) }
|
||||
.disabled(vm.status(for: server) == .stopped)
|
||||
}
|
||||
Spacer()
|
||||
} else { ContentUnavailableView("Select a Server", systemImage: "server.rack") }
|
||||
Divider()
|
||||
HStack {
|
||||
Button("Add Server…", systemImage: "plus") { addingVMs = true }
|
||||
Spacer()
|
||||
Button("Remove Definition", role: .destructive) {
|
||||
pendingRemoval = vm.servers.first { $0.id == selection }
|
||||
}
|
||||
.disabled(selection == nil)
|
||||
}
|
||||
}.padding(20)
|
||||
}.frame(width: 730, height: 420)
|
||||
.confirmationDialog(
|
||||
"Remove this server definition?",
|
||||
isPresented: Binding(
|
||||
get: { pendingRemoval != nil },
|
||||
set: { if !$0 { pendingRemoval = nil } }
|
||||
),
|
||||
titleVisibility: .visible
|
||||
) {
|
||||
Button("Remove Definition", role: .destructive) {
|
||||
if let server = pendingRemoval {
|
||||
vm.removeDefinition(server)
|
||||
selection = nil
|
||||
}
|
||||
pendingRemoval = nil
|
||||
}
|
||||
Button("Cancel", role: .cancel) { pendingRemoval = nil }
|
||||
} message: {
|
||||
Text("This removes the OrionToolbar integration only. The Parallels virtual machine is not deleted.")
|
||||
}
|
||||
.sheet(isPresented: $addingVMs) {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
Text("Add Parallels Virtual Machines").font(.title2.bold())
|
||||
List(vm.discoveredVMs) { machine in
|
||||
HStack {
|
||||
Toggle(machine.name, isOn: Binding(
|
||||
get: { vm.selectedVMIDs.contains(machine.id) },
|
||||
set: { value in
|
||||
if value { vm.selectedVMIDs.insert(machine.id) }
|
||||
else { vm.selectedVMIDs.remove(machine.id) }
|
||||
}
|
||||
))
|
||||
Spacer()
|
||||
if vm.isIntegrated(machine) { Text("Integrated").foregroundStyle(.secondary) }
|
||||
}
|
||||
}
|
||||
HStack {
|
||||
Button("Refresh") { Task { await vm.discoverVMs() } }
|
||||
Spacer()
|
||||
Button("Cancel") { addingVMs = false }
|
||||
Button("Integrate Selected") { vm.integrateSelectedVMs(); addingVMs = false }
|
||||
.disabled(vm.selectedVMIDs.isEmpty)
|
||||
}
|
||||
}.padding(20).frame(width: 530, height: 420)
|
||||
.task { await vm.discoverVMs() }
|
||||
}
|
||||
.sheet(item: $editing) { server in ServerEditor(server: server, isNew: !vm.servers.contains(where: {$0.id == server.id})) { value, isNew in if isNew { vm.add(value) } else { vm.update(value) }; selection = value.id } }
|
||||
}
|
||||
}
|
||||
|
||||
struct ServerEditor: View {
|
||||
@EnvironmentObject private var vm: OrionVMController
|
||||
@Environment(\.dismiss) private var dismiss
|
||||
@State var server: ServerDefinition
|
||||
@State private var iconError: String?
|
||||
let isNew: Bool
|
||||
let save: (ServerDefinition, Bool) -> Void
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 14) {
|
||||
Text(isNew ? "Add Server" : "Edit Server").font(.title2).fontWeight(.semibold)
|
||||
Form {
|
||||
TextField("Display name", text: $server.name)
|
||||
HStack(spacing: 12) {
|
||||
Group {
|
||||
if let path = server.customIconPath, let image = NSImage(contentsOfFile: path) {
|
||||
Image(nsImage: image).resizable().scaledToFit()
|
||||
} else if let image = vm.icon(for: server) {
|
||||
Image(nsImage: image).resizable().scaledToFit()
|
||||
} else {
|
||||
Image(systemName: "server.rack").resizable().scaledToFit()
|
||||
}
|
||||
}
|
||||
.frame(width: 38, height: 38)
|
||||
VStack(alignment: .leading) {
|
||||
Text(server.customIconPath == nil ? "Parallels VM icon (automatic)" : "Custom icon")
|
||||
.font(.caption)
|
||||
HStack {
|
||||
Button("Choose Icon…") { chooseIcon() }
|
||||
Button("Use Parallels Icon") { server.customIconPath = nil }
|
||||
}
|
||||
}
|
||||
}
|
||||
if let iconError { Text(iconError).font(.caption).foregroundStyle(.red) }
|
||||
TextField("Parallels VM name", text: $server.vmName)
|
||||
TextField("IP address / host", text: $server.host)
|
||||
TextField("SSH user", text: $server.sshUser)
|
||||
TextField("SSH port", value: $server.sshPort, format: .number)
|
||||
TextField("SSH identity file (optional)", text: $server.sshIdentityFile, prompt: Text("~/.ssh/id_ed25519"))
|
||||
TextField("Mailpit port (optional)", text: Binding(get: { server.mailpitPort.map(String.init) ?? "" }, set: { server.mailpitPort = Int($0) }))
|
||||
}
|
||||
HStack { Spacer(); Button("Cancel") { dismiss() }; Button("Save") { save(server, isNew); dismiss() }.keyboardShortcut(.defaultAction).disabled(server.name.isEmpty || server.vmName.isEmpty || server.sshPort < 1 || server.sshPort > 65535) }
|
||||
}.padding(20).frame(width: 470)
|
||||
}
|
||||
|
||||
private func chooseIcon() {
|
||||
let panel = NSOpenPanel()
|
||||
panel.allowedContentTypes = [.png, .jpeg, .tiff, .icns, .heic]
|
||||
panel.allowsMultipleSelection = false
|
||||
panel.canChooseDirectories = false
|
||||
guard panel.runModal() == .OK, let source = panel.url else { return }
|
||||
do {
|
||||
let folder = FileManager.default.homeDirectoryForCurrentUser
|
||||
.appendingPathComponent("Library/Application Support/OrionToolbar/Icons", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
|
||||
let destination = folder.appendingPathComponent("\(server.id.uuidString).\(source.pathExtension)")
|
||||
if FileManager.default.fileExists(atPath: destination.path) {
|
||||
try FileManager.default.removeItem(at: destination)
|
||||
}
|
||||
try FileManager.default.copyItem(at: source, to: destination)
|
||||
server.customIconPath = destination.path
|
||||
iconError = nil
|
||||
} catch {
|
||||
iconError = error.localizedDescription
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user