oficina / meet Public

Clone
git clone https://amadan.net/oficina/meet

Plain git — no account needed to clone.

Download

Download this file

1import SwiftUI
2
3/// The camera, microphone and speaker a call is on, and a choice of each
4/// where there is more than one.
5///
6/// One view for both apps, because the thing a person wants here is the
7/// same on a Mac and an iPhone. On iPhone the microphone is an audio
8/// session route and the speaker follows it; on Mac both are devices on
9/// the call's own audio device module.
10///
11/// The audio readout at the bottom is the reason this panel opens at
12/// all, most of the time: someone has noticed the call sounds wrong. It
13/// says which half of "wrong" the counters are seeing, in a sentence,
14/// rather than making them guess between a bad network and a bad device.
15@MainActor public struct DevicePanel: View {
16 @ObservedObject private var call: Call
17 @ObservedObject private var audio: AudioRoutes
18 @State private var camera: String?
19 @State private var cameraRequest = 0
20 @State private var showingAudioDetails = false
21 @Environment(\.dismiss) private var dismiss
22 /// How long a popover, or the sheet holding the panel, takes to go
23 /// before another sheet can open in its place.
24 static let handOver: TimeInterval = 0.45
25 #if os(iOS)
26 @StateObject private var micModes = MicrophoneModes()
27 #endif
28
29 public init(call: Call) {
30 self.call = call
31 self.audio = call.audio
32 }
33
34 public var body: some View {
35 VStack(alignment: .leading, spacing: 16) {
36 cameraRow
37
38 #if os(iOS)
39 if audio.inputs.count > 1 {
40 microphonePicker
41 } else if let only = audio.inputs.first {
42 row("Microphone", only.name)
43 }
44 micMode
45 if !audio.outputName.isEmpty { row("Speaker", audio.outputName) }
46 #else
47 macAudio
48 #endif
49
50 MicLevelRow(mic: call.levels.mic)
51
52 if !call.deviceNote.isEmpty {
53 Label(call.deviceNote, systemImage: "exclamationmark.circle.fill")
54 .font(.callout).foregroundStyle(.red)
55 .fixedSize(horizontal: false, vertical: true)
56 .accessibilityLabel("Device problem: \(call.deviceNote)")
57 }
58
59 noiseToggle
60
61 AudioSelfTestButton(call: call).buttonStyle(.bordered)
62
63 videoQualitySection
64
65 screenSection
66
67 audioFoot
68 }
69 .padding(16)
70 .onAppear {
71 call.refreshDevices()
72 camera = call.currentCamera
73 #if os(iOS)
74 micModes.refresh()
75 #endif
76 }
77 // The picker follows the camera, not the intention: a switch that was
78 // refused leaves the capture where it was, and the control has to go
79 // back rather than keep showing a device the call is not on.
80 .onChange(of: call.currentCamera) { _, now in camera = now }
81 // Devices come and go while the panel is open — a phone offered as a
82 // Continuity Camera, a headset plugged in — so it keeps looking.
83 .task {
84 while !Task.isCancelled {
85 call.refreshDevices()
86 try? await Task.sleep(for: .seconds(1))
87 }
88 }
89 }
90
91 /// A camera the person picked, remembered and switched to. Driven by the
92 /// picker's own setter, which only a person's choice calls — so choosing
93 /// the camera the call is already on (there by fallback, say) counts, as
94 /// it did not in 0.3.3, and the picker following the capture never does.
95 private func pickCamera(_ id: String) {
96 camera = id
97 cameraRequest += 1
98 let request = cameraRequest
99 Task {
100 await call.useCamera(id)
101 // Only the latest pick puts the picker back where the camera is.
102 if request == cameraRequest { camera = call.currentCamera }
103 }
104 }
105
106 /// Always there in a call with a real camera — a camera that has gone
107 /// is exactly when a person needs this row, and 0.3.1 hid it then. A
108 /// picker even for one camera: a Continuity or external camera can
109 /// arrive while the panel is open, and the list follows it.
110 @ViewBuilder private var cameraRow: some View {
111 let state = CameraRowState(
112 cameras: call.cameras.count, offers: call.offersCameras, status: call.cameraStatus)
113 if state != .hidden {
114 VStack(alignment: .leading, spacing: 6) {
115 if state == .noCamera {
116 row("Camera", "No camera found")
117 } else {
118 picker(
119 "Camera",
120 selection: Binding(
121 get: { camera },
122 set: { id in if let id { pickCamera(id) } }),
123 options: call.cameras.map { ($0.id, $0.name) }, identifier: "cameraPicker")
124 }
125 if case .picker(let line, _) = state, let line {
126 Text(line).font(.callout).foregroundStyle(.secondary)
127 .fixedSize(horizontal: false, vertical: true)
128 .accessibilityIdentifier("cameraStatus")
129 }
130 if !call.cameraNote.isEmpty {
131 Label(call.cameraNote, systemImage: "info.circle")
132 .font(.callout).foregroundStyle(.secondary)
133 .fixedSize(horizontal: false, vertical: true)
134 .accessibilityIdentifier("cameraNote")
135 }
136 if let keep = call.cameraToKeep {
137 Button("Use \(keep.name) from now on", systemImage: "checkmark.circle") {
138 pickCamera(keep.id)
139 }
140 .buttonStyle(.bordered)
141 .accessibilityIdentifier("cameraKeep")
142 .accessibilityHint("Remembers this camera for your next calls.")
143 }
144 if state.offersRetry {
145 Button("Try again", systemImage: "arrow.clockwise") {
146 Task { await call.retryCamera() }
147 }
148 .buttonStyle(.bordered)
149 .accessibilityIdentifier("cameraRetry")
150 .accessibilityHint("Looks for cameras again and restarts the camera.")
151 }
152 }
153 }
154 }
155
156 #if os(iOS)
157 private var microphonePicker: some View {
158 VStack(alignment: .leading, spacing: 6) {
159 picker(
160 "Microphone", selection: Binding(
161 get: { audio.currentInput },
162 set: { id in
163 guard let id else { return }
164 do { try audio.use(input: id) } catch { call.noteDevice(error.localizedDescription) }
165 }),
166 options: audio.inputs.map { ($0.id, $0.name) }, identifier: "microphonePicker")
167 // Said before the choice rather than after it: the cost of a
168 // Bluetooth microphone is that the whole call drops to the
169 // hands-free profile, which is narrowband both ways. Someone who
170 // picks it should be picking it knowingly.
171 Text(
172 "A Bluetooth microphone puts the call on the hands-free profile, which is lower quality in both directions."
173 )
174 .font(.footnote).foregroundStyle(.secondary)
175 .fixedSize(horizontal: false, vertical: true)
176 }
177 }
178
179 /// Apple's Mic Mode, named and one tap from its picker. Calls cannot
180 /// set it, only open the place where the person can; see
181 /// MicrophoneModes for why it is worth the row.
182 private var micMode: some View {
183 VStack(alignment: .leading, spacing: 6) {
184 VStack(alignment: .leading, spacing: 2) {
185 Text("Mic Mode").font(.headline)
186 Text(micModes.summary).font(.callout).foregroundStyle(.secondary)
187 .fixedSize(horizontal: false, vertical: true)
188 .accessibilityIdentifier("micMode")
189 }.accessibilityElement(children: .combine)
190 Button("Change Mic Mode", systemImage: "waveform") { micModes.showPicker() }
191 .buttonStyle(.bordered)
192 .accessibilityIdentifier("changeMicMode")
193 .accessibilityHint("Opens the system Mic Mode picker.")
194 Text("Voice Isolation filters out wind, typing and room echo. The choice is kept by iOS, not Calls.")
195 .font(.footnote).foregroundStyle(.secondary)
196 .fixedSize(horizontal: false, vertical: true)
197 }
198 }
199 #endif
200
201 #if os(macOS)
202 /// Microphone and speaker on the call's own audio device module, so a
203 /// choice here moves this call and leaves the Mac's system setting
204 /// alone. "System default" is always the first entry, and follows macOS.
205 private var macAudio: some View {
206 VStack(alignment: .leading, spacing: 12) {
207 if !audio.inputs.isEmpty {
208 picker(
209 "Microphone",
210 selection: Binding(
211 get: { audio.currentInput },
212 set: { id in
213 guard let id, id != audio.currentInput else { return }
214 do {
215 try audio.use(input: id)
216 call.noteDevice("")
217 } catch { call.noteDevice(error.localizedDescription) }
218 }),
219 options: audio.inputs.map { ($0.id, $0.name) }, identifier: "microphonePicker")
220 }
221 InputChannelPicker(audio: audio)
222 if !audio.outputs.isEmpty {
223 picker(
224 "Speaker",
225 selection: Binding(
226 get: { audio.currentOutput },
227 set: { id in
228 guard let id, id != audio.currentOutput else { return }
229 do {
230 try audio.use(output: id)
231 call.noteDevice("")
232 } catch { call.noteDevice(error.localizedDescription) }
233 }),
234 options: audio.outputs.map { ($0.id, $0.name) }, identifier: "speakerPicker")
235 }
236 if !audio.inputs.isEmpty || !audio.outputs.isEmpty {
237 Text("Calls remembers these for next time.")
238 .font(.footnote).foregroundStyle(.secondary)
239 }
240 if !audio.routeNote.isEmpty {
241 Label(audio.routeNote, systemImage: "info.circle")
242 .font(.callout).foregroundStyle(.secondary)
243 .fixedSize(horizontal: false, vertical: true)
244 .accessibilityIdentifier("routeNote")
245 }
246 }
247 }
248 #endif
249
250 /// Said as what it does for the far side, since that is who hears it.
251 private var noiseToggle: some View {
252 VStack(alignment: .leading, spacing: 4) {
253 Toggle("Reduce background noise", isOn: $call.reduceNoise)
254 .accessibilityIdentifier("reduceNoise")
255 Text("Takes out typing, wind and room noise before others hear you.")
256 .font(.footnote).foregroundStyle(.secondary)
257 .fixedSize(horizontal: false, vertical: true)
258 }
259 }
260
261 /// Spec §15.30: Auto, Low bandwidth or Audio only, remembered.
262 private var videoQualitySection: some View {
263 VStack(alignment: .leading, spacing: 4) {
264 Picker("Video quality", selection: $call.videoQuality) {
265 ForEach(VideoQualitySetting.allCases) { setting in
266 Text(setting.title).tag(setting)
267 }
268 }
269 .accessibilityIdentifier("videoQuality")
270 #if os(macOS)
271 .pickerStyle(.menu)
272 #endif
273 Text(VideoQualitySetting.explanation)
274 .font(.footnote).foregroundStyle(.secondary)
275 .fixedSize(horizontal: false, vertical: true)
276 }
277 }
278
279 /// "Optimise for", and while this app is sharing, one line saying how
280 /// the screen is actually leaving — the answer to "it isn't keeping up".
281 private var screenSection: some View {
282 VStack(alignment: .leading, spacing: 4) {
283 Picker("Optimise shared screen for", selection: $call.screenMode) {
284 ForEach(ScreenShareMode.allCases) { mode in
285 Text(mode.title).tag(mode)
286 }
287 }
288 .accessibilityIdentifier("screenMode")
289 #if os(macOS)
290 .pickerStyle(.menu)
291 #endif
292 Text(call.screenMode.explanation)
293 .font(.footnote).foregroundStyle(.secondary)
294 .fixedSize(horizontal: false, vertical: true)
295 }
296 }
297
298 /// The panel's foot: a warning line only when something is wrong, and
299 /// the ⓘ that opens the full readout. The readout used to fill the
300 /// bottom of the panel all the time; most of the time it said all is
301 /// well, at length.
302 private var audioFoot: some View {
303 HStack(alignment: .firstTextBaseline, spacing: 8) {
304 if let warning = AudioWarning.line(
305 health: call.audioHealth, processing: call.audioProcessing, reduceNoise: call.reduceNoise)
306 {
307 Label(warning, systemImage: "exclamationmark.triangle.fill")
308 .font(.callout).foregroundStyle(.orange)
309 .fixedSize(horizontal: false, vertical: true)
310 .accessibilityIdentifier("audioWarning")
311 }
312 Spacer(minLength: 0)
313 Button("Audio details", systemImage: "info.circle") { showingAudioDetails.toggle() }
314 .labelStyle(.iconOnly)
315 .buttonStyle(.borderless)
316 .help("Audio details")
317 .accessibilityIdentifier("audioDetails")
318 .popover(isPresented: $showingAudioDetails) {
319 ScrollView { audioReadout.padding(16) }
320 .frame(minWidth: 280, idealWidth: 320, maxWidth: 360, maxHeight: 420)
321 .fixedSize(horizontal: false, vertical: true)
322 #if os(iOS)
323 .presentationCompactAdaptation(.popover)
324 #endif
325 }
326 }
327 }
328
329 private var audioReadout: some View {
330 VStack(alignment: .leading, spacing: 4) {
331 Text("Audio health").font(.headline)
332 if let health = call.audioHealth {
333 Text(health.summary)
334 .font(.callout).foregroundStyle(.secondary)
335 .fixedSize(horizontal: false, vertical: true)
336 .accessibilityIdentifier("audioHealth")
337 } else {
338 Text("Measuring…").font(.callout).foregroundStyle(.secondary)
339 .accessibilityIdentifier("audioHealth")
340 }
341 if let processing = call.audioProcessing {
342 Text(processing.summary)
343 .font(.callout).foregroundStyle(.secondary)
344 .fixedSize(horizontal: false, vertical: true)
345 .accessibilityIdentifier("audioProcessing")
346 }
347 CopyAudioDiagnosticsButton(title: "Copy call diagnostics") { call.audioDiagnosticsText() }
348 .padding(.top, 6)
349 // Beside the copy, the same diagnostics sent rather than pasted
350 // (spec §15.26). The popover goes first — and on iPhone the Devices
351 // sheet with it — so the report's sheet opens over the call.
352 ReportProblemButton {
353 showingAudioDetails = false
354 #if os(iOS)
355 dismiss()
356 #endif
357 let call = self.call
358 DispatchQueue.main.asyncAfter(deadline: .now() + Self.handOver) { call.reportProblem() }
359 }
360 .buttonStyle(.borderless)
361 .font(.footnote)
362 .disabled(!call.canReportProblem)
363 if call.sharingScreen {
364 Text("Screen sharing").font(.headline).padding(.top, 6)
365 Text(call.screenReport?.summary ?? "Screen: starting…")
366 .font(.callout).foregroundStyle(.secondary)
367 .fixedSize(horizontal: false, vertical: true)
368 .accessibilityIdentifier("screenReport")
369 if !call.screenDetail.isEmpty {
370 Text(call.screenDetail)
371 .font(.callout).foregroundStyle(.secondary)
372 .fixedSize(horizontal: false, vertical: true)
373 .accessibilityIdentifier("screenDetail")
374 }
375 }
376 }
377 .textSelection(.enabled)
378 }
379
380 private func row(_ label: String, _ value: String) -> some View {
381 VStack(alignment: .leading, spacing: 2) {
382 Text(label).font(.headline)
383 Text(value).font(.callout).foregroundStyle(.secondary).textSelection(.enabled)
384 }.accessibilityElement(children: .combine)
385 }
386
387 private func picker(
388 _ label: String, selection: Binding<String?>, options: [(String, String)], identifier: String
389 ) -> some View {
390 Picker(label, selection: selection) {
391 // While a camera is switching there is no current one; say so
392 // rather than show a device the call is not on.
393 if selection.wrappedValue == nil {
394 Text("Choose a device").tag(Optional<String>.none)
395 }
396 ForEach(options, id: \.0) { option in
397 Text(option.1).tag(Optional(option.0))
398 }
399 }
400 .accessibilityIdentifier(identifier)
401 #if os(macOS)
402 .pickerStyle(.menu)
403 #endif
404 }
405}
406
407/// What the panel's Camera row shows, as a rule the tests can hold.
408enum CameraRowState: Equatable {
409 /// A capture with nothing to choose (the interop gate's synthetic one).
410 case hidden
411 /// A real camera was expected and none is connected.
412 case noCamera
413 /// The picker, with a plain-words line when the camera is not working,
414 /// and "Try again" when trying again could help.
415 case picker(line: String?, retry: Bool)
416
417 init(cameras: Int, offers: Bool, status: CameraStatus?) {
418 if cameras == 0 {
419 self = offers ? .noCamera : .hidden
420 return
421 }
422 switch status {
423 case .noCamera?, .live?, nil:
424 self = .picker(line: nil, retry: false)
425 case .starting?:
426 self = .picker(line: status?.panelText, retry: false)
427 case .noSignal?, .disconnected?, .failed?:
428 self = .picker(line: status?.panelText, retry: true)
429 }
430 }
431
432 var offersRetry: Bool {
433 switch self {
434 case .hidden: return false
435 case .noCamera: return true
436 case .picker(_, let retry): return retry
437 }
438 }
439}
440