VMToolbarUSBMenuView.swift 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. struct VMToolbarUSBMenuView: View {
  18. @EnvironmentObject private var session: VMSessionState
  19. var body: some View {
  20. Menu {
  21. if session.allUsbDevices.isEmpty {
  22. Text("No USB devices detected.")
  23. } else {
  24. ForEach(session.allUsbDevices.indices, id: \.self) { i in
  25. let usbDevice = session.allUsbDevices[i]
  26. let connected = session.connectedUsbDevices.contains { $0 == usbDevice }
  27. Button {
  28. if connected {
  29. session.disconnectDevice(usbDevice)
  30. } else {
  31. session.connectDevice(usbDevice)
  32. }
  33. } label: {
  34. MenuLabel((usbDevice.name ?? usbDevice.description) + suffix(connected: connected), systemImage: connected ? "checkmark.circle.fill" : "")
  35. }
  36. }
  37. }
  38. } label: {
  39. if session.isUsbBusy {
  40. Spinner(size: .regular)
  41. } else {
  42. Label("USB", image: "Toolbar USB")
  43. }
  44. }.simultaneousGesture(TapGesture().onEnded {
  45. session.refreshDevices()
  46. })
  47. }
  48. // When < iOS 14.5, the checkmark label image does not show up
  49. private func suffix(connected isConnected: Bool) -> String {
  50. if #unavailable(iOS 14.5), isConnected {
  51. return " ✓"
  52. } else {
  53. return ""
  54. }
  55. }
  56. }
  57. struct VMToolbarUSBMenuView_Previews: PreviewProvider {
  58. static var previews: some View {
  59. VMToolbarUSBMenuView()
  60. }
  61. }