214 lines
12 KiB
C#
214 lines
12 KiB
C#
using System.IO;
|
||
using System.Windows;
|
||
using System.Windows.Controls;
|
||
using System.Windows.Media;
|
||
using System.Windows.Media.Imaging;
|
||
using System.Windows.Threading;
|
||
using OpenCvSharp;
|
||
using Prism.Dialogs;
|
||
using SopHelper.Engine.Camera;
|
||
using SopHelper.Engine.Sop;
|
||
using SopHelper.VVMs.RecipeEditor;
|
||
using Point = System.Windows.Point;
|
||
using Rect = System.Windows.Rect;
|
||
using Size = System.Windows.Size;
|
||
|
||
internal static class Program
|
||
{
|
||
[STAThread]
|
||
private static int Main(string[] args)
|
||
{
|
||
var app = new Application();
|
||
app.Resources.MergedDictionaries.Add(new ResourceDictionary
|
||
{
|
||
Source = new Uri("pack://application:,,,/SopHelper;component/Themes/Styles.xaml"),
|
||
});
|
||
SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext());
|
||
var run = CheckAsync(args);
|
||
_ = run.ContinueWith(_ => app.Dispatcher.BeginInvokeShutdown(DispatcherPriority.Background));
|
||
Dispatcher.Run();
|
||
try { run.GetAwaiter().GetResult(); return 0; }
|
||
catch (Exception ex) { Console.Error.WriteLine(ex); return 1; }
|
||
}
|
||
|
||
private static async Task CheckAsync(string[] args)
|
||
{
|
||
var imageSize = new Size(4000, 2000);
|
||
var display = RegionCanvas.FitImage(new Size(800, 600), imageSize);
|
||
if (display != new Rect(0, 100, 800, 400)) throw new Exception("横向留白计算错误");
|
||
var first = RegionCanvas.ToImage(new Point(160, 180), display, imageSize);
|
||
var last = RegionCanvas.ToImage(new Point(640, 420), display, imageSize);
|
||
var bounds = RegionCanvas.PixelBounds(last, first, imageSize);
|
||
if (bounds != new Int32Rect(800, 400, 2400, 1200)) throw new Exception("反向画框或像素换算错误");
|
||
var clipped = RegionCanvas.ToImage(new Point(900, -50), display, imageSize);
|
||
if (clipped != new Point(4000, 0)) throw new Exception("边界截取错误");
|
||
var portrait = RegionCanvas.FitImage(new Size(800, 600), new Size(1000, 2000));
|
||
if (portrait != new Rect(250, 0, 300, 600)) throw new Exception("纵向图像留白计算错误");
|
||
Console.WriteLine("PASS: 原图像素换算、横竖图留白、反向画框及越界截取");
|
||
|
||
var saveDirectory = Path.Combine(Path.GetTempPath(), "SopHelper-save-" + Guid.NewGuid().ToString("N"));
|
||
Directory.CreateDirectory(saveDirectory);
|
||
var savePath = Path.Combine(saveDirectory, "repeat-save.yaml");
|
||
var notifications = new List<string>();
|
||
var saveVm = new RecipeEditorViewModel();
|
||
try
|
||
{
|
||
saveVm.OnDialogOpened(new DialogParameters
|
||
{
|
||
{ "directory", saveDirectory }, { "new", true },
|
||
{ "onSaved", new Action<string>(notifications.Add) },
|
||
});
|
||
saveVm.Recipe.Name = "首次保存";
|
||
saveVm.Recipe.FileName = "repeat-save";
|
||
var editedRecipe = saveVm.Recipe;
|
||
// 未注册关闭监听器:保存如果仍尝试关闭弹窗,就不能正常完成。
|
||
saveVm.SaveCommand.Execute();
|
||
if (!saveVm.SaveStatus.StartsWith("已保存") || saveVm.Recipe.CanEditFileName ||
|
||
saveVm.Title != "编辑配方 - repeat-save.yaml" || notifications.Count != 1 ||
|
||
SopConfigLoader.Load(savePath).Sop.Name != "首次保存")
|
||
throw new Exception("首次保存后的状态或文件不正确:" + string.Join(";", saveVm.Warnings));
|
||
saveVm.Recipe.Name = "继续修改并保存";
|
||
saveVm.SaveCommand.Execute();
|
||
if (!saveVm.SaveStatus.StartsWith("已保存") || !ReferenceEquals(editedRecipe, saveVm.Recipe) ||
|
||
notifications.Count != 2 || notifications.Any(name => name != "repeat-save.yaml") ||
|
||
SopConfigLoader.Load(savePath).Sop.Name != "继续修改并保存" || Directory.GetFiles(saveDirectory).Length != 1)
|
||
throw new Exception("连续保存未更新原配方文件");
|
||
Console.WriteLine("PASS: 保存不请求关闭、编辑状态保留、新建转为编辑、连续保存更新同一文件并通知主页");
|
||
}
|
||
finally
|
||
{
|
||
saveVm.OnDialogClosed();
|
||
if (File.Exists(savePath)) File.Delete(savePath);
|
||
Directory.Delete(saveDirectory);
|
||
}
|
||
|
||
var node = new RegionNode();
|
||
node.PropertyChanged += (_, _) =>
|
||
{
|
||
if ((node.X1, node.Y1, node.X2, node.Y2) != (800, 400, 3200, 1600))
|
||
throw new Exception("坐标更新通知发出时数据不完整");
|
||
};
|
||
node.SetBounds(bounds);
|
||
|
||
var config = new SopConfig();
|
||
config.Sop.Name = "画框标定";
|
||
config.Sop.Regions["work"] = new RegionDef { X1 = 200, Y1 = 150, X2 = 950, Y2 = 650, Name = "操作区域", Color = "#00B8D4" };
|
||
using var fake = new CaptureCamera();
|
||
using var real = args.Contains("--hardware") ? new CameraService() : null;
|
||
var camera = (ICameraService?)real ?? fake;
|
||
var cameraInfo = real is null ? new CameraInfo { Index = 0, Name = "测试图像" } :
|
||
(await real.EnumerateAsync()).First(c => c.Kind == CameraKind.Hikvision);
|
||
var vm = new RecipeEditorViewModel();
|
||
vm.OnDialogOpened(new DialogParameters
|
||
{
|
||
{ "config", config }, { "new", true }, { "cameraService", camera }, { "cameraInfo", cameraInfo },
|
||
});
|
||
vm.CaptureImageCommand.Execute();
|
||
var deadline = DateTime.UtcNow.AddSeconds(20);
|
||
while (vm.IsCapturing && DateTime.UtcNow < deadline) await Task.Delay(20);
|
||
if (vm.IsCapturing || vm.PreviewImage is null) throw new Exception("取图失败:" + vm.PreviewStatus);
|
||
if (!vm.PreviewImage.IsFrozen || camera.IsConnected || camera.IsGrabbing) throw new Exception("图像未冻结或取图后未释放相机");
|
||
if (vm.Recipe.SelectedRegion is null) throw new Exception("区域未自动选中");
|
||
vm.Recipe.SelectedRegion.SetBounds(new Int32Rect(200, 150, 750, 500));
|
||
var saved = vm.Recipe.ToConfig().Sop.Regions["work"];
|
||
if ((saved.X1, saved.Y1, saved.X2, saved.Y2) != (200, 150, 950, 650)) throw new Exception("画框坐标未写入配方");
|
||
Console.WriteLine($"PASS: {vm.PreviewImage.PixelWidth}x{vm.PreviewImage.PixelHeight} 取图、资源释放和坐标写回配方");
|
||
|
||
var view = new RecipeEditor { DataContext = vm };
|
||
view.Measure(new Size(1020, 720));
|
||
view.Arrange(new Rect(0, 0, 1020, 720));
|
||
view.UpdateLayout();
|
||
var tabs = Descendants(view).OfType<TabControl>().Single();
|
||
tabs.SelectedIndex = 1;
|
||
view.UpdateLayout();
|
||
var canvas = Descendants(view).OfType<RegionCanvas>().Single();
|
||
if (!ReferenceEquals(canvas.Image, vm.PreviewImage) || !ReferenceEquals(canvas.SelectedRegion, vm.Recipe.SelectedRegion))
|
||
throw new Exception("画布绑定错误");
|
||
if (canvas.ActualWidth < 400 || canvas.ActualHeight < 200) throw new Exception("图像预览区域过小");
|
||
var normalCanvasSize = canvas.RenderSize;
|
||
var previewSize = new Size(vm.PreviewImage.PixelWidth, vm.PreviewImage.PixelHeight);
|
||
var normalImage = RegionCanvas.FitImage(normalCanvasSize, previewSize);
|
||
var dialogStyle = Dialog.GetWindowStyle(view);
|
||
var host = new DialogWindow { Style = dialogStyle, Content = view, Opacity = 0, ShowActivated = false, ShowInTaskbar = false };
|
||
if (host.SizeToContent != SizeToContent.Manual || host.ResizeMode != ResizeMode.CanResize ||
|
||
host.HorizontalContentAlignment != HorizontalAlignment.Stretch ||
|
||
host.VerticalContentAlignment != VerticalAlignment.Stretch)
|
||
throw new Exception("配方弹窗未配置为可缩放并拉伸内容");
|
||
// 用较大的客户区模拟最大化,验证整个弹窗内容链路,而非只检查画布自身。
|
||
host.Width = 1920;
|
||
host.Height = 1080;
|
||
host.Show();
|
||
host.UpdateLayout();
|
||
if (view.ActualWidth < host.ActualWidth - 100 || view.ActualHeight < host.ActualHeight - 100 ||
|
||
canvas.ActualWidth <= normalCanvasSize.Width || canvas.ActualHeight <= normalCanvasSize.Height)
|
||
throw new Exception($"放大弹窗后编辑内容或图像画布未扩展:内容 {view.RenderSize},画布 {canvas.RenderSize},窗口 {host.RenderSize}");
|
||
var enlargedImage = RegionCanvas.FitImage(canvas.RenderSize, previewSize);
|
||
var enlargedCanvasSize = canvas.RenderSize;
|
||
if (enlargedImage.Width <= normalImage.Width || enlargedImage.Height <= normalImage.Height)
|
||
throw new Exception("放大弹窗后图像显示尺寸未增大");
|
||
var enlargedPoint = new Point(enlargedImage.X + enlargedImage.Width / 4,
|
||
enlargedImage.Y + enlargedImage.Height / 4);
|
||
var mappedPoint = RegionCanvas.ToImage(enlargedPoint, enlargedImage, previewSize);
|
||
if ((mappedPoint - new Point(previewSize.Width / 4, previewSize.Height / 4)).Length > 0.001)
|
||
throw new Exception("放大后的原图坐标换算错误");
|
||
Console.WriteLine($"PASS: 弹窗内容随尺寸扩展,画布 {normalCanvasSize} → {canvas.RenderSize},图像等比放大且坐标正确");
|
||
host.Width = 1040;
|
||
host.Height = 760;
|
||
host.UpdateLayout();
|
||
if (canvas.ActualWidth >= enlargedCanvasSize.Width || canvas.ActualHeight >= enlargedCanvasSize.Height)
|
||
throw new Exception("还原窗口后画布未缩小");
|
||
if (args.FirstOrDefault(a => a.EndsWith(".png", StringComparison.OrdinalIgnoreCase)) is string output)
|
||
{
|
||
var bitmap = new RenderTargetBitmap(1020, 720, 96, 96, PixelFormats.Pbgra32);
|
||
bitmap.Render(view);
|
||
var encoder = new PngBitmapEncoder();
|
||
encoder.Frames.Add(BitmapFrame.Create(bitmap));
|
||
using var file = File.Create(output);
|
||
encoder.Save(file);
|
||
}
|
||
host.Content = null;
|
||
host.Close();
|
||
vm.OnDialogClosed();
|
||
Console.WriteLine("PASS: 区域页布局、预览与所选区域绑定");
|
||
}
|
||
|
||
private static IEnumerable<DependencyObject> Descendants(DependencyObject parent)
|
||
{
|
||
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
|
||
{
|
||
var child = VisualTreeHelper.GetChild(parent, i);
|
||
yield return child;
|
||
foreach (var next in Descendants(child)) yield return next;
|
||
}
|
||
}
|
||
}
|
||
|
||
internal sealed class CaptureCamera : ICameraService
|
||
{
|
||
public bool IsConnected { get; private set; }
|
||
public bool IsGrabbing { get; private set; }
|
||
public event Action<CameraFrame>? FrameArrived;
|
||
public event Action<bool>? ConnectionChanged;
|
||
#pragma warning disable CS0067
|
||
public event Action<string>? Error;
|
||
#pragma warning restore CS0067
|
||
public Task<List<CameraInfo>> EnumerateAsync() => Task.FromResult(new List<CameraInfo>());
|
||
public Task<bool> ConnectAsync(CameraInfo camera) { IsConnected = true; ConnectionChanged?.Invoke(true); return Task.FromResult(true); }
|
||
public async Task<bool> StartAsync()
|
||
{
|
||
IsGrabbing = true;
|
||
await Task.Run(() =>
|
||
{
|
||
using var mat = new Mat(900, 1600, MatType.CV_8UC3, new Scalar(48, 41, 34));
|
||
for (var x = 0; x < mat.Width; x += 100) Cv2.Line(mat, new OpenCvSharp.Point(x, 0), new OpenCvSharp.Point(x, mat.Height), new Scalar(70, 65, 60));
|
||
for (var y = 0; y < mat.Height; y += 100) Cv2.Line(mat, new OpenCvSharp.Point(0, y), new OpenCvSharp.Point(mat.Width, y), new Scalar(70, 65, 60));
|
||
using var frame = new CameraFrame { FrameId = 1, Timestamp = DateTime.Now, Bgr = mat.Clone() };
|
||
FrameArrived?.Invoke(frame);
|
||
});
|
||
return true;
|
||
}
|
||
public void Stop() => IsGrabbing = false;
|
||
public void Disconnect() { Stop(); IsConnected = false; ConnectionChanged?.Invoke(false); }
|
||
public void Dispose() => Disconnect();
|
||
}
|