UTMVirtualMachine.swift 17 KB

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