Files
VirtualBuddy/VirtualUI/Source/Library/LibraryView.swift
Guilherme Rambo 2a7cf4151b New virtual machine state preservation system (#780)
* Fix HostingWindowController allowing repeated requests to close while waiting for confirmation

* New virtual machine state preservation system with automatic save on close/quit and safe restoration

* Use visible directories for saved state storage for easier debugging in Finder

* Hide state restoration controls for unsupported Linux VMs

* Add app-level preference for what happens by default when attempting to close a running VM

* Use a custom sheet for VM close confirmation

* Improve VM close choice sheet

* Harden session storage against path traversal, fix race conditions in state coordination
2026-10-05 12:51:43 -03:00

230 lines
7.8 KiB
Swift

//
// LibraryView.swift
// VirtualBuddy
//
// Created by Guilherme Rambo on 10/04/22.
//
import SwiftUI
import VirtualCore
public extension String {
static let vb_libraryWindowID = "library"
}
private extension UserDefaults {
/// Not using `AppStorage` because this can't update the view.
var hasSeenFirstLaunchExperience: Bool {
get { bool(forKey: #function) }
set {
set(newValue, forKey: #function)
synchronize()
}
}
}
public struct LibraryView: View {
@ObservedObject private var settingsContainer = VBSettingsContainer.current
@EnvironmentObject private var library: VMLibraryController
@EnvironmentObject private var sessionManager: VirtualMachineSessionUIManager
@Environment(\.openCocoaWindow)
private var openCocoaWindow
@Environment(\.openVirtualBuddySettings)
private var openSettings
/// Whether the first launch experience has been presented in the current app session.
/// The defaults flag itself is not read again, but this is set whenever a non-empty library state is shown.
@State private var canShowFirstLaunchExperience = true
private var shouldShowFirstLaunchExperienceOnEmptyLibrary: Bool {
guard #available(macOS 15.0, *) else { return false }
return canShowFirstLaunchExperience && (!hasSeenFirstLaunchExperience || UserDefaults.standard.bool(forKey: "VBForceFirstLaunchExperience"))
}
/// Set on view initialization only so that when the defaults flag is updated, it doesn't cause the first launch experience to disappear.
private let hasSeenFirstLaunchExperience: Bool
public init() {
hasSeenFirstLaunchExperience = UserDefaults.standard.hasSeenFirstLaunchExperience
}
public var body: some View {
libraryContents
.frame(minWidth: 900, maxWidth: .infinity, minHeight: 600, maxHeight: .infinity)
.toolbar(content: { toolbarContents })
.task {
#if DEBUG
if UserDefaults.standard.bool(forKey: "VBOpenSettings") {
openSettings()
}
#endif
}
}
@ToolbarContentBuilder
private var toolbarContents: some ToolbarContent {
ToolbarItemGroup(placement: .primaryAction) {
Button {
openCocoaWindow {
VMInstallationWizard(library: library)
}
} label: {
Image(systemName: "plus")
}
.help("New virtual machine")
}
}
private var gridSpacing: CGFloat { 16 }
private var gridItemMinSize: CGFloat { 240 }
private var gridColumns: [GridItem] {
[.init(.adaptive(minimum: gridItemMinSize), spacing: gridSpacing)]
}
@ViewBuilder
private var libraryContents: some View {
ZStack {
BlurHashFullBleedBackground(content: .blurHash(.virtualBuddyBackground))
.ignoresSafeArea()
.frame(maxWidth: .infinity, maxHeight: .infinity)
.fullBleedBackgroundDimmed(![.loaded, .loading].contains(library.state.id))
Group {
switch library.state {
case .loaded(let machines):
grid(machines)
.task { canShowFirstLaunchExperience = false }
case .empty:
if shouldShowFirstLaunchExperienceOnEmptyLibrary {
FirstLaunchExperienceView {
sessionManager.launchInstallWizard(library: library)
}
.task { UserDefaults.standard.hasSeenFirstLaunchExperience = true }
} else {
libraryEmptyMessage
}
case .loading:
EmptyView()
case .volumeNotMounted:
libraryVolumeNotMountedMessage
case .directoryMissing:
libraryDirectoryMissingMessage
}
}
.transition(.scale(scale: 1.5).combined(with: .opacity))
}
.animation(.snappy, value: library.state.id)
}
@ViewBuilder
private func grid(_ machines: [VBVirtualMachine]) -> some View {
ScrollViewReader { proxy in
ScrollView(.vertical) {
LazyVGrid(columns: gridColumns, spacing: gridSpacing) {
ForEach(machines) { vm in
Button {
sessionManager.launch(vm, library: library, options: nil)
} label: {
LibraryItemView(vm: vm, name: vm.name)
}
.buttonStyle(.vbLibraryItem)
.environmentObject(library)
.transition(.scale(scale: 0.3).combined(with: .opacity))
.id(vm.id)
}
}
.padding()
.padding(.top)
}
/// Brings a virtual machine that was just duplicated into view.
.onChange(of: library.recentlyDuplicatedMachineIdentifier) { _, identifier in
guard let identifier else { return }
withAnimation { proxy.scrollTo(identifier, anchor: .center) }
}
}
.environment(\.virtualBuddyShowDesktopPictureThumbnails, settingsContainer.settings.showDesktopPictureThumbnails)
}
@ViewBuilder
private var libraryVolumeNotMountedMessage: some View {
BackportedContentUnavailableView(
"Library Not Mounted",
systemImage: "externaldrive.badge.questionmark",
description: Text("""
The volume containing your VirtualBuddy library is not currently mounted.
Once mounted, your virtual machines will appear here.
""")
) {
Button("Try Again") {
library.loadMachines()
}
.keyboardShortcut(.defaultAction)
Button("Open Settings") {
openSettings()
}
}
}
@ViewBuilder
private var libraryDirectoryMissingMessage: some View {
BackportedContentUnavailableView(
"Library Missing",
systemImage: "questionmark.folder",
description: Text("""
VirtualBuddy is unable to locate your library directory.
Review your settings to ensure the directory is set correctly. If it exists, there may be a permission problem.
If you’ve deleted the library directory, you can start a new empty library.
""")
) {
Button("Open Settings") {
openSettings()
}
.keyboardShortcut(.defaultAction)
Button("Create Empty Library") {
library.loadMachines(createLibrary: true)
}
}
}
@ViewBuilder
private var libraryEmptyMessage: some View {
BackportedContentUnavailableView(
"No Virtual Machines",
systemImage: "square.grid.2x2",
description: Text("""
You haven’t created any virtual machines yet. You can create a new one, or select a different library directory in settings.
""")
) {
Button("Create Virtual Machine") {
sessionManager.launchInstallWizard(library: library)
}
.keyboardShortcut(.defaultAction)
Button("Open Settings") {
openSettings()
}
}
}
}
fileprivate extension URL {
var collapsedHomePath: String {
path.replacingOccurrences(of: NSHomeDirectory(), with: "~")
}
}
#if DEBUG
#Preview {
LibraryView()
.environmentObject(VMLibraryController.preview)
.environmentObject(VirtualMachineSessionUIManager.shared)
}
#endif