diff --git a/suixinkan/Features/DroneDock/Models/DroneDockLiveGeometry.swift b/suixinkan/Features/DroneDock/Models/DroneDockLiveGeometry.swift new file mode 100644 index 0000000..35b7ee5 --- /dev/null +++ b/suixinkan/Features/DroneDock/Models/DroneDockLiveGeometry.swift @@ -0,0 +1,33 @@ +import Foundation + +/// SDK 解码帧的原始尺寸和顺时针旋转角度,仅用于定位显示比例,不参与选流。 +struct DroneDockVideoFrameGeometry: Equatable, Sendable { + let width: Int + let height: Int + let rotation: Int +} + +/// 某一路图传在离散事件时的显示几何;不含凭证、视频内容或设备控制信息。 +struct DroneDockLiveGeometry: Equatable, Sendable { + let trigger: String + let role: String + let roomID: String + let streamID: String + let frame: DroneDockVideoFrameGeometry? + let containerWidth: Double + let containerHeight: Double + let hostWidth: Double + let hostHeight: Double + let isSelected: Bool + let sdkVersion: String? + + /// 复用任务页诊断通道;缺失帧信息保留 null,不将未知旋转或尺寸伪造成零。 + var diagnosticFields: [String: Any] { + ["trigger": trigger, "role": role, "room_id": roomID, "stream_id": streamID, + "frame_w": frame?.width as Any? ?? NSNull(), "frame_h": frame?.height as Any? ?? NSNull(), + "rotation": frame?.rotation as Any? ?? NSNull(), "frame_unit": "px", "rotation_unit": "degree", + "container_w": containerWidth, "container_h": containerHeight, + "host_w": hostWidth, "host_h": hostHeight, "container_unit": "pt", + "render_mode": "fit", "is_selected": isSelected, "sdk_version": sdkVersion as Any? ?? NSNull()] + } +} diff --git a/suixinkan/Features/DroneDock/ViewModels/DroneDockShootingTaskViewModel.swift b/suixinkan/Features/DroneDock/ViewModels/DroneDockShootingTaskViewModel.swift index 8376be1..ac13eb6 100644 --- a/suixinkan/Features/DroneDock/ViewModels/DroneDockShootingTaskViewModel.swift +++ b/suixinkan/Features/DroneDock/ViewModels/DroneDockShootingTaskViewModel.swift @@ -882,7 +882,7 @@ final class DroneDockShootingTaskViewModel { if resolvedDisplayPhase().0 == .shooting { return "请关注现场及实时画面。\n请勿关闭本页或息屏。" } switch resolvedDisplayPhase().0 { case .navigating: return "请留在拍摄点,等待无人机到达。" - case .ready: return "确认游客站位与取景后,即可开始拍摄。" + case .ready: return "确认游客站位与取景后开始" case .completed: return "素材已就绪,可前往素材库查看。" case .unknown: return "暂无法确认任务状态,请刷新后重试。" default: return usable(response?.executeGate?.message) ?? "请等待任务状态更新。" diff --git a/suixinkan/UI/DroneDock/DroneDockHomeViewController.swift b/suixinkan/UI/DroneDock/DroneDockHomeViewController.swift index 0071f7a..0bf90ec 100644 --- a/suixinkan/UI/DroneDock/DroneDockHomeViewController.swift +++ b/suixinkan/UI/DroneDock/DroneDockHomeViewController.swift @@ -2,7 +2,7 @@ import SnapKit import UIKit /// 正式机巢首页:朱工提供设备,张工提供订单与今日统计。 -final class DroneDockHomeViewController: BaseViewController { +final class DroneDockHomeViewController: GlobalLoadingPageViewController { /// 与演示数据源隔离的首页状态。 let viewModel: DroneDockHomeViewModel private let paymentControllerFactory: (() -> UIViewController)? @@ -117,6 +117,7 @@ final class DroneDockHomeViewController: BaseViewController { loadMoreTask?.cancel() isLoadingOrdersPage = false isRefreshing = true + setPageLoading(viewModel.response == nil && viewModel.ordersResponse == nil) refreshTask = Task { @MainActor [weak self] in guard let self else { return } let isInitialLoad = self.viewModel.response == nil && self.viewModel.ordersResponse == nil @@ -124,6 +125,7 @@ final class DroneDockHomeViewController: BaseViewController { await self.viewModel.refresh() guard !Task.isCancelled else { return } self.isRefreshing = false + self.setPageLoading(false) self.collectionView.refreshControl?.endRefreshing() self.applySnapshot(animated: true) { [weak self] in if isInitialLoad, let self { diff --git a/suixinkan/UI/DroneDock/DroneDockRemotePreparationViewController.swift b/suixinkan/UI/DroneDock/DroneDockRemotePreparationViewController.swift index 7ad0568..5cb07ec 100644 --- a/suixinkan/UI/DroneDock/DroneDockRemotePreparationViewController.swift +++ b/suixinkan/UI/DroneDock/DroneDockRemotePreparationViewController.swift @@ -3,7 +3,7 @@ import UIKit /// 展示准备信息并提交召唤;业务成功后携同一任务 ID 进入真实拍摄任务页。 @MainActor -final class DroneDockRemotePreparationViewController: BaseViewController { +final class DroneDockRemotePreparationViewController: GlobalLoadingPageViewController { /// 当前订单、准备信息及任务创建状态。 let viewModel: DroneDockPreparationViewModel @@ -162,6 +162,7 @@ final class DroneDockRemotePreparationViewController: BaseViewController { startPlaneStatusPolling() guard !isRefreshing else { return } isRefreshing = true + setPageLoading(viewModel.projectInfo == nil) refreshTask = Task { @MainActor [weak self] in guard let self else { return } let isInitialLoad = self.viewModel.projectInfo == nil @@ -169,6 +170,7 @@ final class DroneDockRemotePreparationViewController: BaseViewController { await self.viewModel.refresh() guard !Task.isCancelled else { return } self.isRefreshing = false + self.setPageLoading(false) self.refreshControl.endRefreshing() self.applySnapshot(animated: true) { [weak self] in guard let self else { return } diff --git a/suixinkan/UI/DroneDock/DroneDockShootingTaskViewController.swift b/suixinkan/UI/DroneDock/DroneDockShootingTaskViewController.swift index d29ff62..5f589a0 100644 --- a/suixinkan/UI/DroneDock/DroneDockShootingTaskViewController.swift +++ b/suixinkan/UI/DroneDock/DroneDockShootingTaskViewController.swift @@ -3,7 +3,7 @@ import UIKit /// 拍摄任务页:前台优先订阅快照、异常时 HTTP 兜底;自动开启图传,飞控仍由用户操作。 @MainActor -final class DroneDockShootingTaskViewController: BaseViewController { +final class DroneDockShootingTaskViewController: GlobalLoadingPageViewController { /// 入口传入的固定任务身份及只读状态,供导航协调和页面测试检查。 let viewModel: DroneDockShootingTaskViewModel /// 图传使用独立状态,刷新与播放不会影响任务阶段或固定布局。 @@ -287,11 +287,14 @@ final class DroneDockShootingTaskViewController: BaseViewController { telemetry.rainText, telemetry.signalText, telemetry.satelliteText], isStale: viewModel.isTelemetryStale, accessibilityPrefix: "drone.task.remote.metric", preservingStaleValues: true) let presentation = viewModel.presentation + setPageLoading(viewModel.response == nil && loading && presentation.phase != .navigating) let value = loading && viewModel.response == nil && presentation.phase != .navigating ? DroneDockTaskPresentation( phase: .loading, title: "正在获取任务状态", message: "正在读取当前拍摄任务", deviceStatus: "—", action: .none, actionTitle: nil, isActionEnabled: false) : presentation - statusView.apply(value, isRefreshing: loading, isPrimaryActionLoading: value.action == .resume - && (submittingCommands.contains(.resume) || viewModel.isCommandLoading(.resume))) + let primaryActionLoading = value.action == .resume + && (submittingCommands.contains(.resume) || viewModel.isCommandLoading(.resume)) + || value.action == .start && (isStartingAction || viewModel.isStartingShooting) + statusView.apply(value, isRefreshing: loading, isPrimaryActionLoading: primaryActionLoading) updateArrivalCountdown() safetyView.apply(model: viewModel, isSimulation: simulationRecordsProvider != nil, isInteractive: isPageVisible && isApplicationActive && !loading, diff --git a/suixinkan/UI/DroneDock/DroneDockTaskLiveView.swift b/suixinkan/UI/DroneDock/DroneDockTaskLiveView.swift index 75f1803..6f02245 100644 --- a/suixinkan/UI/DroneDock/DroneDockTaskLiveView.swift +++ b/suixinkan/UI/DroneDock/DroneDockTaskLiveView.swift @@ -232,6 +232,12 @@ final class DroneDockTaskLiveView: UIView { onDiagnosticEvent?(isNewSession ? "live.receiver.start_requested" : "live.receiver.rooms_updated", [ "receiver_session": sessionID.uuidString, "rooms": requestedRTC.map { ["role": $0.role, "room_id": $0.roomID] }]) + rtcPlayer.setGeometryHandler { [weak self] geometry in + guard let self, self.activeSessionID == sessionID else { return } + var fields = geometry.diagnosticFields + fields["receiver_session"] = sessionID.uuidString + self.onDiagnosticEvent?("live.geometry", fields) + } rtcPlayer.start(requestedRTC, in: rtcView) { [weak self] event in guard let self, self.activeSessionID == sessionID else { return } self.onPlaybackEvent?(event, sessionID) @@ -261,6 +267,7 @@ final class DroneDockTaskLiveView: UIView { "rooms": activeRTC.map { ["role": $0.role, "room_id": $0.roomID] }]) activeSessionID = nil activeRTC = [] + rtcPlayer.setGeometryHandler(nil) rtcPlayer.stop() } diff --git a/suixinkan/UI/DroneDock/DroneDockTaskReadyView.swift b/suixinkan/UI/DroneDock/DroneDockTaskReadyView.swift new file mode 100644 index 0000000..ef5f927 --- /dev/null +++ b/suixinkan/UI/DroneDock/DroneDockTaskReadyView.swift @@ -0,0 +1,260 @@ +import SnapKit +import UIKit + +/// 已到达待开拍面板:蓝色到达提示、分级文案及整行开拍按钮,倒计时只参与显示。 +@MainActor +final class DroneDockTaskReadyView: UIView { + /// 将已允许的主操作交给任务页面,组件自身不请求状态或发送开拍指令。 + var onPrimaryAction: (() -> Void)? + /// 当前排版比例,固定区域内不使用 transform 缩小点击范围。 + private(set) var effectiveScale: CGFloat = 1 + /// 固定区域较矮时收紧文字、图标和间距。 + private(set) var usesCompactLayout = false + + private let content = UIView() + private let header = UIView() + private let iconBackground = UIView() + private let icon = UIImageView(image: UIImage(systemName: "checkmark.circle.fill")) + private let titleLabel = DroneDockStyle.label(size: 23, weight: .semibold, color: UIColor(hex: 0x101523)) + private let promptLabel = DroneDockStyle.label(size: 18, weight: .medium, color: UIColor(hex: 0x101523)) + private let messageLabel = DroneDockStyle.label(size: 14, color: UIColor(hex: 0x6A79A0)) + private let actionButton = UIButton(type: .system) + private let activityIndicator = UIActivityIndicatorView(style: .medium) + private var presentation: DroneDockTaskPresentation? + private var countdownSeconds: Int? + private var identifiersActive = false + private var isPrimaryActionLoading = false + private var headerHeight: Constraint? + private var iconSize: Constraint? + private var textLeading: Constraint? + private var titleHeight: Constraint? + private var promptTop: Constraint? + private var promptHeight: Constraint? + private var messageTop: Constraint? + private var messageHeight: Constraint? + private var actionTop: Constraint? + private var actionHeight: Constraint? + + /// 创建与任务页固定状态区域配合的待开拍面板。 + override init(frame: CGRect) { + super.init(frame: frame) + setupUI() + setupConstraints() + } + + @available(*, unavailable) + required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } + + /// 保留展示模型中的真实限制说明和主操作许可,加载时仅显示对应按钮动画。 + func apply(_ presentation: DroneDockTaskPresentation, isRefreshing: Bool, isPrimaryActionLoading: Bool) { + self.presentation = presentation + self.isPrimaryActionLoading = isPrimaryActionLoading + titleLabel.text = presentation.title + messageLabel.text = presentation.message + actionButton.isHidden = presentation.action == .none || DroneDockHomeMetric.usableText(presentation.actionTitle) == nil + actionButton.isEnabled = presentation.isActionEnabled && !actionButton.isHidden && !isRefreshing && !isPrimaryActionLoading + actionButton.configuration?.image = UIImage(systemName: presentation.action == .refresh ? "arrow.clockwise" : "camera") + countdownSeconds = presentation.action == .start ? presentation.countdownSeconds.map { max(0, $0) } : nil + updateActionTitle() + if isPrimaryActionLoading { activityIndicator.startAnimating() } + else { activityIndicator.stopAnimating() } + actionButton.accessibilityValue = isPrimaryActionLoading ? "处理中" : nil + setIdentifiersActive(identifiersActive) + actionButton.setNeedsUpdateConfiguration() + setNeedsLayout() + } + + /// 更新已有按钮的数字,不改变权限、尺寸或触发任何业务回调。 + func updateCountdown(seconds: Int?) { + countdownSeconds = presentation?.action == .start ? seconds.map { max(0, $0) } : nil + updateActionTitle() + } + + /// 仅当前可见面板暴露公共标识,隐藏时清除数字及加载动画。 + func setIdentifiersActive(_ active: Bool) { + identifiersActive = active + if !active { + activityIndicator.stopAnimating() + updateCountdown(seconds: nil) + } + titleLabel.accessibilityIdentifier = active ? "drone.task.remote.statusTitle" : nil + promptLabel.accessibilityIdentifier = active ? "drone.task.remote.readyPrompt" : nil + messageLabel.accessibilityIdentifier = active ? "drone.task.remote.statusMessage" : nil + actionButton.accessibilityIdentifier = active + ? (presentation?.action == .refresh ? "drone.task.remote.refresh" : "drone.task.remote.primary") : nil + activityIndicator.accessibilityIdentifier = active ? "drone.task.remote.primary.loading" : nil + } + + /// 在固定区域内压缩排版,始终保留至少 44 点的主按钮。 + override func layoutSubviews() { + updateContentLayout() + super.layoutSubviews() + } + + private func setupUI() { + accessibilityIdentifier = "drone.task.remote.ready" + backgroundColor = .white + addSubview(content) + [header, actionButton].forEach(content.addSubview) + [iconBackground, titleLabel, promptLabel, messageLabel].forEach(header.addSubview) + iconBackground.addSubview(icon) + iconBackground.accessibilityIdentifier = "drone.task.remote.readyIcon" + iconBackground.backgroundColor = UIColor(hex: 0xE2EDFF) + iconBackground.layer.cornerRadius = 20.5 + icon.tintColor = UIColor(hex: 0x0671FF) + icon.contentMode = .scaleAspectFit + titleLabel.accessibilityTraits = .header + titleLabel.numberOfLines = 1 + promptLabel.text = "是否开始拍摄?" + promptLabel.numberOfLines = 1 + messageLabel.numberOfLines = 2 + messageLabel.lineBreakMode = .byTruncatingTail + var configuration = UIButton.Configuration.filled() + configuration.imagePadding = 12 + configuration.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(pointSize: 24, weight: .regular) + configuration.background.cornerRadius = 8 + configuration.cornerStyle = .fixed + configuration.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 8, bottom: 0, trailing: 8) + actionButton.configuration = configuration + actionButton.configurationUpdateHandler = { [weak self] button in + guard let self, var configuration = button.configuration else { return } + let foreground = UIColor.white + configuration.background.backgroundColor = UIColor(hex: 0x0671FF) + .withAlphaComponent(button.isEnabled || self.isPrimaryActionLoading ? 1 : 0.35) + configuration.baseForegroundColor = foreground + configuration.imageColorTransformer = UIConfigurationColorTransformer { _ in foreground } + configuration.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { attributes in + var result = attributes + result.font = .monospacedDigitSystemFont(ofSize: self.usesCompactLayout ? 16 : 18, weight: .semibold) + result.foregroundColor = foreground + return result + } + button.configuration = configuration + } + actionButton.addTarget(self, action: #selector(primaryTapped), for: .touchUpInside) + activityIndicator.color = .white + activityIndicator.hidesWhenStopped = true + activityIndicator.isUserInteractionEnabled = false + actionButton.addSubview(activityIndicator) + } + + private func setupConstraints() { + content.snp.makeConstraints { make in + make.leading.trailing.equalToSuperview().inset(18) + make.centerY.equalToSuperview() + } + header.snp.makeConstraints { make in + make.top.leading.trailing.equalToSuperview() + headerHeight = make.height.equalTo(86).constraint + } + iconBackground.snp.makeConstraints { make in + make.top.leading.equalToSuperview() + iconSize = make.size.equalTo(41).constraint + } + icon.snp.makeConstraints { make in + make.center.equalToSuperview() + make.size.equalTo(iconBackground.snp.width).multipliedBy(24.0 / 41.0) + } + titleLabel.snp.makeConstraints { make in + make.top.trailing.equalToSuperview() + textLeading = make.leading.equalTo(iconBackground.snp.trailing).offset(12).constraint + titleHeight = make.height.equalTo(30).constraint + } + promptLabel.snp.makeConstraints { make in + promptTop = make.top.equalTo(titleLabel.snp.bottom).offset(4).constraint + make.leading.trailing.equalTo(titleLabel) + promptHeight = make.height.equalTo(26).constraint + } + messageLabel.snp.makeConstraints { make in + messageTop = make.top.equalTo(promptLabel.snp.bottom).offset(3).constraint + make.leading.trailing.equalTo(titleLabel) + messageHeight = make.height.equalTo(23).constraint + } + actionButton.snp.makeConstraints { make in + actionTop = make.top.equalTo(header.snp.bottom).offset(10).constraint + make.leading.trailing.bottom.equalToSuperview() + actionHeight = make.height.equalTo(50).constraint + } + activityIndicator.snp.makeConstraints { make in + make.centerY.equalToSuperview() + make.trailing.equalToSuperview().inset(12) + make.size.equalTo(20) + } + } + + private func updateActionTitle() { + guard let presentation else { return } + var title = DroneDockHomeMetric.usableText(presentation.actionTitle) + if let seconds = countdownSeconds, let base = title { title = "\(base)(\(seconds)s)" } + UIView.performWithoutAnimation { + actionButton.setTitle(title, for: .normal) + actionButton.configuration?.title = title + actionButton.layoutIfNeeded() + } + } + + private func updateContentLayout() { + guard let presentation, bounds.width > 0, bounds.height > 0 else { return } + let wasCompact = usesCompactLayout + usesCompactLayout = bounds.height < 190 + let compact = usesCompactLayout + let extreme = bounds.height < 120 + let diameter: CGFloat = extreme ? 24 : compact ? 32 : 41 + let iconGap: CGFloat = extreme ? 8 : compact ? 10 : 12 + let titleSize: CGFloat = extreme ? 17 : compact ? 20 : 23 + let promptSize: CGFloat = extreme ? 15 : compact ? 17 : 18 + let messageSize: CGFloat = compact ? 13 : 14 + let buttonHeight: CGFloat = compact ? 44 : 50 + let buttonGap: CGFloat = extreme ? 6 : 10 + let available = max(1, bounds.height - (extreme ? 8 : 12)) + titleLabel.font = .systemFont(ofSize: titleSize, weight: .semibold) + promptLabel.font = .systemFont(ofSize: promptSize, weight: .medium) + messageLabel.font = .systemFont(ofSize: messageSize) + let title = max(ceil(titleLabel.font.lineHeight), compact ? 0 : 30) + var prompt = max(ceil(promptLabel.font.lineHeight), compact ? 0 : 26) + var firstGap: CGFloat = compact ? 2 : 4 + let secondGap: CGFloat = 3 + let textWidth = max(1, bounds.width - 36 - diameter - iconGap) + let paragraph = NSMutableParagraphStyle() + paragraph.minimumLineHeight = messageSize * 1.6 + paragraph.maximumLineHeight = messageSize * 1.6 + let attributes: [NSAttributedString.Key: Any] = [ + .font: messageLabel.font as Any, .foregroundColor: UIColor(hex: 0x6A79A0), .paragraphStyle: paragraph + ] + messageLabel.attributedText = NSAttributedString(string: presentation.message, attributes: attributes) + let measured = (presentation.message as NSString).boundingRect( + with: CGSize(width: textWidth, height: .greatestFiniteMagnitude), + options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: attributes, context: nil).height + var lines = extreme || presentation.message.isEmpty ? 0 : 2 + var body = lines == 0 ? 0 : ceil(min(measured, paragraph.maximumLineHeight * CGFloat(lines))) + while title + firstGap + prompt + (lines > 0 ? secondGap + body : 0) + buttonGap + buttonHeight > available, lines > 0 { + lines -= 1 + body = lines == 0 ? 0 : ceil(min(measured, paragraph.maximumLineHeight * CGFloat(lines))) + } + if title + firstGap + prompt + buttonGap + buttonHeight > available { + prompt = 0 + firstGap = 0 + } + promptLabel.isHidden = prompt == 0 + messageLabel.isHidden = lines == 0 + messageLabel.numberOfLines = max(1, lines) + effectiveScale = compact ? 0.8 : 1 + headerHeight?.update(offset: max(diameter, title + firstGap + prompt + (lines > 0 ? secondGap + body : 0))) + iconSize?.update(offset: diameter) + iconBackground.layer.cornerRadius = diameter / 2 + textLeading?.update(offset: iconGap) + titleHeight?.update(offset: title) + promptTop?.update(offset: firstGap) + promptHeight?.update(offset: prompt) + messageTop?.update(offset: lines > 0 ? secondGap : 0) + messageHeight?.update(offset: body) + actionTop?.update(offset: buttonGap) + actionHeight?.update(offset: buttonHeight) + if wasCompact != usesCompactLayout { actionButton.setNeedsUpdateConfiguration() } + } + + @objc private func primaryTapped() { + guard !isHidden, actionButton.isEnabled, !actionButton.isHidden else { return } + onPrimaryAction?() + } +} diff --git a/suixinkan/UI/DroneDock/DroneDockTaskStatusView.swift b/suixinkan/UI/DroneDock/DroneDockTaskStatusView.swift index 18031c8..8e4959b 100644 --- a/suixinkan/UI/DroneDock/DroneDockTaskStatusView.swift +++ b/suixinkan/UI/DroneDock/DroneDockTaskStatusView.swift @@ -24,6 +24,7 @@ final class DroneDockTaskStatusView: UIView { private let failureView = DroneDockTaskFailureView() private let completedView = DroneDockTaskCompletedView() private let shootingView = DroneDockTaskShootingView() + private let readyView = DroneDockTaskReadyView() private let controlStateView = DroneDockTaskControlStateView() private var presentation: DroneDockTaskPresentation? private var countdownSeconds: Int? @@ -87,17 +88,26 @@ final class DroneDockTaskStatusView: UIView { let isFailure = presentation.phase == .failed let isCompleted = [.postShootUploading, .completed].contains(presentation.phase) let isShooting = presentation.phase == .shooting + let isReady = presentation.phase == .ready let isControlState = [.paused, .returning, .returned].contains(presentation.phase) - contentStack.isHidden = isFailure || isCompleted || isShooting || isControlState + contentStack.isHidden = isFailure || isCompleted || isShooting || isReady || isControlState failureView.isHidden = !isFailure completedView.isHidden = !isCompleted shootingView.isHidden = !isShooting + readyView.isHidden = !isReady controlStateView.isHidden = !isControlState completedView.setIdentifiersActive(isCompleted) shootingView.setIdentifiersActive(isShooting) + readyView.setIdentifiersActive(isReady) controlStateView.setIdentifiersActive(isControlState) - titleLabel.accessibilityIdentifier = isCompleted || isShooting || isControlState ? nil : "drone.task.remote.statusTitle" - messageLabel.accessibilityIdentifier = isCompleted || isShooting || isControlState ? nil : "drone.task.remote.statusMessage" + titleLabel.accessibilityIdentifier = isCompleted || isShooting || isReady || isControlState ? nil : "drone.task.remote.statusTitle" + messageLabel.accessibilityIdentifier = isCompleted || isShooting || isReady || isControlState ? nil : "drone.task.remote.statusMessage" + if isReady { + primaryButton.accessibilityIdentifier = nil + readyView.apply(presentation, isRefreshing: isRefreshing, isPrimaryActionLoading: isPrimaryActionLoading) + setNeedsLayout() + return + } if isControlState { primaryButton.accessibilityIdentifier = nil controlStateView.apply(presentation, isRefreshing: isRefreshing, isPrimaryActionLoading: isPrimaryActionLoading) @@ -144,6 +154,7 @@ final class DroneDockTaskStatusView: UIView { ? seconds.map { max(0, $0) } : nil guard value != countdownSeconds else { return } countdownSeconds = value + readyView.updateCountdown(seconds: value) updatePrimaryButtonTitle() } @@ -166,6 +177,13 @@ final class DroneDockTaskStatusView: UIView { /// 尺寸改变时仅重排内部内容,保留至少 44 点操作区域,不使用 transform 缩放。 override func layoutSubviews() { + if presentation?.phase == .ready { + super.layoutSubviews() + readyView.layoutIfNeeded() + effectiveScale = readyView.effectiveScale + usesCompactLayout = readyView.usesCompactLayout + return + } if let phase = presentation?.phase, [.paused, .returning, .returned].contains(phase) { super.layoutSubviews() controlStateView.layoutIfNeeded() @@ -200,6 +218,9 @@ final class DroneDockTaskStatusView: UIView { private func setupUI() { backgroundColor = .white + addSubview(readyView) + readyView.isHidden = true + readyView.onPrimaryAction = { [weak self] in self?.onPrimaryAction?() } addSubview(controlStateView) controlStateView.isHidden = true controlStateView.onPrimaryAction = { [weak self] in self?.onPrimaryAction?() } @@ -243,6 +264,7 @@ final class DroneDockTaskStatusView: UIView { } private func setupConstraints() { + readyView.snp.makeConstraints { $0.edges.equalToSuperview() } controlStateView.snp.makeConstraints { $0.edges.equalToSuperview() } shootingView.snp.makeConstraints { $0.edges.equalToSuperview() } completedView.snp.makeConstraints { $0.edges.equalToSuperview() } diff --git a/suixinkan/UI/DroneDock/DroneDockVolcEngineAdapter.swift b/suixinkan/UI/DroneDock/DroneDockVolcEngineAdapter.swift index 70d2073..fe3fb76 100644 --- a/suixinkan/UI/DroneDock/DroneDockVolcEngineAdapter.swift +++ b/suixinkan/UI/DroneDock/DroneDockVolcEngineAdapter.swift @@ -4,6 +4,8 @@ import UIKit /// 接收端最小能力,隔离测试无需初始化 SDK 或使用真实凭证。 @MainActor protocol DroneDockRTCReceivingEngine: AnyObject { + /// 仅用于诊断的 SDK 版本;无 SDK 替身可保持未知。 + var sdkVersion: String? { get } /// 创建一个独立接收房间并转交事件。 func makeRoom(_ id: String, onEvent: @escaping @Sendable (DroneDockVolcEvent) -> Void) -> (any DroneDockRTCReceivingRoom)? /// 按 SDK 提供的流 ID 绑定或解绑画布。 @@ -12,6 +14,10 @@ protocol DroneDockRTCReceivingEngine: AnyObject { func destroy() } +extension DroneDockRTCReceivingEngine { + var sdkVersion: String? { nil } +} + /// 单路只收视频的房间;不提供发布、采集或设备控制能力。 @MainActor protocol DroneDockRTCReceivingRoom: AnyObject { @@ -31,6 +37,9 @@ final class DroneDockVolcEngineAdapter: DroneDockRTCReceivingEngine { private let engine: ByteRTCEngine private let delegate: DroneDockVolcDelegate + /// 查询版本不会创建额外引擎或加入房间。 + var sdkVersion: String? { ByteRTCEngine.getSDKVersion() } + private init(engine: ByteRTCEngine, delegate: DroneDockVolcDelegate) { self.engine = engine self.delegate = delegate diff --git a/suixinkan/UI/DroneDock/DroneDockVolcLivePlayer.swift b/suixinkan/UI/DroneDock/DroneDockVolcLivePlayer.swift index ef49c33..cfb78ea 100644 --- a/suixinkan/UI/DroneDock/DroneDockVolcLivePlayer.swift +++ b/suixinkan/UI/DroneDock/DroneDockVolcLivePlayer.swift @@ -4,6 +4,8 @@ import UIKit /// 可替换的双路图传播放器;测试注入内存替身,不初始化 RTC 或连接设备。 @MainActor protocol DroneDockLivePlaying: AnyObject { + /// 设置只读几何事件出口;不触发播放、连接或任务状态刷新。 + func setGeometryHandler(_ handler: (@MainActor (DroneDockLiveGeometry) -> Void)?) /// 同一播放会话可增补或更新凭证,不重建未变化的房间。 func start(_ configurations: [DroneDockVolcLiveConfiguration], in view: UIView, onEvent: @escaping @MainActor (DroneDockLivePlaybackEvent) -> Void) @@ -11,11 +13,21 @@ protocol DroneDockLivePlaying: AnyObject { func stop() } +extension DroneDockLivePlaying { + /// 旧播放器替身无需实现诊断能力。 + func setGeometryHandler(_ handler: (@MainActor (DroneDockLiveGeometry) -> Void)?) {} +} + /// 真实 SDK 入口始终执行编译期禁飞保护,没有运行时放行参数。 @MainActor final class DroneDockVolcLivePlayer: DroneDockLivePlaying { private let receiver = DroneDockLiveReceiver(makeEngine: DroneDockVolcEngineAdapter.make) + /// 几何事件与业务播放事件分离,不改变播放状态机。 + func setGeometryHandler(_ handler: (@MainActor (DroneDockLiveGeometry) -> Void)?) { + receiver.setGeometryHandler(handler) + } + /// Release 通过接收器播放;Debug 在创建 SDK 之前拒绝连接。 func start(_ configurations: [DroneDockVolcLiveConfiguration], in view: UIView, onEvent: @escaping @MainActor (DroneDockLivePlaybackEvent) -> Void) { @@ -51,6 +63,12 @@ final class DroneDockLiveReceiver: DroneDockLivePlaying { private var failedRoles: Set = [] private var generation = UUID() private var onEvent: (@MainActor (DroneDockLivePlaybackEvent) -> Void)? + private var onGeometry: (@MainActor (DroneDockLiveGeometry) -> Void)? + + /// 复用调用方的任务诊断会话,不在接收器中另建日志通道。 + func setGeometryHandler(_ handler: (@MainActor (DroneDockLiveGeometry) -> Void)?) { + onGeometry = handler + } /// 加入只收视频的房间;同一来源只更新 Token,避免后台重查导致画面闪断。 func start(_ configurations: [DroneDockVolcLiveConfiguration], in view: UIView, @@ -201,6 +219,8 @@ final class DroneDockLiveReceiver: DroneDockLivePlaying { _ = engine?.setVideoView(nil, streamID: id) _ = source.room.subscribeVideo(id, subscribe: false) source.streamID = nil + source.frameGeometry = nil + source.reportedFirstFrame = false markReady(false, source: source) return } @@ -209,9 +229,13 @@ final class DroneDockLiveReceiver: DroneDockLivePlaying { let render = engine?.setVideoView(source.view, streamID: id) let subscribe = source.room.subscribeVideo(id, subscribe: true) if render != 0 || subscribe != 0 { sourceFailed(source.configuration.role, message: "图传订阅失败(\(render ?? -1)/\(subscribe)),请重试") } - case .frame(let id, let roomID): + case .frame(let id, let roomID, let geometry): guard let source = source(in: roomID), source.streamID == id else { return } + if let geometry { updateFrameGeometry(geometry, source: source, isFirstFrame: true) } markReady(true, source: source) + case .videoSizeChanged(let id, let roomID, let geometry): + guard let source = source(in: roomID), source.streamID == id else { return } + updateFrameGeometry(geometry, source: source, isFirstFrame: false) case .videoState(let id, let roomID, let state): guard let source = source(in: roomID), source.streamID == id else { return } switch state { @@ -236,6 +260,27 @@ final class DroneDockLiveReceiver: DroneDockLivePlaying { sources.values.first { $0.configuration.roomID == roomID } } + private func updateFrameGeometry(_ geometry: DroneDockVideoFrameGeometry, + source: DroneDockVolcSource, isFirstFrame: Bool) { + let changed = source.frameGeometry != geometry + source.frameGeometry = geometry + if isFirstFrame, !source.reportedFirstFrame { + source.reportedFirstFrame = true + emitGeometry(source, trigger: "first_frame") + } else if changed { + emitGeometry(source, trigger: "video_size_changed") + } + } + + private func emitGeometry(_ source: DroneDockVolcSource, trigger: String) { + guard let streamID = source.streamID, let container else { return } + onGeometry?(DroneDockLiveGeometry(trigger: trigger, role: source.configuration.role, + roomID: source.configuration.roomID, streamID: streamID, frame: source.frameGeometry, + containerWidth: Double(source.view.bounds.width), containerHeight: Double(source.view.bounds.height), + hostWidth: Double(container.bounds.width), hostHeight: Double(container.bounds.height), + isSelected: selection.selectedRole == source.configuration.role, sdkVersion: engine?.sdkVersion)) + } + private func markReady(_ ready: Bool, source: DroneDockVolcSource) { selection.setReady(ready, role: source.configuration.role) if ready { @@ -267,6 +312,7 @@ final class DroneDockLiveReceiver: DroneDockLivePlaying { if let role, let view = sources[role]?.view { container?.bringSubviewToFront(view) } guard displayedRole != role else { return } displayedRole = role + if let role, let source = sources[role] { emitGeometry(source, trigger: "source_changed") } onEvent?(.sourceChanged(role)) } } @@ -279,6 +325,8 @@ private final class DroneDockVolcSource { let room: any DroneDockRTCReceivingRoom let view: UIView var streamID: String? + var frameGeometry: DroneDockVideoFrameGeometry? + var reportedFirstFrame = false var timeoutTask: Task? var expiryTask: Task? @@ -290,7 +338,8 @@ private final class DroneDockVolcSource { /// SDK 工作线程只转交值类型事件;事件带房间和流身份以隔离两路回调。 enum DroneDockVolcEvent: Sendable { case published(String, String, Bool) - case frame(String, String) + case frame(String, String, DroneDockVideoFrameGeometry? = nil) + case videoSizeChanged(String, String, DroneDockVideoFrameGeometry) case videoState(String, String, ByteRTCRemoteVideoState) case roomFailed(String, Int) case connectionLost @@ -313,7 +362,17 @@ final class DroneDockVolcDelegate: NSObject, ByteRTCEngineDelegate, ByteRTCRoomD func rtcEngine(_ engine: ByteRTCEngine, onFirstRemoteVideoFrameDecoded streamId: String, info: ByteRTCStreamInfo, withFrameInfo frameInfo: ByteRTCVideoFrameInfo) { // 未展示的画布也能解码,不能依赖被隐藏视图的 rendered 回调判断首帧。 - emit(.frame(streamId, info.roomId)) + emit(.frame(streamId, info.roomId, Self.geometry(frameInfo))) + } + + func rtcEngine(_ engine: ByteRTCEngine, onRemoteVideoSizeChanged streamId: String, + info: ByteRTCStreamInfo, withFrameInfo frameInfo: ByteRTCVideoFrameInfo) { + emit(.videoSizeChanged(streamId, info.roomId, Self.geometry(frameInfo))) + } + + private static func geometry(_ frameInfo: ByteRTCVideoFrameInfo) -> DroneDockVideoFrameGeometry { + DroneDockVideoFrameGeometry(width: frameInfo.width, height: frameInfo.height, + rotation: frameInfo.rotation.rawValue) } func rtcEngine(_ engine: ByteRTCEngine, onRemoteVideoStateChanged streamId: String, info: ByteRTCStreamInfo, diff --git a/suixinkan/UI/Loading/GlobalLoadingPageViewController.swift b/suixinkan/UI/Loading/GlobalLoadingPageViewController.swift new file mode 100644 index 0000000..2a35de0 --- /dev/null +++ b/suixinkan/UI/Loading/GlobalLoadingPageViewController.swift @@ -0,0 +1,62 @@ +import UIKit + +/// 将页面的阻塞读取接入应用通用 Loading,离页或后台仅释放本页令牌。 +@MainActor +class GlobalLoadingPageViewController: BaseViewController { + private var requestsPageLoading = false + private var pageIsVisible = false + private var applicationIsActive = UIApplication.shared.applicationState == .active + private var pageLoadingToken: UUID? + + override func viewDidLoad() { + super.viewDidLoad() + NotificationCenter.default.addObserver(self, selector: #selector(loadingApplicationWillResignActive), + name: UIApplication.willResignActiveNotification, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(loadingApplicationDidBecomeActive), + name: UIApplication.didBecomeActiveNotification, object: nil) + } + + override func viewDidAppear(_ animated: Bool) { + super.viewDidAppear(animated) + pageIsVisible = true + applicationIsActive = UIApplication.shared.applicationState == .active + updatePageLoading() + } + + override func viewWillDisappear(_ animated: Bool) { + super.viewWillDisappear(animated) + pageIsVisible = false + updatePageLoading() + } + + deinit { + if let token = pageLoadingToken { + Task { @MainActor in GlobalLoadingManager.shared.endRequest(token) } + } + } + + /// 仅首次无可用内容或需要等待的页面读取使用;轮询、分页及按钮进度保持局部反馈。 + func setPageLoading(_ isLoading: Bool) { + requestsPageLoading = isLoading + updatePageLoading() + } + + @objc private func loadingApplicationWillResignActive() { + applicationIsActive = false + updatePageLoading() + } + + @objc private func loadingApplicationDidBecomeActive() { + applicationIsActive = true + updatePageLoading() + } + + private func updatePageLoading() { + if requestsPageLoading && pageIsVisible && applicationIsActive { + if pageLoadingToken == nil { pageLoadingToken = GlobalLoadingManager.shared.beginRequest() } + } else if let token = pageLoadingToken { + pageLoadingToken = nil + GlobalLoadingManager.shared.endRequest(token) + } + } +} diff --git a/suixinkan/UI/ScenicMaterials/ScenicMaterialsViewController.swift b/suixinkan/UI/ScenicMaterials/ScenicMaterialsViewController.swift index 097d854..d493e1b 100644 --- a/suixinkan/UI/ScenicMaterials/ScenicMaterialsViewController.swift +++ b/suixinkan/UI/ScenicMaterials/ScenicMaterialsViewController.swift @@ -4,7 +4,7 @@ import UIKit /// 独立景区空镜库页面,提供筛选、分组预览、选择与前台下载演示,不依赖机巢订单。 @MainActor -final class ScenicMaterialsViewController: BaseViewController { +final class ScenicMaterialsViewController: GlobalLoadingPageViewController { /// 当前景区的素材与本地选择、下载状态。 let viewModel: ScenicMaterialsViewModel @@ -55,11 +55,13 @@ final class ScenicMaterialsViewController: BaseViewController { let session = AppStore.shared.session guard session.accountType == .storeUser, session.userId == viewModel.context.userID, String(session.currentScenicId) == viewModel.context.scenicID else { + setPageLoading(false) refreshControl.endRefreshing() showToast("请使用门店账号并重新进入当前景区素材库") return } let api = ScenicMaterialsAPI(client: NetworkServices.shared.apiClient) + setPageLoading(!refreshControl.isRefreshing) emptyTitle.text = "正在加载素材" emptyMessage.text = "请稍候" retryButton.isHidden = true @@ -69,6 +71,7 @@ final class ScenicMaterialsViewController: BaseViewController { guard let self else { return } await self.viewModel.loadRemoteSessions(api: api) guard !Task.isCancelled else { return } + self.setPageLoading(false) self.refreshControl.endRefreshing() self.refreshDisplay() } @@ -212,6 +215,7 @@ final class ScenicMaterialsViewController: BaseViewController { /// 仅在确认离开页面后作废异步工作,取消返回手势继续保留原来的加载及下载。 private func finishLeaving() { loadTask?.cancel() + setPageLoading(false) isLoadingNextPage = false viewModel.cancelRemoteLoad() authorizationTask?.cancel() diff --git a/suixinkanTests/DroneDockLiveGeometryTests.swift b/suixinkanTests/DroneDockLiveGeometryTests.swift new file mode 100644 index 0000000..bc394d0 --- /dev/null +++ b/suixinkanTests/DroneDockLiveGeometryTests.swift @@ -0,0 +1,246 @@ +import UIKit +import VolcEngineRTC +import XCTest +@testable import suixinkan + +/// 图传几何诊断仅使用内存接收器和播放器,验证日志不能改变播放或网络行为。 +@MainActor +final class DroneDockLiveGeometryTests: XCTestCase { + /// 帧宽高及旋转保留 SDK 原值,缺失信息为 null,便于与实际画布比例对照。 + func testDiagnosticPayloadPreservesRawRotationAndUnknownFrame() throws { + let value = geometry(frame: .init(width: 720, height: 1280, rotation: 90)) + let fields = value.diagnosticFields + XCTAssertEqual(fields["frame_w"] as? Int, 720) + XCTAssertEqual(fields["frame_h"] as? Int, 1280) + XCTAssertEqual(fields["rotation"] as? Int, 90) + XCTAssertEqual(fields["rotation_unit"] as? String, "degree") + XCTAssertEqual(fields["frame_unit"] as? String, "px") + XCTAssertEqual(fields["container_unit"] as? String, "pt") + XCTAssertEqual(fields["container_w"] as? Double, 390) + XCTAssertEqual(fields["container_h"] as? Double, 219.375) + XCTAssertEqual(fields["render_mode"] as? String, "fit") + XCTAssertTrue(JSONSerialization.isValidJSONObject(fields)) + let unknown = geometry(frame: nil).diagnosticFields + for key in ["frame_w", "frame_h", "rotation", "sdk_version"] { + XCTAssertTrue(unknown[key] is NSNull, key) + } + XCTAssertTrue(JSONSerialization.isValidJSONObject(unknown)) + } + + /// 重复首帧及相同尺寸不重复输出,真正尺寸变化只更新诊断,不重新订阅或切流。 + func testFirstFrameAndSizeChangesAreDeduplicatedWithoutChangingSubscriptions() async throws { + let engine = GeometryEngineProbe() + let receiver = DroneDockLiveReceiver(makeEngine: { _, _ in engine }) + let view = UIView(frame: CGRect(x: 0, y: 0, width: 390, height: 219.375)) + var geometries: [DroneDockLiveGeometry] = [] + var playback: [DroneDockLivePlaybackEvent] = [] + receiver.setGeometryHandler { geometries.append($0) } + receiver.start([configuration("airport")], in: view) { playback.append($0) } + defer { receiver.stop() } + let room = try XCTUnwrap(engine.rooms["airport-room"]) + room.emit(.published("airport-stream", "airport-room", true)) + await drain() + let frame = DroneDockVideoFrameGeometry(width: 1920, height: 1080, rotation: 0) + room.emit(.frame("airport-stream", "airport-room", frame)) + await drain() + XCTAssertEqual(geometries.map(\.trigger), ["first_frame", "source_changed"]) + let shown = try XCTUnwrap(geometries.last) + XCTAssertEqual(shown.role, "airport") + XCTAssertEqual(shown.roomID, "airport-room") + XCTAssertEqual(shown.streamID, "airport-stream") + XCTAssertEqual(shown.frame, frame) + XCTAssertEqual(shown.sdkVersion, "TEST-SDK") + XCTAssertEqual(shown.containerWidth, 390) + XCTAssertEqual(shown.containerHeight, 219.375) + XCTAssertEqual(shown.hostWidth, 390) + XCTAssertTrue(shown.isSelected) + for _ in 0..<5 { + room.emit(.frame("airport-stream", "airport-room", frame)) + room.emit(.videoSizeChanged("airport-stream", "airport-room", frame)) + } + await drain() + XCTAssertEqual(geometries.count, 2) + let rotated = DroneDockVideoFrameGeometry(width: 720, height: 1280, rotation: 90) + room.emit(.videoSizeChanged("airport-stream", "airport-room", rotated)) + await drain() + XCTAssertEqual(geometries.last?.trigger, "video_size_changed") + XCTAssertEqual(geometries.last?.frame, rotated) + XCTAssertEqual(geometries.count, 3) + XCTAssertEqual(playback, [.sourceChanged("airport")]) + XCTAssertEqual(room.subscriptions, ["airport-stream:true"]) + XCTAssertEqual(engine.bindings, ["airport-stream"]) + XCTAssertEqual(view.bounds.size, CGSize(width: 390, height: 219.375)) + XCTAssertEqual(view.subviews.first?.bounds.size, view.bounds.size) + } + + /// 尺寸回调不是首帧证据,不能提前开放另一房间或将页面变成正在播放。 + func testSizeCallbackCannotStartPlaybackOrConnectSecondSource() async throws { + let engine = GeometryEngineProbe() + let receiver = DroneDockLiveReceiver(makeEngine: { _, _ in engine }) + let view = UIView(frame: CGRect(x: 0, y: 0, width: 390, height: 219.375)) + var geometries: [DroneDockLiveGeometry] = [] + var playback: [DroneDockLivePlaybackEvent] = [] + receiver.setGeometryHandler { geometries.append($0) } + receiver.start([configuration("airport"), configuration("drone")], in: view) { playback.append($0) } + defer { receiver.stop() } + let room = try XCTUnwrap(engine.rooms["airport-room"]) + room.emit(.published("airport-stream", "airport-room", true)) + await drain() + room.emit(.videoSizeChanged("airport-stream", "airport-room", .init(width: 1440, height: 1080, rotation: 0))) + await drain() + XCTAssertEqual(geometries.map(\.trigger), ["video_size_changed"]) + XCTAssertFalse(try XCTUnwrap(geometries.first).isSelected) + XCTAssertTrue(playback.isEmpty) + XCTAssertNil(engine.rooms["drone-room"]) + XCTAssertEqual(engine.bindings, ["airport-stream"]) + } + + /// 两路尺寸各自保存;错误身份和已释放会话的迟到回调不能污染日志,回退使用机巢尺寸。 + func testSourceSwitchFallbackAndStaleIdentityKeepIndependentGeometry() async throws { + let engine = GeometryEngineProbe() + let receiver = DroneDockLiveReceiver(makeEngine: { _, _ in engine }) + let view = UIView(frame: CGRect(x: 0, y: 0, width: 390, height: 219.375)) + var geometries: [DroneDockLiveGeometry] = [] + receiver.setGeometryHandler { geometries.append($0) } + receiver.start([configuration("airport"), configuration("drone")], in: view) { _ in } + defer { receiver.stop() } + let airport = try XCTUnwrap(engine.rooms["airport-room"]) + let airportFrame = DroneDockVideoFrameGeometry(width: 1920, height: 1080, rotation: 0) + airport.emit(.published("airport-stream", "airport-room", true)) + await drain() + airport.emit(.frame("airport-stream", "airport-room", airportFrame)) + await drain() + let drone = try XCTUnwrap(engine.rooms["drone-room"]) + drone.emit(.published("drone-stream", "drone-room", true)) + await drain() + let droneFrame = DroneDockVideoFrameGeometry(width: 1440, height: 1080, rotation: 0) + drone.emit(.frame("wrong-stream", "drone-room", droneFrame)) + drone.emit(.videoSizeChanged("drone-stream", "wrong-room", droneFrame)) + await drain() + XCTAssertEqual(geometries.count, 2) + drone.emit(.frame("drone-stream", "drone-room", droneFrame)) + await drain() + XCTAssertEqual(geometries.last?.role, "drone") + XCTAssertEqual(geometries.last?.frame, droneFrame) + drone.emit(.videoState("drone-stream", "drone-room", .frozen)) + await drain() + XCTAssertEqual(geometries.last?.trigger, "source_changed") + XCTAssertEqual(geometries.last?.role, "airport") + XCTAssertEqual(geometries.last?.frame, airportFrame) + receiver.stop() + let count = geometries.count + drone.emit(.frame("drone-stream", "drone-room", droneFrame)) + airport.emit(.videoSizeChanged("airport-stream", "airport-room", droneFrame)) + await drain() + XCTAssertEqual(geometries.count, count) + XCTAssertEqual(engine.destroyCount, 1) + } + + /// 诊断回调沿用当前任务会话,离页和重新进入后的旧回调均被丢弃,不能触发播放或新请求。 + func testViewForwardsOnlyCurrentSessionGeometryWithoutChangingPlayback() async throws { + let context = DroneDockShootingTaskTestData.context() + let service = GeometryParameterProbe(response: try DroneDockRTCFixture.response()) + let model = DroneDockLiveViewModel(context: context, taskID: 501, service: service, + allowsDevicePlayback: true, now: { DroneDockRTCFixture.now }, currentContext: { context }) + await model.refresh() + let player = GeometryPlayerProbe() + let view = DroneDockTaskLiveView(rtcPlayer: player) + var records: [[String: Any]] = [] + view.onDiagnosticEvent = { event, fields in if event == "live.geometry" { records.append(fields) } } + view.apply(model) + view.setPlaybackActive(true) + let oldHandler = try XCTUnwrap(player.geometryHandler) + oldHandler(geometry(frame: .init(width: 1440, height: 1080, rotation: 0))) + XCTAssertEqual(records.count, 1) + XCTAssertEqual(records.first?["receiver_session"] as? String, model.playbackSessionID?.uuidString) + XCTAssertEqual(model.state, .connecting) + XCTAssertEqual(player.starts, 1) + XCTAssertEqual(service.calls, 1) + view.setPlaybackActive(false) + oldHandler(geometry(frame: nil)) + XCTAssertEqual(records.count, 1) + XCTAssertNil(player.geometryHandler) + model.invalidate() + await model.refresh() + view.apply(model) + view.setPlaybackActive(true) + oldHandler(geometry(frame: nil)) + XCTAssertEqual(records.count, 1) + try XCTUnwrap(player.geometryHandler)(geometry(frame: .init(width: 1920, height: 1080, rotation: 0))) + XCTAssertEqual(records.count, 2) + XCTAssertNotEqual(records.first?["receiver_session"] as? String, records.last?["receiver_session"] as? String) + XCTAssertEqual(model.state, .connecting) + XCTAssertEqual(player.starts, 2) + XCTAssertEqual(service.calls, 2) + view.setPlaybackActive(false) + } + + /// 尺寸回调是 SDK optional Objective-C 方法,必须确实注册才能收到旋转或分辨率变化。 + func testSDKSizeChangeDelegateSelectorIsRegistered() { + let delegate = DroneDockVolcDelegate { _ in } + XCTAssertTrue(delegate.responds(to: NSSelectorFromString("rtcEngine:onRemoteVideoSizeChanged:info:withFrameInfo:"))) + } + + private func configuration(_ role: String) -> DroneDockVolcLiveConfiguration { + .init(appID: "TEST", roomID: "\(role)-room", userID: "viewer", token: "TEST", + expiresAt: Date().addingTimeInterval(3600), role: role) + } + + private func geometry(frame: DroneDockVideoFrameGeometry?) -> DroneDockLiveGeometry { + .init(trigger: "first_frame", role: "drone", roomID: "TEST-room", streamID: "TEST-stream", frame: frame, + containerWidth: 390, containerHeight: 219.375, hostWidth: 390, hostHeight: 219.375, + isSelected: true, sdkVersion: nil) + } + + private func drain() async { for _ in 0..<20 { await Task.yield() } } +} + +/// 无 SDK 引擎,只记录绑定与房间创建次数。 +@MainActor +private final class GeometryEngineProbe: DroneDockRTCReceivingEngine { + let sdkVersion: String? = "TEST-SDK" + var rooms: [String: GeometryRoomProbe] = [:] + var bindings: [String] = [] + var destroyCount = 0 + func makeRoom(_ id: String, onEvent: @escaping @Sendable (DroneDockVolcEvent) -> Void) -> (any DroneDockRTCReceivingRoom)? { + let room = GeometryRoomProbe(emit: onEvent) + rooms[id] = room + return room + } + func setVideoView(_ view: UIView?, streamID: String) -> Int { bindings.append(streamID); return 0 } + func destroy() { destroyCount += 1 } +} + +/// 所有事件由测试主动发送,不访问网络或设备。 +@MainActor +private final class GeometryRoomProbe: DroneDockRTCReceivingRoom { + let emit: @Sendable (DroneDockVolcEvent) -> Void + var subscriptions: [String] = [] + init(emit: @escaping @Sendable (DroneDockVolcEvent) -> Void) { self.emit = emit } + func join(_ configuration: DroneDockVolcLiveConfiguration) -> Int { 0 } + func updateToken(_ token: String) -> Int { 0 } + func subscribeVideo(_ streamID: String, subscribe: Bool) -> Int { + subscriptions.append("\(streamID):\(subscribe)"); return 0 + } + func destroy() {} +} + +/// 几何和播放回调分离的无网络播放器。 +@MainActor +private final class GeometryPlayerProbe: DroneDockLivePlaying { + var starts = 0 + var geometryHandler: (@MainActor (DroneDockLiveGeometry) -> Void)? + func setGeometryHandler(_ handler: (@MainActor (DroneDockLiveGeometry) -> Void)?) { geometryHandler = handler } + func start(_ configurations: [DroneDockVolcLiveConfiguration], in view: UIView, + onEvent: @escaping @MainActor (DroneDockLivePlaybackEvent) -> Void) { starts += 1 } + func stop() {} +} + +/// 参数查询计数替身,验证诊断不会引入额外接口读取。 +@MainActor +private final class GeometryParameterProbe: DroneDockLiveServing { + let response: DroneDockLiveResponse + var calls = 0 + init(response: DroneDockLiveResponse) { self.response = response } + func live(taskID: Int) async throws -> DroneDockLiveResponse { calls += 1; return response } +} diff --git a/suixinkanTests/DroneDockRemoteHomeViewTests.swift b/suixinkanTests/DroneDockRemoteHomeViewTests.swift index d569169..0782f46 100644 --- a/suixinkanTests/DroneDockRemoteHomeViewTests.swift +++ b/suixinkanTests/DroneDockRemoteHomeViewTests.swift @@ -9,6 +9,8 @@ final class DroneDockRemoteHomeViewTests: XCTestCase { /// 设备请求尚未返回时先展示等高空卡片,返回设备后下方模块不跳动。 func testPendingDeviceRequestKeepsPlaceholderCardAtFullDeviceHeight() async throws { + GlobalLoadingManager.shared.hideAll() + defer { GlobalLoadingManager.shared.hideAll() } let gate = HomeDeviceResponseGate() defer { Task { await gate.release() } } let (controller, session) = makeController(responses: [populatedEnvelope], deviceResponseGate: gate) @@ -20,12 +22,15 @@ final class DroneDockRemoteHomeViewTests: XCTestCase { try await settle(window: window) { session.requests.count == 3 && controller.viewModel.isLoading && (collection.cellForItem(at: path) as? DroneDockDeviceCell)?.cardView.accessibilityIdentifier == "drone.device.empty" + && GlobalLoadingManager.shared.isShowing } let placeholder = try XCTUnwrap((collection.cellForItem(at: path) as? DroneDockDeviceCell)?.cardView) let frame = try XCTUnwrap(collection.collectionViewLayout.layoutAttributesForItem(at: path)).frame XCTAssertEqual(collection.numberOfItems(inSection: 1), 1) XCTAssertEqual(frame.height, 248, accuracy: 0.5) XCTAssertNil(controller.viewModel.response) + XCTAssertTrue(GlobalLoadingManager.shared.isShowing) + XCTAssertTrue(window.subviews.contains { $0 is GlobalLoadingOverlayView }) XCTAssertTrue(visibleTexts(in: placeholder).contains("暂无无人机")) XCTAssertTrue(visibleTexts(in: placeholder).contains("正在加载")) XCTAssertEqual(metricTexts(in: placeholder), Dictionary(uniqueKeysWithValues: metricKeys.map { ($0, "—") })) @@ -37,6 +42,7 @@ final class DroneDockRemoteHomeViewTests: XCTestCase { && !collection.hasUncommittedUpdates } let loadedFrame = try XCTUnwrap(collection.collectionViewLayout.layoutAttributesForItem(at: path)).frame + XCTAssertFalse(GlobalLoadingManager.shared.isShowing) XCTAssertEqual(loadedFrame.minY, frame.minY, accuracy: 0.5) XCTAssertEqual(loadedFrame.height, frame.height, accuracy: 0.5) assertOnlyReadHomepageRequests(session) diff --git a/suixinkanTests/DroneDockShootingTaskViewTests.swift b/suixinkanTests/DroneDockShootingTaskViewTests.swift index a029096..27b618b 100644 --- a/suixinkanTests/DroneDockShootingTaskViewTests.swift +++ b/suixinkanTests/DroneDockShootingTaskViewTests.swift @@ -50,7 +50,7 @@ final class DroneDockShootingTaskViewTests: XCTestCase { XCTAssertFalse(visibleTexts(in: controller.view).contains("正在获取任务状态")) service.finish() try await settle(window) { controller.viewModel.presentation.phase == .ready } - XCTAssertTrue(visibleTexts(in: controller.view).contains("本地模拟:无人机已到达")) + XCTAssertTrue(visibleTexts(in: controller.view).contains("无人机已到达")) } /// 使用模拟 WebSocket 推进任务阶段,断线立即 HTTP 兜底,恢复后停轮询;固定布局不变。 @@ -72,7 +72,7 @@ final class DroneDockShootingTaskViewTests: XCTestCase { socket.emit(try RealtimeTestData.push(XCTUnwrap(JSONSerialization.jsonObject(with: Data(ready.dataJSON.utf8)) as? [String: Any]))) try await settle(window) { controller.viewModel.response?.stateVersion == 2 && clock.pendingCount == 0 } XCTAssertEqual(controller.viewModel.presentation.phase, .ready) - XCTAssertTrue(visibleTexts(in: controller.view).contains("本地模拟:无人机已到达")) + XCTAssertTrue(visibleTexts(in: controller.view).contains("无人机已到达")) service.suspendNext = true service.response = try realtimeViewSnapshot(version: 3, phase: "shooting", title: "本地模拟:正在拍摄") socket.fail() diff --git a/suixinkanTests/DroneDockTaskFixedLayoutTests.swift b/suixinkanTests/DroneDockTaskFixedLayoutTests.swift index 18a8060..0ff4135 100644 --- a/suixinkanTests/DroneDockTaskFixedLayoutTests.swift +++ b/suixinkanTests/DroneDockTaskFixedLayoutTests.swift @@ -36,7 +36,7 @@ final class DroneDockTaskFixedLayoutTests: XCTestCase { let note = try XCTUnwrap(find(in: status, suffix: "failureNote") as? UILabel) XCTAssertFalse(isHidden(note)) XCTAssertEqual(note.text, "无人机离线,暂不可召唤") - } else if [.shooting, .postShootUploading, .completed, .paused, .returning, .returned].contains(phase) { + } else if [.ready, .shooting, .postShootUploading, .completed, .paused, .returning, .returned].contains(phase) { XCTAssertTrue(isHidden(device)) } else { XCTAssertFalse(isHidden(device)) @@ -141,6 +141,91 @@ final class DroneDockTaskFixedLayoutTests: XCTestCase { } } + /// 到达面板采用蓝色圆勾与三级文案,保留完整秒数、整行按钮和实际可点击区域。 + func testReadyPanelMatchesPrototypeAndKeepsCountdownActionTappable() throws { + for size in [CGSize(width: 320, height: 146), compactSize, regularSize] { + let status = makeStatus(size: size) + let ready = DroneDockTaskPresentation(phase: .ready, title: "无人机已到达", + message: "确认游客站位与取景后开始", deviceStatus: "设备摘要不应显示", action: .start, + actionTitle: "开始拍摄", isActionEnabled: true, countdownSeconds: 30) + apply(ready, to: status) + let title = try XCTUnwrap(find(in: status, suffix: "statusTitle") as? UILabel) + let prompt = try XCTUnwrap(find(in: status, suffix: "readyPrompt") as? UILabel) + let message = try XCTUnwrap(find(in: status, suffix: "statusMessage") as? UILabel) + let icon = try XCTUnwrap(find(in: status, suffix: "readyIcon")) + let button = try XCTUnwrap(find(in: status, suffix: "primary") as? UIButton) + XCTAssertEqual(title.text, "无人机已到达") + XCTAssertEqual(prompt.text, "是否开始拍摄?") + XCTAssertEqual(message.text, "确认游客站位与取景后开始") + XCTAssertFalse(isHidden(prompt)) + XCTAssertFalse(isHidden(message)) + XCTAssertEqual(icon.backgroundColor, UIColor(hex: 0xE2EDFF)) + XCTAssertEqual((icon.subviews.first as? UIImageView)?.tintColor, UIColor(hex: 0x0671FF)) + XCTAssertEqual(title.convert(title.bounds, to: status).minY, icon.convert(icon.bounds, to: status).minY, accuracy: 0.5) + XCTAssertEqual(title.convert(title.bounds, to: status).minX, prompt.convert(prompt.bounds, to: status).minX, accuracy: 0.5) + XCTAssertEqual(title.convert(title.bounds, to: status).minX, message.convert(message.bounds, to: status).minX, accuracy: 0.5) + XCTAssertGreaterThan(prompt.convert(prompt.bounds, to: status).minY, title.convert(title.bounds, to: status).maxY) + XCTAssertGreaterThan(message.convert(message.bounds, to: status).minY, prompt.convert(prompt.bounds, to: status).maxY) + XCTAssertTrue(isHidden(try XCTUnwrap(find(in: status, suffix: "deviceStatus")))) + XCTAssertEqual(button.bounds.width, size.width - 36, accuracy: 0.5) + XCTAssertNotNil(button.configuration?.image) + var calls = 0 + status.onPrimaryAction = { calls += 1 } + let initialFrame = button.convert(button.bounds, to: status) + for (index, seconds) in [30, 29, 0].enumerated() { + status.updateCountdown(seconds: seconds) + layoutHierarchy(status) + try assertFullButtonTitle("开始拍摄(\(seconds)s)", button: button) + XCTAssertTrue(button.isEnabled) + XCTAssertEqual(button.convert(button.bounds, to: status), initialFrame) + let center = button.convert(CGPoint(x: button.bounds.midX, y: button.bounds.midY), to: status) + let hit = status.hitTest(center, with: nil) + XCTAssertTrue(hit === button || hit?.isDescendant(of: button) == true) + button.sendActions(for: .touchUpInside) + XCTAssertEqual(calls, index + 1) + } + try assertReadableContainedContent(in: status) + capture(status, name: "已到达-蓝色圆勾三级文案-\(Int(size.width))x\(Int(size.height))") + + status.apply(ready, isPrimaryActionLoading: true) + layoutHierarchy(status) + let spinner = try XCTUnwrap(find(in: status, suffix: "primary.loading") as? UIActivityIndicatorView) + XCTAssertTrue(spinner.isAnimating) + XCTAssertFalse(button.isEnabled) + XCTAssertEqual(title.text, "无人机已到达") + button.sendActions(for: .touchUpInside) + XCTAssertEqual(calls, 3) + status.updateCountdown(seconds: 0) + XCTAssertFalse(button.isEnabled, "倒计时不能覆盖提交中的操作保护") + status.apply(ready) + layoutHierarchy(status) + XCTAssertFalse(spinner.isAnimating) + XCTAssertTrue(button.isEnabled) + } + } + + /// 开拍结果待核对时继续显示原始说明和刷新动作,不误显示可开拍的倒计时。 + func testReadyPanelPreservesOutcomeMessageAndRefreshAction() throws { + let status = makeStatus(size: regularSize) + let value = DroneDockTaskPresentation(phase: .ready, title: "无人机已到达", + message: "操作结果未知,请刷新核对任务状态。", deviceStatus: "拍摄中", action: .refresh, + actionTitle: "刷新状态", isActionEnabled: true, countdownSeconds: 30) + apply(value, to: status) + let button = try XCTUnwrap(find(in: status, suffix: "refresh") as? UIButton) + XCTAssertEqual((find(in: status, suffix: "statusMessage") as? UILabel)?.text, value.message) + XCTAssertEqual(button.title(for: .normal), "刷新状态") + XCTAssertEqual(status.diagnosticFields["countdown"] as? String, "hidden") + var calls = 0 + status.onPrimaryAction = { calls += 1 } + button.sendActions(for: .touchUpInside) + XCTAssertEqual(calls, 1) + status.apply(value, isRefreshing: true) + button.sendActions(for: .touchUpInside) + XCTAssertEqual(calls, 1) + XCTAssertFalse(button.isEnabled) + try assertReadableContainedContent(in: status) + } + /// 从到达到拍摄中再进入错误/完成状态时,独立面板和通用操作互不留下旧入口。 func testShootingPanelTransitionsClearOldCountdownAndRestoreAllowedAction() throws { let status = makeStatus(size: regularSize) diff --git a/suixinkanTests/GlobalPageLoadingTests.swift b/suixinkanTests/GlobalPageLoadingTests.swift new file mode 100644 index 0000000..fd658a9 --- /dev/null +++ b/suixinkanTests/GlobalPageLoadingTests.swift @@ -0,0 +1,90 @@ +import UIKit +import XCTest +@testable import suixinkan + +/// 页面通用 Loading 必须跟随可见性,并与其它页面或请求的令牌相互独立。 +@MainActor +final class GlobalPageLoadingTests: XCTestCase { + override func setUp() { + super.setUp() + GlobalLoadingManager.shared.hideAll() + } + + override func tearDown() { + GlobalLoadingManager.shared.hideAll() + super.tearDown() + } + + /// 页面首次读取可以提前标记,但只有完整出现后才使用通用遮罩。 + func testLoadingWaitsForVisiblePageAndFinishesWithoutLeaking() { + let controller = makeController() + controller.setPageLoading(true) + XCTAssertFalse(GlobalLoadingManager.shared.isShowing) + controller.viewDidAppear(false) + XCTAssertTrue(GlobalLoadingManager.shared.isShowing) + controller.setPageLoading(false) + XCTAssertFalse(GlobalLoadingManager.shared.isShowing) + controller.viewWillDisappear(false) + } + + /// 同步重复刷新展示不会重复持有令牌,成功或错误结束都只需一次释放。 + func testRepeatedLoadingUpdatesOwnOnlyOneToken() { + let controller = makeController() + controller.viewDidAppear(false) + controller.setPageLoading(true) + controller.setPageLoading(true) + controller.setPageLoading(true) + controller.setPageLoading(false) + XCTAssertFalse(GlobalLoadingManager.shared.isShowing) + controller.viewWillDisappear(false) + } + + /// 离页时释放本页;迟到的结束不能关闭另一请求,迟到开始也不能覆盖新页面。 + func testLeavingAndLateUpdatesCannotHideOrCoverAnotherPage() { + let controller = makeController() + controller.viewDidAppear(false) + controller.setPageLoading(true) + let other = GlobalLoadingManager.shared.beginRequest() + controller.viewWillDisappear(false) + XCTAssertTrue(GlobalLoadingManager.shared.isShowing) + controller.setPageLoading(false) + XCTAssertTrue(GlobalLoadingManager.shared.isShowing) + GlobalLoadingManager.shared.endRequest(other) + controller.setPageLoading(true) + XCTAssertFalse(GlobalLoadingManager.shared.isShowing) + } + + /// 后台关闭通用遮罩,返回前台只恢复仍可见且读取未结束的页面。 + func testBackgroundAndForegroundRespectPendingReadAndVisibility() { + let controller = makeController() + controller.viewDidAppear(false) + controller.setPageLoading(true) + NotificationCenter.default.post(name: UIApplication.willResignActiveNotification, object: nil) + XCTAssertFalse(GlobalLoadingManager.shared.isShowing) + GlobalLoadingManager.shared.hideAll() + NotificationCenter.default.post(name: UIApplication.didBecomeActiveNotification, object: nil) + XCTAssertTrue(GlobalLoadingManager.shared.isShowing) + controller.viewWillDisappear(false) + NotificationCenter.default.post(name: UIApplication.didBecomeActiveNotification, object: nil) + XCTAssertFalse(GlobalLoadingManager.shared.isShowing) + } + + /// 请求已在后台完成时,不因页面回到前台而重新展示过期遮罩。 + func testReadFinishingInBackgroundDoesNotRestoreLoading() { + let controller = makeController() + controller.viewDidAppear(false) + controller.setPageLoading(true) + NotificationCenter.default.post(name: UIApplication.willResignActiveNotification, object: nil) + controller.setPageLoading(false) + NotificationCenter.default.post(name: UIApplication.didBecomeActiveNotification, object: nil) + XCTAssertFalse(GlobalLoadingManager.shared.isShowing) + controller.viewWillDisappear(false) + } + + private func makeController() -> GlobalLoadingPageViewController { + let controller = GlobalLoadingPageViewController() + controller.loadViewIfNeeded() + NotificationCenter.default.post(name: UIApplication.didBecomeActiveNotification, object: nil) + return controller + } +}