244 lines
18 KiB
C#
244 lines
18 KiB
C#
using System.Reflection;
|
|
using Avalonia;
|
|
using Avalonia.Controls;
|
|
using Avalonia.Headless;
|
|
using Avalonia.Markup.Xaml.Styling;
|
|
using Avalonia.Themes.Fluent;
|
|
using Avalonia.Threading;
|
|
using Avalonia.VisualTree;
|
|
using OpenCvSharp;
|
|
using SopHelper.Engine.Camera;
|
|
using SopHelper.Training;
|
|
using SopHelper.Engine.Sop;
|
|
using SopHelper.Engine.Training;
|
|
using SopHelper.VVMs.RecipeEditor;
|
|
using Prism.Dialogs;
|
|
using Window = Avalonia.Controls.Window;
|
|
|
|
internal static class Program
|
|
{
|
|
[STAThread]
|
|
public static void Main()
|
|
{
|
|
var root = Path.Combine(Path.GetTempPath(), "recording-limit-smoke-" + Guid.NewGuid().ToString("N"));
|
|
try
|
|
{
|
|
AppBuilder.Configure<Application>().UseSkia().UseHeadless(new AvaloniaHeadlessPlatformOptions { UseHeadlessDrawing = false }).SetupWithoutStarting();
|
|
Application.Current!.Styles.Add(new FluentTheme());
|
|
Application.Current.Styles.Add(new StyleInclude(new Uri("avares://SopHelper.Avalonia/")) { Source = new Uri("avares://SopHelper.Avalonia/Themes/Styles.axaml") });
|
|
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();
|
|
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.Hikvision, Index = 7, SerialNumber = "GLOBAL-CAMERA", 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.RecordCommand.CanExecute(), "Preview is ready for recording");
|
|
var notices = 0;
|
|
model.RecordingLimitReached += message => { notices++; Check(message.Contains("5分钟") && message.Contains(model.LastRecording), "Timeout notice contains the limit and saved path"); };
|
|
model.RecordCommand.Execute();
|
|
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");
|
|
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.RecordCommand.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");
|
|
model.RecordCommand.Execute();
|
|
Check(!model.IsRecording && notices == 1, "Manual stop saves without a timeout popup");
|
|
CheckVideo(model.LastRecording, 1);
|
|
clock.Advance(TimeSpan.FromMinutes(6)); Tick(model);
|
|
Check(notices == 1, "Stopped recordings do not later trigger a timeout");
|
|
camera.Emit(); model.RecordCommand.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);
|
|
}
|
|
finally
|
|
{
|
|
if (Path.GetFileName(root).StartsWith("recording-limit-smoke-") && Directory.Exists(root)) Directory.Delete(root, true);
|
|
}
|
|
}
|
|
private static void Tick(CameraViewModel model) => typeof(CameraViewModel).GetMethod("Tick", BindingFlags.Instance | BindingFlags.NonPublic)!.Invoke(model, null);
|
|
private static void RunSopRecording(string root)
|
|
{
|
|
var store = new RecipeWorkspace(root);
|
|
var config = new SopConfig(); config.Sop.Name = "标准流程"; config.Sop.Parts = [];
|
|
Directory.CreateDirectory(store.DirectoryFor(config.Sop.Name)); SopConfigLoader.Save(config, store.ConfigPath(config.Sop.Name));
|
|
var vm = new RecipeEditorViewModel();
|
|
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.
|
|
typeof(RecipeEditorViewModel).GetProperty(nameof(vm.SopRecording))!.SetValue(vm, model);
|
|
var editor = new RecipeEditor { DataContext = vm };
|
|
var window = new Window { Content = editor, Width = 1180, Height = 820 }; window.Show(); window.UpdateLayout();
|
|
var tabs = editor.GetVisualDescendants().OfType<TabControl>().Single(); tabs.SelectedIndex = 5; window.UpdateLayout();
|
|
Check(tabs.ItemCount == 6 && ((TabItem)tabs.Items[5]!).Header?.ToString() == "SOP流程视频", "Recipe editor contains the SOP recording page");
|
|
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(ReferenceEquals(camera.ConnectedCamera, selected) && camera.EnumerationCount == 0, "SOP recording also uses the global camera directly");
|
|
model.RecordCommand.Execute();
|
|
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");
|
|
clock.Advance(TimeSpan.FromSeconds(1)); camera.Emit();
|
|
model.PauseCommand.Execute();
|
|
clock.Advance(TimeSpan.FromMinutes(10)); camera.Emit(); Tick(model);
|
|
Check(model.IsRecording && model.IsPaused && model.RecordingInfo.Contains("00:00:01"), "Paused time does not advance the recording or trigger the five-minute limit");
|
|
model.RestartCommand.Execute(); FindSopDialog(editor).Close(false); PumpIdle(model);
|
|
Check(model.IsPaused && model.IsRecording, "Cancelling replacement preserves an intentionally paused recording");
|
|
model.PauseCommand.Execute(); clock.Advance(TimeSpan.FromSeconds(1)); camera.Emit();
|
|
model.RecordCommand.Execute(); CheckVideo(model.LastRecording, 2);
|
|
Check(!model.RecordCommand.CanExecute() && model.RestartCommand.CanExecute(), "Existing video can only be replaced through confirmed re-recording");
|
|
var original = File.ReadAllBytes(expectedPath);
|
|
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);
|
|
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");
|
|
model.PlayVideoCommand.Execute(); PumpIdle(model);
|
|
var playbackWait = System.Diagnostics.Stopwatch.StartNew();
|
|
while (model.Playback.IsPlaying && playbackWait.Elapsed < TimeSpan.FromSeconds(4)) PumpFor(20);
|
|
Check(model.Playback.IsAtEnd && model.Playback.Progress == 100 && model.PlayVideoButtonText == "重新播放", "Playback stops at the end and offers replay");
|
|
model.PlayVideoCommand.Execute(); PumpIdle(model);
|
|
Check(model.Playback.IsPlaying && model.Playback.Progress < 50, "Replay starts from the beginning");
|
|
model.StopVideoCommand.Execute(); PumpIdle(model);
|
|
Check(!model.Playback.IsLoaded && model.Playback.Frame is null, "Stop playback clears the player and releases its file");
|
|
Check(File.ReadAllBytes(expectedPath).SequenceEqual(original), "Playback leaves the recorded file unchanged");
|
|
model.PreviewCommand.Execute(); PumpIdle(model); camera.Emit(); Dispatcher.UIThread.RunJobs();
|
|
Check(model.IsPreviewing && !model.Playback.IsLoaded, "Camera preview can restart after playback");
|
|
model.RestartCommand.Execute();
|
|
var dialog = FindSopDialog(editor);
|
|
Check(dialog.Title == "确认重新录制" && File.ReadAllBytes(expectedPath).SequenceEqual(original), "Re-record opens confirmation before changing the old video");
|
|
dialog.Close(false); PumpIdle(model);
|
|
Check(!model.IsRecording && File.ReadAllBytes(expectedPath).SequenceEqual(original), "Cancelling confirmation preserves the old video exactly");
|
|
model.RestartCommand.Execute(); FindSopDialog(editor).Close(true); PumpIdle(model);
|
|
Check(model.IsRecording && model.LastRecording == expectedPath, "Confirming starts a new recording at the standard path");
|
|
Check(Directory.GetFiles(Path.GetDirectoryName(expectedPath)!, "*.avi").Length == 1, "Re-recording keeps only one standard video");
|
|
clock.Advance(TimeSpan.FromMilliseconds(500)); camera.Emit();
|
|
model.RestartCommand.Execute();
|
|
Check(model.IsPaused, "Active recording pauses while replacement confirmation is open");
|
|
clock.Advance(TimeSpan.FromMinutes(6)); camera.Emit();
|
|
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();
|
|
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);
|
|
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);
|
|
Check(reopened.Playback.IsPlaying && reopened.DisplayImage is not null, "Reopened recipe plays its saved video");
|
|
Pump(reopened.ShutdownAsync());
|
|
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);
|
|
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)!);
|
|
File.WriteAllText(other.StandardVideoPath, "damaged-video");
|
|
other.PlayVideoCommand.Execute(); PumpIdle(other);
|
|
Check(!other.Playback.IsLoaded && !other.Playback.IsPlaying && other.Status.Contains("无法打开"), "Damaged video reports an error without leaving a running player");
|
|
Pump(other.ShutdownAsync());
|
|
var fresh = new RecipeEditorViewModel(); var newConfig = new SopConfig(); newConfig.Sop.Name = "新配方";
|
|
fresh.OnDialogOpened(new DialogParameters { { "directory", store.RecipesDirectory }, { "config", newConfig }, { "new", true } });
|
|
Check(!fresh.HasSopRecording, "Unsaved recipes cannot record into an ambiguous directory");
|
|
fresh.SaveCommand.Execute(); Check(fresh.HasSopRecording, "Saving a new recipe enables its SOP recording page");
|
|
Pump(fresh.ShutdownSopRecordingAsync()); fresh.OnDialogClosed();
|
|
}
|
|
private static Window FindSopDialog(RecipeEditor editor)
|
|
{
|
|
Dispatcher.UIThread.RunJobs();
|
|
var dialog = (Window?)typeof(RecipeEditor).GetField("_dialog", BindingFlags.Instance | BindingFlags.NonPublic)!.GetValue(editor);
|
|
Check(dialog is { IsVisible: true }, "Replacement confirmation is visible"); return dialog!;
|
|
}
|
|
private static void PumpIdle(CameraViewModel model)
|
|
{
|
|
var wait = System.Diagnostics.Stopwatch.StartNew();
|
|
while (model.IsBusy && wait.Elapsed < TimeSpan.FromSeconds(5)) { Dispatcher.UIThread.RunJobs(); Thread.Sleep(1); }
|
|
Check(!model.IsBusy, "Recording operation completes after the dialog closes");
|
|
}
|
|
private static void Pump(Task task)
|
|
{
|
|
var wait = System.Diagnostics.Stopwatch.StartNew();
|
|
while (!task.IsCompleted && wait.Elapsed < TimeSpan.FromSeconds(5)) { Dispatcher.UIThread.RunJobs(); Thread.Sleep(1); }
|
|
Check(task.IsCompleted, "Camera shutdown completes"); task.GetAwaiter().GetResult();
|
|
}
|
|
private static void PumpFor(int milliseconds)
|
|
{
|
|
using var cancellation = new CancellationTokenSource(milliseconds);
|
|
Dispatcher.UIThread.MainLoop(cancellation.Token);
|
|
}
|
|
private static void CheckVideo(string path, double expectedSeconds)
|
|
{
|
|
using var video = new VideoCapture(path);
|
|
Check(video.IsOpened(), "Automatically/manual saved AVI can be reopened");
|
|
var duration = video.FrameCount / video.Fps;
|
|
var tolerance = expectedSeconds == 300 ? .001 : 1 / video.Fps + .001;
|
|
Check(Math.Abs(duration - expectedSeconds) < tolerance && duration <= 300, $"Encoded video duration is {expectedSeconds} seconds (within frame precision)");
|
|
using var frame = new Mat(); Check(video.Read(frame) && !frame.Empty(), "Saved AVI contains decodable frames");
|
|
}
|
|
private static void Check(bool value, string message) { if (!value) throw new Exception(message); Console.WriteLine("PASS: " + message); }
|
|
}
|
|
|
|
internal sealed class ManualClock : TimeProvider
|
|
{
|
|
private long _ticks;
|
|
public override long TimestampFrequency => TimeSpan.TicksPerSecond;
|
|
public override long GetTimestamp() => _ticks;
|
|
public void Advance(TimeSpan duration) => _ticks += duration.Ticks;
|
|
}
|
|
internal sealed class FakeCamera : ICameraService
|
|
{
|
|
public CameraInfo? ConnectedCamera { get; private set; }
|
|
public int EnumerationCount { get; private set; }
|
|
public bool IsConnected { get; private set; }
|
|
public bool IsGrabbing { get; private set; }
|
|
public event Action<CameraFrame>? FrameArrived;
|
|
public event Action<bool>? ConnectionChanged;
|
|
public event Action<string>? Error { add { } remove { } }
|
|
public Task<List<CameraInfo>> EnumerateAsync() { EnumerationCount++; return Task.FromResult(new List<CameraInfo> { new() { Name = "测试相机" } }); }
|
|
public Task<bool> ConnectAsync(CameraInfo camera) { ConnectedCamera = camera; IsConnected = true; ConnectionChanged?.Invoke(true); return Task.FromResult(true); }
|
|
public Task<bool> StartAsync() { IsGrabbing = true; return Task.FromResult(true); }
|
|
public void Stop() => IsGrabbing = false;
|
|
public void Disconnect() { Stop(); IsConnected = false; ConnectionChanged?.Invoke(false); }
|
|
public void Dispose() => Disconnect();
|
|
public void Emit()
|
|
{
|
|
using var frame = new CameraFrame { Bgr = new Mat(48, 64, MatType.CV_8UC3, new Scalar(35, 60, 90)) };
|
|
FrameArrived?.Invoke(frame);
|
|
}
|
|
}
|