VMHeadlessSessionState.swift 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. //
  2. // Copyright © 2022 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 IOKit.pwr_mgt
  18. /// Represents the UI state for a single headless VM session.
  19. @MainActor class VMHeadlessSessionState: NSObject, ObservableObject, UTMVirtualMachineDelegate {
  20. let vm: any UTMVirtualMachine
  21. var onStop: (() -> Void)?
  22. @Published var vmState: UTMVirtualMachineState = .stopped
  23. private var hasStarted: Bool = false
  24. private var preventIdleSleepAssertion: IOPMAssertionID?
  25. @Setting("PreventIdleSleep") private var isPreventIdleSleep: Bool = false
  26. init(for vm: any UTMVirtualMachine, onStop: (() -> Void)?) {
  27. self.vm = vm
  28. self.onStop = onStop
  29. super.init()
  30. vm.delegate = self
  31. NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(didWake), name: NSWorkspace.didWakeNotification, object: nil)
  32. }
  33. deinit {
  34. NSWorkspace.shared.notificationCenter.removeObserver(self, name: NSWorkspace.didWakeNotification, object: nil)
  35. }
  36. nonisolated func virtualMachine(_ vm: any UTMVirtualMachine, didTransitionToState state: UTMVirtualMachineState) {
  37. Task { @MainActor in
  38. vmState = state
  39. if state == .started {
  40. hasStarted = true
  41. didStart()
  42. }
  43. if state == .stopped {
  44. if hasStarted {
  45. didStop() // graceful exit
  46. }
  47. hasStarted = false
  48. }
  49. }
  50. }
  51. nonisolated func virtualMachine(_ vm: any UTMVirtualMachine, didErrorWithMessage message: String) {
  52. Task { @MainActor in
  53. NotificationCenter.default.post(name: .vmSessionError, object: nil, userInfo: ["Session": self, "Message": message])
  54. if !hasStarted {
  55. // if we got an error and haven't started, then cleanup
  56. didStop()
  57. }
  58. }
  59. }
  60. nonisolated func virtualMachine(_ vm: any UTMVirtualMachine, didCompleteInstallation success: Bool) {
  61. }
  62. nonisolated func virtualMachine(_ vm: any UTMVirtualMachine, didUpdateInstallationProgress progress: Double) {
  63. }
  64. }
  65. extension VMHeadlessSessionState {
  66. private func didStart() {
  67. NotificationCenter.default.post(name: .vmSessionCreated, object: nil, userInfo: ["Session": self])
  68. if isPreventIdleSleep {
  69. var preventIdleSleepAssertion: IOPMAssertionID = .zero
  70. let success = IOPMAssertionCreateWithName(kIOPMAssertPreventUserIdleSystemSleep as CFString,
  71. IOPMAssertionLevel(kIOPMAssertionLevelOn),
  72. "UTM Virtual Machine Background" as CFString,
  73. &preventIdleSleepAssertion)
  74. if success == kIOReturnSuccess {
  75. self.preventIdleSleepAssertion = preventIdleSleepAssertion
  76. }
  77. }
  78. }
  79. private func didStop() {
  80. NotificationCenter.default.post(name: .vmSessionEnded, object: nil, userInfo: ["Session": self])
  81. if let preventIdleSleepAssertion = preventIdleSleepAssertion {
  82. IOPMAssertionRelease(preventIdleSleepAssertion)
  83. }
  84. onStop?()
  85. }
  86. }
  87. extension Notification.Name {
  88. static let vmSessionCreated = Self("VMSessionCreated")
  89. static let vmSessionEnded = Self("VMSessionEnded")
  90. static let vmSessionError = Self("VMSessionError")
  91. }
  92. // MARK: - Computer wakeup
  93. extension VMHeadlessSessionState {
  94. @objc private func didWake(_ notification: NSNotification) {
  95. if let qemuVM = vm as? UTMQemuVirtualMachine {
  96. Task {
  97. try? await qemuVM.guestAgent?.guestSetTime(NSDate.now.timeIntervalSince1970)
  98. }
  99. }
  100. }
  101. }