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().UseHeadless(new AvaloniaHeadlessPlatformOptions()).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(); var model = new CameraViewModel(camera, root, timeProvider: clock); var window = new CameraWindow(model); window.Show(); model.RefreshCommand.Execute(); model.PreviewCommand.Execute(); 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().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 model = new CameraViewModel(camera, root, config.Sop.Name, clock, sopStandard: true); // 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().Single(); tabs.SelectedIndex = 5; window.UpdateLayout(); Check(tabs.ItemCount == 6 && ((TabItem)tabs.Items[5]!).Header?.ToString() == "SOP流程视频", "Recipe editor contains the SOP recording page"); model.RefreshCommand.Execute(); model.PreviewCommand.Execute(); Thread.Sleep(75); camera.Emit(); Dispatcher.UIThread.RunJobs(); model.RecordCommand.Execute(); 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.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"); Pump(reopened.ShutdownAsync()); var other = new CameraViewModel(new FakeCamera(), root, "另一配方", sopStandard: true); Check(!other.HasStandardVideo && other.StandardVideoPath != expectedPath, "SOP recordings are isolated between recipes"); 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 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 bool IsConnected { get; private set; } public bool IsGrabbing { get; private set; } public event Action? FrameArrived; public event Action? ConnectionChanged; public event Action? Error { add { } remove { } } public Task> EnumerateAsync() => Task.FromResult(new List { new() { Name = "测试相机" } }); public Task ConnectAsync(CameraInfo camera) { IsConnected = true; ConnectionChanged?.Invoke(true); return Task.FromResult(true); } public Task 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); } }