UTMSingleWindowView.swift 2.8 KB

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