Files
suixinkan_uikit/suixinkan/UI/DroneDock/DroneDockTaskStatusView.swift
T
lujiuyin e3979e9e32 feat: 完善机巢任务安全控制与状态诊断
同步新版飞控与 WebSocket 回执合同,完善独立指令等待、暂停继续和返航状态;增加真机诊断并优化倒计时与素材库展示。
2026-11-04 17:34:28 +08:00

373 lines
20 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import SnapKit
import UIKit
/// 固定区域内组合任务状态与主操作,根据可用高度收紧内容,不滚动或改变外部尺寸。
@MainActor
final class DroneDockTaskStatusView: UIView {
/// 当前状态的主操作,由页面协调执行,不在组件中调用接口。
var onPrimaryAction: (() -> Void)?
/// 点击失败原因区域时展开完整说明,由页面协调展示。
var onDetails: (() -> Void)?
/// 当前内容采用的字号和间距参考比例,始终介于 0.8 与 1。
private(set) var effectiveScale: CGFloat = 1
/// 中间区域不足以显示常规内容时采用紧凑布局。
private(set) var usesCompactLayout = false
private let contentStack = UIStackView()
private let titleRow = UIView()
private let iconView = UIImageView()
private let titleLabel = DroneDockStyle.label(size: 22, weight: .semibold)
private let messageLabel = DroneDockStyle.label(size: 14, color: DroneDockStyle.secondary)
private let deviceLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
private let actionRow = UIView()
private let primaryButton = UIButton(type: .system)
private let failureView = DroneDockTaskFailureView()
private let completedView = DroneDockTaskCompletedView()
private let shootingView = DroneDockTaskShootingView()
private let controlStateView = DroneDockTaskControlStateView()
private var presentation: DroneDockTaskPresentation?
private var countdownSeconds: Int?
private var contentTop: Constraint?
private var contentLeading: Constraint?
private var contentTrailing: Constraint?
private var iconSize: Constraint?
private var titleLeading: Constraint?
private var titleRowHeight: Constraint?
private var messageHeight: Constraint?
private var deviceHeight: Constraint?
/// 读取当前可见控件的实际文案和许可,用于对照录屏;不改变布局或任务状态。
var diagnosticFields: [String: Any] {
func descendants(_ root: UIView) -> [UIView] { [root] + root.subviews.flatMap(descendants) }
func isVisible(_ view: UIView) -> Bool {
if view === self { return !view.isHidden }
return !view.isHidden && (view.superview.map(isVisible) ?? false)
}
let visible = descendants(self).filter(isVisible)
let buttonIDs = ["drone.task.remote.primary", "drone.task.remote.refresh", "drone.task.remote.failureRetry",
"drone.task.remote.shooting.indicator"]
let button = visible.compactMap { $0 as? UIButton }.first { buttonIDs.contains($0.accessibilityIdentifier ?? "") }
?? visible.compactMap { $0 as? UIButton }.first
let label = visible.compactMap { $0 as? UILabel }.first {
["drone.task.remote.statusTitle", "drone.task.remote.failureTitle"].contains($0.accessibilityIdentifier ?? "")
}
let message = visible.compactMap { $0 as? UILabel }.first {
["drone.task.remote.statusMessage", "drone.task.remote.failureReason"].contains($0.accessibilityIdentifier ?? "")
}
let countdownState = countdownSeconds == nil ? "hidden" : countdownSeconds == 0 ? "zero" : "running"
return ["phase": presentation?.phase.rawValue ?? "uninitialized",
"title": label?.text ?? presentation?.title ?? "",
"message": message?.text ?? "", "message_visible": message != nil,
"action": presentation.map { String(describing: $0.action) } ?? "none",
"action_title": button?.configuration?.title ?? button?.title(for: .normal) ?? "",
"action_enabled": button?.isEnabled == true && isUserInteractionEnabled,
"action_loading": visible.compactMap { $0 as? UIActivityIndicatorView }.contains { $0.isAnimating },
"interactive": isUserInteractionEnabled, "countdown": countdownState]
}
/// 创建固定状态槽,完成、失败与进行中使用各自的内容布局。
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
setupConstraints()
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 外部容器决定高度;状态内容不会通过固有尺寸推高底部安全区。
override var intrinsicContentSize: CGSize {
CGSize(width: UIView.noIntrinsicMetric, height: UIView.noIntrinsicMetric)
}
/// 更新真实状态与动作许可;刷新期间保留内容,只暂时禁用主操作。
func apply(_ presentation: DroneDockTaskPresentation, isRefreshing: Bool = false, isPrimaryActionLoading: Bool = false) {
self.presentation = presentation
updateCountdown(seconds: presentation.countdownSeconds)
let isFailure = presentation.phase == .failed
let isCompleted = [.postShootUploading, .completed].contains(presentation.phase)
let isShooting = presentation.phase == .shooting
let isControlState = [.paused, .returning, .returned].contains(presentation.phase)
contentStack.isHidden = isFailure || isCompleted || isShooting || isControlState
failureView.isHidden = !isFailure
completedView.isHidden = !isCompleted
shootingView.isHidden = !isShooting
controlStateView.isHidden = !isControlState
completedView.setIdentifiersActive(isCompleted)
shootingView.setIdentifiersActive(isShooting)
controlStateView.setIdentifiersActive(isControlState)
titleLabel.accessibilityIdentifier = isCompleted || isShooting || isControlState ? nil : "drone.task.remote.statusTitle"
messageLabel.accessibilityIdentifier = isCompleted || isShooting || isControlState ? nil : "drone.task.remote.statusMessage"
if isControlState {
primaryButton.accessibilityIdentifier = nil
controlStateView.apply(presentation, isRefreshing: isRefreshing, isPrimaryActionLoading: isPrimaryActionLoading)
setNeedsLayout()
return
}
if isShooting {
primaryButton.accessibilityIdentifier = nil
shootingView.apply(presentation)
setNeedsLayout()
return
}
if isCompleted {
primaryButton.accessibilityIdentifier = nil
completedView.apply(presentation, isRefreshing: isRefreshing)
setNeedsLayout()
return
}
if isFailure {
failureView.apply(presentation, isRefreshing: isRefreshing)
setNeedsLayout()
return
}
titleLabel.text = presentation.title
messageLabel.text = presentation.message
deviceLabel.text = presentation.deviceStatus
let style = Self.style(for: presentation.phase)
iconView.image = UIImage(systemName: style.symbol)
iconView.tintColor = style.color
let actionTitle = DroneDockHomeMetric.usableText(presentation.actionTitle)
primaryButton.isHidden = presentation.action == .none || actionTitle == nil
updatePrimaryButtonTitle()
primaryButton.isEnabled = presentation.isActionEnabled && !primaryButton.isHidden && !isRefreshing
primaryButton.backgroundColor = primaryButton.isEnabled
? DroneDockStyle.primary : DroneDockStyle.primary.withAlphaComponent(0.35)
primaryButton.accessibilityIdentifier = presentation.action == .refresh
? "drone.task.remote.refresh" : "drone.task.remote.primary"
setNeedsLayout()
}
/// 只刷新开拍按钮中的剩余秒数,不变更操作许可、服务端阶段或执行任何回调。
func updateCountdown(seconds: Int?) {
let value = presentation?.phase == .ready && presentation?.action == .start
? seconds.map { max(0, $0) } : nil
guard value != countdownSeconds else { return }
countdownSeconds = value
updatePrimaryButtonTitle()
}
private func updatePrimaryButtonTitle() {
guard let presentation else { return }
let title = DroneDockHomeMetric.usableText(presentation.actionTitle)
let displayedTitle: String?
if presentation.phase == .ready, presentation.action == .start,
let title, let countdownSeconds {
displayedTitle = "\(title)(\(countdownSeconds)s)"
} else {
displayedTitle = title
}
// 秒数直接替换,避免系统按钮的标题过渡暂时保留旧数字。
UIView.performWithoutAnimation {
primaryButton.setTitle(displayedTitle, for: .normal)
primaryButton.layoutIfNeeded()
}
}
/// 尺寸改变时仅重排内部内容,保留至少 44 点操作区域,不使用 transform 缩放。
override func layoutSubviews() {
if let phase = presentation?.phase, [.paused, .returning, .returned].contains(phase) {
super.layoutSubviews()
controlStateView.layoutIfNeeded()
effectiveScale = controlStateView.effectiveScale
usesCompactLayout = controlStateView.usesCompactLayout
return
}
if presentation?.phase == .shooting {
super.layoutSubviews()
shootingView.layoutIfNeeded()
effectiveScale = shootingView.effectiveScale
usesCompactLayout = shootingView.usesCompactLayout
return
}
if let phase = presentation?.phase, [.postShootUploading, .completed].contains(phase) {
super.layoutSubviews()
completedView.layoutIfNeeded()
effectiveScale = 1
usesCompactLayout = completedView.usesCompactLayout
return
}
if presentation?.phase == .failed {
super.layoutSubviews()
failureView.layoutIfNeeded()
effectiveScale = failureView.effectiveScale
usesCompactLayout = failureView.usesCompactLayout
return
}
updateContentLayout()
super.layoutSubviews()
}
private func setupUI() {
backgroundColor = .white
addSubview(controlStateView)
controlStateView.isHidden = true
controlStateView.onPrimaryAction = { [weak self] in self?.onPrimaryAction?() }
addSubview(shootingView)
shootingView.isHidden = true
addSubview(completedView)
completedView.isHidden = true
completedView.onViewMaterials = { [weak self] in self?.onPrimaryAction?() }
addSubview(failureView)
failureView.isHidden = true
failureView.onDetails = { [weak self] in self?.onDetails?() }
failureView.onPrimaryAction = { [weak self] in self?.onPrimaryAction?() }
contentStack.axis = .vertical
contentStack.alignment = .fill
contentStack.spacing = 10
addSubview(contentStack)
contentStack.addArrangedSubview(titleRow)
contentStack.addArrangedSubview(messageLabel)
contentStack.addArrangedSubview(deviceLabel)
contentStack.addArrangedSubview(actionRow)
titleRow.addSubview(iconView)
titleRow.addSubview(titleLabel)
iconView.contentMode = .scaleAspectFit
titleLabel.numberOfLines = 2
titleLabel.lineBreakMode = .byTruncatingTail
titleLabel.accessibilityTraits = .header
titleLabel.accessibilityIdentifier = "drone.task.remote.statusTitle"
messageLabel.numberOfLines = 3
messageLabel.lineBreakMode = .byTruncatingTail
messageLabel.accessibilityIdentifier = "drone.task.remote.statusMessage"
deviceLabel.numberOfLines = 1
deviceLabel.lineBreakMode = .byTruncatingTail
deviceLabel.accessibilityIdentifier = "drone.task.remote.deviceStatus"
actionRow.addSubview(primaryButton)
primaryButton.layer.cornerRadius = 9
primaryButton.titleLabel?.font = .monospacedDigitSystemFont(ofSize: 15, weight: .semibold)
primaryButton.titleLabel?.lineBreakMode = .byTruncatingTail
primaryButton.setTitleColor(.white, for: .normal)
primaryButton.setTitleColor(.white.withAlphaComponent(0.9), for: .disabled)
primaryButton.addTarget(self, action: #selector(primaryTapped), for: .touchUpInside)
}
private func setupConstraints() {
controlStateView.snp.makeConstraints { $0.edges.equalToSuperview() }
shootingView.snp.makeConstraints { $0.edges.equalToSuperview() }
completedView.snp.makeConstraints { $0.edges.equalToSuperview() }
failureView.snp.makeConstraints { make in make.edges.equalToSuperview() }
contentStack.snp.makeConstraints { make in
contentTop = make.top.equalToSuperview().offset(12).constraint
contentLeading = make.leading.equalToSuperview().offset(16).constraint
contentTrailing = make.trailing.equalToSuperview().inset(16).constraint
}
titleRow.snp.makeConstraints { make in titleRowHeight = make.height.equalTo(36).priority(999).constraint }
iconView.snp.makeConstraints { make in
make.leading.centerY.equalToSuperview()
iconSize = make.size.equalTo(36).constraint
}
titleLabel.snp.makeConstraints { make in
titleLeading = make.leading.equalTo(iconView.snp.trailing).offset(10).constraint
make.trailing.centerY.equalToSuperview()
}
messageLabel.snp.makeConstraints { make in messageHeight = make.height.equalTo(34).priority(999).constraint }
deviceLabel.snp.makeConstraints { make in deviceHeight = make.height.equalTo(16).priority(999).constraint }
actionRow.snp.makeConstraints { make in make.height.equalTo(44) }
primaryButton.snp.makeConstraints { make in
make.edges.equalToSuperview()
}
}
private func updateContentLayout() {
guard let presentation, bounds.width > 0, bounds.height > 0 else { return }
let isExtreme = bounds.height < 120
let horizontalInset: CGFloat = isExtreme ? 12 : 16
let verticalInset: CGFloat = isExtreme ? 6 : 12
let width = max(1, bounds.width - horizontalInset * 2)
let availableHeight = max(1, bounds.height - verticalInset * 2)
let message = DroneDockHomeMetric.usableText(presentation.message)
let hasMessage = message != nil && message != DroneDockHomeMetric.usableText(presentation.title)
let device = DroneDockHomeMetric.usableText(presentation.deviceStatus)
let hasDevice = device != nil && device != "—"
let naturalTitle = max(36, Self.textHeight(presentation.title, font: .systemFont(ofSize: 22, weight: .semibold),
width: width - 46, lines: 2))
let naturalMessage = hasMessage ? Self.textHeight(message, font: .systemFont(ofSize: 14), width: width, lines: 3) : 0
let naturalDevice = hasDevice ? UIFont.systemFont(ofSize: 12).lineHeight : 0
let naturalGaps = CGFloat(1 + (hasMessage ? 1 : 0) + (hasDevice ? 1 : 0)) * 10
let naturalHeight = naturalTitle + naturalMessage + naturalDevice + 44 + naturalGaps
effectiveScale = min(1, max(0.8, availableHeight / max(1, naturalHeight)))
usesCompactLayout = bounds.height < 190 || naturalHeight * effectiveScale > availableHeight
// 先收紧图标和间距;只有不足九成空间时才缩小文字。
let fontScale: CGFloat = effectiveScale >= 0.9 ? 1 : effectiveScale / 0.9
titleLabel.font = .systemFont(ofSize: max(17, 22 * fontScale), weight: .semibold)
messageLabel.font = .systemFont(ofSize: max(12, 14 * fontScale))
deviceLabel.font = .systemFont(ofSize: 12)
let icon: CGFloat = isExtreme ? 20 : usesCompactLayout ? 24 : 36 * effectiveScale
let gap: CGFloat = isExtreme ? 4 : max(4, 10 * effectiveScale)
let titleGap: CGFloat = usesCompactLayout ? 8 : 10 * effectiveScale
titleLabel.numberOfLines = usesCompactLayout ? 1 : 2
messageLabel.numberOfLines = usesCompactLayout ? 2 : 3
messageLabel.isHidden = !hasMessage || isExtreme
deviceLabel.isHidden = !hasDevice || usesCompactLayout
let titleWidth = max(1, width - icon - titleGap)
var titleHeight = max(icon, Self.textHeight(presentation.title, font: titleLabel.font,
width: titleWidth, lines: titleLabel.numberOfLines))
var messageLineCount = messageLabel.numberOfLines
var bodyHeight = messageLabel.isHidden ? 0 : Self.textHeight(message, font: messageLabel.font,
width: width, lines: messageLineCount)
let deviceTextHeight = deviceLabel.isHidden ? 0 : ceil(deviceLabel.font.lineHeight)
var contentHeight: CGFloat {
titleHeight + bodyHeight + deviceTextHeight + 44
+ CGFloat(1 + (messageLabel.isHidden ? 0 : 1) + (deviceLabel.isHidden ? 0 : 1)) * gap
}
while contentHeight > availableHeight && messageLineCount > 1 && !messageLabel.isHidden {
messageLineCount -= 1
bodyHeight = Self.textHeight(message, font: messageLabel.font, width: width, lines: messageLineCount)
}
if contentHeight > availableHeight && titleLabel.numberOfLines > 1 {
titleLabel.numberOfLines = 1
titleHeight = max(icon, ceil(titleLabel.font.lineHeight))
}
if contentHeight > availableHeight && !messageLabel.isHidden {
messageLabel.isHidden = true
bodyHeight = 0
}
messageLabel.numberOfLines = messageLineCount
let top = verticalInset + max(0, (availableHeight - contentHeight) / 2)
contentTop?.update(offset: top)
contentLeading?.update(offset: horizontalInset)
contentTrailing?.update(inset: horizontalInset)
iconSize?.update(offset: icon)
titleLeading?.update(offset: titleGap)
titleRowHeight?.update(offset: titleHeight)
messageHeight?.update(offset: max(1, bodyHeight))
deviceHeight?.update(offset: max(1, deviceTextHeight))
contentStack.spacing = gap
}
private static func textHeight(_ text: String?, font: UIFont, width: CGFloat, lines: Int) -> CGFloat {
guard let text, !text.isEmpty else { return ceil(font.lineHeight) }
let height = (text as NSString).boundingRect(with: CGSize(width: max(1, width), height: .greatestFiniteMagnitude),
options: [.usesLineFragmentOrigin, .usesFontLeading],
attributes: [.font: font], context: nil).height
return ceil(min(height, font.lineHeight * CGFloat(lines)))
}
private static func style(for phase: DroneDockTaskDisplayPhase) -> (symbol: String, color: UIColor) {
switch phase {
case .loading: ("clock.arrow.circlepath", DroneDockStyle.primary)
case .navigating: ("paperplane.fill", DroneDockStyle.primary)
case .ready: ("checkmark.circle.fill", DroneDockStyle.success)
case .shooting: ("video.fill", DroneDockStyle.primary)
case .postShootUploading: ("checkmark.circle.fill", DroneDockStyle.success)
case .postShootUploadFailed: ("exclamationmark.circle.fill", DroneDockStyle.warning)
case .paused: ("pause.circle.fill", DroneDockStyle.warning)
case .returning: ("arrow.uturn.backward.circle.fill", DroneDockStyle.warning)
case .returned: ("house.circle.fill", DroneDockStyle.warning)
case .completed: ("checkmark.circle.fill", DroneDockStyle.success)
case .failed: ("xmark.circle.fill", UIColor(hex: 0xD46B62))
case .blocked, .readError: ("exclamationmark.circle.fill", DroneDockStyle.warning)
case .unknown: ("questionmark.circle.fill", DroneDockStyle.secondary)
}
}
@objc private func primaryTapped() {
guard primaryButton.isEnabled, !primaryButton.isHidden else { return }
onPrimaryAction?()
}
}