| 1 | import AppKit |
| 2 | @_spi(Fixtures) import CallsKit |
| 3 | import Foundation |
| 4 | import LiveKitWebRTC |
| 5 | import ScreenCaptureKit |
| 6 | import SwiftUI |
| 7 | |
| 8 | // A separate test executable: synthetic video and fixture credentials are never |
| 9 | // compiled into CallsMac. Input travels on stdin, not argv or a saved file. |
| 10 | struct Input: Decodable { |
| 11 | let origin: String |
| 12 | let room: String |
| 13 | let cookies: String |
| 14 | let chatSnapshot: String? |
| 15 | let invitation: String? |
| 16 | } |
| 17 | @main struct Interop { |
| 18 | @MainActor static var screen: SyntheticScreen? |
| 19 | @MainActor static var display: DisplayCapture? |
| 20 | @MainActor static var webrtcLogger: LKRTCCallbackLogger? |
| 21 | @MainActor static let cameras = SyntheticCameras() |
| 22 | @MainActor static var stage: StagePreview? |
| 23 | // A defaults domain of its own, so the gate's camera choices are never |
| 24 | // remembered into anyone's real preferences. |
| 25 | @MainActor static let camera = ManagedCamera( |
| 26 | backend: cameras, defaults: UserDefaults(suiteName: "calls-interop-\(UUID().uuidString)")!) |
| 27 | @MainActor static func main() async { |
| 28 | if CommandLine.arguments.count == 3, CommandLine.arguments[1] == "--lobby-snapshots" { |
| 29 | do { try await LobbySnapshots.save(to: CommandLine.arguments[2]) } catch { exit(1) } |
| 30 | return |
| 31 | } |
| 32 | if CommandLine.arguments.count == 3, CommandLine.arguments[1] == "--call-snapshots" { |
| 33 | do { |
| 34 | try await CallSnapshots.save(to: URL(fileURLWithPath: CommandLine.arguments[2])) |
| 35 | } catch { exit(1) } |
| 36 | return |
| 37 | } |
| 38 | if CommandLine.arguments.count == 3, CommandLine.arguments[1] == "--connecting-snapshots" { |
| 39 | do { |
| 40 | try await CallSnapshots.saveConnecting(to: URL(fileURLWithPath: CommandLine.arguments[2])) |
| 41 | } catch { exit(1) } |
| 42 | return |
| 43 | } |
| 44 | if CommandLine.arguments.count == 3, CommandLine.arguments[1] == "--glass-snapshots" { |
| 45 | do { |
| 46 | try await CallSnapshots.saveGlass(to: URL(fileURLWithPath: CommandLine.arguments[2])) |
| 47 | } catch { exit(1) } |
| 48 | return |
| 49 | } |
| 50 | if CommandLine.arguments.count == 3, CommandLine.arguments[1] == "--speaker-snapshots" { |
| 51 | do { |
| 52 | try await CallSnapshots.saveSpeaker(to: URL(fileURLWithPath: CommandLine.arguments[2])) |
| 53 | } catch { exit(1) } |
| 54 | return |
| 55 | } |
| 56 | if CommandLine.arguments.count == 2, CommandLine.arguments[1] == "--mini-clicks" { |
| 57 | // Under NSApplication's own run loop, as the app is: the surface |
| 58 | // tracks a press with a nested event loop, which Swift's async main |
| 59 | // alone does not survive. |
| 60 | NSApplication.shared.setActivationPolicy(.accessory) |
| 61 | Task { @MainActor in |
| 62 | let call = Call(playAudio: false) |
| 63 | CallFixture.grid.apply(to: call) |
| 64 | let results = await MiniWindowProbe.run(call: call) |
| 65 | for r in results { print((r.passed ? "ok " : "FAIL ") + r.name + (r.passed ? "" : " — " + r.detail)) } |
| 66 | print("mini-clicks: \(results.filter(\.passed).count) of \(results.count) presses did what they should") |
| 67 | fflush(stdout) |
| 68 | exit(results.allSatisfy(\.passed) ? 0 : 1) |
| 69 | } |
| 70 | NSApplication.shared.run() |
| 71 | } |
| 72 | if CommandLine.arguments.count == 3, CommandLine.arguments[1] == "--stage-snapshots" { |
| 73 | do { |
| 74 | try await StageSnapshots.save(to: URL(fileURLWithPath: CommandLine.arguments[2])) |
| 75 | } catch { exit(1) } |
| 76 | return |
| 77 | } |
| 78 | if CommandLine.arguments.count >= 3, CommandLine.arguments[1] == "--portrait-snapshots" { |
| 79 | do { |
| 80 | try await PortraitSnapshots.save( |
| 81 | to: URL(fileURLWithPath: CommandLine.arguments[2]), |
| 82 | before: CommandLine.arguments.dropFirst(3).contains("before")) |
| 83 | } catch { exit(1) } |
| 84 | return |
| 85 | } |
| 86 | if CommandLine.arguments.count == 4, CommandLine.arguments[1] == "--pip-snapshots" { |
| 87 | do { |
| 88 | try await PiPSnapshots.save( |
| 89 | to: URL(fileURLWithPath: CommandLine.arguments[2]), tag: CommandLine.arguments[3]) |
| 90 | } catch { exit(1) } |
| 91 | return |
| 92 | } |
| 93 | if CommandLine.arguments.count == 3, CommandLine.arguments[1] == "--settings-snapshots" { |
| 94 | do { |
| 95 | try await SettingsSnapshots.save(to: URL(fileURLWithPath: CommandLine.arguments[2])) |
| 96 | } catch { exit(1) } |
| 97 | return |
| 98 | } |
| 99 | if CommandLine.arguments.count == 3, CommandLine.arguments[1] == "--bar-layout" { |
| 100 | exit(await BarLayoutHarness.run(to: URL(fileURLWithPath: CommandLine.arguments[2])) ? 0 : 1) |
| 101 | } |
| 102 | if CommandLine.arguments.count == 2, CommandLine.arguments[1] == "--audio-start-stall" { |
| 103 | exit(await AudioStartStallHarness.run() ? 0 : 1) |
| 104 | } |
| 105 | if CommandLine.arguments.count == 2, CommandLine.arguments[1] == "--audio-selftest" { |
| 106 | exit(await AudioSelfTestHarness.run() ? 0 : 1) |
| 107 | } |
| 108 | guard let line = readLine(), |
| 109 | let input = try? JSONDecoder().decode(Input.self, from: Data(line.utf8)), |
| 110 | let url = URL(string: input.origin), url.scheme == "http", url.host == "127.0.0.1" |
| 111 | else { exit(2) } |
| 112 | // Decoders the gate can wedge (spec §15.22), set before the call's |
| 113 | // factory is made; only for the scenarios that ask, so every other |
| 114 | // gate decodes exactly as the apps do. |
| 115 | if ProcessInfo.processInfo.environment["CALLS_DECODER_WEDGE"] == "1" { DecoderWedge.enabled = true } |
| 116 | let call = Call(playAudio: false, audioInput: SyntheticVoice()) |
| 117 | if ProcessInfo.processInfo.environment["CALLS_SCREEN_WATCHDOG"] == "0" { Call.screenWatchdogEnabled = false } |
| 118 | // Quality reports every N seconds rather than thirty (spec §15.26), so |
| 119 | // the gate sees one inside its call. A number of seconds, at least one. |
| 120 | if let seconds = ProcessInfo.processInfo.environment["CALLS_QUALITY_INTERVAL"].flatMap(Double.init), seconds >= 1 { |
| 121 | Call.qualityInterval = seconds |
| 122 | } |
| 123 | // The automatic report (spec §15.29) on the first window that may send |
| 124 | // one, whatever the call is like, so the gate sees one reach the log: |
| 125 | // the trigger to name, one of "freezes", "rtt", "reconnecting", |
| 126 | // "screen". Anything else is ignored. |
| 127 | if let trigger = ProcessInfo.processInfo.environment["CALLS_AUTO_REPORT_TEST"], |
| 128 | AutoReportRules.triggers.contains(trigger) |
| 129 | { |
| 130 | Call.autoReportForTest = trigger |
| 131 | } |
| 132 | // WebRTC's own log, filtered to the video encoder, into a file: for |
| 133 | // diagnosing the gate's screen scenarios by hand. Never credentials: |
| 134 | // the filter keeps encoder lines only. |
| 135 | if let base = ProcessInfo.processInfo.environment["CALLS_WEBRTC_LOG"] { |
| 136 | let path = "\(base).\(getpid())" |
| 137 | FileManager.default.createFile(atPath: path, contents: nil) |
| 138 | let handle = FileHandle(forWritingAtPath: path) |
| 139 | let logger = LKRTCCallbackLogger() |
| 140 | logger.severity = .info |
| 141 | let everything = ProcessInfo.processInfo.environment["CALLS_WEBRTC_LOG_ALL"] == "1" |
| 142 | logger.start { message in |
| 143 | let lower = message.lowercased() |
| 144 | guard everything || ["h264", "encod", "videotoolbox", "vtcompression", "resolution", "adapt", "quality"].contains(where: lower.contains) |
| 145 | else { return } |
| 146 | let stamp = String(format: "%.3f ", Date().timeIntervalSince1970) |
| 147 | handle?.write(Data((stamp + message).utf8)) |
| 148 | } |
| 149 | Interop.webrtcLogger = logger |
| 150 | } |
| 151 | // 0.4.1's motion sizing, without the H.264 level cap, for measuring it. |
| 152 | if ProcessInfo.processInfo.environment["CALLS_SCREEN_UNCAPPED"] == "1" { ScreenSendPolicy.levelCapped = false } |
| 153 | // The gate's ICE block (ICETestBlock) from the start, before any |
| 154 | // connection exists: a peer joining whose connections cannot come up. |
| 155 | if let ms = ProcessInfo.processInfo.environment["CALLS_TEST_ICE_BLOCK_MS"].flatMap(Double.init), ms > 0 { |
| 156 | call.blockICEForTest(ms: ms) |
| 157 | } |
| 158 | // §15.28: the stand-in for an app from before it, which neither mends |
| 159 | // its connections nor says which app it is; and the version this |
| 160 | // bundle-less executable says it is otherwise. |
| 161 | if ProcessInfo.processInfo.environment["CALLS_AUTO_RECOVERY"] == "0" { Call.autoRecovery = false } |
| 162 | if ProcessInfo.processInfo.environment["CALLS_TEST_NO_CLIENT"] == "1" { Call.sendsClientInfo = false } |
| 163 | Call.clientVersion = ProcessInfo.processInfo.environment["CALLS_TEST_CLIENT_VERSION"] ?? "9.9.9" |
| 164 | let preview = input.chatSnapshot.map { ChatPreview(call: call, path: $0) } |
| 165 | do { |
| 166 | try await call.join( |
| 167 | origin: input.origin, room: input.room, cookies: input.cookies, capture: Interop.camera) |
| 168 | } catch { |
| 169 | print("FAIL native start") |
| 170 | exit(1) |
| 171 | } |
| 172 | Task.detached { |
| 173 | while let command = readLine() { |
| 174 | if command == "leave" { |
| 175 | await call.leave() |
| 176 | exit(0) |
| 177 | } |
| 178 | if command == "mute" { |
| 179 | await call.mute() |
| 180 | print("{\"muted\":\(await call.muted)}") |
| 181 | fflush(stdout) |
| 182 | } |
| 183 | // Portrait video (2026-10-21): the full-window call, live, off |
| 184 | // screen, and where its pictures are placed. |
| 185 | if command.hasPrefix("stage-open") { |
| 186 | let dims = command.split(separator: " ").dropFirst().compactMap { Double($0) } |
| 187 | let size = dims.count == 2 ? NSSize(width: dims[0], height: dims[1]) : NSSize(width: 1000, height: 640) |
| 188 | await MainActor.run { |
| 189 | if let stage = Interop.stage { stage.resize(size) } else { Interop.stage = StagePreview(call: call, size: size) } |
| 190 | } |
| 191 | print("{\"stageOpen\":true}") |
| 192 | fflush(stdout) |
| 193 | } |
| 194 | if command == "placement" { |
| 195 | let line = await MainActor.run { Interop.stage?.placements() ?? "{}" } |
| 196 | print(line) |
| 197 | fflush(stdout) |
| 198 | } |
| 199 | if command == "chat" { |
| 200 | await call.sendChat("native chat probe") |
| 201 | print("{\"chatCommandHandled\":true}") |
| 202 | fflush(stdout) |
| 203 | } |
| 204 | if command == "snapshot" { |
| 205 | let saved = await preview?.save() ?? false |
| 206 | _ = await preview?.saveCall(call: call) |
| 207 | print("{\"chatSnapshotSaved\":\(saved)}") |
| 208 | fflush(stdout) |
| 209 | } |
| 210 | if command == "share" { |
| 211 | await call.loadInvitation() |
| 212 | let invitation = await call.invitationURL?.absoluteString |
| 213 | let refused = await !call.invitationError.isEmpty |
| 214 | let ready = invitation != nil && invitation == input.invitation |
| 215 | print("{\"invitationReady\":\(ready),\"invitationRefused\":\(refused)}") |
| 216 | fflush(stdout) |
| 217 | } |
| 218 | if command == "audio-default" || command == "audio-missing" { |
| 219 | let succeeded = await MainActor.run { |
| 220 | do { |
| 221 | try call.audio.use(input: command == "audio-default" ? "" : "no-such-device") |
| 222 | try call.audio.use(output: "") |
| 223 | return true |
| 224 | } catch { return false } |
| 225 | } |
| 226 | print("{\"audioSwitched\":\(succeeded)}") |
| 227 | fflush(stdout) |
| 228 | } |
| 229 | // The camera stops sending, and the watchdog has to notice and |
| 230 | // restart it: frames come back on the next open. |
| 231 | if command == "camera-stall" { |
| 232 | await MainActor.run { Interop.cameras.stalled = true } |
| 233 | print("{\"cameraStalled\":true}") |
| 234 | fflush(stdout) |
| 235 | } |
| 236 | if command.hasPrefix("camera ") { |
| 237 | let id = String(command.dropFirst("camera ".count)) |
| 238 | await call.useCamera(id) |
| 239 | let now = await call.currentCamera ?? "" |
| 240 | let note = await call.deviceNote |
| 241 | print("{\"camera\":\"\(now)\",\"cameraRefused\":\(note.isEmpty ? "false" : "true")}") |
| 242 | fflush(stdout) |
| 243 | } |
| 244 | // §5.4, sending. `screen-end` is the capture ending on its own, |
| 245 | // which is the path the system's stop control takes. |
| 246 | if command == "screen-on" { |
| 247 | let screen = await SyntheticScreen() |
| 248 | await MainActor.run { Interop.screen = screen } |
| 249 | await call.shareScreen(screen) |
| 250 | let on = await call.sharingScreen |
| 251 | print("{\"screenSharing\":\(on)}") |
| 252 | fflush(stdout) |
| 253 | } |
| 254 | // "Optimise for", as the device panel sets it. |
| 255 | if command.hasPrefix("screen-mode ") { |
| 256 | let mode = ScreenShareMode(rawValue: String(command.dropFirst("screen-mode ".count))) |
| 257 | if let mode { await MainActor.run { call.screenMode = mode } } |
| 258 | print("{\"screenMode\":\"\(mode?.rawValue ?? "")\"}") |
| 259 | fflush(stdout) |
| 260 | } |
| 261 | // The motion gate: a 1080p page scrolling at 30 fps. |
| 262 | if command == "screen-motion" { |
| 263 | let screen = await SyntheticScreen(motion: true) |
| 264 | await MainActor.run { Interop.screen = screen } |
| 265 | await call.shareScreen(screen) |
| 266 | let on = await call.sharingScreen |
| 267 | print("{\"screenSharing\":\(on)}") |
| 268 | fflush(stdout) |
| 269 | } |
| 270 | // A still page repeated once a second as the Mac's capture repeats |
| 271 | // one, changed every N seconds (0: never): `screen-still 0`. |
| 272 | if command.hasPrefix("screen-still") { |
| 273 | let every = Double(command.split(separator: " ").dropFirst().first ?? "") ?? 0 |
| 274 | let screen = await SyntheticScreen(stillChangingEvery: every) |
| 275 | await MainActor.run { Interop.screen = screen } |
| 276 | await call.shareScreen(screen) |
| 277 | let on = await call.sharingScreen |
| 278 | print("{\"screenSharing\":\(on)}") |
| 279 | fflush(stdout) |
| 280 | } |
| 281 | // A thin uplink, for the same gate: `uplink 1200000`, or `uplink 0` |
| 282 | // to lift it. |
| 283 | if command.hasPrefix("uplink ") { |
| 284 | let bps = Int(command.dropFirst("uplink ".count)) ?? 0 |
| 285 | await call.limitUplink(bps > 0 ? bps : nil) |
| 286 | print("{\"uplink\":\(bps)}") |
| 287 | fflush(stdout) |
| 288 | } |
| 289 | if command == "screen-off" { |
| 290 | await call.stopSharingScreen() |
| 291 | print("{\"screenSharing\":false}") |
| 292 | fflush(stdout) |
| 293 | } |
| 294 | // The synthetic screen stops producing anything, as a capture |
| 295 | // with every surface held does; the watchdog has to restart it. |
| 296 | if command == "screen-stall" { |
| 297 | await MainActor.run { Interop.screen?.stall() } |
| 298 | print("{\"screenStalled\":true}") |
| 299 | fflush(stdout) |
| 300 | } |
| 301 | // Every screen encoding switched off behind the watchdog's back: |
| 302 | // frames go in and nothing comes out. |
| 303 | if command == "screen-encoder-stall" { |
| 304 | await call.stallScreenEncoderForTest() |
| 305 | print("{\"encoderStalled\":true}") |
| 306 | fflush(stdout) |
| 307 | } |
| 308 | // The real thing: this Mac's main display through ScreenCaptureKit |
| 309 | // and the hardware encoder, at the given queue depth. Needs Screen |
| 310 | // Recording permission for the process running the gate. |
| 311 | if command.hasPrefix("screen-display") { |
| 312 | let depth = Int(command.split(separator: " ").dropFirst().first ?? "") ?? 6 |
| 313 | await MainActor.run { MacScreenCapture.queueDepth = depth } |
| 314 | let display = await DisplayCapture() |
| 315 | await MainActor.run { Interop.display = display } |
| 316 | await call.shareScreen(display) |
| 317 | let on = await call.sharingScreen |
| 318 | print("{\"screenSharing\":\(on)}") |
| 319 | fflush(stdout) |
| 320 | } |
| 321 | // The receiving side's watch treats every screen as frozen. |
| 322 | if command.hasPrefix("screen-freeze-test ") { |
| 323 | let ms = Double(command.dropFirst("screen-freeze-test ".count)) ?? 0 |
| 324 | await call.freezeScreenWatchForTest(seconds: ms / 1000) |
| 325 | print("{\"screenFrozenForTest\":true}") |
| 326 | fflush(stdout) |
| 327 | } |
| 328 | // §15.22: this app's screen decoders stop putting out pictures |
| 329 | // while packets keep arriving — a wedge no keyframe mends and a |
| 330 | // new transceiver does. `sticky` wedges the new ones too. |
| 331 | if command == "screen-decoder-wedge" || command == "screen-decoder-wedge sticky" { |
| 332 | let n = DecoderWedge.wedgeScreens(sticky: command.hasSuffix("sticky")) |
| 333 | print("{\"decoderWedged\":\(n)}") |
| 334 | fflush(stdout) |
| 335 | } |
| 336 | if command == "screen-decoder-release" { |
| 337 | DecoderWedge.release() |
| 338 | print("{\"decoderReleased\":true}") |
| 339 | fflush(stdout) |
| 340 | } |
| 341 | // "Copy call diagnostics", as the panel would copy it. |
| 342 | if command == "diagnostics" { |
| 343 | let text = await call.audioDiagnosticsText() |
| 344 | if let data = try? JSONSerialization.data(withJSONObject: ["diagnostics": text]), |
| 345 | let line = String(data: data, encoding: .utf8) |
| 346 | { |
| 347 | print(line) |
| 348 | fflush(stdout) |
| 349 | } |
| 350 | } |
| 351 | // Every candidate either way leads nowhere for this long. |
| 352 | if command.hasPrefix("ice-block ") { |
| 353 | let ms = Double(command.dropFirst("ice-block ".count)) ?? 0 |
| 354 | await call.blockICEForTest(ms: ms) |
| 355 | print("{\"iceBlocked\":true}") |
| 356 | fflush(stdout) |
| 357 | } |
| 358 | if command == "screen-reshare-test" { |
| 359 | await call.reshareScreenForTest() |
| 360 | print("{\"reshared\":true}") |
| 361 | fflush(stdout) |
| 362 | } |
| 363 | if command == "screen-end" { |
| 364 | await Interop.screen?.end() |
| 365 | let on = await call.sharingScreen |
| 366 | print("{\"screenSharing\":\(on)}") |
| 367 | fflush(stdout) |
| 368 | } |
| 369 | if command == "share-snapshot" { |
| 370 | let saved = await preview?.saveInvitation(call: call) ?? false |
| 371 | print("{\"invitationSnapshotSaved\":\(saved)}") |
| 372 | fflush(stdout) |
| 373 | } |
| 374 | } |
| 375 | } |
| 376 | // Long enough for the member scenario, screens and all, and for the |
| 377 | // motion gate's three modes: the gate always says `leave` long before |
| 378 | // this runs out. |
| 379 | // CALLS_INTEROP_SECONDS for the soaks, which outlast that (§15.22). |
| 380 | let life = Int(ProcessInfo.processInfo.environment["CALLS_INTEROP_SECONDS"] ?? "") ?? 400 |
| 381 | for _ in 0..<life { |
| 382 | try? await Task.sleep(nanoseconds: 1_000_000_000) |
| 383 | let stats = await call.sampleStats() |
| 384 | if let data = try? JSONSerialization.data(withJSONObject: [ |
| 385 | "phase": call.state?.phase ?? "", "peer": call.state?.peer ?? "", "stats": stats, |
| 386 | "receivedChatProbe": call.chat.contains { $0.hasSuffix(": browser chat probe") }, |
| 387 | "sentChatProbe": call.chat.contains("You: native chat probe"), |
| 388 | "receivedChatCount": call.receivedChatCount, |
| 389 | // §15.19: remote peers this app has been told are muted. |
| 390 | "remoteMuted": (call.state?.peers ?? []).filter { |
| 391 | $0.peer != call.state?.peer && call.isMuted($0.peer) |
| 392 | }.count, |
| 393 | // §5.4: what the stage would caption each screen, in the order |
| 394 | // they started. The words, not a count: the caption is the only |
| 395 | // place a screen says whose it is. |
| 396 | "screenCaptions": call.screens.map { screenCaption(call.name(of: $0)) }, |
| 397 | "sharingScreen": call.sharingScreen, |
| 398 | // §15.22: the sharer's notice, word for word. |
| 399 | "screenRecovery": call.screenRecovery, |
| 400 | // §15.23: "Reconnecting…" said for the call, and on how many tiles. |
| 401 | "reconnecting": call.reconnecting, |
| 402 | // The call's status line, word for word ("A participant's media |
| 403 | // could not connect." among them). |
| 404 | "status": call.status, |
| 405 | // Each remote peer's client as the roster has it (§15.28). |
| 406 | "clients": Dictionary( |
| 407 | uniqueKeysWithValues: (call.state?.peers ?? []).filter { $0.peer != call.state?.peer }.map { |
| 408 | ($0.peer, $0.client ?? "") |
| 409 | }), |
| 410 | // What each remote tile says above the name, word for word. |
| 411 | "notices": Dictionary( |
| 412 | uniqueKeysWithValues: (call.state?.peers ?? []).filter { $0.peer != call.state?.peer }.map { |
| 413 | ($0.peer, call.levels.peer($0.peer).notices) |
| 414 | }), |
| 415 | "reconnectingPeers": call.reconnectingPeers.count, |
| 416 | "syntheticScreenFrames": Interop.screen?.produced ?? 0, |
| 417 | "cameraOpens": Interop.camera.opens, |
| 418 | "cameraStatus": { |
| 419 | switch call.cameraStatus { |
| 420 | case .live?: return "live" |
| 421 | case .starting?: return "starting" |
| 422 | case .noSignal?: return "no-signal" |
| 423 | case .disconnected?: return "disconnected" |
| 424 | case .failed?: return "failed" |
| 425 | case .noCamera?: return "none" |
| 426 | case nil: return "" |
| 427 | } |
| 428 | }(), |
| 429 | ]), let text = String(data: data, encoding: .utf8) { |
| 430 | print(text) |
| 431 | fflush(stdout) |
| 432 | } |
| 433 | } |
| 434 | await call.leave() |
| 435 | exit(0) |
| 436 | } |
| 437 | } |
| 438 | |
| 439 | /// The main display, captured by the shipping MacScreenCapture with no |
| 440 | /// picker: the gate's way to put ScreenCaptureKit, the frame handling and |
| 441 | /// the hardware encoder under test together. |
| 442 | @MainActor final class DisplayCapture: ScreenCapture { |
| 443 | let mac = MacScreenCapture() |
| 444 | func start(source: RTCVideoSource, ended: @escaping @MainActor () -> Void) async throws { |
| 445 | let content = try await SCShareableContent.excludingDesktopWindows(false, onScreenWindowsOnly: true) |
| 446 | guard let display = content.displays.first else { throw CancellationError() } |
| 447 | try await mac.start(display: display, source: source, ended: ended) |
| 448 | } |
| 449 | func stop() { mac.stop() } |
| 450 | var counts: ScreenCaptureCounts { mac.counts } |
| 451 | func restart() async -> Bool { await mac.restart() } |
| 452 | var frameSize: (width: Int, height: Int)? { mac.frameSize } |
| 453 | } |
| 454 | |
| 455 | // Render the shipping chat view against real received messages. This fixture |
| 456 | // window sits off-screen and never activates or interrupts the user's call. |
| 457 | @MainActor private final class ChatPreview { |
| 458 | let window: NSWindow |
| 459 | let view: NSHostingView<AnyView> |
| 460 | let path: String |
| 461 | init(call: Call, path: String) { |
| 462 | NSApplication.shared.setActivationPolicy(.prohibited) |
| 463 | self.path = path |
| 464 | view = NSHostingView( |
| 465 | rootView: AnyView( |
| 466 | ChatView(call: call).padding(12).background(Color.white).environment(\.colorScheme, .light)) |
| 467 | ) |
| 468 | window = NSWindow( |
| 469 | contentRect: NSRect(x: -2000, y: -2000, width: 600, height: 200), |
| 470 | styleMask: [.borderless], backing: .buffered, defer: false) |
| 471 | window.isReleasedWhenClosed = false |
| 472 | window.contentView = view |
| 473 | window.orderFront(nil) |
| 474 | } |
| 475 | func save() -> Bool { |
| 476 | view.layoutSubtreeIfNeeded() |
| 477 | guard let bitmap = view.bitmapImageRepForCachingDisplay(in: view.bounds) else { return false } |
| 478 | view.cacheDisplay(in: view.bounds, to: bitmap) |
| 479 | guard let data = bitmap.representation(using: .png, properties: [:]) else { return false } |
| 480 | do { |
| 481 | try data.write(to: URL(fileURLWithPath: path)) |
| 482 | return true |
| 483 | } catch { return false } |
| 484 | } |
| 485 | func saveCall(call: Call) async -> Bool { |
| 486 | var saved = true |
| 487 | for (name, grid, chat) in [ |
| 488 | ("call-focus.png", false, false), |
| 489 | ("call-chat.png", false, true), |
| 490 | ("call-grid.png", true, false), |
| 491 | ] { |
| 492 | view.rootView = AnyView( |
| 493 | MacCallView(call: call, grid: grid, showingChat: chat, style: .classic, leave: {}).id(name) |
| 494 | .padding(20).tint(CallsAppearance.accent).background(Color.white) |
| 495 | .environment(\.colorScheme, .light)) |
| 496 | window.setContentSize(NSSize(width: 900, height: 540)) |
| 497 | try? await Task.sleep(for: .milliseconds(300)) |
| 498 | saved = saveImage(named: name) && saved |
| 499 | } |
| 500 | view.rootView = AnyView( |
| 501 | VStack(alignment: .leading, spacing: 0) { |
| 502 | Text("Devices").font(.headline).padding(.horizontal, 16).padding(.top, 16) |
| 503 | DevicePanel(call: call) |
| 504 | Spacer(minLength: 0) |
| 505 | }.frame(width: 300) |
| 506 | .background(Color.white).environment(\.colorScheme, .light)) |
| 507 | window.setContentSize(NSSize(width: 300, height: 340)) |
| 508 | try? await Task.sleep(for: .milliseconds(300)) |
| 509 | saved = saveImage(named: "call-devices.png") && saved |
| 510 | view.rootView = AnyView( |
| 511 | ChatView(call: call).padding(12) |
| 512 | .background(Color.white).environment(\.colorScheme, .light)) |
| 513 | window.setContentSize(NSSize(width: 600, height: 200)) |
| 514 | return saved |
| 515 | } |
| 516 | private func saveImage(named name: String) -> Bool { |
| 517 | view.layoutSubtreeIfNeeded() |
| 518 | guard let bitmap = view.bitmapImageRepForCachingDisplay(in: view.bounds) else { return false } |
| 519 | view.cacheDisplay(in: view.bounds, to: bitmap) |
| 520 | guard let data = bitmap.representation(using: .png, properties: [:]) else { return false } |
| 521 | let target = URL(fileURLWithPath: path).deletingLastPathComponent().appendingPathComponent(name) |
| 522 | do { |
| 523 | try data.write(to: target) |
| 524 | return true |
| 525 | } catch { return false } |
| 526 | } |
| 527 | func saveInvitation(call: Call) async -> Bool { |
| 528 | view.rootView = AnyView( |
| 529 | MeetingInvitationView(call: call, close: {}) |
| 530 | .background(Color.white).environment(\.colorScheme, .light)) |
| 531 | window.setContentSize(NSSize(width: 440, height: 340)) |
| 532 | try? await Task.sleep(for: .milliseconds(250)) |
| 533 | view.layoutSubtreeIfNeeded() |
| 534 | guard let bitmap = view.bitmapImageRepForCachingDisplay(in: view.bounds) else { return false } |
| 535 | view.cacheDisplay(in: view.bounds, to: bitmap) |
| 536 | guard let data = bitmap.representation(using: .png, properties: [:]) else { return false } |
| 537 | let target = URL(fileURLWithPath: path).deletingLastPathComponent().appendingPathComponent( |
| 538 | "share-meeting.png") |
| 539 | do { |
| 540 | try data.write(to: target) |
| 541 | return true |
| 542 | } catch { return false } |
| 543 | } |
| 544 | } |
| 545 | |