将标准流程视频从旧训练模块独立出来
This commit is contained in:
parent
b15f12a92a
commit
e27aba66a2
@ -89,15 +89,3 @@ public sealed class SaveFileDialog
|
||||
if(file is null)return false; FileName=file.TryGetLocalPath()??throw new IOException("请选择本地保存位置");return true;
|
||||
}
|
||||
}
|
||||
public sealed class OpenFolderDialog
|
||||
{ public string Title { get; set; } = "选择文件夹";
|
||||
public string InitialDirectory { get; set; } = "";
|
||||
public string FolderName { get; private set; } = "";
|
||||
public async Task<bool?> ShowDialogAsync()
|
||||
{
|
||||
var storage=DesktopPlatform.Owner.StorageProvider;
|
||||
var folders=await storage.OpenFolderPickerAsync(new FolderPickerOpenOptions { Title=Title,AllowMultiple=false,
|
||||
SuggestedStartLocation=Directory.Exists(InitialDirectory)?await storage.TryGetFolderFromPathAsync(InitialDirectory):null });
|
||||
if(folders.Count==0)return false; FolderName=folders[0].TryGetLocalPath()??throw new IOException("请选择本地文件夹");return true;
|
||||
}
|
||||
}
|
||||
|
||||
@ -5,7 +5,7 @@ using SopHelper.Engine.Sop;
|
||||
using OpenCvSharp;
|
||||
using SopHelper.Presentation.Imaging;
|
||||
|
||||
namespace SopHelper.Training;
|
||||
namespace SopHelper.SopVideo;
|
||||
|
||||
public sealed partial class CameraViewModel
|
||||
{
|
||||
@ -5,7 +5,7 @@ using OpenCvSharp;
|
||||
using SopHelper.Engine.Training;
|
||||
using SopHelper.Presentation;
|
||||
|
||||
namespace SopHelper.Training;
|
||||
namespace SopHelper.SopVideo;
|
||||
|
||||
public sealed partial class CameraViewModel
|
||||
{
|
||||
@ -27,7 +27,7 @@ public sealed partial class CameraViewModel
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(source) || _closing) return;
|
||||
var destination = Path.GetFullPath(StandardVideoPath);
|
||||
if (!RecipeWorkspace.IsWithin(destination, _recipeRecordingDirectory!))
|
||||
if (!RecipeWorkspace.IsWithin(destination, SaveDirectory))
|
||||
throw new IOException("标准视频路径不在当前配方目录中");
|
||||
if (Path.GetFullPath(source).Equals(destination, OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal))
|
||||
{ Status = "所选文件已经是当前标准视频"; return; }
|
||||
@ -63,7 +63,7 @@ public sealed partial class CameraViewModel
|
||||
RecordingInfo = $"已导入 · {duration.TotalSeconds:F1} 秒";
|
||||
Status = "标准视频已导入当前配方的 sop_stand/sop.avi,可播放或测试流程";
|
||||
StateChanged();
|
||||
try { SopStandardVideoDuration.Remember(Path.GetDirectoryName(_recipeRecordingDirectory!)!, duration); }
|
||||
try { SopStandardVideoDuration.Remember(Path.GetDirectoryName(SaveDirectory)!, duration); }
|
||||
catch (Exception error) when (error is IOException or UnauthorizedAccessException)
|
||||
{ Status += ";标准用时保存失败:" + error.Message; }
|
||||
}
|
||||
@ -2,7 +2,6 @@
|
||||
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
using Avalonia;
|
||||
using SopHelper.Presentation;
|
||||
using Avalonia.Media;
|
||||
@ -10,11 +9,13 @@ using SopHelper.Presentation.Imaging;
|
||||
using SopHelper.Presentation.Threading;
|
||||
using OpenCvSharp;
|
||||
using SopHelper.Engine.Camera;
|
||||
using SopHelper.Engine.Training;
|
||||
using Prism.Commands;
|
||||
using Prism.Mvvm;
|
||||
|
||||
namespace SopHelper.Training;
|
||||
namespace SopHelper.SopVideo;
|
||||
|
||||
/// <summary>管理当前配方的标准视频、录像预览和流程回测,关闭时统一释放相机与播放资源。</summary>
|
||||
public sealed partial class CameraViewModel : BindableBase
|
||||
{
|
||||
private readonly ICameraService _camera;
|
||||
@ -22,9 +23,6 @@ public sealed partial class CameraViewModel : BindableBase
|
||||
private readonly object _frames = new();
|
||||
private readonly Dispatcher _dispatcher;
|
||||
private readonly DispatcherTimer _timer;
|
||||
private readonly string _settingsPath;
|
||||
private readonly string? _recipeRecordingDirectory;
|
||||
private readonly bool _sopStandard;
|
||||
private readonly Func<CameraInfo?> _selectedCameraProvider;
|
||||
private readonly Stopwatch _previewClock = Stopwatch.StartNew();
|
||||
private Mat? _latest;
|
||||
@ -35,7 +33,6 @@ public sealed partial class CameraViewModel : BindableBase
|
||||
private bool _busy, _previewing, _recording;
|
||||
private bool _paused;
|
||||
private string _status = "使用运行设置中选中的相机,点击“开启相机预览”";
|
||||
private string _directory;
|
||||
private string _lastRecording = "";
|
||||
private string _recordingInfo = "未录像";
|
||||
private CameraInfo? _previewCamera, _observedCamera;
|
||||
@ -57,18 +54,16 @@ public sealed partial class CameraViewModel : BindableBase
|
||||
public bool IsPaused { get => _paused; private set { SetProperty(ref _paused, value); StateChanged(); } }
|
||||
public string PauseButtonText => IsPaused ? "继续录制" : "暂停录制";
|
||||
public string StandardVideoPath => Path.Combine(SaveDirectory, "sop.avi");
|
||||
public bool HasStandardVideo => _sopStandard && File.Exists(StandardVideoPath);
|
||||
public bool HasStandardVideo => File.Exists(StandardVideoPath);
|
||||
public Func<Task<bool>>? ConfirmRestartAsync { get; set; }
|
||||
public bool CanChangeDirectory => _recipeRecordingDirectory is null && !IsBusy && !IsRecording && !_closing;
|
||||
public string PreviewButtonText => IsPreviewing ? "关闭相机" : "开启相机预览";
|
||||
public string RecordingInfo { get => _recordingInfo; private set => SetProperty(ref _recordingInfo, value); }
|
||||
public string SaveDirectory { get => _directory; set => SetProperty(ref _directory, _recipeRecordingDirectory ?? value); }
|
||||
public string SaveDirectory { get; }
|
||||
public string LastRecording { get => _lastRecording; private set { SetProperty(ref _lastRecording, value); UpdateCommands(); } }
|
||||
public double RecordingFps { get; set; } = 30;
|
||||
public DelegateCommand PreviewCommand { get; }
|
||||
public DelegateCommand StartRecordingCommand { get; }
|
||||
public DelegateCommand StopRecordingCommand { get; }
|
||||
public DelegateCommand BrowseCommand { get; }
|
||||
public DelegateCommand RevealCommand { get; }
|
||||
public DelegateCommand PauseCommand { get; }
|
||||
public DelegateCommand RestartCommand { get; }
|
||||
@ -82,36 +77,28 @@ public sealed partial class CameraViewModel : BindableBase
|
||||
public DelegateCommand ImportVideoCommand { get; }
|
||||
public event Action<string>? RecordingLimitReached;
|
||||
|
||||
public CameraViewModel(ICameraService camera, string root, string? recipeName = null, TimeProvider? timeProvider = null, bool sopStandard = false, Func<CameraInfo?>? selectedCameraProvider = null)
|
||||
/// <summary>绑定已保存配方的固定视频目录,并接管传入相机的生命周期。</summary>
|
||||
public CameraViewModel(ICameraService camera, string root, string recipeName, TimeProvider? timeProvider = null, Func<CameraInfo?>? selectedCameraProvider = null)
|
||||
{
|
||||
_selectedCameraProvider = selectedCameraProvider ?? (() => null);
|
||||
_recorder = new VideoRecorder(timeProvider);
|
||||
_camera = camera; _dispatcher = Dispatcher.CurrentDispatcher;
|
||||
var recipeDirectory = string.IsNullOrWhiteSpace(recipeName) ? null : new SopHelper.Engine.Training.RecipeWorkspace(root).DirectoryFor(recipeName);
|
||||
_sopStandard = sopStandard;
|
||||
if (sopStandard && recipeDirectory is null) throw new ArgumentException("SOP录像必须属于已保存的配方");
|
||||
_recipeRecordingDirectory = recipeDirectory is null ? null : Path.Combine(recipeDirectory, sopStandard ? "sop_stand" : "recordings");
|
||||
_directory = _recipeRecordingDirectory ?? Path.Combine(root, "workspace", "recordings");
|
||||
_settingsPath = recipeDirectory is null ? Path.Combine(root, "workspace", "camera-settings.json") : Path.Combine(recipeDirectory, sopStandard ? "sop-camera-settings.json" : "camera-settings.json");
|
||||
try
|
||||
{
|
||||
SaveDirectory = _recipeRecordingDirectory ?? ReadSaveDirectory(root);
|
||||
}
|
||||
catch (Exception e) { Status = "录像目录配置读取失败:" + e.Message; }
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(recipeName);
|
||||
SaveDirectory = Path.Combine(new RecipeWorkspace(root).DirectoryFor(recipeName), "sop_stand");
|
||||
PreviewCommand = Command(TogglePreviewAsync, () => !IsBusy && !_closing && !IsTestingFlow && (IsPreviewing || SelectedCamera != null));
|
||||
StartRecordingCommand = Command(StartRecordingAsync, () => !IsBusy && !_closing && !IsRecording && !HasStandardVideo && IsPreviewing && Preview != null && HasRecentFrame);
|
||||
StopRecordingCommand = Command(() => { StopRecording(); return Task.CompletedTask; }, () => !IsBusy && !_closing && IsRecording);
|
||||
PauseCommand = Command(() => { TogglePause(); return Task.CompletedTask; }, () => !IsBusy && !_closing && IsRecording);
|
||||
RestartCommand = Command(RestartRecordingAsync, () => _sopStandard && !IsBusy && !_closing && !IsTestingFlow && HasStandardVideo && IsPreviewing && Preview != null && HasRecentFrame);
|
||||
PlayVideoCommand = Command(PlayVideoAsync, () => _sopStandard && !IsBusy && !_closing && !IsTestingFlow && !IsRecording && HasStandardVideo && !Playback.IsPlaying);
|
||||
RestartCommand = Command(RestartRecordingAsync, () => !IsBusy && !_closing && !IsTestingFlow && HasStandardVideo && IsPreviewing && Preview != null && HasRecentFrame);
|
||||
PlayVideoCommand = Command(PlayVideoAsync, () => !IsBusy && !_closing && !IsTestingFlow && !IsRecording && HasStandardVideo && !Playback.IsPlaying);
|
||||
PauseVideoCommand = Command(() => { Playback.Pause(); Status = "视频播放已暂停"; return Task.CompletedTask; }, () => !IsBusy && !_closing && !IsTestingFlow && Playback.IsPlaying);
|
||||
ToggleVideoPlaybackCommand = Command(async () =>
|
||||
{
|
||||
if (Playback.IsPlaying) { Playback.Pause(); Status = "视频播放已暂停"; }
|
||||
else await PlayVideoAsync();
|
||||
}, () => _sopStandard && !IsBusy && !_closing && !IsTestingFlow && !IsRecording && HasStandardVideo);
|
||||
ImportVideoCommand = Command(ImportVideoAsync, () => _sopStandard && !IsBusy && !_closing && !IsTestingFlow && !IsRecording);
|
||||
TestFlowCommand = Command(StartFlowTestAsync, () => _sopStandard && !IsBusy && !_closing && !IsTestingFlow && !IsRecording && HasStandardVideo && FlowTestConfigProvider is not null);
|
||||
}, () => !IsBusy && !_closing && !IsTestingFlow && !IsRecording && HasStandardVideo);
|
||||
ImportVideoCommand = Command(ImportVideoAsync, () => !IsBusy && !_closing && !IsTestingFlow && !IsRecording);
|
||||
TestFlowCommand = Command(StartFlowTestAsync, () => !IsBusy && !_closing && !IsTestingFlow && !IsRecording && HasStandardVideo && FlowTestConfigProvider is not null);
|
||||
StopVideoCommand = Command(async () => { await Playback.StopAsync(); EndFlowTest("测试已停止"); Status = "视频播放已停止"; }, () => !IsBusy && !_closing && Playback.IsLoaded);
|
||||
PreviousVideoFrameCommand = Command(() => Playback.StepFrameAsync(-1), () => CanSeekVideo && !_closing && !Playback.IsSeeking);
|
||||
NextVideoFrameCommand = Command(() => Playback.StepFrameAsync(1), () => CanSeekVideo && !_closing && !Playback.IsSeeking);
|
||||
@ -133,24 +120,10 @@ public sealed partial class CameraViewModel : BindableBase
|
||||
}
|
||||
};
|
||||
Playback.Failed += message => { EndFlowTest(message); Status = message; };
|
||||
BrowseCommand = Command(async () =>
|
||||
{
|
||||
var picker = new OpenFolderDialog { Title = "选择录像保存目录" };
|
||||
if (Directory.Exists(SaveDirectory)) picker.InitialDirectory = SaveDirectory;
|
||||
if (await picker.ShowDialogAsync() == true) { SaveDirectory = picker.FolderName; SaveSettings(); }
|
||||
}, () => CanChangeDirectory);
|
||||
RevealCommand = Command(() =>
|
||||
{
|
||||
if (!string.IsNullOrEmpty(LastRecording) && File.Exists(LastRecording))
|
||||
{
|
||||
DesktopPlatform.Reveal(LastRecording);
|
||||
}
|
||||
else
|
||||
{
|
||||
Directory.CreateDirectory(SaveDirectory);
|
||||
var info = new ProcessStartInfo("explorer.exe") { UseShellExecute = true };
|
||||
info.ArgumentList.Add(Path.GetFullPath(SaveDirectory)); Process.Start(info);
|
||||
}
|
||||
Directory.CreateDirectory(SaveDirectory);
|
||||
DesktopPlatform.Reveal(SaveDirectory);
|
||||
return Task.CompletedTask;
|
||||
}, () => !IsBusy && !_closing);
|
||||
_camera.FrameArrived += OnFrame;
|
||||
@ -159,9 +132,8 @@ public sealed partial class CameraViewModel : BindableBase
|
||||
_timer = new DispatcherTimer(TimeSpan.FromMilliseconds(250), DispatcherPriority.Background, (_, _) => Tick(), _dispatcher);
|
||||
_timer.Start();
|
||||
if (HasStandardVideo) { LastRecording = StandardVideoPath; RecordingInfo = "已有SOP流程视频"; Status = "已有标准视频,可播放、测试流程或导入视频替换"; }
|
||||
if (SelectedCamera is null && !HasStandardVideo) Status = _sopStandard
|
||||
? "可导入标准视频,或先在运行设置中选择相机后录制"
|
||||
: "请先在运行设置中选择相机,再开启录像预览";
|
||||
if (SelectedCamera is null && !HasStandardVideo)
|
||||
Status = "可导入标准视频,或先在运行设置中选择相机后录制";
|
||||
}
|
||||
|
||||
private DelegateCommand Command(Func<Task> action, Func<bool> canExecute)
|
||||
@ -180,7 +152,7 @@ public sealed partial class CameraViewModel : BindableBase
|
||||
private void UpdateCommands() { foreach (var command in _commands) command.RaiseCanExecuteChanged(); }
|
||||
private void StateChanged()
|
||||
{
|
||||
RaisePropertyChanged(nameof(CanChangeDirectory)); RaisePropertyChanged(nameof(SelectedCameraName));
|
||||
RaisePropertyChanged(nameof(SelectedCameraName));
|
||||
RaisePropertyChanged(nameof(PreviewButtonText)); UpdateCommands();
|
||||
RaisePropertyChanged(nameof(PauseButtonText)); RaisePropertyChanged(nameof(HasStandardVideo));
|
||||
RaisePropertyChanged(nameof(CanSeekVideo));
|
||||
@ -227,14 +199,11 @@ public sealed partial class CameraViewModel : BindableBase
|
||||
{
|
||||
if (IsRecording) return Task.CompletedTask;
|
||||
if (HasStandardVideo) throw new InvalidOperationException("已有SOP流程视频,请使用“重新录制”并确认删除旧视频");
|
||||
if (string.IsNullOrWhiteSpace(SaveDirectory)) throw new ArgumentException("请选择录像保存目录");
|
||||
var directory = Path.GetFullPath(SaveDirectory.Trim());
|
||||
SaveDirectory = directory; SaveSettings();
|
||||
lock (_frames)
|
||||
{
|
||||
if (_latest == null || !_camera.IsGrabbing) throw new InvalidOperationException("尚未收到相机画面,请先开启预览");
|
||||
if (Stopwatch.GetElapsedTime(_lastFrameTick).TotalSeconds > 2) throw new IOException("超过2秒未收到相机画面,请重新连接后再录像");
|
||||
LastRecording = _recorder.Start(directory, _latest, RecordingFps, _sopStandard ? "sop.avi" : null);
|
||||
LastRecording = _recorder.Start(SaveDirectory, _latest, RecordingFps, "sop.avi");
|
||||
}
|
||||
IsRecording = true; Status = "正在录像,最长5分钟;到时自动停止并保存"; Tick();
|
||||
return Task.CompletedTask;
|
||||
@ -261,20 +230,20 @@ public sealed partial class CameraViewModel : BindableBase
|
||||
if (!confirmed && resumeOnCancel && IsRecording && IsPaused) TogglePause();
|
||||
}
|
||||
if (!confirmed) { Status = "已取消重新录制,原视频已保留"; return; }
|
||||
// Do not delete until the camera is ready and the user has explicitly confirmed.
|
||||
// 用户确认且相机仍有新帧后,才允许清除旧视频。
|
||||
if (_closing || !_camera.IsGrabbing || !HasRecentFrame) throw new IOException("相机画面已中断,原视频保留,请重新连接后再试");
|
||||
StopRecording();
|
||||
await Playback.StopAsync();
|
||||
if (!SopHelper.Engine.Training.RecipeWorkspace.IsWithin(StandardVideoPath, _recipeRecordingDirectory!))
|
||||
if (!RecipeWorkspace.IsWithin(StandardVideoPath, SaveDirectory))
|
||||
throw new IOException("SOP录像路径不在当前配方目录中");
|
||||
File.Delete(StandardVideoPath);
|
||||
SopHelper.Engine.Training.SopStandardVideoDuration.Remember(Path.GetDirectoryName(_recipeRecordingDirectory!)!, TimeSpan.Zero);
|
||||
SopStandardVideoDuration.Remember(Path.GetDirectoryName(SaveDirectory)!, TimeSpan.Zero);
|
||||
LastRecording = "";
|
||||
RecordingInfo = "未录像";
|
||||
Status = "已清除旧视频,请点击“开始录像”进行重新录制";
|
||||
StateChanged();
|
||||
}
|
||||
/// <summary>结束编码并更新录像路径、时长和命令状态,标准录像与普通录像共用此收尾入口。</summary>
|
||||
/// <summary>结束编码并更新录像路径、时长和命令状态。</summary>
|
||||
private void StopRecording()
|
||||
{
|
||||
RecordingResult? result;
|
||||
@ -284,12 +253,9 @@ public sealed partial class CameraViewModel : BindableBase
|
||||
{
|
||||
LastRecording = result.Path;
|
||||
RecordingInfo = $"已保存 · {result.Duration.TotalSeconds:F1} 秒 · {result.Frames} 帧";
|
||||
Status = _sopStandard ? "SOP流程视频已保存到当前配方的 sop_stand 目录" : "录像已保存,可在主窗口导入视频继续标注";
|
||||
if (_sopStandard)
|
||||
{
|
||||
try { SopHelper.Engine.Training.SopStandardVideoDuration.Remember(Path.GetDirectoryName(_recipeRecordingDirectory!)!, result.Duration); }
|
||||
catch (Exception error) { Status += ";标准用时记忆保存失败:" + error.Message; }
|
||||
}
|
||||
Status = "SOP流程视频已保存到当前配方的 sop_stand 目录";
|
||||
try { SopStandardVideoDuration.Remember(Path.GetDirectoryName(SaveDirectory)!, result.Duration); }
|
||||
catch (Exception error) { Status += ";标准用时记忆保存失败:" + error.Message; }
|
||||
}
|
||||
}
|
||||
/// <summary>在采集线程处理录像及最新预览图缓存,界面属性通过调度器更新。</summary>
|
||||
@ -340,7 +306,7 @@ public sealed partial class CameraViewModel : BindableBase
|
||||
{
|
||||
if (!connected) Post(() =>
|
||||
{
|
||||
if (_camera.IsConnected) return; // Ignore a queued disconnect from the previous connection.
|
||||
if (_camera.IsConnected) return; // 忽略上一次连接延迟送达的断开事件。
|
||||
StopRecording(); IsPreviewing = false;
|
||||
if (!Playback.IsLoaded) ClearPreview();
|
||||
});
|
||||
@ -399,22 +365,6 @@ public sealed partial class CameraViewModel : BindableBase
|
||||
lock (_frames) { _latest?.Dispose(); _latest = null; }
|
||||
Preview = null;
|
||||
}
|
||||
internal static string ReadSaveDirectory(string root)
|
||||
{
|
||||
var path = Path.Combine(root, "workspace", "camera-settings.json");
|
||||
if (File.Exists(path))
|
||||
{
|
||||
using var json = JsonDocument.Parse(File.ReadAllText(path));
|
||||
var directory = json.RootElement.GetProperty("directory").GetString();
|
||||
if (!string.IsNullOrWhiteSpace(directory)) return directory;
|
||||
}
|
||||
return Path.Combine(root, "workspace", "recordings");
|
||||
}
|
||||
private void SaveSettings()
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(_settingsPath)!);
|
||||
File.WriteAllText(_settingsPath, JsonSerializer.Serialize(new { directory = SaveDirectory }));
|
||||
}
|
||||
public Task ShutdownAsync() => _shutdown ??= ShutdownCoreAsync();
|
||||
/// <summary>停止录像、回测和预览,解除事件订阅并释放此视图模型持有的资源。</summary>
|
||||
private async Task ShutdownCoreAsync()
|
||||
@ -3,7 +3,7 @@
|
||||
using System.Net.Http;
|
||||
using SopHelper.Engine.Sop;
|
||||
|
||||
namespace SopHelper.Training;
|
||||
namespace SopHelper.SopVideo;
|
||||
|
||||
/// <summary>旧配置兼容占位;Agent只负责编写步骤,禁止用作判定模型。</summary>
|
||||
public sealed class DesktopSequenceVisionClient(HttpClient http) : IVisionDecisionClient
|
||||
@ -7,7 +7,7 @@ using Avalonia.Media;
|
||||
using Avalonia.VisualTree;
|
||||
using SopHelper.Engine.Sop;
|
||||
|
||||
namespace SopHelper.Training;
|
||||
namespace SopHelper.SopVideo;
|
||||
|
||||
/// <summary>放在原始像素尺寸的画布中,与视频和手部骨架一起等比缩放。</summary>
|
||||
public sealed class FlowTestRegionOverlay : Control
|
||||
@ -7,7 +7,7 @@ using Prism.Mvvm;
|
||||
using SopHelper.Presentation.Imaging;
|
||||
using SopHelper.Engine.Common;
|
||||
|
||||
namespace SopHelper.Training;
|
||||
namespace SopHelper.SopVideo;
|
||||
|
||||
/// <summary>在后台解码录制的 AVI,界面线程只更新当前一帧。</summary>
|
||||
public sealed class RecordedVideoPlayback : BindableBase
|
||||
@ -5,7 +5,7 @@ using OpenCvSharp;
|
||||
using SopHelper.Engine.Sop;
|
||||
using SopHelper.Engine.SopAgent;
|
||||
|
||||
namespace SopHelper.Training;
|
||||
namespace SopHelper.SopVideo;
|
||||
|
||||
/// <summary>按草稿模式用同服务、同裁剪检查完成/前序参考;不替代手部触发及整轮回放。</summary>
|
||||
public sealed class SopDraftReferenceVerifier(IVisionDecisionClient? vision = null)
|
||||
@ -5,7 +5,7 @@ using OpenCvSharp;
|
||||
using SopHelper.Engine.Sop;
|
||||
using SopHelper.Engine.SopAgent;
|
||||
|
||||
namespace SopHelper.Training;
|
||||
namespace SopHelper.SopVideo;
|
||||
|
||||
public interface ISopDraftVideoVerifier
|
||||
{
|
||||
@ -6,7 +6,7 @@ using SopHelper.Engine.Common;
|
||||
using SopHelper.Engine.Inference;
|
||||
using SopHelper.Engine.Sop;
|
||||
|
||||
namespace SopHelper.Training;
|
||||
namespace SopHelper.SopVideo;
|
||||
|
||||
/// <summary>独立的录像测试轮次,使用生产 SOP 引擎,不影响运行页统计。</summary>
|
||||
public sealed class SopVideoFlowTest : IDisposable
|
||||
@ -1,58 +0,0 @@
|
||||
<Window xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="SopHelper.Training.CameraWindow" Title="SopHelper · 相机与录像" Width="1080" Height="800" MinWidth="840" MinHeight="650" WindowStartupLocation="CenterOwner" xmlns:conv="using:Avalonia.Data.Converters">
|
||||
<Window.Styles>
|
||||
<StyleInclude Source="avares://SopHelper.Avalonia/Training/Styles.axaml" />
|
||||
<Style Selector="TextBlock.state1">
|
||||
<Setter Property="Foreground" Value="#F0533C" />
|
||||
</Style>
|
||||
</Window.Styles>
|
||||
<Window.Resources>
|
||||
</Window.Resources>
|
||||
<Grid Margin="18">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="*" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
<TextBlock Text="相机与录像" FontSize="22" FontWeight="Bold" Foreground="{StaticResource Accent}" Margin="0,0,0,16" />
|
||||
<Grid Grid.Row="1" Margin="0,0,0,10">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="{Binding SelectedCameraName}" VerticalAlignment="Center" TextWrapping="Wrap" Margin="0,0,10,6" />
|
||||
<Button Grid.Column="1" Content="{Binding PreviewButtonText}" Command="{Binding PreviewCommand}" />
|
||||
</Grid>
|
||||
<Border Grid.Row="2" Background="#080E14" BorderBrush="{StaticResource Line}" BorderThickness="1" CornerRadius="6" Classes="panel">
|
||||
<Grid>
|
||||
<TextBlock Text="开启相机后在此显示实时画面" HorizontalAlignment="Center" Foreground="{StaticResource Dim}" />
|
||||
<Image Source="{Binding Preview}" Stretch="Uniform" />
|
||||
<Border HorizontalAlignment="Left" VerticalAlignment="Top" Margin="12" Padding="10,5" Background="#CC101820" CornerRadius="4" Classes="panel">
|
||||
<TextBlock Text="{Binding RecordingInfo}" Foreground="{StaticResource Dim}" Classes.state1="{Binding IsRecording}" />
|
||||
</Border>
|
||||
</Grid>
|
||||
</Border>
|
||||
<StackPanel Grid.Row="3" Margin="0,14,0,0">
|
||||
<TextBlock Text="录像保存目录" />
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBox Text="{Binding SaveDirectory, Mode=TwoWay}" IsEnabled="{Binding CanChangeDirectory}" Margin="0,6,10,8" />
|
||||
<Button Grid.Column="1" Content="选择目录…" Command="{Binding BrowseCommand}" Margin="0,6,6,8" />
|
||||
<Button Grid.Column="2" Content="打开保存位置" Command="{Binding RevealCommand}" Margin="0,6,0,8" />
|
||||
</Grid>
|
||||
<DockPanel>
|
||||
<Button DockPanel.Dock="Left" Content="开始录像" Command="{Binding StartRecordingCommand}" BorderBrush="{StaticResource Accent}" MinWidth="110" />
|
||||
<Button DockPanel.Dock="Left" Content="{Binding PauseButtonText}" Command="{Binding PauseCommand}" MinWidth="110" Margin="8,0,0,0" />
|
||||
<Button DockPanel.Dock="Left" Content="停止录像" Command="{Binding StopRecordingCommand}" MinWidth="110" Margin="8,0,0,0" />
|
||||
<TextBlock Text="AVI / MJPEG · 30 fps · 最长5分钟,到时自动停止并提示" Foreground="{StaticResource Dim}" Margin="12,0,0,6" TextWrapping="Wrap" />
|
||||
</DockPanel>
|
||||
<TextBlock Text="{Binding LastRecording}" TextTrimming="CharacterEllipsis" Foreground="{StaticResource Dim}" Margin="0,0,0,8" ToolTip.Tip="{Binding LastRecording}" />
|
||||
</StackPanel>
|
||||
<TextBlock Grid.Row="4" Text="{Binding Status}" TextWrapping="Wrap" Margin="0,8,0,0" />
|
||||
</Grid>
|
||||
</Window>
|
||||
@ -1,44 +0,0 @@
|
||||
// 录像窗口事件层:展示录像限制提示,并等待视图模型安全停止后完成窗口关闭。
|
||||
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Threading;
|
||||
|
||||
namespace SopHelper.Training;
|
||||
public partial class CameraWindow : Window
|
||||
{
|
||||
public CameraViewModel Model { get; }
|
||||
private bool _closedSafely,_closeRequested;
|
||||
private Window? _recordingLimitDialog;
|
||||
public CameraWindow(CameraViewModel model)
|
||||
{
|
||||
InitializeComponent();Model=model;DataContext=model;Closing+=OnSafeClosing;
|
||||
Model.RecordingLimitReached+=ShowRecordingLimit;
|
||||
Closed+=(_,_)=>Model.RecordingLimitReached-=ShowRecordingLimit;
|
||||
}
|
||||
private async void ShowRecordingLimit(string message)
|
||||
{
|
||||
if(_closeRequested || !IsVisible || _recordingLimitDialog is not null)return;
|
||||
var confirm=new Button { Content="确定",HorizontalAlignment=Avalonia.Layout.HorizontalAlignment.Right,MinWidth=80 };
|
||||
var dialog=new Window
|
||||
{
|
||||
Title="录像时长提示",Width=460,SizeToContent=SizeToContent.Height,CanResize=false,
|
||||
WindowStartupLocation=WindowStartupLocation.CenterOwner,
|
||||
Content=new StackPanel
|
||||
{
|
||||
Margin=new Avalonia.Thickness(20),Spacing=16,
|
||||
Children={new TextBlock { Text=message,TextWrapping=Avalonia.Media.TextWrapping.Wrap },confirm}
|
||||
}
|
||||
};
|
||||
confirm.Click+=(_,_)=>dialog.Close();
|
||||
_recordingLimitDialog=dialog;
|
||||
try { await dialog.ShowDialog(this); }
|
||||
finally { _recordingLimitDialog=null; }
|
||||
}
|
||||
private async void OnSafeClosing(object? sender,WindowClosingEventArgs e)
|
||||
{
|
||||
if(_closedSafely)return;e.Cancel=true;if(_closeRequested)return;_closeRequested=true;IsEnabled=false;
|
||||
_recordingLimitDialog?.Close();
|
||||
try{await Model.ShutdownAsync();}catch(Exception error){System.Diagnostics.Trace.TraceError("关闭相机时出错:"+error);}
|
||||
_closedSafely=true;Dispatcher.UIThread.Post(Close);
|
||||
}
|
||||
}
|
||||
@ -1,73 +0,0 @@
|
||||
<Styles xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
|
||||
<Styles.Resources>
|
||||
<SolidColorBrush x:Key="Bg" Color="#101820" />
|
||||
<SolidColorBrush x:Key="Panel" Color="#16222E" />
|
||||
<SolidColorBrush x:Key="Line" Color="#2C4257" />
|
||||
<SolidColorBrush x:Key="Fg" Color="#DCEBF5" />
|
||||
<SolidColorBrush x:Key="Dim" Color="#8FAFC4" />
|
||||
<SolidColorBrush x:Key="Accent" Color="#00B8D4" />
|
||||
</Styles.Resources>
|
||||
<Style Selector="Window">
|
||||
<Setter Property="FontFamily" Value="Microsoft YaHei, Noto Sans CJK SC, sans-serif" />
|
||||
<Setter Property="Background" Value="{StaticResource Bg}" />
|
||||
<Setter Property="Foreground" Value="{StaticResource Fg}" />
|
||||
</Style>
|
||||
<Style Selector="TextBlock">
|
||||
<Setter Property="Foreground" Value="{StaticResource Fg}" />
|
||||
<Setter Property="VerticalAlignment" Value="Center" />
|
||||
<Setter Property="FontSize" Value="13" />
|
||||
</Style>
|
||||
<Style Selector="TextBlock.Hint">
|
||||
<Setter Property="Foreground" Value="{StaticResource Dim}" />
|
||||
<Setter Property="TextWrapping" Value="Wrap" />
|
||||
<Setter Property="Margin" Value="0,6,0,12" />
|
||||
<Setter Property="LineHeight" Value="21" />
|
||||
</Style>
|
||||
<Style Selector="Button">
|
||||
<Setter Property="Foreground" Value="{StaticResource Fg}" />
|
||||
<Setter Property="Background" Value="{StaticResource Panel}" />
|
||||
<Setter Property="BorderBrush" Value="{StaticResource Line}" />
|
||||
<Setter Property="Padding" Value="12,8" />
|
||||
<Setter Property="Margin" Value="0,0,6,6" />
|
||||
<Setter Property="Cursor" Value="Hand" />
|
||||
</Style>
|
||||
<Style Selector="TextBox">
|
||||
<Setter Property="Foreground" Value="{StaticResource Fg}" />
|
||||
<Setter Property="Background" Value="#101820" />
|
||||
<Setter Property="BorderBrush" Value="{StaticResource Line}" />
|
||||
<Setter Property="Padding" Value="7" />
|
||||
<Setter Property="Margin" Value="0,4,0,10" />
|
||||
<Setter Property="CaretBrush" Value="{StaticResource Accent}" />
|
||||
</Style>
|
||||
<Style Selector="TextBox.password">
|
||||
<Setter Property="Foreground" Value="{StaticResource Fg}" />
|
||||
<Setter Property="Background" Value="#101820" />
|
||||
<Setter Property="BorderBrush" Value="{StaticResource Line}" />
|
||||
<Setter Property="Padding" Value="7" />
|
||||
<Setter Property="Margin" Value="0,4,0,10" />
|
||||
</Style>
|
||||
<Style Selector="TabControl">
|
||||
<Setter Property="Background" Value="{StaticResource Panel}" />
|
||||
<Setter Property="BorderBrush" Value="{StaticResource Line}" />
|
||||
<Setter Property="Padding" Value="12" />
|
||||
</Style>
|
||||
<Style Selector="TabItem">
|
||||
<Setter Property="Foreground" Value="{StaticResource Dim}" />
|
||||
</Style>
|
||||
<Style Selector="ListBox">
|
||||
<Setter Property="Background" Value="#101820" />
|
||||
<Setter Property="Foreground" Value="{StaticResource Fg}" />
|
||||
<Setter Property="BorderBrush" Value="{StaticResource Line}" />
|
||||
<Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled" />
|
||||
</Style>
|
||||
<Style Selector="ListBoxItem">
|
||||
<Setter Property="Padding" Value="10,8" />
|
||||
</Style>
|
||||
<Style Selector="ComboBox">
|
||||
<Setter Property="Foreground" Value="{StaticResource Fg}" />
|
||||
</Style>
|
||||
<Style Selector="ComboBoxItem">
|
||||
<Setter Property="Foreground" Value="{StaticResource Fg}" />
|
||||
<Setter Property="Padding" Value="10,8" />
|
||||
</Style>
|
||||
</Styles>
|
||||
@ -1,4 +1,4 @@
|
||||
<UserControl xmlns="https://github.com/avaloniaui" xmlns:ed="clr-namespace:SopHelper.VVMs.RecipeEditor" xmlns:prism="http://prismlibrary.com/" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="SopHelper.VVMs.RecipeEditor.RecipeEditor" x:Name="RecipeEditorRoot" prism:ViewModelLocator.AutoWireViewModel="True" Background="{StaticResource Bg}" xmlns:conv="using:Avalonia.Data.Converters" xmlns:training="clr-namespace:SopHelper.Training" xmlns:sop="clr-namespace:SopHelper.VVMs.SopPage">
|
||||
<UserControl xmlns="https://github.com/avaloniaui" xmlns:ed="clr-namespace:SopHelper.VVMs.RecipeEditor" xmlns:prism="http://prismlibrary.com/" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="SopHelper.VVMs.RecipeEditor.RecipeEditor" x:Name="RecipeEditorRoot" prism:ViewModelLocator.AutoWireViewModel="True" Background="{StaticResource Bg}" xmlns:conv="using:Avalonia.Data.Converters" xmlns:video="clr-namespace:SopHelper.SopVideo" xmlns:sop="clr-namespace:SopHelper.VVMs.SopPage">
|
||||
<UserControl.DataTemplates>
|
||||
<DataTemplate DataType="{x:Type ed:TextItem}">
|
||||
<Grid Classes="Row">
|
||||
@ -386,7 +386,7 @@
|
||||
<Viewbox Stretch="Uniform">
|
||||
<Grid Width="{Binding DisplayImage.PixelWidth, FallbackValue=1}" Height="{Binding DisplayImage.PixelHeight, FallbackValue=1}">
|
||||
<Image Source="{Binding DisplayImage}" Stretch="Fill" />
|
||||
<training:FlowTestRegionOverlay x:Name="FlowTestRegionsOverlay" Regions="{Binding FlowTestRegions}" IsVisible="{Binding ShowFlowTestOverlay}" IsHitTestVisible="False" />
|
||||
<video:FlowTestRegionOverlay x:Name="FlowTestRegionsOverlay" Regions="{Binding FlowTestRegions}" IsVisible="{Binding ShowFlowTestOverlay}" IsHitTestVisible="False" />
|
||||
<sop:HandOverlay x:Name="FlowTestHandsOverlay" Result="{Binding Playback.Analysis}" ShowBounds="True" IsVisible="{Binding ShowFlowTestOverlay}" IsHitTestVisible="False" />
|
||||
</Grid>
|
||||
</Viewbox>
|
||||
|
||||
@ -4,7 +4,7 @@ using Avalonia.Controls;
|
||||
using Avalonia.Platform.Storage;
|
||||
using Avalonia.Threading;
|
||||
using System.ComponentModel;
|
||||
using SopHelper.Training;
|
||||
using SopHelper.SopVideo;
|
||||
namespace SopHelper.VVMs.RecipeEditor;
|
||||
public partial class RecipeEditor : UserControl
|
||||
{
|
||||
|
||||
@ -42,8 +42,8 @@ public partial class RecipeEditorViewModel : BindableBase, IDialogAware
|
||||
private Func<CameraInfo?>? _selectedCameraProvider;
|
||||
private Func<bool> _canUseCamera = () => true;
|
||||
private Task? _shutdown;
|
||||
private SopHelper.Training.CameraViewModel? _sopRecording;
|
||||
public SopHelper.Training.CameraViewModel? SopRecording { get => _sopRecording; private set => SetProperty(ref _sopRecording, value); }
|
||||
private SopHelper.SopVideo.CameraViewModel? _sopRecording;
|
||||
public SopHelper.SopVideo.CameraViewModel? SopRecording { get => _sopRecording; private set => SetProperty(ref _sopRecording, value); }
|
||||
public bool HasSopRecording => SopRecording is not null;
|
||||
|
||||
private bool _showRegionPreview;
|
||||
@ -213,10 +213,9 @@ public partial class RecipeEditorViewModel : BindableBase, IDialogAware
|
||||
private void InitializeRecipeTools()
|
||||
{
|
||||
if (SopRecording is not null || string.IsNullOrEmpty(_path) || !File.Exists(_path)) return;
|
||||
// Use a separate camera service so SOP capture cannot dispose the operator page's service.
|
||||
var recipeDirectory = Path.GetDirectoryName(_path)!;
|
||||
var root = Path.GetDirectoryName(Path.GetDirectoryName(recipeDirectory)!)!;
|
||||
SopRecording = new SopHelper.Training.CameraViewModel(new CameraService(), root, Path.GetFileNameWithoutExtension(_path), sopStandard: true, selectedCameraProvider: _selectedCameraProvider);
|
||||
SopRecording = new SopHelper.SopVideo.CameraViewModel(new CameraService(), root, Path.GetFileNameWithoutExtension(_path), selectedCameraProvider: _selectedCameraProvider);
|
||||
SopRecording.FlowTestConfigProvider = () => Recipe.ToConfig();
|
||||
SopRecording.Playback.PropertyChanged += (_, e) =>
|
||||
{
|
||||
|
||||
@ -11,7 +11,7 @@ using SopHelper.Engine.Sop;
|
||||
using SopHelper.Engine.SopAgent;
|
||||
using SopHelper.Presentation;
|
||||
using SopHelper.Presentation.Imaging;
|
||||
using SopHelper.Training;
|
||||
using SopHelper.SopVideo;
|
||||
|
||||
namespace SopHelper.VVMs.RecipeEditor;
|
||||
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Interactivity;
|
||||
using SopHelper.Training;
|
||||
using SopHelper.SopVideo;
|
||||
|
||||
namespace SopHelper.VVMs.SopPage;
|
||||
|
||||
|
||||
@ -11,7 +11,7 @@ using SopHelper;
|
||||
using SopHelper.Engine.Camera;
|
||||
using SopHelper.Engine.Training;
|
||||
using SopHelper.Models;
|
||||
using SopHelper.Training;
|
||||
using SopHelper.SopVideo;
|
||||
using SopHelper.VVMs.SopPage;
|
||||
using SopHelper.VVMs.RecipeEditor;
|
||||
using System.Text.Json;
|
||||
@ -400,8 +400,6 @@ internal static class Smoke
|
||||
await ChooseRecipeClose(titlebarModal,"DiscardRecipeAndCloseButton");
|
||||
for(var i=0;i<100&&lifetime.Windows.Contains(titlebarModal);i++)await Task.Delay(20);
|
||||
Check(!lifetime.Windows.Contains(titlebarModal),"Titlebar close awaits SOP camera shutdown and closes the Prism dialog");
|
||||
var recorder=new CameraWindow(new CameraViewModel(new FakeCamera(),Path.Combine(Path.GetTempPath(),"sophelper-avalonia-smoke")));
|
||||
recorder.Show();await Task.Delay(100);Save(recorder,"camera");recorder.Close();
|
||||
var fitted=RegionCanvas.FitImage(new Size(1000,800),new Size(1920,1080));
|
||||
var pixel=RegionCanvas.ToImage(fitted.Center,fitted,new Size(1920,1080));
|
||||
Check(Math.Abs(pixel.X-960)<.001&&Math.Abs(pixel.Y-540)<.001,"ROI maps letterbox center back to original pixels");
|
||||
|
||||
@ -8,7 +8,7 @@ using Avalonia.Threading;
|
||||
using Avalonia.VisualTree;
|
||||
using OpenCvSharp;
|
||||
using SopHelper.Engine.Camera;
|
||||
using SopHelper.Training;
|
||||
using SopHelper.SopVideo;
|
||||
using SopHelper.Engine.Sop;
|
||||
using SopHelper.Engine.Training;
|
||||
using SopHelper.VVMs.RecipeEditor;
|
||||
@ -33,85 +33,7 @@ internal static class Program
|
||||
Application.Current.Styles.Add(new StyleInclude(new Uri("avares://SopHelper.Avalonia/")) { Source = new Uri("avares://SopHelper.Avalonia/Themes/Styles.axaml") });
|
||||
if (!args.Contains("--usb-camera-only")) { CheckRunStatistics(); CheckStandardDuration(root); }
|
||||
Check(VideoRecorder.MaximumDuration == TimeSpan.FromMinutes(5), "Production recording limit is five minutes");
|
||||
var clock = new ManualClock();
|
||||
using var camera = new FakeCamera();
|
||||
CameraInfo? selected = null;
|
||||
var model = new CameraViewModel(camera, root, timeProvider: clock, selectedCameraProvider: () => selected);
|
||||
var window = new CameraWindow(model); window.Show(); Dispatcher.UIThread.RunJobs(); window.UpdateLayout();
|
||||
var pauseButton = window.GetVisualDescendants().OfType<Button>().Single(b => ReferenceEquals(b.Command, model.PauseCommand));
|
||||
Check(!pauseButton.IsEffectivelyEnabled && pauseButton.Content?.ToString() == "暂停录制", "Part recording exposes a pause button disabled before recording");
|
||||
CheckRecordingButtons(window, model, false, false);
|
||||
Check(!model.PreviewCommand.CanExecute() && model.SelectedCameraName.Contains("运行设置"), "Recording requires the camera selected in runtime settings");
|
||||
Check(!window.GetVisualDescendants().OfType<ComboBox>().Any() && !window.GetVisualDescendants().OfType<Button>().Any(b => b.Content?.ToString() == "刷新相机"), "Recording window has no camera selector or refresh button");
|
||||
selected = new CameraInfo { Kind = CameraKind.Uvc, Index = 7, Name = "运行设置中的相机" };
|
||||
Tick(model); model.PreviewCommand.Execute();
|
||||
Check(ReferenceEquals(camera.ConnectedCamera, selected) && camera.EnumerationCount == 0, "Recording uses the exact global camera without enumerating devices");
|
||||
Thread.Sleep(75); camera.Emit(); Dispatcher.UIThread.RunJobs();
|
||||
Check(model.StartRecordingCommand.CanExecute(), "Preview is ready for recording");
|
||||
CheckRecordingButtons(window, model, true, false);
|
||||
if (args.Contains("--usb-camera-only"))
|
||||
{
|
||||
model.StartRecordingCommand.Execute();
|
||||
clock.Advance(TimeSpan.FromSeconds(1));camera.Emit();Tick(model);
|
||||
model.StopRecordingCommand.Execute();
|
||||
Check(!model.IsRecording&&model.IsPreviewing,"USB recording saves while keeping preview active");
|
||||
CheckVideo(model.LastRecording,1);
|
||||
Pump(model.ShutdownAsync());window.Close();
|
||||
Check(!camera.IsConnected&&!camera.IsGrabbing,"Closing USB recording releases the camera");
|
||||
return;
|
||||
}
|
||||
var notices = 0;
|
||||
model.RecordingLimitReached += message => { notices++; Check(message.Contains("5分钟") && message.Contains(model.LastRecording), "Timeout notice contains the limit and saved path"); };
|
||||
model.StartRecordingCommand.Execute();
|
||||
CheckRecordingButtons(window, model, false, true);
|
||||
for (var second = 1; second <= 299; second++) { clock.Advance(TimeSpan.FromSeconds(1)); camera.Emit(); }
|
||||
Tick(model);
|
||||
Check(model.IsRecording && notices == 0, "Recording continues at 4:59 without a popup");
|
||||
clock.Advance(TimeSpan.FromSeconds(1)); camera.Emit();
|
||||
// Simulate a delayed UI callback while the acquisition thread keeps receiving frames.
|
||||
clock.Advance(TimeSpan.FromMilliseconds(700)); camera.Emit();
|
||||
Tick(model);
|
||||
Check(!model.IsRecording && model.IsPreviewing && notices == 1, "Timeout stops recording once and keeps the preview running");
|
||||
CheckRecordingButtons(window, model, true, false);
|
||||
CheckVideo(model.LastRecording, 300);
|
||||
var popup = (Window?)typeof(CameraWindow).GetField("_recordingLimitDialog", BindingFlags.Instance | BindingFlags.NonPublic)!.GetValue(window);
|
||||
Check(popup is { IsVisible: true } && popup.Title == "录像时长提示", "Timeout opens the modal notification");
|
||||
Check(popup!.GetVisualDescendants().OfType<TextBlock>().Any(t => t.Text?.Contains("5分钟") == true), "Popup displays the five-minute explanation");
|
||||
Tick(model); Tick(model); Check(notices == 1, "Later timer ticks do not repeat the popup");
|
||||
popup!.Close(); Dispatcher.UIThread.RunJobs();
|
||||
model.StartRecordingCommand.Execute();
|
||||
Check(model.IsRecording, "A second recording starts with a fresh timeout");
|
||||
clock.Advance(TimeSpan.FromSeconds(1)); camera.Emit(); Tick(model);
|
||||
Check(model.IsRecording && notices == 1, "Previous recording duration does not carry over");
|
||||
Check(pauseButton.IsEffectivelyEnabled, "Part recording enables the pause button while recording");
|
||||
pauseButton.Command!.Execute(pauseButton.CommandParameter); Dispatcher.UIThread.RunJobs();
|
||||
clock.Advance(TimeSpan.FromMinutes(6)); camera.Emit(); Tick(model);
|
||||
Check(model.IsRecording && model.IsPaused && model.IsPreviewing && notices == 1 && model.RecordingInfo.Contains("00:00:01"), "Part recording excludes paused time from duration and timeout while keeping preview active");
|
||||
Check(pauseButton.Content?.ToString() == "继续录制", "Part recording button offers resume when paused");
|
||||
CheckRecordingButtons(window, model, false, true);
|
||||
pauseButton.Command.Execute(pauseButton.CommandParameter); Dispatcher.UIThread.RunJobs();
|
||||
Check(!model.IsPaused && pauseButton.Content?.ToString() == "暂停录制", "Part recording resumes through the same button");
|
||||
clock.Advance(TimeSpan.FromSeconds(1)); camera.Emit(); Tick(model);
|
||||
pauseButton.Command.Execute(pauseButton.CommandParameter);
|
||||
model.StopRecordingCommand.Execute();
|
||||
Check(!model.IsRecording && notices == 1, "Manual stop saves without a timeout popup");
|
||||
Check(!model.IsPaused && !pauseButton.IsEffectivelyEnabled && pauseButton.Content?.ToString() == "暂停录制", "Stopping a paused part recording resets the pause button");
|
||||
CheckRecordingButtons(window, model, true, false);
|
||||
CheckVideo(model.LastRecording, 2);
|
||||
clock.Advance(TimeSpan.FromMinutes(6)); Tick(model);
|
||||
Check(notices == 1, "Stopped recordings do not later trigger a timeout");
|
||||
camera.Emit(); model.StartRecordingCommand.Execute();
|
||||
for (var second = 1; second <= 300; second++) { clock.Advance(TimeSpan.FromSeconds(1)); camera.Emit(); }
|
||||
Tick(model);
|
||||
Check(notices == 2 && !model.IsRecording, "A later recording independently stops at its own five-minute limit");
|
||||
CheckVideo(model.LastRecording, 300);
|
||||
window.Close();
|
||||
var shutdown = model.ShutdownAsync();
|
||||
var wait = System.Diagnostics.Stopwatch.StartNew();
|
||||
while (!shutdown.IsCompleted && wait.Elapsed < TimeSpan.FromSeconds(5)) { Dispatcher.UIThread.RunJobs(); Thread.Sleep(1); }
|
||||
shutdown.GetAwaiter().GetResult(); Dispatcher.UIThread.RunJobs();
|
||||
Check(!window.IsVisible, "Closing the camera also closes its notification and releases resources");
|
||||
RunSopRecording(root);
|
||||
RunSopRecording(root, args.Contains("--usb-camera-only"));
|
||||
}
|
||||
finally
|
||||
{
|
||||
@ -130,7 +52,7 @@ internal static class Program
|
||||
&& start.IsEffectivelyEnabled == canStart && stop.IsEffectivelyEnabled == canStop,
|
||||
$"Separate recording buttons keep fixed labels and correct availability (start={canStart}, stop={canStop})");
|
||||
}
|
||||
private static void RunSopRecording(string root)
|
||||
private static void RunSopRecording(string root, bool usbCameraOnly)
|
||||
{
|
||||
var store = new RecipeWorkspace(root);
|
||||
var config = new SopConfig(); config.Sop.Name = "标准流程"; config.Sop.Parts = [];
|
||||
@ -139,14 +61,14 @@ internal static class Program
|
||||
vm.OnDialogOpened(new DialogParameters { { "directory", store.RecipesDirectory }, { "path", store.ConfigPath(config.Sop.Name) }, { "config", config }, { "new", false } });
|
||||
Pump(vm.ShutdownSopRecordingAsync());
|
||||
var clock = new ManualClock(); using var camera = new FakeCamera();
|
||||
var selected = new CameraInfo { Index = 3, Name = "全局SOP相机" };
|
||||
var model = new CameraViewModel(camera, root, config.Sop.Name, clock, sopStandard: true, selectedCameraProvider: () => selected);
|
||||
// Substitute the camera at the presentation boundary; never open real test hardware.
|
||||
CameraInfo? selected = null;
|
||||
var model = new CameraViewModel(camera, root, config.Sop.Name, clock, selectedCameraProvider: () => selected);
|
||||
// 在界面边界注入假相机,覆盖标准视频操作且避免占用现场设备。
|
||||
typeof(RecipeEditorViewModel).GetProperty(nameof(vm.SopRecording))!.SetValue(vm, model);
|
||||
var editor = new RecipeEditor { DataContext = vm };
|
||||
var window = new Window { Content = editor, Width = 1040, Height = 760 }; window.Show(); window.UpdateLayout();
|
||||
var tabs = editor.GetVisualDescendants().OfType<TabControl>().Single(); tabs.SelectedIndex = 5; window.UpdateLayout();
|
||||
Check(tabs.ItemCount == 7 && ((TabItem)tabs.Items[5]!).Header?.ToString() == "SOP流程视频", "Recipe editor contains the SOP recording page");
|
||||
var tabs = editor.GetVisualDescendants().OfType<TabControl>().Single(); tabs.SelectedIndex = 1; window.UpdateLayout();
|
||||
Check(tabs.ItemCount == 3 && ((TabItem)tabs.Items[1]!).Header?.ToString() == "SOP流程视频", "Recipe editor contains the SOP recording page");
|
||||
var previewButton = editor.GetVisualDescendants().OfType<Button>().Single(b => ReferenceEquals(b.Command, model.PreviewCommand));
|
||||
var videoButtons = ((Panel)previewButton.Parent!).Children.OfType<Button>().ToArray();
|
||||
Check(ReferenceEquals(videoButtons[0].Command, model.PreviewCommand) && ReferenceEquals(videoButtons[1].Command, model.StartRecordingCommand) && ReferenceEquals(videoButtons[^1].Command, model.RevealCommand), "Preview precedes recording and saved location is last");
|
||||
@ -155,14 +77,46 @@ internal static class Program
|
||||
Check(videoButtons.All(b => b.TranslatePoint(new Point(b.Bounds.Width, 0), editor)!.Value.X <= editor.Bounds.Width), "Separate recording buttons wrap within a narrow editor");
|
||||
window.Width = 1040; window.UpdateLayout();
|
||||
Check(!editor.GetVisualDescendants().OfType<Button>().Any(b => b.Content?.ToString() == "刷新相机"), "SOP page has no independent camera refresh");
|
||||
model.PreviewCommand.Execute(); Thread.Sleep(75); camera.Emit(); Dispatcher.UIThread.RunJobs();
|
||||
Check(!model.PreviewCommand.CanExecute(), "Recording requires the camera selected in runtime settings");
|
||||
selected = new CameraInfo { Index = 3, Name = "全局SOP相机" };
|
||||
Tick(model);
|
||||
model.PreviewCommand.Execute(); PumpIdle(model); Thread.Sleep(75); camera.Emit(); Dispatcher.UIThread.RunJobs();
|
||||
Check(ReferenceEquals(camera.ConnectedCamera, selected) && camera.EnumerationCount == 0, "SOP recording also uses the global camera directly");
|
||||
CheckRecordingButtons(editor, model, true, false);
|
||||
model.StartRecordingCommand.Execute();
|
||||
CheckRecordingButtons(editor, model, false, true);
|
||||
Check(!model.PlayVideoCommand.CanExecute(), "Playback is disabled until recording has stopped and saved");
|
||||
var expectedPath = Path.Combine(store.DirectoryFor(config.Sop.Name), "sop_stand", "sop.avi");
|
||||
Check(model.LastRecording == expectedPath && !model.CanChangeDirectory, "SOP video is stored separately under its current recipe");
|
||||
Check(model.LastRecording == expectedPath, "SOP video is stored separately under its current recipe");
|
||||
if (usbCameraOnly)
|
||||
{
|
||||
clock.Advance(TimeSpan.FromSeconds(1)); camera.Emit();
|
||||
model.StopRecordingCommand.Execute();
|
||||
Check(!model.IsRecording && model.IsPreviewing, "USB recording saves while keeping preview active");
|
||||
CheckVideo(expectedPath, 1);
|
||||
window.Close(); Pump(vm.ShutdownSopRecordingAsync());
|
||||
Check(!camera.IsConnected && !camera.IsGrabbing, "Closing USB recording releases the camera");
|
||||
vm.OnDialogClosed();
|
||||
return;
|
||||
}
|
||||
// 以虚拟时钟推进录像时限,仍通过配方编辑器验证保存和通知。
|
||||
var notices = 0;
|
||||
model.RecordingLimitReached += message =>
|
||||
{
|
||||
notices++;
|
||||
Check(message.Contains("5分钟") && message.Contains(expectedPath), "Timeout notice contains the limit and standard video path");
|
||||
};
|
||||
for (var second = 1; second <= 299; second++) { clock.Advance(TimeSpan.FromSeconds(1)); camera.Emit(); }
|
||||
Tick(model);
|
||||
Check(model.IsRecording && notices == 0, "Recording continues at 4:59 without notification");
|
||||
clock.Advance(TimeSpan.FromSeconds(1)); camera.Emit(); Tick(model); Tick(model);
|
||||
Check(!model.IsRecording && model.IsPreviewing && notices == 1, "Timeout saves once and keeps preview active");
|
||||
CheckVideo(expectedPath, 300);
|
||||
var limitDialog = (Window?)typeof(RecipeEditor).GetField("_dialog", BindingFlags.Instance | BindingFlags.NonPublic)!.GetValue(editor);
|
||||
Check(limitDialog is { IsVisible: true, Title: "录像时长提示" }, "Recipe editor displays the recording limit notification");
|
||||
limitDialog!.Close(); PumpFor(20);
|
||||
model.RestartCommand.Execute(); FindSopDialog(editor).Close(true); PumpIdle(model);
|
||||
model.StartRecordingCommand.Execute();
|
||||
clock.Advance(TimeSpan.FromSeconds(1)); camera.Emit();
|
||||
model.PauseCommand.Execute();
|
||||
clock.Advance(TimeSpan.FromMinutes(10)); camera.Emit(); Tick(model);
|
||||
@ -180,7 +134,7 @@ internal static class Program
|
||||
model.PlayVideoCommand.Execute(); PumpIdle(model);
|
||||
Check(model.Playback.IsPlaying && !model.IsPreviewing && model.DisplayImage is { PixelWidth: 64, PixelHeight: 48 }, "Saved SOP video plays inside the page after releasing the camera");
|
||||
Check(editor.GetVisualDescendants().OfType<Image>().Any(i => ReferenceEquals(i.Source, model.Playback.Frame)), "SOP image control displays the decoded video frame");
|
||||
model.PlayVideoCommand.Execute(); PumpIdle(model); PumpFor(100);
|
||||
model.ToggleVideoPlaybackCommand.Execute(); PumpIdle(model); PumpFor(100);
|
||||
var pausedProgress = model.Playback.Progress; PumpFor(100);
|
||||
Check(!model.Playback.IsPlaying && model.Playback.Progress == pausedProgress && model.DisplayImage is not null, "Playback pause holds the frame and progress");
|
||||
Pump(model.Playback.SeekAsync(80));
|
||||
@ -237,12 +191,15 @@ internal static class Program
|
||||
FindSopDialog(editor).Close(false); PumpIdle(model);
|
||||
Check(model.IsRecording && !model.IsPaused, "Cancelling replacement resumes a previously active recording");
|
||||
clock.Advance(TimeSpan.FromMilliseconds(500)); camera.Emit();
|
||||
window.Close(); Pump(vm.ShutdownSopRecordingAsync()); Dispatcher.UIThread.RunJobs();
|
||||
// 通过配方编辑器的关闭确认完成录像收尾。
|
||||
window.Close();
|
||||
FindSopDialog(editor).Close(RecipeCloseChoice.Discard);
|
||||
Pump(vm.ShutdownAsync()); PumpFor(50);
|
||||
Check(!window.IsVisible && !model.IsRecording, "Closing the editor stops and finalizes the SOP video");
|
||||
CheckVideo(expectedPath, 1);
|
||||
Check(!File.ReadAllBytes(expectedPath).SequenceEqual(original), "Confirmed re-record replaces the prior video");
|
||||
vm.OnDialogClosed();
|
||||
var reopened = new CameraViewModel(new FakeCamera(), root, config.Sop.Name, sopStandard: true);
|
||||
var reopened = new CameraViewModel(new FakeCamera(), root, config.Sop.Name);
|
||||
Check(reopened.HasStandardVideo && reopened.LastRecording == expectedPath, "Reopening the recipe restores its existing SOP video");
|
||||
Check(reopened.PlayVideoCommand.CanExecute() && !reopened.PreviewCommand.CanExecute(), "Existing videos can play without a selected or connected camera");
|
||||
reopened.PlayVideoCommand.Execute(); PumpIdle(reopened);
|
||||
@ -253,7 +210,7 @@ internal static class Program
|
||||
Check(!reopened.Playback.IsLoaded, "Closing playback disposes the video reader");
|
||||
using (var exclusive = new FileStream(expectedPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
|
||||
Check(exclusive.Length > 0, "Video file is unlocked after player shutdown");
|
||||
var other = new CameraViewModel(new FakeCamera(), root, "另一配方", sopStandard: true);
|
||||
var other = new CameraViewModel(new FakeCamera(), root, "另一配方");
|
||||
Check(!other.HasStandardVideo && other.StandardVideoPath != expectedPath, "SOP recordings are isolated between recipes");
|
||||
Check(!other.PlayVideoCommand.CanExecute(), "Playback is disabled when the recipe has no saved video");
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(other.StandardVideoPath)!);
|
||||
@ -306,24 +263,6 @@ internal static class Program
|
||||
}
|
||||
clock.Advance(TimeSpan.FromMinutes(1));
|
||||
Check(statistics.FlowElapsed == TimeSpan.FromSeconds(12), "Completion freezes the final flow timer");
|
||||
var config = new SopConfig(); config.Sop.Name = "计时甲"; config.Sop.Settings.AutoResetOnComplete = false;
|
||||
config.Sop.Steps.Add(new StepDef { Id = 1, Detection = new StepCondition { Method = "object_present", TargetObject = "part", StableFrames = 1 } });
|
||||
config.Sop.Steps.Add(new StepDef { Id = 2, Detection = new StepCondition { Method = "object_present", TargetObject = "part", StableFrames = 1 } });
|
||||
var engine = new SopEngine(); engine.Load(config); engine.Start(); Thread.Sleep(20);
|
||||
var frame = new SopHelper.Engine.Common.FrameResult { Detections = [new() { Label = "part", Confidence = 1 }] };
|
||||
engine.ProcessFrame(frame);
|
||||
Check(engine.CurrentStep?.Id == 2 && engine.Statistics.FlowElapsed > engine.Statistics.StepElapsed && engine.Statistics.CompletedCount == 0, "Engine resets the step timer while preserving the flow timer at a step transition");
|
||||
engine.TogglePause(); var paused = engine.Statistics.FlowElapsed; Thread.Sleep(20);
|
||||
Check(engine.Statistics.FlowElapsed == paused, "Engine pause freezes live statistics");
|
||||
engine.TogglePause(); engine.ProcessFrame(frame); engine.ProcessFrame(frame);
|
||||
Check(engine.Statistics.CompletedCount == 1 && engine.State == EngineState.Completed, "Engine counts completion only when all steps finish");
|
||||
engine.Load(config); engine.Start(); engine.Stop(); engine.ProcessFrame(frame);
|
||||
Check(engine.Statistics.CompletedCount == 1 && engine.State == EngineState.Idle, "Reloading and stopping preserve the session count and prevent further judgement");
|
||||
var other = new SopConfig(); other.Sop.Name = "计时乙"; engine.Load(other);
|
||||
Check(engine.Statistics.CompletedCount == 0 && engine.GetStatistics("计时甲").CompletedCount == 1, "Recipe counts and timing histories remain isolated within the session");
|
||||
config.Sop.Settings.AutoResetOnComplete = true; config.Sop.Settings.ResetDelaySec = 1;
|
||||
engine.Load(config); engine.Start(); engine.ProcessFrame(frame); engine.ProcessFrame(frame); engine.Stop(); Thread.Sleep(1100);
|
||||
Check(engine.State == EngineState.Idle && engine.Statistics.CompletedCount == 2, "Stopping cancels a pending automatic reset without counting another round");
|
||||
}
|
||||
private static void CheckStandardDuration(string root)
|
||||
{
|
||||
|
||||
@ -4,7 +4,7 @@ using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using SopHelper.Engine.Sop;
|
||||
using SopHelper.Engine.SopAgent;
|
||||
using SopHelper.Training;
|
||||
using SopHelper.SopVideo;
|
||||
|
||||
/// <summary>真实服务测速:与界面相同,先生成,再基于当前草稿回测修订。</summary>
|
||||
internal static class AgentBenchmarkChecks
|
||||
|
||||
@ -6,7 +6,7 @@ using Prism.Dialogs;
|
||||
using SopHelper.Engine.Sop;
|
||||
using SopHelper.Engine.SopAgent;
|
||||
using SopHelper.Engine.Training;
|
||||
using SopHelper.Training;
|
||||
using SopHelper.SopVideo;
|
||||
using SopHelper.VVMs.RecipeEditor;
|
||||
using Window = Avalonia.Controls.Window;
|
||||
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
using System.Text.Json;
|
||||
using Avalonia.Threading;
|
||||
using SopHelper.Engine.Sop;
|
||||
using SopHelper.Training;
|
||||
using SopHelper.SopVideo;
|
||||
using SopHelper.Engine.SopAgent;
|
||||
|
||||
/// <summary>显式指定 --live 时,用真实视频、手部模型和当前视觉服务验证整轮流程。</summary>
|
||||
|
||||
@ -10,7 +10,7 @@ using Prism.Dialogs;
|
||||
using SopHelper.Engine.Common;
|
||||
using SopHelper.Engine.Sop;
|
||||
using SopHelper.Engine.Training;
|
||||
using SopHelper.Training;
|
||||
using SopHelper.SopVideo;
|
||||
using SopHelper.VVMs.RecipeEditor;
|
||||
using SopHelper.VVMs.SopPage;
|
||||
using Window = Avalonia.Controls.Window;
|
||||
@ -34,6 +34,14 @@ internal static class Program
|
||||
if (args.Contains("--live")) { LiveVideoFlowChecks.Run(args); return; }
|
||||
if (args.Contains("--agent-generation-only")) { AgentDraftGenerationChecks.Run(root); return; }
|
||||
if (args.Contains("--optimization-only")) { OptimizeStepsChecks.Run(); return; }
|
||||
// 单独验证标准视频链路,便于定位回放与流程回测问题。
|
||||
if (args.Contains("--standard-video-only"))
|
||||
{
|
||||
RecipeCloseChecks.Run(root);
|
||||
StandardVideoImportChecks.Run(root);
|
||||
CheckVideoPage(root);
|
||||
return;
|
||||
}
|
||||
CheckAiFlow();
|
||||
CheckSequenceEditor();
|
||||
StepTestDecisionChecks.Run();
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
using OpenCvSharp;
|
||||
using SopHelper.Engine.Sop;
|
||||
using SopHelper.Engine.SopAgent;
|
||||
using SopHelper.Training;
|
||||
using SopHelper.SopVideo;
|
||||
|
||||
internal static class ReferenceEvidenceChecks
|
||||
{
|
||||
|
||||
@ -3,7 +3,7 @@ using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using OpenCvSharp;
|
||||
using SopHelper.Engine.Sop;
|
||||
using SopHelper.Training;
|
||||
using SopHelper.SopVideo;
|
||||
|
||||
/// <summary>真实手部模型与生产引擎的时序试验;截断时间仅控制输入视频,绝不作为判定条件。</summary>
|
||||
internal static class SequenceTrialChecks
|
||||
|
||||
Loading…
Reference in New Issue
Block a user