UTMVirtualMachine.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  1. //
  2. // Copyright © 2023 osy. All rights reserved.
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. //
  16. import Foundation
  17. import Combine
  18. #if canImport(AppKit)
  19. import AppKit
  20. #elseif canImport(UIKit)
  21. import UIKit
  22. #endif
  23. private let kUTMBundleExtension = "utm"
  24. private let kScreenshotPeriodSeconds = 60.0
  25. let kUTMBundleScreenshotFilename = "screenshot.png"
  26. private let kUTMBundleViewFilename = "view.plist"
  27. /// UTM virtual machine backend
  28. protocol UTMVirtualMachine: AnyObject, Identifiable {
  29. associatedtype Capabilities: UTMVirtualMachineCapabilities
  30. associatedtype Configuration: UTMConfiguration
  31. /// Path where the .utm is stored
  32. var pathUrl: URL { get }
  33. /// True if the .utm is loaded outside of the default storage
  34. ///
  35. /// This indicates that we cannot access outside the container.
  36. var isShortcut: Bool { get }
  37. /// The VM is running in disposible mode
  38. ///
  39. /// This indicates that changes should not be saved.
  40. var isRunningAsDisposible: Bool { get }
  41. /// Set by caller to handle VM events
  42. var delegate: (any UTMVirtualMachineDelegate)? { get set }
  43. /// Set by caller to handle changes in `config` or `registryEntry`
  44. var onConfigurationChange: (() -> Void)? { get set }
  45. /// Set by caller to handle changes in `state` or `screenshot`
  46. var onStateChange: (() -> Void)? { get set }
  47. /// Configuration for this VM
  48. var config: Configuration { get }
  49. /// Additional configuration on a short lived, per-host basis
  50. ///
  51. /// This includes display size, bookmarks to removable drives, etc.
  52. var registryEntry: UTMRegistryEntry { get }
  53. /// Current VM state
  54. var state: UTMVirtualMachineState { get }
  55. /// If non-null, is the most recent screenshot of the running VM
  56. var screenshot: UTMVirtualMachineScreenshot? { get }
  57. /// If non-null, `saveSnapshot` and `restoreSnapshot` will not work due to the reason specified
  58. var snapshotUnsupportedError: Error? { get }
  59. /// If true, this VM does not have any active display
  60. var isHeadless: Bool { get }
  61. static func isVirtualMachine(url: URL) -> Bool
  62. /// Get name of UTM virtual machine from a file
  63. /// - Parameter url: File URL
  64. /// - Returns: The name of the VM
  65. static func virtualMachineName(for url: URL) -> String
  66. /// Get the path of a UTM virtual machine from a name and parent directory
  67. /// - Parameters:
  68. /// - name: VM name
  69. /// - parentUrl: Base directory file URL
  70. /// - Returns: URL of virtual machine
  71. static func virtualMachinePath(for name: String, in parentUrl: URL) -> URL
  72. /// Returns supported capabilities for this backend
  73. static var capabilities: Capabilities { get }
  74. /// Instantiate a new virtual machine
  75. /// - Parameters:
  76. /// - packageUrl: Package where the virtual machine resides
  77. /// - configuration: New virtual machine configuration
  78. /// - isShortcut: Indicate that this package cannot be moved
  79. init(packageUrl: URL, configuration: Configuration, isShortcut: Bool) throws
  80. /// Discard any changes to configuration by reloading from disk
  81. /// - Parameter packageUrl: URL to reload from, if nil then use the existing package URL
  82. func reload(from packageUrl: URL?) throws
  83. /// Save .utm bundle to disk
  84. ///
  85. /// This will create a configuration file and any auxiliary data files if needed.
  86. func save() async throws
  87. /// Called when we save the config
  88. func updateRegistryFromConfig() async throws
  89. /// Called whenever the registry entry changes
  90. func updateConfigFromRegistry()
  91. /// Called when we have a duplicate UUID
  92. /// - Parameters:
  93. /// - uuid: New UUID
  94. /// - name: Optionally change name as well
  95. /// - entry: Optionally copy data from an entry
  96. func changeUuid(to uuid: UUID, name: String?, copyingEntry entry: UTMRegistryEntry?)
  97. /// Starts the VM
  98. /// - Parameter options: Options for startup
  99. func start(options: UTMVirtualMachineStartOptions) async throws
  100. /// Stops the VM
  101. /// - Parameter method: How to handle the stop request
  102. func stop(usingMethod method: UTMVirtualMachineStopMethod) async throws
  103. /// Restarts the VM
  104. func restart() async throws
  105. /// Pauses the VM
  106. func pause() async throws
  107. /// Resumes the VM
  108. func resume() async throws
  109. /// Saves the current VM state
  110. /// - Parameter name: Optional snaphot name (default if nil)
  111. func saveSnapshot(name: String?) async throws
  112. /// Deletes the saved VM state
  113. /// - Parameter name: Optional snaphot name (default if nil)
  114. func deleteSnapshot(name: String?) async throws
  115. /// Restore saved VM state
  116. /// - Parameter name: Optional snaphot name (default if nil)
  117. func restoreSnapshot(name: String?) async throws
  118. /// Request a screenshot of the primary graphics device
  119. /// - Returns: true if successful and the screenshot will be in `screenshot`
  120. @discardableResult func takeScreenshot() async -> Bool
  121. /// If screenshot is modified externally, this must be called
  122. func reloadScreenshotFromFile() throws
  123. }
  124. /// Supported capabilities for a UTM backend
  125. protocol UTMVirtualMachineCapabilities {
  126. /// The backend supports killing the VM process.
  127. var supportsProcessKill: Bool { get }
  128. /// The backend supports saving/restoring VM state.
  129. var supportsSnapshots: Bool { get }
  130. /// The backend supports taking screenshots.
  131. var supportsScreenshots: Bool { get }
  132. /// The backend supports running without persisting changes.
  133. var supportsDisposibleMode: Bool { get }
  134. /// The backend supports booting into recoveryOS.
  135. var supportsRecoveryMode: Bool { get }
  136. /// The backend supports remote sessions.
  137. var supportsRemoteSession: Bool { get }
  138. }
  139. /// Delegate for UTMVirtualMachine events
  140. protocol UTMVirtualMachineDelegate: AnyObject {
  141. /// Called when VM state changes
  142. ///
  143. /// Will always be called from the main thread.
  144. /// - Parameters:
  145. /// - vm: Virtual machine
  146. /// - state: New state
  147. func virtualMachine(_ vm: any UTMVirtualMachine, didTransitionToState state: UTMVirtualMachineState)
  148. /// Called when VM errors
  149. ///
  150. /// Will always be called from the main thread.
  151. /// - Parameters:
  152. /// - vm: Virtual machine
  153. /// - message: Localized error message when supported, English message otherwise
  154. func virtualMachine(_ vm: any UTMVirtualMachine, didErrorWithMessage message: String)
  155. /// Called when VM installation updates progress
  156. /// - Parameters:
  157. /// - vm: Virtual machine
  158. /// - progress: Number between 0.0 and 1.0 indiciating installation progress
  159. func virtualMachine(_ vm: any UTMVirtualMachine, didUpdateInstallationProgress progress: Double)
  160. /// Called when VM successfully completes installation
  161. /// - Parameters:
  162. /// - vm: Virtual machine
  163. /// - success: True if installation is successful
  164. func virtualMachine(_ vm: any UTMVirtualMachine, didCompleteInstallation success: Bool)
  165. }
  166. /// Virtual machine state
  167. enum UTMVirtualMachineState: Int, Codable, CaseIterable, Sendable {
  168. case stopped
  169. case starting
  170. case started
  171. case pausing
  172. case paused
  173. case resuming
  174. case saving
  175. case restoring
  176. case stopping
  177. }
  178. /// Additional options for VM start
  179. struct UTMVirtualMachineStartOptions: OptionSet, Codable {
  180. let rawValue: UInt
  181. /// Boot without persisting any changes.
  182. static let bootDisposibleMode = Self(rawValue: 1 << 0)
  183. /// Boot into recoveryOS (when supported).
  184. static let bootRecovery = Self(rawValue: 1 << 1)
  185. /// Start VDI session where a remote client will connect to.
  186. static let remoteSession = Self(rawValue: 1 << 2)
  187. }
  188. /// Method to stop the VM
  189. enum UTMVirtualMachineStopMethod: Int, Codable, CaseIterable, Sendable {
  190. /// Sends a request to the guest to shut down gracefully.
  191. case request
  192. /// Sends a hardware power down signal.
  193. case force
  194. /// Terminate the VM process.
  195. case kill
  196. }
  197. // MARK: - Class functions
  198. extension UTMVirtualMachine {
  199. private static var fileManager: FileManager {
  200. FileManager.default
  201. }
  202. static func isVirtualMachine(url: URL) -> Bool {
  203. return url.pathExtension == kUTMBundleExtension
  204. }
  205. static func virtualMachineName(for url: URL) -> String {
  206. (fileManager.displayName(atPath: url.path) as NSString).deletingPathExtension
  207. }
  208. static func virtualMachinePath(for name: String, in parentUrl: URL) -> URL {
  209. let illegalFileNameCharacters = CharacterSet(charactersIn: ",/:\\?%*|\"<>")
  210. let name = name.components(separatedBy: illegalFileNameCharacters).joined(separator: "-")
  211. return parentUrl.appendingPathComponent(name).appendingPathExtension(kUTMBundleExtension)
  212. }
  213. /// Instantiate a new VM from a new configuration
  214. /// - Parameters:
  215. /// - configuration: New configuration
  216. /// - destinationUrl: Directory to store VM
  217. init(newForConfiguration configuration: Self.Configuration, destinationUrl: URL) throws {
  218. let packageUrl = Self.virtualMachinePath(for: configuration.information.name, in: destinationUrl)
  219. try self.init(packageUrl: packageUrl, configuration: configuration, isShortcut: false)
  220. }
  221. }
  222. // MARK: - Snapshots
  223. extension UTMVirtualMachine {
  224. func saveSnapshot(name: String?) async throws {
  225. throw UTMVirtualMachineError.notImplemented
  226. }
  227. func deleteSnapshot(name: String?) async throws {
  228. throw UTMVirtualMachineError.notImplemented
  229. }
  230. func restoreSnapshot(name: String?) async throws {
  231. throw UTMVirtualMachineError.notImplemented
  232. }
  233. }
  234. // MARK: - Screenshot
  235. struct UTMVirtualMachineScreenshot {
  236. let image: PlatformImage
  237. let pngData: Data?
  238. init?(contentsOfURL url: URL) {
  239. #if canImport(AppKit)
  240. guard let image = NSImage(contentsOf: url) else {
  241. return nil
  242. }
  243. #elseif canImport(UIKit)
  244. guard let image = UIImage(contentsOfURL: url) else {
  245. return nil
  246. }
  247. #endif
  248. self.image = image
  249. self.pngData = Self.createData(from: image)
  250. }
  251. init(wrapping image: PlatformImage) {
  252. self.image = image
  253. self.pngData = Self.createData(from: image)
  254. }
  255. private static func createData(from image: PlatformImage) -> Data? {
  256. #if canImport(AppKit)
  257. guard let cgref = image.cgImage(forProposedRect: nil, context: nil, hints: nil) else {
  258. return nil
  259. }
  260. let newrep = NSBitmapImageRep(cgImage: cgref)
  261. newrep.size = image.size
  262. return newrep.representation(using: .png, properties: [:])
  263. #elseif canImport(UIKit)
  264. return image.pngData()
  265. #endif
  266. }
  267. }
  268. extension UTMVirtualMachine {
  269. nonisolated var isScreenshotEnabled: Bool {
  270. !UserDefaults.standard.bool(forKey: "NoScreenshot")
  271. }
  272. nonisolated private var isScreenshotSaveEnabled: Bool {
  273. isScreenshotEnabled && !UserDefaults.standard.bool(forKey: "NoSaveScreenshot")
  274. }
  275. private var screenshotUrl: URL {
  276. pathUrl.appendingPathComponent(kUTMBundleScreenshotFilename)
  277. }
  278. func startScreenshotTimer() -> Timer {
  279. // delete existing screenshot if required
  280. if !isScreenshotSaveEnabled && !isRunningAsDisposible {
  281. try? deleteScreenshot()
  282. }
  283. let timer = Timer(timeInterval: kScreenshotPeriodSeconds, repeats: true) { [weak self] timer in
  284. guard let self = self else {
  285. timer.invalidate()
  286. return
  287. }
  288. guard self.isScreenshotEnabled else {
  289. return
  290. }
  291. if self.state == .started {
  292. Task { @MainActor in
  293. await self.takeScreenshot()
  294. }
  295. }
  296. }
  297. RunLoop.main.add(timer, forMode: .default)
  298. return timer
  299. }
  300. func loadScreenshot() -> UTMVirtualMachineScreenshot? {
  301. UTMVirtualMachineScreenshot(contentsOfURL: screenshotUrl)
  302. }
  303. func saveScreenshot() throws {
  304. guard isScreenshotSaveEnabled && !isRunningAsDisposible else {
  305. return
  306. }
  307. guard let screenshot = screenshot else {
  308. return
  309. }
  310. try screenshot.pngData?.write(to: screenshotUrl)
  311. }
  312. func deleteScreenshot() throws {
  313. try Self.fileManager.removeItem(at: screenshotUrl)
  314. }
  315. @MainActor func takeScreenshot() async -> Bool {
  316. return false
  317. }
  318. }
  319. // MARK: - Save UTM
  320. @MainActor extension UTMVirtualMachine {
  321. func save() async throws {
  322. let existingPath = pathUrl
  323. let newPath = Self.virtualMachinePath(for: config.information.name, in: existingPath.deletingLastPathComponent())
  324. try await config.save(to: existingPath)
  325. try await updateRegistryFromConfig()
  326. let hasRenamed: Bool
  327. if !isShortcut && existingPath.path != newPath.path {
  328. try await Task.detached {
  329. try Self.fileManager.moveItem(at: existingPath, to: newPath)
  330. }.value
  331. hasRenamed = true
  332. } else {
  333. hasRenamed = false
  334. }
  335. // reload the config if we renamed in order to point all the URLs to the right path
  336. if hasRenamed {
  337. try reload(from: newPath)
  338. try await updateRegistryBasics() // update bookmark
  339. }
  340. // update last modified date
  341. try? updateLastModified()
  342. }
  343. /// Set the package's last modified time
  344. /// - Parameter date: Last modified date
  345. nonisolated func updateLastModified(to date: Date = Date()) throws {
  346. try FileManager.default.setAttributes([.modificationDate: date], ofItemAtPath: pathUrl.path)
  347. }
  348. }
  349. // MARK: - Registry functions
  350. @MainActor extension UTMVirtualMachine {
  351. nonisolated func loadRegistry() -> UTMRegistryEntry {
  352. let registryEntry = UTMRegistry.shared.entry(for: self)
  353. // migrate legacy view state
  354. let viewStateUrl = pathUrl.appendingPathComponent(kUTMBundleViewFilename)
  355. registryEntry.migrateUnsafe(viewStateURL: viewStateUrl)
  356. return registryEntry
  357. }
  358. /// Default implementation
  359. func updateRegistryFromConfig() async throws {
  360. try await updateRegistryBasics()
  361. }
  362. /// Called when we save the config
  363. func updateRegistryBasics() async throws {
  364. if registryEntry.uuid != id {
  365. changeUuid(to: id, name: nil, copyingEntry: registryEntry)
  366. }
  367. registryEntry.name = name
  368. let oldPath = registryEntry.package.path
  369. let oldRemoteBookmark = registryEntry.package.remoteBookmark
  370. registryEntry.package = try UTMRegistryEntry.File(url: pathUrl)
  371. if registryEntry.package.path == oldPath {
  372. registryEntry.package.remoteBookmark = oldRemoteBookmark
  373. }
  374. }
  375. }
  376. // MARK: - Identity
  377. extension UTMVirtualMachine {
  378. var id: UUID {
  379. config.information.uuid
  380. }
  381. var name: String {
  382. config.information.name
  383. }
  384. }
  385. // MARK: - Errors
  386. enum UTMVirtualMachineError: Error {
  387. case notImplemented
  388. }
  389. extension UTMVirtualMachineError: LocalizedError {
  390. var errorDescription: String? {
  391. switch self {
  392. case .notImplemented:
  393. return NSLocalizedString("Not implemented.", comment: "UTMVirtualMachine")
  394. }
  395. }
  396. }
  397. // MARK: - Non-asynchronous version (to be removed)
  398. extension UTMVirtualMachine {
  399. func requestVmStart(options: UTMVirtualMachineStartOptions = []) {
  400. Task {
  401. do {
  402. try await start(options: options)
  403. } catch {
  404. delegate?.virtualMachine(self, didErrorWithMessage: error.localizedDescription)
  405. }
  406. }
  407. }
  408. func requestVmStop(force: Bool = false) {
  409. Task {
  410. do {
  411. try await stop(usingMethod: force ? .kill : .force)
  412. } catch {
  413. delegate?.virtualMachine(self, didErrorWithMessage: error.localizedDescription)
  414. }
  415. }
  416. }
  417. func requestVmReset() {
  418. Task {
  419. do {
  420. try await restart()
  421. } catch {
  422. delegate?.virtualMachine(self, didErrorWithMessage: error.localizedDescription)
  423. }
  424. }
  425. }
  426. func requestVmPause(save: Bool = false) {
  427. Task {
  428. do {
  429. try await pause()
  430. if save {
  431. try await saveSnapshot(name: nil)
  432. }
  433. } catch {
  434. delegate?.virtualMachine(self, didErrorWithMessage: error.localizedDescription)
  435. }
  436. }
  437. }
  438. func requestVmSaveState() {
  439. Task {
  440. do {
  441. try await saveSnapshot(name: nil)
  442. } catch {
  443. delegate?.virtualMachine(self, didErrorWithMessage: error.localizedDescription)
  444. }
  445. }
  446. }
  447. func requestVmDeleteState() {
  448. Task {
  449. do {
  450. try await deleteSnapshot(name: nil)
  451. } catch {
  452. delegate?.virtualMachine(self, didErrorWithMessage: error.localizedDescription)
  453. }
  454. }
  455. }
  456. func requestVmResume() {
  457. Task {
  458. do {
  459. try await resume()
  460. try? await deleteSnapshot(name: nil)
  461. } catch {
  462. delegate?.virtualMachine(self, didErrorWithMessage: error.localizedDescription)
  463. }
  464. }
  465. }
  466. func requestGuestPowerDown() {
  467. Task {
  468. do {
  469. try await stop(usingMethod: .request)
  470. } catch {
  471. delegate?.virtualMachine(self, didErrorWithMessage: error.localizedDescription)
  472. }
  473. }
  474. }
  475. }