UTMSingleWindowView.swift 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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 SwiftUI
  17. @MainActor
  18. struct UTMSingleWindowView: View {
  19. private var isInteractive: Bool {
  20. data != nil
  21. }
  22. #if WITH_REMOTE
  23. typealias DataType = UTMRemoteData
  24. #else
  25. typealias DataType = UTMData
  26. #endif
  27. private let data: DataType?
  28. @State private var session: VMSessionState?
  29. @State private var identifier: VMSessionState.WindowID?
  30. private let vmSessionCreatedNotification = NotificationCenter.default.publisher(for: .vmSessionCreated)
  31. private let vmSessionEndedNotification = NotificationCenter.default.publisher(for: .vmSessionEnded)
  32. init(data: DataType? = nil) {
  33. self.data = data
  34. }
  35. var body: some View {
  36. ZStack {
  37. if let session = session {
  38. VMWindowView(id: identifier!, isInteractive: isInteractive).environmentObject(session)
  39. } else if isInteractive {
  40. #if WITH_REMOTE
  41. RemoteContentView(remoteClientState: data!.remoteClient.state).environmentObject(data!)
  42. #else
  43. ContentView().environmentObject(data!)
  44. #endif
  45. } else {
  46. VStack {
  47. Text("Waiting for VM to connect to display...")
  48. .font(.headline)
  49. BusyIndicator()
  50. }
  51. }
  52. }
  53. .onAppear {
  54. session = VMSessionState.allActiveSessions.first?.value
  55. if let session = session {
  56. identifier = session.newWindow().windowID
  57. }
  58. }
  59. .onReceive(vmSessionCreatedNotification) { output in
  60. let newSession = output.userInfo!["Session"] as! VMSessionState
  61. withAnimation {
  62. session = newSession
  63. identifier = newSession.newWindow().windowID
  64. }
  65. }
  66. .onReceive(vmSessionEndedNotification) { output in
  67. let endedSession = output.userInfo!["Session"] as! VMSessionState
  68. if endedSession == session {
  69. withAnimation {
  70. session = nil
  71. }
  72. }
  73. }
  74. }
  75. }
  76. struct UTMSingleWindowView_Previews: PreviewProvider {
  77. static var previews: some View {
  78. UTMSingleWindowView(data: UTMSingleWindowView.DataType())
  79. }
  80. }