App.xaml.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. using Prism.DryIoc;
  2. using Prism.Ioc;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Reflection;
  7. using System.Runtime.InteropServices;
  8. using System.Text.Json;
  9. using System.Windows;
  10. using System.Windows.Media;
  11. using TeamAAS.Camera.Interfaces;
  12. using TeamAAS.Robot.Interfaces;
  13. using TeamAAS.Robot;
  14. using TeamAAS.Dialogs;
  15. using TeamAAS.ViewModels;
  16. using TeamAAS.Views;
  17. using TeamAAS.FlowEngine;
  18. using TeamAAS.FlowEditor.Execution;
  19. using TeamAAS.FlowEngine.Interfaces;
  20. using TeamAAS.FlowEngine.Execution;
  21. using System.Diagnostics;
  22. using TeamAAS.Communication;
  23. using TeamAAS.Camera;
  24. using TeamAAS.Core;
  25. using TeamAAS.Feeder.Interfaces;
  26. using TeamAAS.Feeder;
  27. using TeamAAS.Motion;
  28. using TeamAAS.Models;
  29. using TeamAAS.Localization;
  30. using TeamAAS.Theme;
  31. using PropertyGridLib.Localization;
  32. namespace TeamAAS
  33. {
  34. public partial class App : PrismApplication
  35. {
  36. public static SystemConfiguration SystemConfig { get; set; } = new SystemConfiguration();
  37. /// <summary>
  38. /// Runtime 根目录(业务依赖、Plugins、native 库统一存放于此)。
  39. /// 根目录只保留 EXE + 配置类文件夹(Config/Logs/Products/Recipe/zh-CN)。
  40. /// </summary>
  41. public static string RuntimeDir => PathHelper.RuntimeDir;
  42. protected override Window CreateShell()
  43. {
  44. return Container.Resolve<MainWindow>();
  45. }
  46. protected override void OnStartup(StartupEventArgs e)
  47. {
  48. // 1) 把 native DLL 搜索路径指向 Runtime\dll\x64(OpenCV 等非 .NET 库)
  49. SetupNativeDllSearchPath();
  50. // 2) 注册 AssemblyResolve:在 Runtime 下递归查找缺失程序集,重复 DLL 直接跳过
  51. AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
  52. // 3) 加载插件(Plugins 现在位于 Runtime\Plugins)
  53. string pluginsPath = PathHelper.PluginsDir;
  54. PluginLoader.Instance.LoadFrom(pluginsPath);
  55. // 4) 加载系统配置(字体/标题/主题/主色)
  56. LoadSystemConfig();
  57. // 5) 初始化多语言系统
  58. InitializeLocalization();
  59. // 6) 初始化全局变量管理器(加载机器级 Global 固定变量)
  60. GlobalVariableManager.Instance.LoadGlobalScoped();
  61. // 7) 初始化 ResultRegistry(订阅全局变量变化)
  62. ResultRegistry.Initialize();
  63. // 7.1) 探测可用视觉引擎(反射扫描 + 尝试加载已知引擎类库),
  64. // 并按配置设置当前引擎(Vision.EngineName)——主页画面/标定页随引擎切换
  65. TeamAAS.Vision.VisualEngineManager.Instance.Discover();
  66. TeamAAS.Vision.VisualEngineManager.Instance.SetCurrent(SystemConfig?.Vision?.EngineName);
  67. // 8) 全局窗口自适应:所有 Window(主窗/子窗体/对话框/弹窗)Loaded 后自动挂 UiScaler,
  68. // 以后新增任何窗体都无需手动接线
  69. EventManager.RegisterClassHandler(typeof(Window), FrameworkElement.LoadedEvent,
  70. new RoutedEventHandler(OnAnyWindowLoaded), true);
  71. // 9) 全局异常兑底:任何未处理异常先落主页日志(含堆栈),UI 线程异常标记已处理避免闪退;
  72. // 进程级/任务级异常虽救不回来,但至少留下死因可查。触发场景如:VM 控件污染
  73. // 应用级画刷资源导致 HC 样式 String→Brush 强转失败(详见 Plugins.Vm/VmThemeGuard)
  74. DispatcherUnhandledException += (s, args) =>
  75. {
  76. AppLogger.Error("UI 线程未处理异常: " + args.Exception.Message, args.Exception, nameof(App));
  77. args.Handled = true;
  78. };
  79. AppDomain.CurrentDomain.UnhandledException += (s, args) =>
  80. AppLogger.Error("致命未处理异常(进程即将退出): " + args.ExceptionObject, args.ExceptionObject as Exception, nameof(App));
  81. System.Threading.Tasks.TaskScheduler.UnobservedTaskException += (s, args) =>
  82. {
  83. AppLogger.Error("未观察的任务异常: " + args.Exception.Message, args.Exception, nameof(App));
  84. args.SetObserved();
  85. };
  86. base.OnStartup(e);
  87. }
  88. /// <summary>
  89. /// 全局窗口 Loaded 钩子:主窗口计算全局缩放因子,弹窗/子窗体跟随。
  90. /// (UiScaler.Attach 内部有幂等保护,重复触发不会重复挂接。)
  91. /// </summary>
  92. private static void OnAnyWindowLoaded(object sender, RoutedEventArgs e)
  93. {
  94. if (!(sender is Window window)) return;
  95. if (Application.Current.MainWindow == window)
  96. UiScaler.AttachMain(window);
  97. else
  98. UiScaler.Attach(window);
  99. }
  100. /// <summary>
  101. /// 把 Runtime\dll\<arch> 加入 native DLL 搜索路径(P/Invoke、DllImport 用)。
  102. /// 通过 SetDllDirectory 让 LoadLibrary 在该目录查找 native 库。
  103. /// 架构按当前进程位数自动选择 x86 / x64,兼容 32 位与 64 位部署。
  104. /// </summary>
  105. private static void SetupNativeDllSearchPath()
  106. {
  107. try
  108. {
  109. string arch = IntPtr.Size == 8 ? "x64" : "x86";
  110. string nativeDir = Path.Combine(RuntimeDir, "dll", arch);
  111. if (Directory.Exists(nativeDir))
  112. {
  113. SetDllDirectory(nativeDir);
  114. }
  115. }
  116. catch { /* 失败不影响启动,缺失 native 库时由调用方报错 */ }
  117. }
  118. [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
  119. private static extern bool SetDllDirectory(string lpPathName);
  120. private static readonly Dictionary<string, Assembly> _resolvedCache =
  121. new Dictionary<string, Assembly>(StringComparer.OrdinalIgnoreCase);
  122. /// <summary>
  123. /// 在 Runtime 目录下递归查找缺失程序集;同名 DLL 已加载过则直接返回缓存,跳过重复加载避免报错。
  124. /// 同时兼容旧的 EXE 根目录布局(迁移期内根目录残留 DLL 也能找到)。
  125. /// </summary>
  126. private Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs e)
  127. {
  128. try
  129. {
  130. string name = new AssemblyName(e.Name).Name;
  131. if (string.IsNullOrEmpty(name)) return null;
  132. // 1) 已加载过 → 直接返回(跳过重复,避免重复加载报错
  133. if (_resolvedCache.TryGetValue(name, out var cached))
  134. return cached;
  135. // 2) Runtime 目录递归查找(包含 Plugins 子目录、dll 子目录等)
  136. var found = TryFindAssembly(RuntimeDir, name);
  137. if (found != null)
  138. {
  139. _resolvedCache[name] = found;
  140. return found;
  141. }
  142. // 3) 兼容:根目录残留 DLL 也能找到(迁移期间用)
  143. var rootPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, name + ".dll");
  144. if (File.Exists(rootPath))
  145. {
  146. var asm = Assembly.LoadFrom(rootPath);
  147. _resolvedCache[name] = asm;
  148. return asm;
  149. }
  150. }
  151. catch { }
  152. return null;
  153. }
  154. /// <summary>
  155. /// 在指定根目录下递归查找匹配名称的 .dll,找到第一个即返回。
  156. /// 多个位置存在同名 DLL 时优先返回 Plugins 子目录的版本(避免插件重复依赖冲突)。
  157. /// </summary>
  158. private static Assembly TryFindAssembly(string rootDir, string name)
  159. {
  160. if (!Directory.Exists(rootDir)) return null;
  161. string target = name + ".dll";
  162. string firstHit = null;
  163. // 优先 Plugins 子目录(插件依赖隔离)
  164. var pluginsSub = Path.Combine(rootDir, "Plugins");
  165. if (Directory.Exists(pluginsSub))
  166. {
  167. var p = Path.Combine(pluginsSub, target);
  168. if (File.Exists(p)) firstHit = p;
  169. }
  170. // 再扫描 Runtime 全部子目录(深度优先)
  171. if (firstHit == null)
  172. {
  173. foreach (var file in Directory.EnumerateFiles(rootDir, target, SearchOption.AllDirectories))
  174. {
  175. firstHit = file;
  176. break;
  177. }
  178. }
  179. if (firstHit == null) return null;
  180. try { return Assembly.LoadFrom(firstHit); }
  181. catch { return null; }
  182. }
  183. protected override void OnInitialized()
  184. {
  185. // 运行引擎接线:注入通讯管理器 + 启动心跳监听(触发运行产品执行)
  186. FlowRunner.Instance.Communication = CoreManager.Communication;
  187. FlowRunner.Instance.StartHeartbeat();
  188. base.OnInitialized();
  189. }
  190. protected override void OnExit(ExitEventArgs e)
  191. {
  192. // 退出前把所有相机停止采集并断开,避免设备句柄残留导致下次打不开
  193. try { CameraManager.Instance.CloseAll(); } catch { }
  194. try { MotionManager.Instance.CloseAll(); } catch { }
  195. base.OnExit(e);
  196. }
  197. private static void LoadSystemConfig()
  198. {
  199. try
  200. {
  201. var path = PathHelper.SystemConfigurationFile;
  202. if (File.Exists(path))
  203. {
  204. var json = File.ReadAllText(path);
  205. SystemConfig = JsonSerializer.Deserialize<SystemConfiguration>(json) ?? new SystemConfiguration();
  206. }
  207. }
  208. catch { SystemConfig = new SystemConfiguration(); }
  209. // 应用插件日志配置(根目录/路径公式/默认等级)
  210. TeamAAS.Logging.PluginLogger.Configure(SystemConfig.PluginLog);
  211. UpdateFontResources();
  212. ApplyTheme();
  213. }
  214. /// <summary>
  215. /// 初始化多语言系统
  216. /// </summary>
  217. private static void InitializeLocalization()
  218. {
  219. try
  220. {
  221. // 1. 加载所有语言包(.json 人类可读格式)
  222. // PostBuild 会把根目录的 Localization 移到 Runtime\Localization,两个路径都兼容
  223. var localizationPath = PathHelper.ResolveLocalizationDir();
  224. GlobalLocalizationManager.Instance.LoadLanguagePacks(localizationPath);
  225. // 2. 设置回退语言为中文(当前语言=回退语言时,直接显示中文原文)
  226. GlobalLocalizationManager.Instance.FallbackLanguage = "zh-CN";
  227. // 3. 注入 PropertyGrid 全局翻译钩子:把 [DisplayName]/[Description]/[Category]
  228. // 特性里的中文原文交给 GlobalLocalizationManager 查语言包翻译(插件零改动)
  229. LocalizationManager.TextResolver = text => GlobalLocalizationManager.Instance.Translate(text);
  230. // 4. 从系统配置加载上次保存的语言
  231. var savedLanguage = SystemConfig?.Language ?? "zh-CN";
  232. GlobalLocalizationManager.Instance.CurrentLanguage = savedLanguage;
  233. // 5. 同步 PropertyGrid 语言(culture 开集,直接用语言代码)
  234. SyncPropertyGridLanguage();
  235. // 6. 监听语言切换事件(设置页切换语言后,PropertyGrid 实时刷新)
  236. GlobalLocalizationManager.Instance.LanguageChanged += (s, e) =>
  237. {
  238. SyncPropertyGridLanguage();
  239. };
  240. Console.WriteLine($"[Localization] 多语言系统已初始化,当前语言: {savedLanguage}");
  241. }
  242. catch (Exception ex)
  243. {
  244. Console.WriteLine($"[Localization] 初始化失败: {ex.Message}");
  245. }
  246. }
  247. /// <summary>
  248. /// 同步 PropertyGrid 语言设置(culture 开集,直接使用语言代码,如 "en-US"、"ja-JP")
  249. /// </summary>
  250. private static void SyncPropertyGridLanguage()
  251. {
  252. var currentLang = GlobalLocalizationManager.Instance.CurrentLanguage;
  253. LocalizationManager.CurrentCulture = currentLang;
  254. }
  255. public static void UpdateFontResources()
  256. {
  257. var font = SystemConfig?.Font ?? new FontSizeSettings();
  258. var resources = Application.Current?.Resources;
  259. if (resources == null) return;
  260. resources["NavButtonFontSize"] = font.NavButtonFont;
  261. resources["NavButtonWidth"] = font.NavButtonWidth;
  262. resources["NavButtonHeight"] = font.NavButtonHeight;
  263. resources["NavIconSize"] = font.NavIconSize;
  264. resources["TopBarHeight"] = font.TopBarHeight;
  265. resources["CenterTitleFontSize"] = font.CenterTitleFont;
  266. resources["ThemeIconFontSize"] = font.ThemeIconSize;
  267. resources["StatusBarHeight"] = font.StatusBarHeight;
  268. resources["StatusBarFontSize"] = font.StatusBarFont;
  269. var title = SystemConfig?.Title ?? "TeamAAS";
  270. resources["CenterTitleText"] = title;
  271. if (Application.Current.MainWindow != null)
  272. Application.Current.MainWindow.Title = title;
  273. }
  274. // ────────────────────────────────────────────────────────────────────
  275. // 主题与主色已下沉到 TeamAAS.Core\TeamAAS.Global\Theme(命名空间 TeamAAS.Theme):
  276. // ThemeManager(门面:ApplyTheme/UpdateTheme/UpdateAccent/RepairTheme)
  277. // + VmResourceGuard(资源守护)+ ThemeOverlay(覆盖字典/主色派生)+ ColorUtility。
  278. // 主程序只调用门面接口,不感知实现细节——保持主程序简洁。
  279. // ────────────────────────────────────────────────────────────────────
  280. /// <summary>
  281. /// 按 SystemConfiguration 完整应用(启动/设置页保存时调用):
  282. /// 读取配置后转发给 TeamAAS.Theme.ThemeManager。
  283. /// </summary>
  284. public static void ApplyTheme()
  285. {
  286. var cfg = SystemConfig ?? new SystemConfiguration();
  287. bool dark = string.Equals(cfg.Theme, "Dark", StringComparison.OrdinalIgnoreCase);
  288. AppLogger.Info($"ApplyTheme: dark={dark}, accent={cfg.AccentColor}", nameof(App));
  289. ThemeManager.ApplyTheme(dark, cfg.AccentColor);
  290. }
  291. /// <summary>
  292. /// 保存系统配置到 Config\SystemConfiguration.json(主题/主色/字体/标题)。
  293. /// </summary>
  294. public static void SaveSystemConfig()
  295. {
  296. try
  297. {
  298. var path = PathHelper.SystemConfigurationFile;
  299. var json = JsonSerializer.Serialize(SystemConfig, new JsonSerializerOptions { WriteIndented = true });
  300. File.WriteAllText(path, json);
  301. // 保存后立即应用插件日志配置
  302. TeamAAS.Logging.PluginLogger.Configure(SystemConfig.PluginLog);
  303. }
  304. catch (Exception ex)
  305. {
  306. AppLogger.Error("系统配置保存失败", ex, nameof(App));
  307. }
  308. }
  309. protected override void RegisterTypes(IContainerRegistry containerRegistry)
  310. {
  311. containerRegistry.RegisterSingleton<MainWindowViewModel>();
  312. // 注册设备管理器并加载配置(相机/机器人/通讯/供料器)
  313. // CameraManager 使用懒汉单例,DI 容器直接复用单例实例
  314. containerRegistry.RegisterInstance<ICameraManager>(CameraManager.Instance);
  315. containerRegistry.RegisterInstance<IRobotManager>(RobotManager.Instance);
  316. containerRegistry.RegisterInstance<CommunicationManager>(CommunicationManager.Instance);
  317. containerRegistry.RegisterInstance<IFeederManager>(FeederManager.Instance);
  318. containerRegistry.RegisterInstance<IPluginLoader>(PluginLoader.Instance);
  319. containerRegistry.RegisterInstance<MotionManager>(MotionManager.Instance);
  320. var commManager = CommunicationManager.Instance;
  321. commManager.LoadConfig();
  322. var cameraManager = CameraManager.Instance;
  323. cameraManager.LoadConfig();
  324. var robotManager = RobotManager.Instance;
  325. robotManager.LoadConfig();
  326. var feederManager = FeederManager.Instance;
  327. feederManager.LoadConfig();
  328. // 运动控制设备(设备内核新增):加载 Config\MotionDevices.json,无配置文件时为空列表
  329. var motionManager = MotionManager.Instance;
  330. motionManager.LoadConfig();
  331. // 将 DI 单例赋值给 CoreManager,确保全局同一实例
  332. CoreManager.Camera = cameraManager;
  333. CoreManager.Robot = robotManager;
  334. CoreManager.Communication = commManager;
  335. CoreManager.Feeder = feederManager;
  336. CoreManager.Motion = motionManager;
  337. // SDK 服务注册表接线:把同一批单例注册进 ServiceRegistry(适配器,零行为变化)。
  338. // 具体类型 + 接口双注册:CoreManager 门面按具体类型取,插件按接口经 IPluginContext 取。
  339. var sdkRegistry = TeamAAS.Global.ServiceRegistry.Default;
  340. sdkRegistry.Register(cameraManager);
  341. sdkRegistry.Register<ICameraManager>(cameraManager);
  342. sdkRegistry.Register(robotManager);
  343. sdkRegistry.Register<IRobotManager>(robotManager);
  344. sdkRegistry.Register(commManager);
  345. sdkRegistry.Register(feederManager);
  346. sdkRegistry.Register<IFeederManager>(feederManager);
  347. sdkRegistry.Register(motionManager);
  348. containerRegistry.RegisterSingleton<SettingViewModel>();
  349. containerRegistry.RegisterForNavigation<HomeView>("HomeView");
  350. containerRegistry.RegisterForNavigation<ProductView>("ProductView");
  351. containerRegistry.RegisterForNavigation<SettingView>("SettingView");
  352. containerRegistry.RegisterForNavigation<CalibrationView>("CalibrationView");
  353. containerRegistry.RegisterForNavigation<StatisticsView>("StatisticsView");
  354. containerRegistry.RegisterForNavigation<UserView>("UserView");
  355. }
  356. }
  357. }