// // VMLibraryController.swift // VirtualCore // // Created by Guilherme Rambo on 10/04/22. // import SwiftUI import Combine import OSLog import BuddyFoundation @MainActor public final class VMLibraryController: ObservableObject { private let logger = Logger(for: VMLibraryController.self) public enum State: Identifiable { public enum ID: Int { case loading case loaded case empty case volumeNotMounted case directoryMissing } public var id: ID { switch self { case .loading: .loading case .loaded: .loaded case .empty: .empty case .volumeNotMounted: .volumeNotMounted case .directoryMissing: .directoryMissing } } case loading case loaded([VBVirtualMachine]) case empty case volumeNotMounted case directoryMissing var isVolumeNotMounted: Bool { id == .volumeNotMounted } } /// ``reload(animated:)`` exits early if this lock is not available, preventing the library from being loaded twice at the same time. private let transactionLock = NSLock() @Published public private(set) var state = State.loading { didSet { if case .loaded(let machines) = state { self.virtualMachines = machines } else { self.virtualMachines = [] } let conflictingIdentifiers = Self.conflictingIdentifiers(in: virtualMachines) if conflictingIdentifiers != conflictingMachineIdentifiers { conflictingMachineIdentifiers = conflictingIdentifiers } } } @Published public private(set) var virtualMachines: [VBVirtualMachine] = [] /// Identifiers that more than one virtual machine in the library has, which happens when a bundle is copied outside of VirtualBuddy. /// Those virtual machines can't be told apart by anything that finds a virtual machine by its identifier. @Published public private(set) var conflictingMachineIdentifiers = Set() /// Virtual machines that are currently being duplicated. @Published public private(set) var duplicatingMachineIdentifiers = Set() /// The most recent virtual machine that was created by duplicating another one, so that it can be brought into view. @Published public private(set) var recentlyDuplicatedMachineIdentifier: VBVirtualMachine.ID? /// Identifiers for all VMs that are currently in a "booted" state (starting, booted, or paused). @Published public private(set) var bootedMachineIdentifiers = Set() private let bootedInstances = NSMapTable(keyOptions: [.objectPersonality, .strongMemory], valueOptions: [.objectPersonality, .weakMemory]) /// Populated when ``bootedMachineIdentifiers`` is not empty, invalidated when the last booted machine identifier is unregistered via ``unregisterBootedVM(identifier:)``. private var preventTerminationAssertion: PreventTerminationAssertion? /// Observes notifications about volume mount/unmount that are used when library resides in a removable volume. private var volumeNotificationsTask: Task? /// Set when the library is loaded. private var isLibraryInRemovableVolume = false let settingsContainer: VBSettingsContainer 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", "heic" ] public private(set) lazy var templatesController = VMTemplatesController(library: self) public init(settingsContainer: VBSettingsContainer = .current) { 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, label: "Library", signal: updateSignal ) loadMachines() bind() } private var settings: VBSettings { didSet { self.libraryURL = settings.libraryURL /// A change of library directory has already loaded the machines again. if settings.showExternalVirtualMachinesInLibrary != oldValue.showExternalVirtualMachinesInLibrary, settings.libraryURL == oldValue.libraryURL { reload() } } } @Published public private(set) var libraryURL: URL { didSet { guard oldValue != libraryURL else { return } stopObservingRemovableVolumeNotifications() loadMachines() } } private lazy var cancellables = Set() private lazy var fileManager = FileManager() private var hasLoadedMachinesOnce = false private func bind() { settingsContainer.$settings.sink { [weak self] newSettings in self?.settings = newSettings } .store(in: &cancellables) updateSignal .debounce(for: .milliseconds(200), scheduler: DispatchQueue.main) .sink { [weak self] url in guard let self else { return } /// Ignore file change notifications in the guest additions or downloads directories. guard !url.path.contains(GuestAdditionsDiskImage.imagesRootURL.path) else { return } guard !url.path.contains(VBSettings.current.downloadsDirectoryURL.path) else { return } guard let bundleURL = url.virtualMachineBundleParent else { self.logger.fault("Failed to determine VM bundle URL for changed file \(url.lastPathComponent)") return } self.handleBundleChanged(at: bundleURL) } .store(in: &cancellables) } private func handleBundleChanged(at bundleURL: URL) { logger.debug("Bundle changed: \(bundleURL.lastPathComponent)") loadMachines() } public func loadMachines(createLibrary: Bool = false) { guard transactionLock.try() else { logger.warning("Skip load machines: transaction lock already taken") return } defer { transactionLock.unlock() } #if DEBUG guard !simulateState() else { return } #endif let path = libraryURL.path logger.debug("Loading machines from \(path.quoted)") if createLibrary, !libraryURL.isReadableDirectory { do { try fileManager.createDirectory(at: libraryURL, withIntermediateDirectories: true) } catch { NSApp.presentError(error) return } } isLibraryInRemovableVolume = Self.isLibraryURLInRemovableVolume(libraryURL) observeRemovableVolumeNotifications() guard libraryURL.isReadableDirectory else { if isLibraryInRemovableVolume { logger.warning("External volume library directory not found at \(path.quoted)") state = .volumeNotMounted } else { logger.warning("Library directory not found at \(path.quoted)") state = .directoryMissing } return } filePresenter.presentedItemURL = libraryURL guard let enumerator = fileManager.enumerator(at: libraryURL, includingPropertiesForKeys: [.creationDateKey], options: [.skipsHiddenFiles, .skipsPackageDescendants, .skipsSubdirectoryDescendants], errorHandler: nil) else { logger.fault("Failed to create directory enumerator for library at \(path.quoted)") state = .directoryMissing return } var machines = [VBVirtualMachine]() func loadMachine(at url: URL) { do { let machine = try VBVirtualMachine(bundleURL: url, createIfNeeded: false) if let index = machines.firstIndex(where: { $0.id == machine.id }) { machines[index] = machine } else { machines.append(machine) } } catch is VBVirtualMachine.BundleDirectoryMissingError { /// This error can occur when the bundle is deleted in Finder. logger.debug("Ignoring BundleDirectoryMissingError for \(url.lastPathComponent)") } catch { assertionFailure("Failed to construct VM model: \(error)") } } while let url = enumerator.nextObject() as? URL { guard url.pathExtension == VBVirtualMachine.bundleExtension else { continue } loadMachine(at: url) } /// Virtual machines stored outside the library directory stay remembered while the user chooses not to see them. let externalBundleURLs = showsExternalVirtualMachines ? 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) if !hasLoadedMachinesOnce { hasLoadedMachinesOnce = true migrateBackgroundHashesForLegacyThumbnails() } } public func reload(animated: Bool = true) { if animated { withAnimation(.spring()) { loadMachines() } } else { loadMachines() } } public func validateNewName(_ name: String, for vm: VBVirtualMachine) throws { /// No need to validate if name is not changed. guard name != vm.name else { return } try urlForRenaming(vm, to: name) } // MARK: - VM Controller References private final class Coordinator { private let lock = NSRecursiveLock() private var _activeVMControllers = [VBVirtualMachine.ID: WeakReference]() /// References to all active `VMController` instances by VM identifier. /// May hold references to invalidated controllers because this does not hold a strong reference to them. var activeVMControllers: [VBVirtualMachine.ID: WeakReference] { get { lock.withLock { _activeVMControllers } } set { lock.withLock { _activeVMControllers = newValue } } } func activeController(for virtualMachineID: VBVirtualMachine.ID) -> VMController? { activeVMControllers[virtualMachineID]?.object } /// Called when a new `VMController` is initialized so that we can reference it /// outside the scope of the view hierarchy (for automation). func addController(_ controller: VMController) { activeVMControllers[controller.id] = WeakReference(controller) } /// Called when a `VMController` is dying so that we can cleanup our reference to it. func removeController(_ controller: VMController) { activeVMControllers[controller.id] = nil } } nonisolated(unsafe) private let coordinator = Coordinator() public nonisolated var activeVMControllers: [WeakReference] { Array(coordinator.activeVMControllers.values) } public nonisolated func activeController(for virtualMachineID: VBVirtualMachine.ID) -> VMController? { coordinator.activeVMControllers[virtualMachineID]?.object } /// Called when a new `VMController` is initialized so that we can reference it /// outside the scope of the view hierarchy (for automation). nonisolated func addController(_ controller: VMController) { coordinator.activeVMControllers[controller.id] = WeakReference(controller) } /// Called when a `VMController` is dying so that we can cleanup our reference to it. nonisolated func removeController(_ controller: VMController) { coordinator.activeVMControllers[controller.id] = nil } // MARK: - Migration private var alwaysAttemptLegacyThumbnailMigration: Bool { #if DEBUG UserDefaults.standard.bool(forKey: "VBAlwaysAttemptLegacyThumbnailMigration") #else false #endif } private static let migratedLegacyThumbnailBackgroundHashesDefaultsKey = "migratedLegacyThumbnailBackgroundHashes_2" private var migratedLegacyThumbnailBackgroundHashes: Bool { get { guard !alwaysAttemptLegacyThumbnailMigration else { return false } return UserDefaults.standard.bool(forKey: Self.migratedLegacyThumbnailBackgroundHashesDefaultsKey) } set { guard !alwaysAttemptLegacyThumbnailMigration else { return } UserDefaults.standard.set(newValue, forKey: Self.migratedLegacyThumbnailBackgroundHashesDefaultsKey) } } private func migrateBackgroundHashesForLegacyThumbnails() { guard !migratedLegacyThumbnailBackgroundHashes else { return } let machines = self.virtualMachines /// Skip setting migration flag for empty machines in case user library has not been mounted yet. guard !machines.isEmpty else { return } defer { migratedLegacyThumbnailBackgroundHashes = true } logger.debug("Generating missing background hashes for legacy thumbnails...") Task { let needingMigration = machines.filter { $0.configuration.systemType == .mac && $0.metadata.backgroundHash == .virtualBuddyBackground } guard !needingMigration.isEmpty else { logger.debug("Found no machines needing background hash migration.") return } logger.debug("Found machines needing background hash migration: \(needingMigration.map(\.name).formatted(.list(type: .and)))") for var machine in needingMigration { do { guard let thumbnail = machine.thumbnailImage() else { logger.debug("Ignoring \(machine.name) for background hash migration because it doesn't have a thumbnail.") continue } if #available(macOS 15.0, *) { let isDRMProtectedBug = await thumbnail.detectDRMProtectedVideoBug() guard !isDRMProtectedBug else { logger.notice("Invalidating thumbnail for \(machine.name): detected \"DRM Protected Video\" bug in its thumbnail.") try machine.invalidateThumbnail() try machine.invalidateScreenshot() continue } } let hash = try thumbnail.blurHash(numberOfComponents: (.vbBlurHashSize, .vbBlurHashSize)) .require("Background hash generation failed.") machine.metadata.backgroundHash = BlurHashToken(value: hash) try await MainActor.run { try machine.saveMetadata() } logger.info("Migrated background hash for \(machine.name)") } catch { logger.warning("Error migrating background hash for \(machine.name) - \(error, privacy: .public)") } } } } } // MARK: - Queries public struct MACAddressConflict: Hashable { public let macAddress: String public let vmName: String public init(macAddress: String, runningVMName: String) { self.macAddress = macAddress self.vmName = runningVMName } } public extension VMLibraryController { func virtualMachines(matching predicate: (VBVirtualMachine) -> Bool) -> [VBVirtualMachine] { virtualMachines.filter(predicate) } func virtualMachine(named name: String) -> VBVirtualMachine? { virtualMachines(matching: { $0.name.caseInsensitiveCompare(name) == .orderedSame }).first } func macAddressConflicts(for vm: VBVirtualMachine) -> [MACAddressConflict] { let candidates = Set( vm.configuration.hardware.networkDevices .map { $0.macAddress.uppercased() } .filter { !$0.isEmpty } ) guard !candidates.isEmpty else { return [] } var conflicts: [MACAddressConflict] = [] for runningID in bootedMachineIdentifiers where runningID != vm.id { guard let runningVM = virtualMachines.first(where: { $0.id == runningID }) else { continue } for device in runningVM.configuration.hardware.networkDevices { let mac = device.macAddress.uppercased() guard candidates.contains(mac) else { continue } conflicts.append(MACAddressConflict(macAddress: mac, runningVMName: runningVM.name)) } } return conflicts } } // MARK: - Active Copies public extension VMLibraryController { /// Finds running virtual machines that can't run at the same time as one that's about to resume a saved session. func activeCopyConflicts(for vm: VBVirtualMachine, macAddresses: [String]) -> [SavedSessionActiveCopyConflict] { let running = bootedMachineIdentifiers.compactMap { id in virtualMachines.first { $0.id == id } } return SavedSessionActiveCopyConflict.conflicts(for: vm, macAddresses: macAddresses, among: running) } } // MARK: - Management Actions public extension VMLibraryController { /// Whether the virtual machine is running, paused, or in the middle of saving or restoring. func isExecuting(_ vm: VBVirtualMachine) -> Bool { bootedMachineIdentifiers.contains(vm.id) || activeController(for: vm.id)?.state.isActive == true } /// Whether the virtual machine's bundle is being copied, which makes it unavailable for anything that would change it. func isBeingDuplicated(_ vm: VBVirtualMachine) -> Bool { duplicatingMachineIdentifiers.contains(vm.id) } /// Returns once the virtual machine isn't being duplicated, immediately if it isn't. /// Starting, resuming and everything else that changes a virtual machine's bundle waits for this. func waitForDuplication(of id: VBVirtualMachine.ID) async { guard duplicatingMachineIdentifiers.contains(id) else { return } for await identifiers in $duplicatingMachineIdentifiers.values where !identifiers.contains(id) { return } } /// Duplicates a virtual machine without opening or resuming it. /// /// A virtual machine with a saved session is duplicated along with it, and the copy continues independently. /// The copy only becomes visible once it's complete. /// /// The virtual machine can't be started, resumed, discarded, renamed or trashed while it's being copied. @discardableResult func duplicate(_ vm: VBVirtualMachine) async throws -> VBVirtualMachine { guard !isBeingDuplicated(vm) else { throw Failure("\"\(vm.name)\" is already being duplicated.") } /// From here on, nothing new can start working on the virtual machine until the copy is done. duplicatingMachineIdentifiers.insert(vm.id) defer { duplicatingMachineIdentifiers.remove(vm.id) } let copyURL = try urlForRenaming(vm, to: "Copy of " + vm.name) let sourceURL = vm.bundleURL func copy() async throws -> VBVirtualMachine { /// Checked again inside the exclusion, since it could have been started while this was waiting for its turn. guard !isExecuting(vm) else { throw Failure("\"\(vm.name)\" is in use. Use Save & Close or shut it down before duplicating it.") } return try await performOffMainActor { try VMBundleDuplicator().duplicate(bundleAt: sourceURL, to: copyURL) } } let duplicate: VBVirtualMachine if let controller = activeController(for: vm.id) { /// Anything the virtual machine's controller is asked to do is held back until the copy is complete. duplicate = try await controller.performExclusively { try await copy() } } else { 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 return duplicate } func moveToTrash(_ vm: VBVirtualMachine) async throws { guard !isBeingDuplicated(vm) else { throw Failure("\"\(vm.name)\" is being duplicated. Wait for that to finish before moving it to the trash.") } try await NSWorkspace.shared.recycle([vm.bundleURL]) externalMachines.remove(vm.bundleURL) reload() } func rename(_ vm: VBVirtualMachine, to newName: String) throws { guard !isBeingDuplicated(vm) else { throw Failure("\"\(vm.name)\" is being duplicated. Wait for that to finish before renaming it.") } let newURL = try urlForRenaming(vm, to: newName) try fileManager.moveItem(at: vm.bundleURL, to: newURL) if isExternal(vm) { externalMachines.remove(vm.bundleURL) externalMachines.add(newURL) } reload(animated: false) } @discardableResult func urlForRenaming(_ vm: VBVirtualMachine, to name: String) throws -> URL { guard name.count >= 3 else { throw Failure("Name must be at least 3 characters long.") } let newURL = vm .bundleURL .deletingLastPathComponent() .appendingPathComponent(name) .appendingPathExtension(VBVirtualMachine.bundleExtension) guard !fileManager.fileExists(atPath: newURL.path) else { throw Failure("Another virtual machine is already using this name, please choose another one.") } return newURL } } extension NSWorkspace: @retroactive @unchecked Sendable { } // MARK: - Identifier Conflicts public extension VMLibraryController { /// Whether another virtual machine in the library has the same identifier as this one. func hasIdentifierConflict(_ vm: VBVirtualMachine) -> Bool { conflictingMachineIdentifiers.contains(vm.uuid) } /// The other virtual machines in the library that have the same identifier as this one, which doesn't have to be in the library itself. func identifierConflicts(for vm: VBVirtualMachine) -> [VBVirtualMachine] { let path = ExternalVirtualMachineStore.canonicalPath(for: vm.bundleURL) return virtualMachines.filter { $0.uuid == vm.uuid && ExternalVirtualMachineStore.canonicalPath(for: $0.bundleURL) != path } } /// Gives a virtual machine a new identifier, so that it can be told apart from the ones it was copied from or to. /// /// Nothing about the guest changes. Whatever found the virtual machine by its previous identifier no longer does. /// The virtual machine doesn't have to be in the library. /// /// - Returns: The virtual machine with its new identifier. @discardableResult func assignNewIdentifier(to vm: VBVirtualMachine) throws -> VBVirtualMachine { try assignNewIdentifier(to: vm) { try VBVirtualMachine.carryApprovedSettings(from: $0, to: $1) } } } extension VMLibraryController { /// - Parameter keepApprovals: Approves again, for the virtual machine with its new identifier, the settings that are approved for it with its current one. @discardableResult func assignNewIdentifier(to vm: VBVirtualMachine, keepApprovals: VMBundleDuplicator.ApprovalCarrier) throws -> VBVirtualMachine { /// A virtual machine that's open would save its previous identifier again along with its other metadata. guard !isExecuting(vm), activeController(for: vm.id) == nil else { throw Failure("\"\(vm.name)\" is open. Close its window, then try again.") } guard !isBeingDuplicated(vm) else { throw Failure("\"\(vm.name)\" is being duplicated. Wait for that to finish, then try again.") } let current = try VBVirtualMachine(bundleURL: vm.bundleURL, isNewInstall: false, createIfNeeded: false) var updated = current updated.uuid = UUID() try updated.saveMetadata() logger.notice("Assigned new identifier \(updated.uuid, privacy: .public) to \(vm.bundleURL.lastPathComponent.quoted), replacing \(current.uuid, privacy: .public)") /// Approvals cover the identifier, so the settings that were approved for this bundle are approved again under the new one. /// A bundle that was copied outside of VirtualBuddy has no approvals of its own, so it gains none from this. /// Without them the virtual machine only asks for its settings to be reviewed, which is not worth failing for. do { try keepApprovals(current, updated) } catch { logger.error("Unable to keep approved settings for \(vm.bundleURL.lastPathComponent, privacy: .public): \(error.localizedDescription, privacy: .public)") } reload(animated: false) return updated } } private extension VMLibraryController { static func conflictingIdentifiers(in machines: [VBVirtualMachine]) -> Set { var seen = Set() var shared = Set() for machine in machines where !seen.insert(machine.uuid).inserted { shared.insert(machine.uuid) } return shared } } // MARK: - External Virtual Machines public extension VMLibraryController { /// Whether virtual machines opened from outside the library directory show up in the library, which is the user's choice. var showsExternalVirtualMachines: Bool { settings.showExternalVirtualMachinesInLibrary } /// 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, or if the user chose not to see /// virtual machines from outside the library directory in the library. /// /// - 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 showsExternalVirtualMachines, !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 { /// Adds virtual machine to the list of booted machines. func registerBootedVM(_ instance: VMInstance) { let id = instance.virtualMachineModel.id logger.debug("Registering booted VM \(id.shortID, privacy: .public)") bootedMachineIdentifiers.insert(id) bootedInstances.setObject(instance, forKey: id as NSString) startPreventingAppTerminationIfNeeded() } /// Removes virtual machine from the list of booted machines. func unregisterBootedVM(_ instance: VMInstance) { let id = instance.virtualMachineModel.id logger.debug("Unregistering booted VM \(id.shortID, privacy: .public)") bootedMachineIdentifiers.remove(id) bootedInstances.removeObject(forKey: id as NSString) stopPreventingAppTerminationIfNeeded() } /// Closes guest connections before the application exits. func stopGuestCommunication() async { let instances = Array(bootedInstances.dictionaryRepresentation().values) await withTaskGroup(of: Void.self) { group in for instance in instances { group.addTask { await instance.stopGuestCommunication() } } } } } // MARK: - App Termination Assertion public extension VMLibraryController { /// Identifies the assertion that's held while virtual machines are running. /// /// The assertion has no handler of its own: what happens to running virtual machines when the app quits /// is decided in one place, by the app's termination sequence, which saves or shuts them down. nonisolated static let runningMachinesAssertionID = "codes.rambo.VirtualBuddy.runningMachines" } private extension VMLibraryController { func startPreventingAppTerminationIfNeeded() { guard !bootedMachineIdentifiers.isEmpty else { return } guard preventTerminationAssertion == nil || preventTerminationAssertion?.isValid == false else { return } logger.notice("Start preventing app termination") preventTerminationAssertion = NSApp.preventTermination(id: Self.runningMachinesAssertionID, reason: "virtual machines are currently running") } func stopPreventingAppTerminationIfNeeded() { guard bootedMachineIdentifiers.isEmpty else { return } guard preventTerminationAssertion != nil else { return } logger.notice("Stop preventing app termination") preventTerminationAssertion?.invalidate() preventTerminationAssertion = nil } } // MARK: - Removable Volume Detection /// External volume detection extension VMLibraryController { /// `true` if the specified file URL lives in a removable volume that could be unmounted when the app attempts to access it. static func isLibraryURLInRemovableVolume(_ url: URL) -> Bool { if let isInRemovableVolume = url.isInRemovableVolume { isInRemovableVolume } else if url.path.hasPrefix("/Volumes") { /// Assume removable volume when path starts with `/Volumes`. /// This is technically wrong as an external volume can be mounted anywhere and the built-in data /// volume is also located in `/Volumes`, but that one will always be mounted when this is used. /// It's fine to do here because this is only meant to be used for reporting things in the UI. true } else { /// Settings stores the removable volume state of the library directory when the user customizes it, /// use that fact as the final response if above checks fail. /// This is needed because we could be checking a URL for a directory that doesn't currently exist, /// and the mount could be somewhere other than `/Volumes`, so we have to go with what we knew before. VBSettings.current.isLibraryInRemovableVolume } } } extension URL { /// Whether the file resides in a removable volume, or `nil` if it can't be determined. var isInRemovableVolume: Bool? { guard let volumeURL = try? resourceValues(forKeys: [.volumeURLKey]).volume else { return nil } return (try? volumeURL.resourceValues(forKeys: [.volumeIsRemovableKey]))?.volumeIsRemovable } } private extension VMLibraryController { func observeRemovableVolumeNotifications() { /// Only observe when the library or a virtual machine stored outside of it could be in a volume that comes and goes. guard isLibraryInRemovableVolume || (showsExternalVirtualMachines && !externalMachines.references.isEmpty) else { return } guard volumeNotificationsTask == nil || volumeNotificationsTask?.isCancelled == true else { return } logger.debug(#function) volumeNotificationsTask = Task.detached(priority: .background) { [weak self] in await withTaskGroup { group in group.addTask { for await notification in NSWorkspace.shared.notificationCenter.notifications(named: NSWorkspace.didMountNotification) { guard !Task.isCancelled else { return } await self?.handleVolumeNotification(notification) } } group.addTask { for await notification in NSWorkspace.shared.notificationCenter.notifications(named: NSWorkspace.didUnmountNotification) { guard !Task.isCancelled else { return } await self?.handleVolumeNotification(notification) } } } } } func stopObservingRemovableVolumeNotifications() { logger.debug(#function) volumeNotificationsTask?.cancel() volumeNotificationsTask = nil } func handleVolumeNotification(_ notification: Notification) { let isMount = notification.name == NSWorkspace.didMountNotification guard let volumeURL = notification.userInfo?[NSWorkspace.volumeURLUserInfoKey] as? URL 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) /// Virtual machines stored outside the library directory come and go with their volumes. let affectsExternalMachines = showsExternalVirtualMachines && externalMachines.hasReferences(inVolumeAt: volumeURL) 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() } } #if DEBUG // MARK: - Debug State Simulation private extension VMLibraryController { func simulateState() -> Bool { if UserDefaults.standard.bool(forKey: "VBSimulateLibraryVolumeNotMounted") { state = .volumeNotMounted return true } else if UserDefaults.standard.bool(forKey: "VBSimulateLibraryDirectoryMissing") { state = .directoryMissing return true } else if UserDefaults.standard.bool(forKey: "VBSimulateLibraryEmpty") { state = .empty return true } else { return false } } } #endif