Files
VirtualBuddy/VirtualCore/Source/Settings/VBSettings.swift
Guilherme Rambo 3522f6520c Xcode integration (#818)
* Implement Xcode integration for running and debugging a Mac app in a virtual machine

* Fix xcodeproj/xcworkspace not selectable in open panel

* Improve Xcode project setup UI

* Add dedicated Developer tab in settings and global toggle for developer features

* Improve developer settings UI

* Add managed preference for disabling developer features
2026-11-20 17:37:23 -03:00

236 lines
9.5 KiB
Swift

//
// VBSettings.swift
// VirtualCore
//
// Created by Guilherme Rambo on 05/06/22.
//
import AppKit
import ManagedPreferencesKit
import OSLog
private let logger = Logger(subsystem: VirtualCoreConstants.subsystemName, category: String(describing: VBSettings.self))
/// What happens when the window of a running virtual machine is closed.
public enum VMCloseBehavior: String, CaseIterable, Identifiable, Sendable {
/// Asks every time, offering to save the state or shut down.
case ask
/// Saves the state of virtual machines that support it.
case saveState
/// Shuts the virtual machine down.
case shutDown
public var id: String { rawValue }
public var title: String {
switch self {
case .ask: "Ask every time"
case .saveState: "Save state"
case .shutDown: "Shutdown"
}
}
}
public struct VBSettings: Hashable, Sendable {
public static var current: VBSettings { VBSettingsContainer.current.settings }
public static let updateChannelDidChangeNotification = Notification.Name("VBSettingsUpdateChannelDidChangeNotification")
public static let currentVersion = 3
public var version: Int = Self.currentVersion
public var libraryURL: URL {
didSet {
guard libraryURL != oldValue else { return }
isLibraryInRemovableVolume = libraryURL.isInRemovableVolume ?? false
}
}
public var updateChannel: AppUpdateChannel {
didSet {
guard updateChannel != oldValue else { return }
NotificationCenter.default.post(name: Self.updateChannelDidChangeNotification, object: updateChannel)
}
}
public var enableTSSCheck: Bool
/// The user's choice, preserved even when a profile disables developer features.
public var developerFeaturesEnabled = false
/// Show desktop picture from guest VM in thumbnails instead of the blur hash version.
/// Currently not exposed in the UI.
public var showDesktopPictureThumbnails: Bool
/// What to do when the window of a running virtual machine is closed.
public var closeBehavior: VMCloseBehavior
/// Enables using the new ASIF format for boot disk images (requires macOS 26+ host).
public var bootDiskImagesUseASIF: Bool
/// Updated when user changes the library directory.
/// This helps ``VMLibraryController`` determine whether the library is in a removable volume
/// so that it can better handle the case where the app is launched before the volume is mounted.
public var isLibraryInRemovableVolume: Bool
public func requireDeveloperFeatures(
preferences: ManagedPreferenceReader<VirtualBuddyManagedPreferences> = VirtualBuddyManagedPreferences.schema.reader()
) throws {
guard !preferences.value(for: .disableDeveloperFeatures, default: false) else {
throw Failure("Developer features are disabled by your organization.")
}
guard developerFeaturesEnabled else {
throw Failure("To use Xcode debugging, enable Developer Features in VirtualBuddy Settings → Developer.")
}
}
}
extension VBSettings {
static let defaultUpdateChannel: AppUpdateChannel = .release
static let defaultEnableTSSCheck = true
static let defaultShowDesktopPictureThumbnails = false
static let defaultCloseBehavior = VMCloseBehavior.ask
static let defaultBootDiskImagesUseASIF: Bool = {
if #available(macOS 26, *) {
true
} else {
false
}
}()
init() {
self.libraryURL = .defaultVirtualBuddyLibraryURL
self.updateChannel = Self.defaultUpdateChannel
self.enableTSSCheck = Self.defaultEnableTSSCheck
self.showDesktopPictureThumbnails = Self.defaultShowDesktopPictureThumbnails
self.bootDiskImagesUseASIF = Self.defaultBootDiskImagesUseASIF
self.closeBehavior = Self.defaultCloseBehavior
self.isLibraryInRemovableVolume = false
}
private struct Keys {
static let version = "version"
static let libraryPath: String = {
#if DEBUG
return ProcessInfo.isSwiftUIPreview ? "libraryPath-preview" : "libraryPath"
#else
return "libraryPath"
#endif
}()
static let updateChannel = "updateChannel"
static let enableTSSCheck = "enableTSSCheck"
static let developerFeaturesEnabled = "developerFeaturesEnabled"
static let showDesktopPictureThumbnails = "showDesktopPictureThumbnails"
static let bootDiskImagesUseASIF = "bootDiskImagesUseASIF"
static let closeBehavior = "closeBehavior"
static let isLibraryInRemovableVolume = "isLibraryInRemovableVolume"
}
init(with defaults: UserDefaults, isXcodeInstalled: () -> Bool = {
NSWorkspace.shared.urlForApplication(withBundleIdentifier: "com.apple.dt.Xcode") != nil
}) throws {
defaults.register(defaults: [
Keys.enableTSSCheck: Self.defaultEnableTSSCheck
])
self.version = defaults.integer(forKey: Keys.version)
self.enableTSSCheck = defaults.bool(forKey: Keys.enableTSSCheck)
if defaults.object(forKey: Keys.developerFeaturesEnabled) == nil {
defaults.set(isXcodeInstalled(), forKey: Keys.developerFeaturesEnabled)
}
self.developerFeaturesEnabled = defaults.bool(forKey: Keys.developerFeaturesEnabled)
self.showDesktopPictureThumbnails = defaults.bool(forKey: Keys.showDesktopPictureThumbnails)
self.bootDiskImagesUseASIF = defaults.bool(forKey: Keys.bootDiskImagesUseASIF)
self.closeBehavior = defaults.string(forKey: Keys.closeBehavior).flatMap(VMCloseBehavior.init(rawValue:)) ?? Self.defaultCloseBehavior
self.isLibraryInRemovableVolume = defaults.bool(forKey: Keys.isLibraryInRemovableVolume)
if let path = defaults.string(forKey: Keys.libraryPath) {
self.libraryURL = URL(fileURLWithPath: path)
} else {
if version == 2 || version == 1 {
/// Default library folder changed in VBSettings version 3,
/// so if we're decoding settings from a previous release without a
/// library defined, use the old default, which may have user VMs in it.
///
/// There's a high chance this never gets hit because the legacy default folder is likely
/// to be in user defaults, even if the user never changed it.
self.libraryURL = ._legacyDefaultVirtualBuddyLibraryURLForMigrationOnly
} else {
self.libraryURL = .defaultVirtualBuddyLibraryURL
}
}
if let appUpdateChannelID = defaults.string(forKey: Keys.updateChannel) {
logger.debug("Found channel \(appUpdateChannelID, privacy: .public) in user defaults")
let restoredChannel = AppUpdateChannel.channelsByID[appUpdateChannelID] ?? .release
let defaultChannel = AppUpdateChannel.defaultChannel(for: .current)
if restoredChannel == .release, defaultChannel != .release {
logger.debug("Settings specify release channel, but current build is for \(defaultChannel, privacy: .public), setting channel to \(defaultChannel, privacy: .public)")
self.updateChannel = defaultChannel
} else {
self.updateChannel = restoredChannel
}
} else {
let defaultChannel = AppUpdateChannel.defaultChannel(for: .current)
logger.debug("No channel set in preferences, using default channel \(defaultChannel, privacy: .public) for build type \(VBBuildType.current, privacy: .public)")
self.updateChannel = defaultChannel
}
}
func write(to defaults: UserDefaults) throws {
defaults.set(version, forKey: Keys.version)
defaults.set(libraryURL.path, forKey: Keys.libraryPath)
defaults.set(updateChannel.id, forKey: Keys.updateChannel)
defaults.set(enableTSSCheck, forKey: Keys.enableTSSCheck)
defaults.set(developerFeaturesEnabled, forKey: Keys.developerFeaturesEnabled)
defaults.set(showDesktopPictureThumbnails, forKey: Keys.showDesktopPictureThumbnails)
defaults.set(bootDiskImagesUseASIF, forKey: Keys.bootDiskImagesUseASIF)
defaults.set(closeBehavior.rawValue, forKey: Keys.closeBehavior)
defaults.set(isLibraryInRemovableVolume, forKey: Keys.isLibraryInRemovableVolume)
}
}
public extension URL {
static let _legacyDefaultVirtualBuddyLibraryURLForMigrationOnly: URL = {
do {
let baseURL = try FileManager.default.url(
for: .documentDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: false
)
return baseURL
.appendingPathComponent("VirtualBuddy")
} catch {
fatalError("VirtualBuddy is unable to write to your user's documents directory, this is bad!")
}
}()
static let defaultVirtualBuddyLibraryURL: URL = {
do {
let baseURL = try FileManager.default.url(
for: .applicationSupportDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: true
)
let url = baseURL.appendingPathComponent("VirtualBuddy")
try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
return url
} catch {
fatalError("VirtualBuddy is unable to write to your user's Library/Application Support directory, this is bad!")
}
}()
}