From fbdb8f089855eb4944cfdaae7c6b09044f7b4789 Mon Sep 17 00:00:00 2001 From: tfarcraw <123211521@163.com> Date: Fri, 20 Nov 2026 22:02:14 +0800 Subject: [PATCH] =?UTF-8?q?=E4=B8=BA=E5=BA=94=E7=94=A8=E5=85=A5=E5=8F=A3?= =?UTF-8?q?=E8=A1=A5=E5=85=85=E8=AF=A6=E7=BB=86=E4=B8=AD=E6=96=87=E6=B3=A8?= =?UTF-8?q?=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/SopHelper.Avalonia/App.axaml.cs | 58 +++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/src/SopHelper.Avalonia/App.axaml.cs b/src/SopHelper.Avalonia/App.axaml.cs index 3ec089f..4dbf735 100644 --- a/src/SopHelper.Avalonia/App.axaml.cs +++ b/src/SopHelper.Avalonia/App.axaml.cs @@ -16,83 +16,141 @@ using SopHelper.VVMs.RecipeEditor; using SopHelper.VVMs.SopPage; namespace SopHelper; +/// +/// Avalonia 应用入口,基于 Prism 和 DryIoc 完成依赖注册、主窗口创建与导航初始化。 +/// 同时负责 D3 视觉服务的自动启动,以及主窗口关闭时的取消和资源释放。 +/// public partial class App : PrismApplication { + // 应用持有的相机服务;可以由外部注入,也可以在注册依赖时创建默认实现。 private ICameraService? _camera; + // 使用同一个相机服务创建检测流水线,并将该实例交给容器供其他组件共享。 private DetectionPipeline? _pipeline; + // 默认启动流程会尝试拉起 D3;使用注入相机的构造函数时关闭此行为。 private readonly bool _autoStartD3 = true; + // 主窗口关闭时通知异步启动流程退出;等待任务结束后再释放此取消源。 private readonly CancellationTokenSource _d3StartupCancellation = new(); + // 保存启动任务,既避免重复启动,也用于判断取消源何时可以安全释放。 private Task? _d3Startup; + + /// 默认应用构造入口,启用 D3 服务自动启动。 public App() { } + + /// + /// 使用外部提供的相机服务创建应用,并禁用 D3 自动启动,便于测试或自定义宿主接入。 + /// 注入的相机仍会在主窗口关闭时由本应用释放。 + /// + /// 供界面和检测流水线共享的相机服务。 public App(ICameraService camera) { _camera=camera; _autoStartD3=false; } + + /// 加载 App.axaml 中的应用资源,再执行 Prism 的初始化流程。 public override void Initialize() { AvaloniaXamlLoader.Load(this); base.Initialize(); } + + /// 配置全局异常记录,并向 Prism 容器注册模型、导航页面与业务服务。 + /// Prism 提供的依赖注册入口。 protected override void RegisterTypes(IContainerRegistry containerRegistry) { + // AppDomain 异常只记录信息;此处没有拦截或阻止进程终止的逻辑。 AppDomain.CurrentDomain.UnhandledException+=(_,e)=>Log(e.ExceptionObject as Exception,"AppDomain"); + // UI 调度器异常记录后标记为已处理,避免继续沿调度器的未处理异常路径传播。 Avalonia.Threading.Dispatcher.UIThread.UnhandledException+=(_,e)=>{Log(e.Exception,"Dispatcher");e.Handled=true;}; + // 按特性扫描当前应用程序集:带 ModelAttribute 的类型统一注册为单例。 foreach(var model in Assembly.GetExecutingAssembly().GetTypes().Where(t=>t.GetCustomAttribute()!=null)) containerRegistry.RegisterSingleton(model); + // 页面以类型名作为 Prism 导航键;导航特性中的 ViewName 应与注册键保持一致。 foreach(var view in Assembly.GetExecutingAssembly().GetTypes().Where(t=>t.GetCustomAttribute()!=null)) containerRegistry.RegisterForNavigation(view,view.Name); + // 导航模型保存侧栏页面列表和选中状态,供主窗口及页面共享。 containerRegistry.RegisterSingleton(); + // 优先复用注入的相机,否则创建默认服务;流水线使用同一相机实例。 _camera??=new CameraService();_pipeline=new DetectionPipeline(_camera); containerRegistry.RegisterInstance(_camera); containerRegistry.RegisterInstance(_pipeline); + // SOP 执行引擎与 SOP 页面视图模型使用单例,复用其运行状态。 containerRegistry.RegisterSingleton(); containerRegistry.RegisterSingleton(); + // 注册配方编辑对话框的视图/视图模型配对,并指定承载对话框的窗口类型。 containerRegistry.RegisterDialog("RecipeEditorDialog"); containerRegistry.RegisterDialogWindow(); } + /// 创建主窗口,按页面特性生成侧栏导航,并绑定窗口打开和关闭时的生命周期逻辑。 + /// 由 Prism 容器解析出的主窗口。 protected override AvaloniaObject CreateShell() { var navigation=Container.Resolve(); + // Index 决定侧栏顺序;显示名称和导航目标来自页面的 NavigationPageAttribute。 foreach(var type in Assembly.GetExecutingAssembly().GetTypes().Where(t=>t.GetCustomAttribute()!=null) .OrderBy(t=>t.GetCustomAttribute()!.Index)) { var page=type.GetCustomAttribute()!; + // 每个页面创建独立的导航项,集中加入导航模型供界面绑定。 var item=Container.Resolve();item.ViewName=page.ViewName;item.DisplayName=page.DisplayName;navigation.Pages.Add(item); } var window=Container.Resolve(); window.Opened+=(_,_)=> { + // 等窗口打开、内容区域就绪后再选中首页;SelectedIndex 的 setter 会触发导航。 if(navigation.Pages.Count>0) navigation.SelectedIndex=0; + // 不阻塞窗口打开;保留异步任务,确保本应用实例最多发起一次自动启动。 if(_autoStartD3) _d3Startup ??= StartD3Async(); }; window.Closed+=(_,_)=> { + // 先取消可能仍在进行的服务探测或就绪等待,再安排取消源的释放。 + // 未完成的任务仍可能读取令牌,因此将 Dispose 延后到任务结束,并在默认调度器执行。 _d3StartupCancellation.Cancel(); if(_d3Startup is null || _d3Startup.IsCompleted) _d3StartupCancellation.Dispose(); else _ = _d3Startup.ContinueWith(_ => _d3StartupCancellation.Dispose(), TaskScheduler.Default); + // 分别释放相机和流水线;任一释放失败都会记录日志,不影响另一个资源的清理。 try{_camera?.Dispose();}catch(Exception ex){Log(ex,"Exit.Camera");} try{_pipeline?.Dispose();}catch(Exception ex){Log(ex,"Exit.Pipeline");} }; return window; } + /// + /// 按环境配置检查 D3 服务并在需要时启动本机进程,将进度与结果显示到 SOP 页面日志。 + /// 具体的健康探测、已有服务复用、本机启动和超时控制由 D3ServiceStartup 负责。 + /// private async Task StartD3Async() { + // 未指定提供方或明确使用 d3/d3-lite 时才参与自动启动,其他提供方直接跳过。 var provider=Environment.GetEnvironmentVariable("SOPHELPER_VISION_PROVIDER")?.Trim().ToLowerInvariant(); if(provider is not (null or "" or "d3" or "d3-lite")) return; var sop=Container.Resolve(); try { + // 不使用 HttpClient 的全局超时;单次探测及整体启动期限由启动服务自行控制。 + // 将响应缓冲上限设为 64 KiB,健康检查无需接收大型响应。 using var http=new System.Net.Http.HttpClient { Timeout=Timeout.InfiniteTimeSpan, MaxResponseContentBufferSize=65536 }; + // 从环境变量和默认目录生成配置,包含接口地址、本机 Python/启动脚本和日志位置。 var options=D3StartupOptions.FromEnvironment(AppContext.BaseDirectory,Presentation.DesktopPlatform.WorkspaceRoot); + // 将启动过程中的状态文本交给视图模型;视图模型负责调度到界面线程更新日志。 var progress=new Progress(message=>sop.ReportD3Service(message)); var result=await new D3ServiceStartup(http,new D3LocalProcess()).EnsureReadyAsync(options,progress,_d3StartupCancellation.Token); + // 未就绪且并非主动跳过时才作为异常状态报告,例如启动失败或等待超时。 sop.ReportD3Service(result.Message,!result.Ready&&!result.Skipped); } + // 关闭窗口导致的取消属于正常退出;其他异常同时反馈到页面并写入错误日志。 catch(OperationCanceledException) { } catch(Exception error) { sop.ReportD3Service("djev 自动启动失败:"+error.Message,true);Log(error,"djev.Startup"); } } + /// 保留 Prism 默认配置,并设置本项目的视图/视图模型命名约定。 protected override void ConfigureViewModelLocator() { base.ConfigureViewModelLocator(); + // 视图模型与视图位于同一程序集、同一命名空间,类型名为视图完整名称追加 ViewModel。 ViewModelLocationProvider.SetDefaultViewTypeToViewModelTypeResolver(t=>Type.GetType($"{t.FullName}ViewModel, {t.Assembly.FullName}")); } + + /// 将异常摘要输出到控制台,并尝试追加到程序目录下的 logs/error.log。 + /// 要记录的异常;为空时直接返回。 + /// 异常来源标签,用于区分 UI、启动或资源释放等阶段。 private static void Log(Exception? exception,string from) { if(exception is null)return; + // 当前日志仅包含本地时间、来源和异常消息,不包含堆栈或内部异常详情。 var line=$"[{DateTime.Now:HH:mm:ss.fff}] [{from}] {exception.Message}";Console.WriteLine(line); + // 文件日志采用尽力写入方式;忽略目录权限或文件占用等写入错误,避免记录异常时再次抛错。 try{var directory=Path.Combine(AppContext.BaseDirectory,"logs");Directory.CreateDirectory(directory);File.AppendAllText(Path.Combine(directory,"error.log"),line+Environment.NewLine);}catch{ } } }