/** 全屏分类设置。发现列表仅在解锁期间开放,保存仍由后端逐项校验。 */ import { useCallback, useEffect, useMemo, useRef, useState, type KeyboardEvent } from "react"; import { api } from "../lib/ipc"; import { BUILD, VERSION_LABEL } from "../lib/version"; import { firmwareLabel, teamName } from "../lib/format"; import { aimPoint, paintCrosshair, paintGrid, type Geometry } from "../lib/reticle"; import type { ConfigView, CrosshairConfig, HudView, Snapshot, TeamHealthDto } from "../lib/types"; import { Button, Field, Select, Slider, Switch } from "./controls"; import { HealthBar } from "./HealthBar"; import { Icon, type IconName } from "./Icon"; interface Props { snapshot: Snapshot; hud: HudView; onHud: (hud: HudView) => void; calibrating: boolean; onCalibrating: (active: boolean) => void; onClose: () => void; closing?: boolean; connected?: boolean; onExitComplete?: () => void; onNeedsUnlock: (reason: string) => void; onError: (message: string) => void; onInfo: (message: string) => void; onConfig: (config: ConfigView) => void; } const SAVE_DEBOUNCE_MS = 350; interface Category { id: string; label: string; en: string; hint: string; preview?: boolean } const CATEGORY_ICONS: Record = { general: "settings", devices: "devices", reticle: "target", calibration: "calibration", grid: "grid", health: "health", feedback: "feedback", slots: "splitView", media: "camera", security: "lock", }; export function SettingsPanel({ snapshot, hud, onHud, calibrating, onCalibrating, onClose, closing = false, connected = true, onExitComplete, onNeedsUnlock, onError, onInfo, onConfig }: Props) { const config = snapshot.config; const locked = !snapshot.unlocked && config.role !== "referee"; const isTeam = config.role === "team"; const panelRef = useRef(null); const closeButton = useRef(null); const unlockCallback = useRef(onNeedsUnlock); unlockCallback.current = onNeedsUnlock; useEffect(() => { if (closing && window.matchMedia("(prefers-reduced-motion: reduce)").matches) onExitComplete?.(); }, [closing, onExitComplete]); useEffect(() => { const previous = document.activeElement instanceof HTMLElement ? document.activeElement : null; const panel = panelRef.current; closeButton.current?.focus({ preventScroll: true }); return () => { if (previous?.isConnected && (document.activeElement === document.body || panel?.contains(document.activeElement))) { previous.focus({ preventScroll: true }); } }; }, []); useEffect(() => { if (locked) return; void api.setDiscoveryOpen(true).catch(err => unlockCallback.current(err instanceof Error ? err.message : String(err))); return () => { void api.setDiscoveryOpen(false).catch(() => undefined); }; }, [locked]); const [pending, setPending] = useState(null); const pendingSave = useRef(null); const saveCallbacks = useRef({ onConfig, onError }); saveCallbacks.current = { onConfig, onError }; // 立即关闭或开始画面校准时,也提交最后一份草稿。 useEffect(() => () => { const last = pendingSave.current; pendingSave.current = null; if (last) void api.saveHud(last).then(saveCallbacks.current.onConfig).catch(err => saveCallbacks.current.onError(String(err))); }, []); useEffect(() => { if (!pending) return; const timer = window.setTimeout(() => { pendingSave.current = null; setPending(null); void api.saveHud(pending).then(onConfig).catch(err => onError(err instanceof Error ? err.message : String(err))); }, SAVE_DEBOUNCE_MS); return () => window.clearTimeout(timer); }, [pending, onConfig, onError]); const update = useCallback((change: (draft: HudView) => void) => { const next = structuredClone(hud); change(next); onHud(next); pendingSave.current = next; setPending(next); }, [hud, onHud]); const run = async (action: () => Promise) => { try { onConfig(await action()); await api.refresh(); } catch (err) { const message = err instanceof Error ? err.message : String(err); if (message.includes("密码")) onNeedsUnlock(message); else onError(message); } }; const cameraOptions = useMemo(() => snapshot.cameras.map(camera => ({ value: camera.id, label: camera.idText, hint: `${camera.addr} · ${camera.online ? "在线" : "离线"} · 固件 ${firmwareLabel(camera)}${camera.compatible ? "" : ` · 协议 ${camera.protocol} 不匹配`}`, })), [snapshot.cameras]); const armorOptions = useMemo(() => snapshot.armorBoards.map(board => ({ value: board.id, label: board.idText, hint: `${board.addr} · ${teamName(board.team, config.teamNames)} · ${board.hp} 血 · ${board.online ? "在线" : "离线"}`, })), [snapshot.armorBoards, config.teamNames]); const categories = useMemo(() => [ { id: "general", label: "常规", en: "GENERAL", hint: "选择客户端的运行模式。" }, ...(isTeam ? [ { id: "devices", label: "设备绑定", en: "DEVICES", hint: "选择本机接收的图传板与装甲板,核对所属队伍。" }, { id: "reticle", label: "瞄准器", en: "RETICLE", hint: "调整准星外观,预览效果与操作画面一致。", preview: true }, { id: "calibration", label: "瞄点校准", en: "CALIBRATION", hint: "调整镜头与弹着点的偏移,偏移按画面比例保存。", preview: true }, { id: "grid", label: "辅助网格", en: "GRID", hint: "选择画面辅助线的样式、密度和透明度。", preview: true }, { id: "health", label: "血条", en: "ARMOR", hint: "左侧显示本队血量,右侧显示对手血量;血条长度与剩余血量成正比。", preview: true }, { id: "feedback", label: "受击与提示", en: "FEEDBACK", hint: "设置受击反馈和画面读数。" }, ] : [{ id: "slots", label: "画面槽位", en: "SLOTS", hint: "自动分配两队的图传与装甲板,也可手动调整。" }]), { id: "media", label: "录制与截图", en: "CAPTURE", hint: "截图保存为 PNG;录制保存为 MP4,需要 ffmpeg。" }, { id: "security", label: "安全", en: "ACCESS", hint: "密码用于防止现场误改;能修改本机配置或程序的人仍可绕过。" }, ], [isTeam]); const [active, setActive] = useState("general"); const [next, setNext] = useState(null); const [direction, setDirection] = useState(1); const current = categories.find(category => category.id === active) ?? categories[0]; const selected = next ?? current.id; const switchCategory = (id: string) => { if (id === current.id) { setNext(null); return; } setDirection(categories.findIndex(item => item.id === id) > categories.findIndex(item => item.id === current.id) ? 1 : -1); setNext(id); }; const navigate = (event: KeyboardEvent, index: number) => { let target = index; if (event.key === "ArrowDown") target = (index + 1) % categories.length; else if (event.key === "ArrowUp") target = (index - 1 + categories.length) % categories.length; else if (event.key === "Home") target = 0; else if (event.key === "End") target = categories.length - 1; else return; event.preventDefault(); switchCategory(categories[target].id); panelRef.current?.querySelector(`#settings-tab-${categories[target].id}`)?.focus(); }; const trapFocus = (event: KeyboardEvent) => { if (event.key !== "Tab") return; const nodes = Array.from(panelRef.current?.querySelectorAll( 'button:not(:disabled), input:not(:disabled), select:not(:disabled), [tabindex="0"]', ) ?? []).filter(node => node.tabIndex >= 0 && node.getClientRects().length > 0); const first = nodes[0], last = nodes[nodes.length - 1]; if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last?.focus(); } else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first?.focus(); } }; const camera = snapshot.cameras.find(item => item.id === config.cameraId); const cameraStats = snapshot.stats.find(item => item.camera === config.cameraId); const board = snapshot.armorBoards.find(item => item.id === config.armorId); const cameraState = !connected ? "本地通道断开" : config.cameraId === null ? "未绑定" : !camera?.online ? "离线" : !camera.compatible ? "协议不匹配" : cameraStats?.online && cameraStats.hasFrames ? "正在接收" : "已发现 · 等待画面"; const armorState = !connected ? "本地通道断开" : config.armorId === null ? "未绑定" : !board?.online ? "离线" : board.team === 255 ? "等待队伍设置" : board.team !== config.team ? "队伍不匹配" : "在线"; const mirrorControls = <> void run(() => api.setMirror(mirror))} /> void run(() => api.setMirrorVertical(mirror))} /> ; const content = () => { switch (current.id) { case "general": return <> void run(() => api.bindCamera(id))} /> void run(() => api.setTeam(team))} /> {mirrorControls}
图传{config.cameraIdText ?? "—"}{cameraState} 装甲板{config.armorIdText ?? "—"}{armorState}
{cameraOptions.length === 0 &&

尚未发现图传板。请检查供电、Wi-Fi 与防火墙,确认设备与本机处于同一网络。

} ; case "reticle": return <> update(draft => { draft.crosshair.visible = visible; })} /> update(draft => { draft.crosshair.color = event.target.value; })} />{hud.crosshair.color.toUpperCase()} ; case "calibration": return
update(draft => { draft.crosshair.offsetX = offsetX; draft.crosshair.offsetY = offsetY; })} />
; case "grid": return <> update(draft => { draft.grid.visible = visible; })} /> void run(() => api.setRefereeSlots({ ...snapshot.slots, cameraA, manual: true }))} /> void run(() => api.setRefereeSlots({ ...snapshot.slots, armorA, manual: true }))} /> { const value = event.target.value.trim(); if (value !== config.recordingDir) void run(() => api.setRecordingOptions({ dir: value, ffmpeg: null, crf: null, preset: null })); }} />
{ const value = event.target.value.trim(); if (value && value !== config.ffmpeg) void run(() => api.setRecordingOptions({ dir: null, ffmpeg: value, crf: null, preset: null })); }} />

界面内回放仅支持允许访问的目录,默认包含 ~/Movies/cam-desktop。其他目录中的视频可用系统播放器打开。

; case "security": return <>
清空本机配置

原配置备份为 .bak,之后需重启程序。

退出客户端

正在进行的录制会先结束并保存。

; } }; return ; } /* ───────────────────────────────────────────────────────────── 实时预览 */ /** * 预览窗:用真正的绘制代码画一遍当前设置。 * * 它不是一个示意图——`paintCrosshair` / `paintGrid` 就是画面里用的那两个函数。所以"预览里 * 对、画面上偏"这种最坏的情况在这里不可能发生。 * * 血量那根滑杆是刻意加的:低血阈值与脉动只有真的把血拖下去才看得见。 */ function Preview({ hud, team, mirrored, mirroredVertical }: { hud: HudView; team: number; mirrored: boolean; mirroredVertical: boolean }) { const canvasRef = useRef(null); const [demoHp, setDemoHp] = useState(68); useEffect(() => { const canvas = canvasRef.current; if (!canvas) return; const paint = () => { const dpr = window.devicePixelRatio || 1; const width = canvas.clientWidth; const height = canvas.clientHeight; if (width === 0 || height === 0) return; canvas.width = Math.round(width * dpr); canvas.height = Math.round(height * dpr); const ctx = canvas.getContext("2d"); if (!ctx) return; ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.clearRect(0, 0, width, height); ctx.save(); ctx.translate(mirrored ? width : 0, mirroredVertical ? height : 0); ctx.scale(mirrored ? -1 : 1, mirroredVertical ? -1 : 1); // 伪画面:一块低饱和的远景色 + 一条地平线。它的作用是让准星与网格有一个"深色背景 // 之上"的参照,而不是浮在一片纯黑里看不出对比。 const sky = ctx.createLinearGradient(0, 0, 0, height); sky.addColorStop(0, "#141d25"); sky.addColorStop(0.55, "#1b2630"); sky.addColorStop(1, "#0b1015"); ctx.fillStyle = sky; ctx.fillRect(0, 0, width, height); ctx.strokeStyle = "rgba(120, 150, 170, 0.16)"; ctx.lineWidth = 1; ctx.beginPath(); ctx.moveTo(0, height * 0.62); ctx.lineTo(width, height * 0.62); ctx.stroke(); const geometry: Geometry = { left: 0, top: 0, drawWidth: width, drawHeight: height, }; if (hud.grid.visible) paintGrid(ctx, geometry, hud.grid); ctx.restore(); if (hud.crosshair.visible) { // 预览里的偏移按比例缩到这块小画布上,方向与真画面一致。 const aim = aimPoint(geometry, hud.crosshair, mirrored, width, height, mirroredVertical); paintCrosshair(ctx, aim.x, aim.y, Math.min(width, height), hud.crosshair); } }; paint(); // 字体与尺寸都可能在挂载之后才稳定:等一帧再画一次,别拿一个 0×0 的画布交付。 const raf = requestAnimationFrame(paint); const observer = new ResizeObserver(paint); observer.observe(canvas); return () => { cancelAnimationFrame(raf); observer.disconnect(); }; }, [hud, mirrored, mirroredVertical]); // 预览用的血量。`available` 恒为 true:占位符的形态在真画面上看更清楚。 const mock: TeamHealthDto = { team, name: "预览", available: true, placeholder: "", hp: demoHp, hps: [], board: null, boardText: null, critical: demoHp <= hud.health.lowThreshold, outcome: null, }; return (
HUD PREVIEW 合成画面 · 非设备图传
{hud.health.visible && (
)}
预览血量 `${value}`} onChange={setDemoHp} /> 低血 ≤{hud.health.lowThreshold}
); } /* ───────────────────────────────────────────────────────────── 校准 */ /** 瞄准器偏移:拖画面校准 + 数值微调 + 归零。 */ function Calibration({ crosshair, calibrating, onCalibrating, onChange, }: { crosshair: CrosshairConfig; calibrating: boolean; onCalibrating: (active: boolean) => void; onChange: (offsetX: number, offsetY: number) => void; }) { return (

摄像头与枪管不同轴时,可将瞄准点调整到弹着点。偏移按 画面比例保存,更换分辨率或调整窗口大小后仍有效。

`${(value * 100).toFixed(2)}%`} onChange={(value) => onChange(value, crosshair.offsetY)} /> `${(value * 100).toFixed(2)}%`} onChange={(value) => onChange(crosshair.offsetX, value)} />
); } /* ───────────────────────────────────────────────────────── 改密码 */ /** 改密码。 */ function ChangePassword({ onDone, onError, }: { onDone: (message: string) => void; onError: (message: string) => void; }) { const [current, setCurrent] = useState(""); const [fresh, setFresh] = useState(""); const [busy, setBusy] = useState(false); return (
setCurrent(event.target.value)} /> setFresh(event.target.value)} />
); }