From dfd0d0b5188f78ed73ded7bf7d1cb79f0f2d7b45 Mon Sep 17 00:00:00 2001 From: Guilherme Rambo Date: Mon, 30 Nov 2026 12:37:07 -0300 Subject: [PATCH] Improve support for virtual machines stored outside the library --- .../ExternalVirtualMachineStore.swift | 206 ++++++++++++++ .../Helpers/DirectoryObserver.swift | 21 ++ .../Virtualization/VMLibraryController.swift | 127 ++++++++- .../ExternalVirtualMachineTests.swift | 253 ++++++++++++++++++ .../Library/Components/LibraryItemView.swift | 56 +++- .../VirtualMachineSessionUIManager.swift | 5 +- 6 files changed, 652 insertions(+), 16 deletions(-) create mode 100644 VirtualCore/Source/Virtualization/ExternalVirtualMachineStore.swift create mode 100644 VirtualCoreTests/ExternalVirtualMachineTests.swift diff --git a/VirtualCore/Source/Virtualization/ExternalVirtualMachineStore.swift b/VirtualCore/Source/Virtualization/ExternalVirtualMachineStore.swift new file mode 100644 index 0000000..2774311 --- /dev/null +++ b/VirtualCore/Source/Virtualization/ExternalVirtualMachineStore.swift @@ -0,0 +1,206 @@ +import Foundation +import OSLog +import BuddyFoundation + +/// Remembers virtual machines that are shown in the library but stored outside the library directory, +/// such as those opened from an external volume. +final class ExternalVirtualMachineStore { + + /// Points to a virtual machine bundle stored outside the library directory. + struct Reference: Codable, Hashable { + /// Where the bundle was last seen. Used when the bookmark can't be resolved. + var path: String + /// Where the volume containing the bundle was mounted when the bundle was last seen. + /// Tells a bundle that's on a volume that isn't mounted apart from one that no longer exists. + var volumePath: String? + /// Follows the bundle when it's renamed or moved. + var bookmark: Data? + + init(bundleURL: URL) { + self.path = ExternalVirtualMachineStore.canonicalPath(for: bundleURL) + self.volumePath = (try? bundleURL.resourceValues(forKeys: [.volumeURLKey]))?.volume?.path + self.bookmark = try? bundleURL.bookmarkData() + } + } + + static let defaultsKey: String = { + #if DEBUG + ProcessInfo.isSwiftUIPreview ? "externalVirtualMachines-preview" : "externalVirtualMachines" + #else + "externalVirtualMachines" + #endif + }() + + private let logger = Logger(for: ExternalVirtualMachineStore.self) + + private let defaults: UserDefaults + + private(set) var references: [Reference] { + didSet { + guard references != oldValue else { return } + write() + } + } + + init(defaults: UserDefaults) { + self.defaults = defaults + self.references = Self.read(from: defaults) + } + + /// `true` if the bundle is stored directly inside the library directory, which is where the library looks for virtual machines. + static func isBundle(at bundleURL: URL, inLibraryAt libraryURL: URL) -> Bool { + bundleURL.standardizedFileURL.deletingLastPathComponent().path == libraryURL.standardizedFileURL.path + } + + /// The path used to tell bundles apart, which is the same no matter which symbolic links were followed to reach the bundle. + static func canonicalPath(for bundleURL: URL) -> String { + bundleURL.standardizedFileURL.resolvingSymlinksInPath().path + } + + func contains(_ bundleURL: URL) -> Bool { + let path = Self.canonicalPath(for: bundleURL) + + return references.contains { $0.path == path } + } + + func add(_ bundleURL: URL) { + let reference = Reference(bundleURL: bundleURL) + + if let index = references.firstIndex(where: { $0.path == reference.path }) { + references[index] = reference + } else { + references.append(reference) + } + } + + func remove(_ bundleURL: URL) { + let path = Self.canonicalPath(for: bundleURL) + + references.removeAll { $0.path == path } + } + + /// Whether any of the virtual machines were last seen in the volume mounted at the specified location. + func hasReferences(inVolumeAt volumeURL: URL) -> Bool { + let volumePath = volumeURL.standardizedFileURL.path + let prefix = volumePath.hasSuffix("/") ? volumePath : volumePath + "/" + + return references.contains { $0.volumePath == volumePath || $0.path.hasPrefix(prefix) } + } + + /// Locations of the bundles that can currently be reached. + /// + /// Bundles that were renamed or moved are followed to their new location. + /// Those that are now in the library directory or in the trash, or that no longer exist, are forgotten. + /// Those in a volume that isn't mounted are left out, but remembered so that they come back once it's mounted. + func resolveAvailableBundleURLs(excludingContentsOf libraryURL: URL) -> [URL] { + let libraryURL = libraryURL.resolvingSymlinksInPath() + var resolvedReferences = [Reference]() + var availableURLs = [URL]() + + for reference in references { + guard let bundleURL = locateBundle(for: reference) else { + if isVolumeMounted(for: reference) { + logger.notice("Forgetting external virtual machine that no longer exists at \(reference.path.quoted)") + } else { + resolvedReferences.append(reference) + } + continue + } + + guard !Self.isBundle(at: bundleURL, inLibraryAt: libraryURL) else { + logger.notice("Forgetting external virtual machine that's now in the library directory: \(bundleURL.lastPathComponent.quoted)") + continue + } + + guard !bundleURL.isInTrash else { + logger.notice("Forgetting external virtual machine that's now in the trash: \(bundleURL.lastPathComponent.quoted)") + continue + } + + /// A bundle can be referenced twice if it's moved to where another one that no longer exists used to be. + guard !availableURLs.contains(where: { $0.path == bundleURL.path }) else { continue } + + /// The bookmark is only created again when the bundle has moved, since a bookmark that was just resolved is still good. + let isCurrent = reference.path == bundleURL.path && reference.bookmark != nil + + resolvedReferences.append(isCurrent ? reference : Reference(bundleURL: bundleURL)) + availableURLs.append(bundleURL) + } + + references = resolvedReferences + + return availableURLs + } + +} + +// MARK: - Resolution + +private extension ExternalVirtualMachineStore { + /// The current location of the bundle, or `nil` if it can't be reached. + func locateBundle(for reference: Reference) -> URL? { + if let bookmark = reference.bookmark { + var isStale = false + + /// Resolving must never prompt the user or attempt to mount a volume, as it happens whenever the library is loaded. + if let url = try? URL(resolvingBookmarkData: bookmark, options: [.withoutUI, .withoutMounting], bookmarkDataIsStale: &isStale), + url.isReadableDirectory + { + return URL(fileURLWithPath: Self.canonicalPath(for: url), isDirectory: true) + } + } + + let lastKnownURL = URL(fileURLWithPath: reference.path, isDirectory: true) + + return lastKnownURL.isReadableDirectory ? lastKnownURL : nil + } + + /// `false` when it can't be determined, so that a virtual machine is never forgotten just because its volume is not mounted. + func isVolumeMounted(for reference: Reference) -> Bool { + guard let volumePath = reference.volumePath else { return false } + + let volumeURL = URL(fileURLWithPath: volumePath, isDirectory: true) + + /// An empty directory can be left behind where a volume used to be mounted, so check that a volume is really mounted there. + guard let mountedVolumeURL = (try? volumeURL.resourceValues(forKeys: [.volumeURLKey]))?.volume else { return false } + + return mountedVolumeURL.standardizedFileURL.path == volumeURL.standardizedFileURL.path + } +} + +private extension URL { + var isInTrash: Bool { + var relationship = FileManager.URLRelationship.other + + do { + try FileManager.default.getRelationship(&relationship, of: .trashDirectory, in: [], toItemAt: self) + } catch { + return false + } + + return relationship == .contains + } +} + +// MARK: - Persistence + +private extension ExternalVirtualMachineStore { + static func read(from defaults: UserDefaults) -> [Reference] { + guard let data = defaults.data(forKey: defaultsKey) else { return [] } + + do { + return try PropertyListDecoder().decode([Reference].self, from: data) + } catch { + Logger(for: ExternalVirtualMachineStore.self).error("Failed to read external virtual machines: \(error, privacy: .public)") + return [] + } + } + + func write() { + do { + defaults.set(try PropertyListEncoder().encode(references), forKey: Self.defaultsKey) + } catch { + logger.error("Failed to save external virtual machines: \(error, privacy: .public)") + } + } +} diff --git a/VirtualCore/Source/Virtualization/Helpers/DirectoryObserver.swift b/VirtualCore/Source/Virtualization/Helpers/DirectoryObserver.swift index 52c2b2e..0d02e5b 100644 --- a/VirtualCore/Source/Virtualization/Helpers/DirectoryObserver.swift +++ b/VirtualCore/Source/Virtualization/Helpers/DirectoryObserver.swift @@ -24,6 +24,27 @@ final class DirectoryObserver: NSObject, NSFilePresenter { NSFileCoordinator.addFilePresenter(self) } + /// Stops observing. Must be called before discarding an observer. + func invalidate() { + NSFileCoordinator.removeFilePresenter(self) + } + + func presentedItemDidMove(to newURL: URL) { + logger.debug("Presented item moved: \(newURL.path)") + + presentedItemURL = newURL + + sendSignalIfNeeded(for: newURL) + } + + func accommodatePresentedItemDeletion() async throws { + guard let presentedItemURL else { return } + + logger.debug("Presented item deleted: \(presentedItemURL.path)") + + sendSignalIfNeeded(for: presentedItemURL) + } + private func sendSignalIfNeeded(for url: URL) { guard fileExtensions.contains(url.pathExtension) else { return } diff --git a/VirtualCore/Source/Virtualization/VMLibraryController.swift b/VirtualCore/Source/Virtualization/VMLibraryController.swift index d3effbf..7ded264 100644 --- a/VirtualCore/Source/Virtualization/VMLibraryController.swift +++ b/VirtualCore/Source/Virtualization/VMLibraryController.swift @@ -82,6 +82,12 @@ public final class VMLibraryController: ObservableObject { private let filePresenter: DirectoryObserver private let updateSignal = PassthroughSubject() + /// Virtual machines that are shown in the library but stored outside the library directory. + private let externalMachines: ExternalVirtualMachineStore + + /// Observes changes to the bundles of virtual machines stored outside the library directory, by bundle path. + private var externalBundleObservers = [String: DirectoryObserver]() + private static let observedFileExtensions: Set = [ VBVirtualMachine.bundleExtension, "plist", @@ -94,6 +100,7 @@ public final class VMLibraryController: ObservableObject { self.settingsContainer = settingsContainer self.settings = settingsContainer.settings self.libraryURL = settingsContainer.settings.libraryURL + self.externalMachines = ExternalVirtualMachineStore(defaults: settingsContainer.defaults) self.filePresenter = DirectoryObserver( presentedItemURL: settingsContainer.settings.libraryURL, fileExtensions: Self.observedFileExtensions, @@ -212,9 +219,7 @@ public final class VMLibraryController: ObservableObject { var machines = [VBVirtualMachine]() - while let url = enumerator.nextObject() as? URL { - guard url.pathExtension == VBVirtualMachine.bundleExtension else { continue } - + func loadMachine(at url: URL) { do { let machine = try VBVirtualMachine(bundleURL: url, createIfNeeded: false) @@ -231,6 +236,18 @@ public final class VMLibraryController: ObservableObject { } } + while let url = enumerator.nextObject() as? URL { + guard url.pathExtension == VBVirtualMachine.bundleExtension else { continue } + + loadMachine(at: url) + } + + let externalBundleURLs = externalMachines.resolveAvailableBundleURLs(excludingContentsOf: libraryURL) + + externalBundleURLs.forEach(loadMachine(at:)) + + observeExternalBundles(at: externalBundleURLs) + let sortedMachines = machines.sorted(by: { $0.bundleURL.creationDate > $1.bundleURL.creationDate }) self.state = sortedMachines.isEmpty ? .empty : .loaded(sortedMachines) @@ -505,6 +522,12 @@ public extension VMLibraryController { duplicate = try await copy() } + /// The copy of a virtual machine stored outside the library directory is created next to it, + /// so it needs to be added in order to show up in the library. + if isExternal(vm) { + externalMachines.add(copyURL) + } + reload() recentlyDuplicatedMachineIdentifier = duplicate.id @@ -519,6 +542,8 @@ public extension VMLibraryController { try await NSWorkspace.shared.recycle([vm.bundleURL]) + externalMachines.remove(vm.bundleURL) + reload() } @@ -531,6 +556,11 @@ public extension VMLibraryController { try fileManager.moveItem(at: vm.bundleURL, to: newURL) + if isExternal(vm) { + externalMachines.remove(vm.bundleURL) + externalMachines.add(newURL) + } + reload(animated: false) } @@ -557,6 +587,74 @@ public extension VMLibraryController { extension NSWorkspace: @retroactive @unchecked Sendable { } +// MARK: - External Virtual Machines + +public extension VMLibraryController { + /// Whether the virtual machine is shown in the library but stored outside the library directory. + func isExternal(_ vm: VBVirtualMachine) -> Bool { + !ExternalVirtualMachineStore.isBundle(at: vm.bundleURL, inLibraryAt: libraryURL) + } + + /// Makes a virtual machine that's stored outside the library directory show up in the library, without moving or copying it. + /// Does nothing if the virtual machine is stored in the library directory. + /// + /// - Returns: The virtual machine as loaded by the library, or `nil` if it's not available in the library. + @discardableResult + func addExternalVirtualMachine(at bundleURL: URL) -> VBVirtualMachine? { + let path = ExternalVirtualMachineStore.canonicalPath(for: bundleURL) + + if !ExternalVirtualMachineStore.isBundle(at: bundleURL, inLibraryAt: libraryURL), !externalMachines.contains(bundleURL) { + logger.notice("Adding external virtual machine at \(path.quoted)") + + externalMachines.add(bundleURL) + + reload() + } + + return virtualMachines.first { ExternalVirtualMachineStore.canonicalPath(for: $0.bundleURL) == path } + } + + /// Stops showing a virtual machine that's stored outside the library directory, leaving its files untouched. + func removeExternalVirtualMachine(_ vm: VBVirtualMachine) throws { + guard isExternal(vm) else { + throw Failure("\"\(vm.name)\" is stored in the library directory. Move it to the trash to remove it from the library.") + } + guard !isExecuting(vm) else { + throw Failure("\"\(vm.name)\" is in use. Use Save & Close or shut it down before removing it from the library.") + } + guard !isBeingDuplicated(vm) else { + throw Failure("\"\(vm.name)\" is being duplicated. Wait for that to finish before removing it from the library.") + } + + logger.notice("Removing external virtual machine at \(vm.bundleURL.path.quoted)") + + externalMachines.remove(vm.bundleURL) + + reload() + } +} + +private extension VMLibraryController { + /// Starts observing the specified bundles for changes and stops observing all others. + func observeExternalBundles(at bundleURLs: [URL]) { + let paths = Set(bundleURLs.map(\.path)) + + for (path, observer) in externalBundleObservers where !paths.contains(path) { + observer.invalidate() + externalBundleObservers[path] = nil + } + + for bundleURL in bundleURLs where externalBundleObservers[bundleURL.path] == nil { + externalBundleObservers[bundleURL.path] = DirectoryObserver( + presentedItemURL: bundleURL, + fileExtensions: Self.observedFileExtensions, + label: "External", + signal: updateSignal + ) + } + } +} + // MARK: - Booted VM Tracking public extension VMLibraryController { @@ -659,8 +757,8 @@ extension URL { private extension VMLibraryController { func observeRemovableVolumeNotifications() { - /// Only observe when library lives in a removable volume. - guard isLibraryInRemovableVolume else { return } + /// Only observe when the library or a virtual machine stored outside of it could be in a volume that comes and goes. + guard isLibraryInRemovableVolume || !externalMachines.references.isEmpty else { return } guard volumeNotificationsTask == nil || volumeNotificationsTask?.isCancelled == true else { return } @@ -695,19 +793,20 @@ private extension VMLibraryController { func handleVolumeNotification(_ notification: Notification) { let isMount = notification.name == NSWorkspace.didMountNotification - if isMount { - /// Don't care about mount notifications unless we're currently waiting for the volume to mount. - guard state.isVolumeNotMounted else { return } - } - guard let volumeURL = notification.userInfo?[NSWorkspace.volumeURLUserInfoKey] as? URL else { return } - /// Cheap way to check if mounted volume is our library volume. - guard libraryURL.path.hasPrefix(volumeURL.path) else { return } + /// Cheap way to check if the volume is our library volume. + /// Don't care about it being mounted unless we're currently waiting for the volume to mount. + let affectsLibrary = libraryURL.path.hasPrefix(volumeURL.path) && (!isMount || state.isVolumeNotMounted) - logger.notice("Library volume mounted: \(volumeURL.path.quoted)") + /// Virtual machines stored outside the library directory come and go with their volumes. + let affectsExternalMachines = externalMachines.hasReferences(inVolumeAt: volumeURL) - /// Try to load machines again now that library is mounted. + guard affectsLibrary || affectsExternalMachines else { return } + + logger.notice("Volume \(isMount ? "mounted" : "unmounted", privacy: .public): \(volumeURL.path.quoted)") + + /// Load machines again now that what's available has changed. loadMachines() } } diff --git a/VirtualCoreTests/ExternalVirtualMachineTests.swift b/VirtualCoreTests/ExternalVirtualMachineTests.swift new file mode 100644 index 0000000..1525851 --- /dev/null +++ b/VirtualCoreTests/ExternalVirtualMachineTests.swift @@ -0,0 +1,253 @@ +import Foundation +import Testing +@testable import VirtualCore + +@MainActor +struct ExternalVirtualMachineTests { + + // MARK: - Store + + @Test func rememberedBundleIsAvailableAcrossLaunches() throws { + let fixture = try Fixture() + defer { fixture.cleanUp() } + let bundleURL = try fixture.makeExternalBundle(named: "External") + + fixture.makeStore().add(bundleURL) + + #expect(fixture.availablePaths(in: fixture.makeStore()) == [fixture.canonicalPath(bundleURL)]) + } + + @Test func addingTheSameBundleTwiceKeepsOneReference() throws { + let fixture = try Fixture() + defer { fixture.cleanUp() } + let bundleURL = try fixture.makeExternalBundle(named: "External") + let store = fixture.makeStore() + + store.add(bundleURL) + store.add(bundleURL) + + #expect(store.references.count == 1) + #expect(store.contains(bundleURL)) + } + + @Test func followsBundleThatWasRenamed() throws { + let fixture = try Fixture() + defer { fixture.cleanUp() } + let bundleURL = try fixture.makeExternalBundle(named: "External") + let store = fixture.makeStore() + store.add(bundleURL) + + let renamedURL = fixture.externalURL.appendingPathComponent("Renamed.vbvm") + try FileManager.default.moveItem(at: bundleURL, to: renamedURL) + + #expect(fixture.availablePaths(in: store) == [fixture.canonicalPath(renamedURL)]) + #expect(store.contains(renamedURL)) + #expect(!store.contains(bundleURL)) + } + + @Test func forgetsBundleThatNoLongerExists() throws { + let fixture = try Fixture() + defer { fixture.cleanUp() } + let bundleURL = try fixture.makeExternalBundle(named: "External") + let store = fixture.makeStore() + store.add(bundleURL) + + try FileManager.default.removeItem(at: bundleURL) + + #expect(fixture.availablePaths(in: store).isEmpty) + #expect(store.references.isEmpty) + } + + @Test func forgetsBundleThatWasMovedIntoTheLibrary() throws { + let fixture = try Fixture() + defer { fixture.cleanUp() } + let bundleURL = try fixture.makeExternalBundle(named: "External") + let store = fixture.makeStore() + store.add(bundleURL) + + try FileManager.default.moveItem(at: bundleURL, to: fixture.libraryURL.appendingPathComponent("External.vbvm")) + + #expect(fixture.availablePaths(in: store).isEmpty) + #expect(store.references.isEmpty) + } + + @Test func remembersBundleWhileItsVolumeIsNotMounted() throws { + let fixture = try Fixture() + defer { fixture.cleanUp() } + + let volumePath = "/Volumes/\(UUID().uuidString)" + let reference = try PropertyListDecoder().decode( + ExternalVirtualMachineStore.Reference.self, + from: PropertyListEncoder().encode(["path": "\(volumePath)/External.vbvm", "volumePath": volumePath]) + ) + fixture.defaults.set(try PropertyListEncoder().encode([reference]), forKey: ExternalVirtualMachineStore.defaultsKey) + + let store = fixture.makeStore() + + #expect(fixture.availablePaths(in: store).isEmpty) + #expect(store.references == [reference]) + #expect(store.hasReferences(inVolumeAt: URL(fileURLWithPath: volumePath))) + #expect(!store.hasReferences(inVolumeAt: URL(fileURLWithPath: "/Volumes/\(UUID().uuidString)"))) + } + + @Test func removedBundleIsNoLongerAvailable() throws { + let fixture = try Fixture() + defer { fixture.cleanUp() } + let bundleURL = try fixture.makeExternalBundle(named: "External") + let store = fixture.makeStore() + store.add(bundleURL) + + store.remove(bundleURL) + + #expect(fixture.availablePaths(in: fixture.makeStore()).isEmpty) + #expect(FileManager.default.fileExists(atPath: bundleURL.path)) + } + + // MARK: - Library + + @Test func externalVirtualMachineShowsUpInTheLibraryWithoutBeingCopied() throws { + let fixture = try Fixture() + defer { fixture.cleanUp() } + let libraryBundleURL = try fixture.makeBundle(at: fixture.libraryURL.appendingPathComponent("Internal.vbvm")) + let externalBundleURL = try fixture.makeExternalBundle(named: "External") + let library = fixture.makeLibrary() + + #expect(library.virtualMachines.map(\.name) == ["Internal"]) + + let added = try #require(library.addExternalVirtualMachine(at: externalBundleURL)) + + #expect(Set(library.virtualMachines.map(\.name)) == ["Internal", "External"]) + #expect(library.isExternal(added)) + #expect(fixture.canonicalPath(added.bundleURL) == fixture.canonicalPath(externalBundleURL)) + #expect(try FileManager.default.contentsOfDirectory(atPath: fixture.libraryURL.path) == [libraryBundleURL.lastPathComponent]) + + /// A library created later, like on the next launch, shows it as well. + #expect(Set(fixture.makeLibrary().virtualMachines.map(\.name)) == ["Internal", "External"]) + } + + @Test func externalVirtualMachineMakesAnEmptyLibraryLoaded() throws { + let fixture = try Fixture() + defer { fixture.cleanUp() } + let externalBundleURL = try fixture.makeExternalBundle(named: "External") + let library = fixture.makeLibrary() + + #expect(library.state.id == .empty) + + library.addExternalVirtualMachine(at: externalBundleURL) + + #expect(library.state.id == .loaded) + } + + @Test func virtualMachineInTheLibraryDirectoryIsNotExternal() throws { + let fixture = try Fixture() + defer { fixture.cleanUp() } + let bundleURL = try fixture.makeBundle(at: fixture.libraryURL.appendingPathComponent("Internal.vbvm")) + let library = fixture.makeLibrary() + + let vm = try #require(library.addExternalVirtualMachine(at: bundleURL)) + + #expect(!library.isExternal(vm)) + #expect(library.virtualMachines.count == 1) + #expect(fixture.makeStore().references.isEmpty) + #expect(throws: (any Error).self) { try library.removeExternalVirtualMachine(vm) } + } + + @Test func removingExternalVirtualMachineLeavesItsFilesUntouched() throws { + let fixture = try Fixture() + defer { fixture.cleanUp() } + let externalBundleURL = try fixture.makeExternalBundle(named: "External") + let library = fixture.makeLibrary() + let vm = try #require(library.addExternalVirtualMachine(at: externalBundleURL)) + + try library.removeExternalVirtualMachine(vm) + + #expect(library.virtualMachines.isEmpty) + #expect(FileManager.default.fileExists(atPath: externalBundleURL.path)) + #expect(fixture.makeLibrary().virtualMachines.isEmpty) + } + + @Test func renamedExternalVirtualMachineStaysInTheLibrary() throws { + let fixture = try Fixture() + defer { fixture.cleanUp() } + let externalBundleURL = try fixture.makeExternalBundle(named: "External") + let library = fixture.makeLibrary() + let vm = try #require(library.addExternalVirtualMachine(at: externalBundleURL)) + + try library.rename(vm, to: "Renamed") + + #expect(library.virtualMachines.map(\.name) == ["Renamed"]) + #expect(FileManager.default.fileExists(atPath: fixture.externalURL.appendingPathComponent("Renamed.vbvm").path)) + #expect(fixture.makeLibrary().virtualMachines.map(\.name) == ["Renamed"]) + } + + @Test func duplicateOfExternalVirtualMachineShowsUpNextToIt() async throws { + let fixture = try Fixture() + defer { fixture.cleanUp() } + let externalBundleURL = try fixture.makeExternalBundle(named: "External") + let library = fixture.makeLibrary() + let vm = try #require(library.addExternalVirtualMachine(at: externalBundleURL)) + + let copy = try await library.duplicate(vm) + + #expect(fixture.canonicalPath(copy.bundleURL.deletingLastPathComponent()) == fixture.canonicalPath(fixture.externalURL)) + #expect(Set(library.virtualMachines.map(\.name)) == ["External", "Copy of External"]) + #expect(try FileManager.default.contentsOfDirectory(atPath: fixture.libraryURL.path).isEmpty) + } + +} + +/// A library directory and a directory outside of it, with their own settings. +@MainActor +private struct Fixture { + let rootURL: URL + let libraryURL: URL + let externalURL: URL + let suiteName: String + let defaults: UserDefaults + + init() throws { + rootURL = FileManager.default.temporaryDirectory.appendingPathComponent("ExternalVirtualMachineTests-\(UUID().uuidString)", isDirectory: true) + libraryURL = rootURL.appendingPathComponent("Library", isDirectory: true) + externalURL = rootURL.appendingPathComponent("External", isDirectory: true) + suiteName = "ExternalVirtualMachineTests.\(UUID().uuidString)" + defaults = try #require(UserDefaults(suiteName: suiteName)) + + try FileManager.default.createDirectory(at: libraryURL, withIntermediateDirectories: true) + try FileManager.default.createDirectory(at: externalURL, withIntermediateDirectories: true) + } + + func cleanUp() { + defaults.removePersistentDomain(forName: suiteName) + try? FileManager.default.removeItem(at: rootURL) + } + + @discardableResult + func makeBundle(at url: URL) throws -> URL { + var vm = try VBVirtualMachine(bundleURL: url, isNewInstall: true) + /// The library only loads bundles that have their metadata on disk. + try vm.saveMetadata() + return vm.bundleURL + } + + func makeExternalBundle(named name: String) throws -> URL { + try makeBundle(at: externalURL.appendingPathComponent(name).appendingPathExtension(VBVirtualMachine.bundleExtension)) + } + + func makeStore() -> ExternalVirtualMachineStore { + ExternalVirtualMachineStore(defaults: defaults) + } + + func makeLibrary() -> VMLibraryController { + let container = VBSettingsContainer(with: defaults) + container.settings.libraryURL = libraryURL + return VMLibraryController(settingsContainer: container) + } + + func canonicalPath(_ url: URL) -> String { + ExternalVirtualMachineStore.canonicalPath(for: url) + } + + func availablePaths(in store: ExternalVirtualMachineStore) -> [String] { + store.resolveAvailableBundleURLs(excludingContentsOf: libraryURL).map(canonicalPath) + } +} diff --git a/VirtualUI/Source/Library/Components/LibraryItemView.swift b/VirtualUI/Source/Library/Components/LibraryItemView.swift index 7482476..2328dc3 100644 --- a/VirtualUI/Source/Library/Components/LibraryItemView.swift +++ b/VirtualUI/Source/Library/Components/LibraryItemView.swift @@ -102,12 +102,20 @@ struct LibraryItemView: View { private var isHighlighted: Bool { library.recentlyDuplicatedMachineIdentifier == vm.id } + /// Whether the virtual machine is stored outside the library directory. + private var isExternal: Bool { library.isExternal(vm) } + var body: some View { VStack(spacing: 12) { ArtworkView(virtualMachine: vm) .overlay(alignment: .bottom) { LibraryThumbnailBadges(systemInformation: vm.guestSystemInformation, savedSession: vm.savedSession) } + .overlay(alignment: .topTrailing) { + if isExternal { + ExternalLocationLibraryBadge(bundleURL: vm.bundleURL) + } + } .overlay { if isDuplicating { ZStack { @@ -226,6 +234,16 @@ struct LibraryItemView: View { Divider() + if isExternal { + Button { + library.performRemoveFromLibrary(for: vm) + } label: { + Text("Remove from Library") + } + .disabled(library.isExecuting(vm) || isDuplicating) + .help("Stop showing this virtual machine in the library, leaving its files where they are.") + } + Button { library.performMoveToTrash(for: vm) } label: { @@ -304,6 +322,8 @@ extension View { } private struct LibraryThumbnailBadges: View { + static var margin: Double { 3 } + let systemInformation: VBGuestSystemInformation? let savedSession: VBSavedSessionDescriptor? @@ -320,7 +340,7 @@ private struct LibraryThumbnailBadges: View { } } .lineLimit(1) - .padding(3) + .padding(Self.margin) .foregroundStyle(.secondary) } } @@ -352,6 +372,32 @@ private struct GuestSystemInfoLibraryBadge: View { } } +/// Marks a virtual machine that's shown in the library but stored outside the library directory. +private struct ExternalLocationLibraryBadge: View { + let bundleURL: URL + + private var location: String { + (bundleURL.deletingLastPathComponent().path as NSString).abbreviatingWithTildeInPath + } + + var body: some View { + Image(systemName: "externaldrive") + .symbolVariant(.fill) + .font(.headline.weight(.medium)) + .padding(.horizontal, 4) + .padding(.vertical, 4) + .contentShape(.rect) + .padding(LibraryThumbnailBadges.margin) + .foregroundStyle(.secondary) + .accessibilityLabel(helpText) + .help(helpText) + } + + private var helpText: Text { + Text("Stored outside the library, in \(location)", bundle: #bundle) + } +} + /// Marks a saved virtual machine in the library. private struct SavedSessionLibraryBadge: View { let descriptor: VBSavedSessionDescriptor @@ -446,6 +492,14 @@ extension VMLibraryController { } } } + + func performRemoveFromLibrary(for vm: VBVirtualMachine) { + do { + try removeExternalVirtualMachine(vm) + } catch { + NSAlert(error: error).runModal() + } + } } #if DEBUG diff --git a/VirtualUI/Source/Session/VirtualMachineSessionUIManager.swift b/VirtualUI/Source/Session/VirtualMachineSessionUIManager.swift index 17f5954..2c46bc1 100644 --- a/VirtualUI/Source/Session/VirtualMachineSessionUIManager.swift +++ b/VirtualUI/Source/Session/VirtualMachineSessionUIManager.swift @@ -248,7 +248,10 @@ private extension VirtualMachineSessionUIManager { do { let vm = try VBVirtualMachine(bundleURL: url) - launch(vm, library: library, options: options) + /// A virtual machine opened from outside the library directory shows up in the library from then on. + let libraryVM = library.addExternalVirtualMachine(at: vm.bundleURL) + + launch(libraryVM ?? vm, library: library, options: options) } catch { let alert = NSAlert(error: error) alert.runModal()